body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>Im not that good at C, so go easy on me, but I wanted to be able to have individual bit access in C without using a ton of functions to do bit manipulation on a <code>uint8_t</code>. Tell me where I could improve upon it</p>
<pre><code>#include <stdio.h>
#pragma pack(1)
union bit_array {
struct {
unsigned char b8:1, b7:1, b6:1, b5:1, b4:1, b3:1, b2:1, b1:1;
} bits;
unsigned char value;
};
int main() {
// Creates char with binary value 11111111
union bit_array test = { 1, 1, 1, 1, 1, 1, 1, 1 };
// Displays 11111111 (255)
printf("%u\n", test.value);
// Sets 8th bit of binary value to 0
// 11111111 (255) -> 11111110 (254)
test.bits.b8 = 0;
// Displays 11111110 (254)
printf("%u\n", test.value);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T23:22:46.777",
"Id": "512296",
"Score": "5",
"body": "Your current code does not show how you intend to use the bitwise access. The `main` function should demonstrate exactly that, but in the code you posted, it doesn't. Without this information, we cannot tell you how to write _really_ good code for this task."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T00:31:14.870",
"Id": "512300",
"Score": "1",
"body": "@RolandIllig The reason why i like this implementation is because you can do a lot of things with it, but I have now updated my code to show one of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T06:34:50.503",
"Id": "512311",
"Score": "1",
"body": "b0 - b7 probably are more understandable. `{a, b, c, d, e, f, g, h}` giving `hgfedcba` (if I read your code right) is also less evident. You set b8 but the bit to the right is set. At least if 11111110 means 254. **4.** `uint8_t` is better than `unsigned char`."
}
] |
[
{
"body": "<p>This code is not portable. The order of bit-fields within a word is completely compiler-dependent, so the test that appears to work on one platform may give completely different results on another.</p>\n<p>You have avoided a common trap of using signed 1-bit fields (which can hold values <code>0</code> and <code>-1</code>) - these unsigned ones are much better.</p>\n<p>I don't think there's any need for the <code>bits</code> member to be named - I would use an anonymous member there.</p>\n<p>The numbering of bits is unconventional - most programmers would expect <code>b0</code> to be the least-significant bit, and <code>b7</code> the most significant (corresponding to 2⁰ and 2⁷ value of those bits in integers).</p>\n<p>The test would be better if it were <em>self-checking</em> - return with non-zero status if any of the expectations are not met. For example:</p>\n<pre><code>int main(void)\n{\n int failures = 0;\n\n {\n /* First test */\n union bit_array test = { {1, 1, 1, 1, 1, 1, 1, 1} };\n if (test.value != 0xFF) {\n fprintf(stderr, "Test 1 expected 0xff, got %#04hhx\\n", test.value);\n ++failures;\n }\n }\n\n {\n /* Second test */\n union bit_array test = { {1, 1, 1, 1, 1, 1, 1, 1} };\n test.bits.b8 = 0;\n if (test.value != 0xFE) {\n fprintf(stderr, "Test 2 expected 0xfe, got %#04hhx\\n", test.value);\n ++failures;\n }\n }\n\n return failures != 0;\n}\n</code></pre>\n<p>We need tests of the most-significant bit, and setting as well as resetting bits. I'll leave that as an exercise.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T18:07:24.497",
"Id": "512354",
"Score": "0",
"body": "If the order of bit fields is dependant on system endianness, can I use a preprossecor directive to determine what order the struct's members are declared in?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T19:38:57.650",
"Id": "512365",
"Score": "0",
"body": "It's not dependent on _endianness_; that's only tangentially related. I don't believe there's a reliable compile-time test - see this [relevant Stack Overflow answer](//stackoverflow.com/a/19376742/4850040)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T20:38:56.093",
"Id": "512375",
"Score": "0",
"body": "I thought that [the bit field ordering was dependent on the endianness of the platform](https://stackoverflow.com/a/1490142/14797264), and it was limited to high-order to low-order or low-order to high-order"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T01:23:50.530",
"Id": "512387",
"Score": "0",
"body": "The 4 in `%#04hhx` in interesting. I'd expect 2."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T01:26:15.170",
"Id": "512388",
"Score": "1",
"body": "@QuestionLimitGoBrrrrr The bit field ordering is not specified to match the byte endianness."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T06:50:27.827",
"Id": "512401",
"Score": "0",
"body": "@chux, the `4` is to give space for two hex digits after the two leading characters produced by the `#`. Remember that the number is a _field width_, not a digit count (and yes, I do find it annoying to adjust them whenever I add or remove `#` from the conversion)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T07:01:12.363",
"Id": "512402",
"Score": "0",
"body": "I don't think that bit-fields are even required to be sequential - as I understand it, a compiler is permitted to arrange bit fields for best performance (not straddling word/byte boundaries for instance)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T07:40:07.400",
"Id": "512408",
"Score": "1",
"body": "4 then does make sense in `%#04hhx`. I find `0x%02X` to deemphasize the prefix as lower case, but upper case digits clearer to read output and ditch the pesky `#` with its 0 exemption. I expect `%#04hhx\\n\", 0` to print `0000`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T07:43:35.893",
"Id": "512410",
"Score": "0",
"body": "Ah, `.2` is much nicer - I'll be using that from now on. Thanks @chux! (and yes, we can quickly demonstrate in shell that `printf '%#04x\\n' 0` produces `0000` - ugh!)"
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T12:26:08.457",
"Id": "259721",
"ParentId": "259707",
"Score": "4"
}
},
{
"body": "<p><strong>I wanted to be able to have individual bit access in C without using a ton of functions to do bit manipulation on a <code>uint8_t</code></strong></p>\n<p>All things with bit-fields invite implementation defined behaviors. Even using <code>unsigned char</code> is implementation defined.</p>\n<blockquote>\n<p>A bit-field shall have a type that is a qualified or unqualified version of <code>_Bool</code>, <code>signed int</code>, <code>unsigned int</code>, or some other implementation-defined type. C17dr § 6.7.2.1 5</p>\n</blockquote>\n<hr />\n<p><strong>Tell me where I could improve upon it</strong></p>\n<p>It really is not that hard to form portable set/get bit functions.</p>\n<p>Only 2 functions are needed: <code>BitGet()</code> and <code>BitSet()</code></p>\n<p>Sample unchecked code below uses <code>unsigned</code> as <code>uint8_t</code> itself is <em>optional</em>. Narrow <code>uint8_t</code> is not really needed to make generic <code>set/get</code> as much code will promote to <code>unsigned/int</code> anyway.</p>\n<pre><code>#define UNSIGNED_BIT_WIDTH (CHAR_BIT * sizeof(unsigned))\n\nunsigned BitGet(unsigned x, unsigned index) {\n index %= UNSIGNED_BIT_WIDTH; // Likely just an 'and' operation\n return (x >> index) & 1;\n}\n\nvoid BitSet(unsigned x, unsigned index, bool value) {\n index %= UNSIGNED_BIT_WIDTH;\n if (value) {\n x |= 1u << index;\n } else {\n x &= ~(1u << index);\n }\n}\n</code></pre>\n<p>Other alternatives include macros, <code>inline</code>, etc.</p>\n<hr />\n<p><strong>without using a ton of functions</strong></p>\n<p>I estimate the weight of the above function, using <a href=\"https://www.quora.com/What-is-the-weight-of-one-bit-computers\" rel=\"nofollow noreferrer\">0.2 GB/g</a>, at about 6 pico-grams. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T03:59:49.817",
"Id": "512392",
"Score": "0",
"body": "5.9847 pico-grams..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T07:27:37.953",
"Id": "512406",
"Score": "0",
"body": "@DavidC.Rankin What's a few femto-grams between friends?"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T01:37:29.173",
"Id": "259744",
"ParentId": "259707",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T22:29:48.320",
"Id": "259707",
"Score": "0",
"Tags": [
"c",
"bitset"
],
"Title": "Individual bit access in C"
}
|
259707
|
<p>Main function will ask what the user wants to do. LoginSystem class will handle the sign up and login process as well with the checking if password is right. passwordHashing will use bcrpyt to salt and hash the password.</p>
<pre><code>import bcrypt
from loginDbMySQL import insert, logging_in
def main():
login_instance = LoginSystem()
check = True
while check == True:
value = input("1-Login, 2-Sign-up, 3-Exit\n")
if value == "1":
login_instance.login()
check = True
elif value == "2":
login_instance.sign_up()
check = True
elif value == "3":
check = False
class LoginSystem():
def sign_up(self):
username = input("Enter a username: ")
password = input("Enter a password: ")
password_hash = self.passwordHashing(password)
insert(username, password_hash)
def login(self):
username = input("Enter a username: ")
password = input("Enter a password: ")
password_hash = logging_in(username)
self.comparePassword(password, password_hash)
def passwordHashing(self, password):
password_bytes = password.encode('utf8')
salt = bcrypt.gensalt(14)
password_hash_byte = bcrypt.hashpw(password_bytes, salt)
password_hash_str = password_hash_byte.decode()
return password_hash_str
def comparePassword(self,password,password_hash):
if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):
print("Welcome")
else:
print("Incorrect Information")
if __name__ == "__main__":
main()
</code></pre>
<p>loginDbMySQL handles the database insertion, checking, and query's</p>
<pre><code>import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="*******",
database="*******"
)
mycursor = mydb.cursor()
def insert(username,password_hash):
mycursor = mydb.cursor(buffered=True)
select_query = "SELECT usernames FROM login_table WHERE usernames= %s"
mycursor.execute(select_query, (username,))
check = mycursor.fetchone()
if check == None:
mycursor.execute("INSERT INTO login_table (usernames, password_hashs) VALUES (%s,%s)", (username, password_hash))
mydb.commit()
print("Account created!")
else:
print("Account already exist.")
def logging_in(username):
mycursor = mydb.cursor(buffered=True)
select_query = "SELECT * FROM login_table WHERE usernames= %s"
mycursor.execute(select_query, (username,))
check = mycursor.fetchone()
if check == None:
print("Incorrect information.")
else:
return check[1]
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T01:44:56.483",
"Id": "512303",
"Score": "1",
"body": "I'm stuck on my phone so I can't write a new answer, but your mechanisms of using strings as queries for this is not injection-safe. You should create programmable functions in the SQL side and then using a `callproc` execute the functions which will escape any input passed into arguments of the function. Unfortunately, that requires more DB work on your side, separate from the Python. I can confirm this from my own tests of the same functions you've used (or similar) and then the string replacement and execute inserts the way you're doing them didn't work right."
}
] |
[
{
"body": "<p>Let's start with the SQL and your <code>loginDbMySQL</code> stuff first.</p>\n<h3>You should probably reconsider the naming of your SQL table columns.</h3>\n<p>Bare minimum reproducible example with a table that has automatic incrementation, a UID as the primary key, and the username field 'username' and 'passwd_hash'. <strong>You should name columns to be descriptive of the value per record, not as plurals unless you are storing multiple items for each field in the record.</strong></p>\n<p>So, let's make the table accordingly, and also have a unique constraint on usernames - you don't want duplicate usernames. The username also becomes the primary key since we want unique usernames:</p>\n<pre class=\"lang-sql prettyprint-override\"><code>create or replace table login_tests.login_table\n(\n uname varchar(50) not null,\n passwd_hash varchar(1000) not null\n);\n\nalter table login_tests.login_table\n add primary key (uname);\n</code></pre>\n<p>Note we're using <code>uname</code> as the primary key, so you can only have unique usernames. This is entirely permitted in SQL.</p>\n<h3>SQL query mechanisms being used are NOT SQL-Injection-Safe!</h3>\n<p>Next, let's look at one of the glaring problems in your code: <strong>your queries and routines are not injection-safe!</strong> I can easily pass a value in that can escape the 'argument' being called and simply cause chaos with SQL injections. The way around this is to build predetermined procedures in the DB and call that, and then pass the arguments in with <code>callproc</code> calls.</p>\n<p>To start with, you have three separate queries - one to determine if a user exists, one to insert a user, and then a similar select query for logging in. But, we can use the same <code>SELECT</code> for the same task! Saves us code!</p>\n<p>Also, you aren't really using SELECT functions for anything other than checking if a username exists on insert (fixed later), and getting hashed pw data for a given username.</p>\n<p>Firstly, on the MySQL side we need to create the functions.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>CREATE PROCEDURE GetPWHash(username varchar(50))\nBEGIN\n SELECT passwd_hash FROM login_table WHERE uname = username;\nEND;\n\nCREATE PROCEDURE GetUserData(username varchar(50))\nBEGIN\n SELECT * FROM login_table WHERE uname = username:\nEND;\n\nCREATE PROCEDURE AddUser(username varchar(50), pass_hash varchar(1000))\nBEGIN\n INSERT INTO login_table(uname, passwd_hash) VALUES (username, pass_hash);\n COMMIT;\nEND;\n</code></pre>\n<p>We'll then call the relevant procedures with a <code>cursor.callproc(ProcedureName, [argument])</code> call instead. It's <strong>not considered smart</strong> to build your queries in strings because it is typically extremely unlikely you will be able to properly escape the queries. The <code>callproc</code> function will automatically escape them before passing them to the function.</p>\n<p>You'll see me replace your functions accordingly as we go and edit each function and call. So let's begin with those.</p>\n<h3>INSERT function doesn't need a select to check if the user exists - DB insert will simply fail if a user exists because of primary key restrictions.</h3>\n<p>You're doing testing here with an extra DB call which requires more disk I/O for reading.</p>\n<p>So let's simply rewrite your insert function entirely. It's not really pythonic in its current state, and you make an unnecessary extra DB call.\nFurther, you should consider a DB cursor for each one, without global declarations. So I'll provide you some revisions.</p>\n<p>Let's start with your <code>insert</code> function:</p>\n<pre><code>def insert(username, password_hash):\n cursor = mydb.cursor(buffered=True)\n cursor.callproc('AddUser', [username, password_hash])\n cursor.close()\n</code></pre>\n<p>We should not access the 'username' ahead of time, we can simply catch the error (the <code>callproc</code> function throws a <code>mysql.connector.errors.IntegrityError</code> class error when we violate a constraint). No need to check if the user exists already, and as I included earlier I wrote a <code>COMMIT</code> into the <code>AddUser</code> function. No need to make the db commit as a result, it commits after it adds! (Actually confirmed this checking the DB after the <code>callproc</code>!)</p>\n<h3>Logging In Function: Use callproc!</h3>\n<p>Again, we should be using <code>callproc</code> and such so you eliminate an SQL Injection risk. Further, your 'logging in' function in loginDbMySQL is... not really 'logging in'. It's more fetching user data, so let's name it accordingly.</p>\n<pre><code>def logging_in(username):\n\n mycursor = mydb.cursor(buffered=True)\n mycursor.callproc('GetUserData', [username])\n select_query = "SELECT * FROM login_table WHERE usernames= %s"\n data = mycursor.fetchone()\n # INCOMPLETE FUNCTION\n</code></pre>\n<p>But because this is an incomplete function that does nothing, I essentially suggest removing it.</p>\n<p>And in its place put a useful function - <code>getUserPWHash</code> - which will call the SQL and only return the PW hash for the specified user (if it exists).</p>\n<pre><code>def getUserPWHash(username):\n mycursor = mydb.cursor(buffered=True)\n mycursor.callproc('GetPWHash', [username])\n data = mycursor.fetchone()\n return data\n</code></pre>\n<p>This will be useful later, as you will see when we dig into your other code.</p>\n<hr />\n<p>So, taking into account the SQL bits, we have a bunch of code tweaks on the flip side in your <code>login.py</code> script.</p>\n<p>Let's start with your <code>LogInSystem</code> class.</p>\n<h3>Code Duplication - can be reduced by adding a static method for prompting for credentials</h3>\n<p>You have two cases where you would benefit from a separate function from which you can request credentials. Registration, and logging in. Let's start by adding a new method to your class for this - called <code>promptForCreds</code>. This is going to have a special decorator - <code>@staticmethod</code> - this tells the system that this function is able to stand on its own and does NOT require a dependency on the object itself (<code>self</code>) in the declaration of the method:</p>\n<pre><code>@staticmethod\ndef promptForCreds():\n username = input("Enter a username: ")\n password = input("Enter a password: ")\n\n return username, password\n</code></pre>\n<p>This will eventually be used here in your sign up and login functions. We'll apply this in a later revision suggestion.</p>\n<h3>Reduce the need of multiple variables - like in the SQL sections.</h3>\n<p>So you end up having a bunch of one-time-use variables in <code>passwordHashing</code>, like you did in the SQL bits.</p>\n<p>We can simply replace the use of variables to hold values by directly putting the variables in line. If we name the items accordingly, we don't need additional variables to hold them, since it's clear what the objects are (they're already arguments passed into functions!)</p>\n<p>Oh, and the <code>passwordHashing</code> method can also be a <code>@staticmethod</code> object too - it doesn't depend on any other components within your class specifically.</p>\n<pre><code>@staticmethod\ndef passwordHashing(password):\n return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')\n</code></pre>\n<p>This looks long but it can be broken across multiple lines if you keep the parentheses around the <code>bcrypt.hashpw</code> call. But, this reduces those one-use variables AND puts everything into a simple return call - and only one of them. No extra variables!</p>\n<h3>Another static method - <code>comparePassword</code></h3>\n<p>This one's a minor change and pretty simple - just add a decorator ahead of <code>comparePassword</code>.</p>\n<pre><code>@staticmethod\ndef comparePassword(password, password_hash):\n if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):\n print("Welcome")\n else:\n print("Incorrect Information")\n</code></pre>\n<h3>Remove code duplication in <code>sign_up</code> and <code>login</code>.</h3>\n<p>And now here's why I created that new method - we get to take four lines of code and condense it into two. This code is duplicated, yes, but we don't have to run the prompt twice individually.</p>\n<pre><code>def sign_up(self):\n username, password = self.promptForCreds()\n insert(username, self.passwordHashing(password))\n\ndef login(self):\n username, password = self.promptForCreds()\n password_hash = getUserPWHash(username)\n self.comparePassword(password, password_hash)\n</code></pre>\n<p>See what I did here? Username and password are obtained by the other function and then returned. Saves us from having to create the prompt twice! See what niceness I did there?</p>\n<p>So your <code>LoginSystem</code> class becomes this:</p>\n<pre><code>class LoginSystem:\n @staticmethod\n def promptForCreds():\n username = input("Enter a username: ")\n password = input("Enter a password: ")\n return username, password\n\n @staticmethod\n def passwordHashing(password):\n return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')\n\n @staticmethod\n def comparePassword(password, password_hash):\n if bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8')):\n print("Welcome")\n else:\n print("Incorrect Information")\n\n def sign_up(self):\n username, password = self.promptForCreds\n insert(username, self.passwordHashing(password))\n\n def login(self):\n username, password = self.promptForCreds\n password_hash = getUserPWHash(username)\n self.comparePassword(password, password_hash)\n</code></pre>\n<hr />\n<p>Now, let's look at your <code>main()</code> function.</p>\n<h3>Non-pythonic way of iterating over the checks!</h3>\n<p>You're doing something I wouldn't do here, which is using <code>while var == True</code>. Pythonically, you can reduce this to this: just do <code>while var:</code> for iterating while a variable is True. However, I suggest you do something else, which (once again) reduces the memory usage by not needing to define a variable.</p>\n<pre><code>def main():\n login_instance = LoginSystem()\n\n while True:\n value = input("1-Login, 2-Sign-up, 3-Exit\\n")\n if value == "1":\n login_instance.login()\n elif value == "2":\n login_instance.sign_up()\n elif value == "3":\n pass # Do nothing, we'll just exit as normal.\n else:\n continue # Continue prompting until we get a valid value.\n\n break\n</code></pre>\n<p>This reduces the complexity and need to assign True or False. Just iterate infinitely and break on any value that is valid (1, 2, or 3), or keep going and prompting more until we get only one valid value.</p>\n<h3>You really should be triggering errors or returning Bools for your login functionality though.</h3>\n<p>The only problem with your approach is you have no way to catch whether a login was successful or not (or the same case with a registration).</p>\n<p>You can approach this in one of two ways - either return errors on failures, or make your functions return a boolean instead of just printing statements.</p>\n<p>I suggest you rename your <code>comparePassword</code> function to <code>validateCredentials</code> and then adjust it to return a True or False - <code>True</code> for valid credentials, <code>False</code> for invalid. Or, just return the result of <code>bcrypt.checkpw</code>:</p>\n<pre><code>@staticmethod\ndef validateCredentials(password, password_hash):\n return bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8'))\n</code></pre>\n<p>Now, we'll use this for <code>login</code> functionality:</p>\n<pre><code>def login(self):\n username, password = self.promptForCreds\n password_hash = getUserPWHash(username)\n if self.validateCredentials(password, password_hash):\n print("Welcome!")\n else:\n print("Invalid Login")\n</code></pre>\n<p>Note that simply printing output is simple - you really should consider making <em>this</em> return a <code>bool</code> as well. This way you can utilize the results.</p>\n<p>So that would look like this:</p>\n<pre><code>def login(self):\n username, password = self.promptForCreds\n password_hash = getUserPWHash(username)\n return self.validateCredentials(password, password_hash)\n</code></pre>\n<p>This would then mean we have to revise later for when <code>value</code> is 1:</p>\n<pre><code># ...\n if value == "1":\n if login_instance.login():\n print("Welcome!")\n else:\n print("Access denied")\n</code></pre>\n<p>Now, we have a similar case with <code>insert</code> but we're going to use error codes instead.</p>\n<p>Back in <code>loginDbMySQL</code> way earlier in this review, I basically removed print statements and error checking from your <code>insert</code> function. This was intentional, because we'll handle insert via error code data/returns.</p>\n<p>So, in the conditional for when <code>value</code> is 2:</p>\n<pre><code> elif value == "2":\n try:\n login_instance.sign_up()\n print("Sign up complete.")\n except mysql.connector.errors.IntegrityError:\n print("Unable to register account.")\n</code></pre>\n<p>This ultimately makes it a more usable login system function. It requires a single import added though - <code>mysql.connector.errors</code>. This is so we can import the error class for the exception handler.</p>\n<hr />\n<hr />\n<h3>The code with all my revisions:</h3>\n<p><strong>login.py:</strong></p>\n<pre><code>import bcrypt\nimport mysql.connector.errors\nfrom loginDbMySQL import insert, getUserPWHash\n\n\nclass LoginSystem:\n @staticmethod\n def promptForCreds():\n username = input("Enter a username: ")\n password = input("Enter a password: ")\n return username, password\n\n @staticmethod\n def passwordHashing(password):\n return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt(14)).decode('utf-8')\n\n @staticmethod\n def validateCredentials(password, password_hash):\n return bcrypt.checkpw(password.encode('utf8'), password_hash.encode('utf8'))\n\n def sign_up(self):\n username, password = self.promptForCreds\n insert(username, self.passwordHashing(password))\n\n def login(self):\n username, password = self.promptForCreds\n password_hash = getUserPWHash(username)\n return self.validateCredentials(password, password_hash)\n\n\ndef main():\n login_instance = LoginSystem()\n\n while True:\n value = input("1-Login, 2-Sign-up, 3-Exit\\n")\n if value == "1":\n if login_instance.login():\n print("Welcome!")\n else:\n print("Access denied")\n elif value == "2":\n try:\n login_instance.sign_up()\n print("Sign up complete.")\n except mysql.connector.errors.IntegrityError:\n print("Unable to register - username already taken.")\n elif value == "3":\n pass # exit\n else:\n continue\n\n break\n\n\nif __name__ == "__main__":\n main()\n</code></pre>\n<p><strong>loginDbMySQL.py:</strong></p>\n<pre><code>import mysql.connector\n\n\nmydb = mysql.connector.connect(\n host="localhost",\n user="root",\n password="*******",\n database="*******"\n)\n\n\ndef insert(username, password_hash):\n mycursor = mydb.cursor(buffered=True)\n mycursor.execute("AddUser", [username, password_hash])\n mycursor.close()\n print("Account created!")\n\n\ndef getUserPWHash(username):\n mycursor = mydb.cursor(buffered=True)\n mycursor.callproc('GetPWHash', [username])\n data = mycursor.fetchone()\n return data\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T19:32:56.397",
"Id": "512984",
"Score": "0",
"body": "@MaartenBodewes you try debugging an completely exploding Exchange server and code review. I have a large update coming today since I now have cycles to look at this more :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-12T02:55:52.690",
"Id": "514440",
"Score": "0",
"body": "Hello, I've been busy with final exam and finally got a chance to really look at the code you showed to me. Thank you for the help and will be definitely incorporating these tip and code in future programs. One problem, do you know why getUserPWHash is returning None?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-12T13:40:40.977",
"Id": "514467",
"Score": "0",
"body": "@drakebakincake it will return None if there're no results. Which means that whatever username you've passed in is not matching in the DB and returning no data. It's a case sensitive search in the DB as written (which is how you had it originally)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-12T19:13:57.113",
"Id": "514489",
"Score": "0",
"body": "The username is the same as the uname in the table, maybe the username is changes as it pass through to the procedure in mysql?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-12T21:49:32.387",
"Id": "514499",
"Score": "0",
"body": "@drakebakincake possibly, but it's a case sensitive search. It's possible though there's extra characters from your Input that need to be stripped, but that'll require more thorough debugging. At the moment I'm neck deep in some other tasks."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T21:02:32.077",
"Id": "259776",
"ParentId": "259710",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259776",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-18T23:41:00.363",
"Id": "259710",
"Score": "3",
"Tags": [
"python",
"mysql",
"hash"
],
"Title": "Login system using bcrypt and MySQL, to be used for any future projects"
}
|
259710
|
<p>I'm new to C#, and want to conform as much as possible to good design patterns. This code is the beginning of a Microservice, running as Asp.Net. It is based on a Microsoft tutorial doing similar work.</p>
<p>It has three functional components currently:</p>
<ol>
<li>Converts a CSV file to JSON, for return via REST</li>
<li>A REST controller to test the conversion of the CSV to JSON return</li>
<li>A background service which monitors a directory looking for changed files. The file attributes (Path, Date, Checksum) are stored in a MongoDB database via a Repository.</li>
</ol>
<p><strong>Opinions/Recommendations regarding the design patterns welcomed.</strong></p>
<p>The full code can be found at: <a href="https://github.com/BioComSoftware/unite-radimaging-source-n2m2.git" rel="nofollow noreferrer">https://github.com/BioComSoftware/unite-radimaging-source-n2m2.git</a></p>
<p><em><strong>BONUS:</strong></em> Notice in <code>FileSearchHostedService.cs</code>, I instantiate the Repository objects explicitly. I think it would be more appropriate to have them as Dependency Injection - but I couldn't get it to work. Notice the commented-out lines that would have done this. My understanding is; I would need to do this with <code>IScopedProcessingService</code> - but I have no idea how to do this with this specific code.</p>
<p><a href="https://i.stack.imgur.com/MCItv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MCItv.png" alt="Structure" /></a></p>
<p><em><strong>[Startup.cs]</strong></em></p>
<pre><code>using unite.radimaging.source.n2m2.Data;
using unite.radimaging.source.n2m2.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
//using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace unite.radimaging.source.n2m2 {
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime.
// Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
services.AddControllers();
services.AddScoped<IFoundFileContext, FoundFileContext>();
services.AddScoped<IFoundFileRepository, FoundFileRepository>();
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseExceptionHandler("/error");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
}
}
</code></pre>
<p><em><strong>[FoundFileRepository.cs]</strong></em></p>
<pre><code>using unite.radimaging.source.n2m2.Data;
using unite.radimaging.source.n2m2.Entities;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace unite.radimaging.source.n2m2.Repositories {
public class FoundFileRepository : IFoundFileRepository {
private readonly IFoundFileContext _context;
public FoundFileRepository(IFoundFileContext context) {
_context = context ?? throw new ArgumentNullException(nameof(context));
}
public async Task<IEnumerable<FoundFile>> GetFiles() {
return await _context
.FoundFiles
.Find(p => true)
.ToListAsync();
}
public async Task<FoundFile> GetFile(string id) {
return await _context
.FoundFiles
.Find(p => p.Id == id)
.FirstOrDefaultAsync();
}
public async Task<FoundFile> GetFileByPath(string path) {
return await _context
.FoundFiles
.Find(p => p.Path == path)
.FirstOrDefaultAsync();
}
public async Task<FoundFile> GetFileByChecksum(string checksum) {
return await _context
.FoundFiles
.Find(p => p.Checksum == checksum)
.FirstOrDefaultAsync();
}
//public async Task<IEnumerable<FoundFile>> GetFileByMtime(string mtime) {
// FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.ElemMatch<DateTime>(p => p.Mtime, mtime);
// return await _context
// .FoundFiles
// .Find(filter)
// .ToListAsync();
//}
//public async Task<IEnumerable<FoundFile>> GetFileBySize(long size) {
// FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.ElemMatch<long>(p => p.Size, size);
// return await _context
// .FoundFiles
// .Find(filter)
// .ToListAsync();
//}
public async Task CreateFile(FoundFile foundFile) {
await _context.FoundFiles.InsertOneAsync(foundFile);
}
public async Task<bool> UpdateFile(FoundFile foundFile) {
var updateResult = await _context.FoundFiles.ReplaceOneAsync(
filter: g => g.Path == foundFile.Path, replacement: foundFile);
return updateResult.IsAcknowledged && updateResult.ModifiedCount > 0;
}
public async Task<bool> DeleteFile(string path) {
FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.Eq(p => p.Path, path);
DeleteResult deleteResult = await _context
.FoundFiles
.DeleteOneAsync(filter);
return deleteResult.IsAcknowledged
&& deleteResult.DeletedCount > 0;
}
}
}
</code></pre>
<p><em><strong>[FileSearchHostedService.cs]</strong></em></p>
<pre><code>using unite.radimaging.source.n2m2.Repositories;
using unite.radimaging.source.n2m2.Entities;
using unite.radimaging.source.n2m2.Data;
using Serilog;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
namespace unite.radimaging.source.n2m2.HostedServices.FileSearchHostedService {
public class FileSearchHostedService : BackgroundService {
private readonly IConfiguration _configuration;
//private IFoundFileRepository _repository;
public FileSearchHostedService(
//IFoundFileRepository repository,
IConfiguration configuration
) {
//_repository = repository ?? throw new ArgumentNullException(nameof(repository));
_configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
}
protected override async Task ExecuteAsync(CancellationToken cancellationToken) {
Log.Information("FileSearchHostedService: File searching started.");
cancellationToken.Register(() => Log.Information("Processing service stopped"));
//string checksum;
string _msg;
string _current_path;
FileInfo _current_fileinfo;
FoundFile _foundFile;
FoundFile _existingFile;
// Convert these two lines to Dependency Injections if possible
FoundFileContext FoundfileContext = new FoundFileContext(_configuration); // Normal instantiation, in leiu of injection
FoundFileRepository _repository = new FoundFileRepository(FoundfileContext); // Normal instantiation, in leiu of injection
string dir = _configuration.GetValue<string>("FileSearchSettings:SearchDir");
while (!cancellationToken.IsCancellationRequested) {
string[] files = Directory.GetFiles(dir);
foreach (string filename in files) {
_msg = $"'{filename}' ";
_current_fileinfo = new FileInfo(filename);
_current_path = Path.GetFullPath(Path.Combine(_current_fileinfo.Directory.ToString(), _current_fileinfo.Name));
_existingFile = await _repository.GetFileByPath (_current_path);
_foundFile = new FoundFile() {
Path = _current_path,
Size = _current_fileinfo.Length,
Mtime = _current_fileinfo.LastWriteTime,
Checksum = FileChecksum.getChecksum(filename)
};
if (_existingFile == null) {
_msg += $"does not exist in MongoDB. Creating new entry ";
// Creating a new entry in MongoDB should prolly be it's own class
// but until I figure out dependency injection for the repo, it creates more
// processing than its worth
try {
await _repository.CreateFile(_foundFile);
_msg += "(OK)";
}
catch (Exception e) {
_msg += $"(FAILED with '{e.Message}'";
}
}
else if (_foundFile.Equals(_existingFile)) {
_msg += "is already in the database. No further processing needed.";
}
else {
_msg += $"has changed since being added to MongoDB. Updating entry ";
try {
var _result = await _repository.UpdateFile(_foundFile);
if (!_result == true) {
throw new ApplicationException("FoundFileRepository.UpdateFile did not return 'true'. Unknown MongoDB error updating the document.");
}
_msg += "(OK)";
}
catch (Exception e) {
_msg += $"(FAILED with '{e.Message}')";
}
};
Log.Debug(_msg);
}
await Task.Delay(_configuration.GetValue<int>("FileSearchSettings:Delay"),cancellationToken);
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T12:13:19.080",
"Id": "512322",
"Score": "0",
"body": "Welcome to CodeReview! From what aspect(s) are you looking for a review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T12:20:41.900",
"Id": "512323",
"Score": "0",
"body": "@PeterCsala Thanks. Since I'm new to C#, there's three things I'd like a review on. 1) The general class structure/layout (see the image of VS's Solution Explorer.) 2) Whether my classes need to be more subdivided (See `FileSearchHostedService.cs`... It will be searching, checking, and creating new MongoDB entries. It does a lot) and 3) How/If I can instantiate the `FoundFileRepository` as a Dependency Injection instead of a explicit new(). Thanks again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T13:55:03.213",
"Id": "512325",
"Score": "3",
"body": "Welcome to the Code Review Community. We may not be able to help with `3) How/If`since we only review working code and can't write new code. Other than that, excellent question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T07:41:03.477",
"Id": "512409",
"Score": "1",
"body": "Not gonna do a review, but: 1) no not use underscores at the start of local variables. 2) use PascalCase/camelCase where necessary and don't use underscores to separate parts of a compound word. 3) Fix typos (\"leiu\"). 4) The `_msg += ` thing is deeply annoying. Just do a `Log.Debug` each time, that way your code is clearer. 4) Decrease your nesting: at several points you have a `try` inside an `if` (or `else`) inside a `foreach` inside a `while`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T09:58:03.993",
"Id": "512431",
"Score": "0",
"body": "@BCdotWEB Does Visual Studio have a spellchecker like eclipse?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T10:06:33.100",
"Id": "512432",
"Score": "1",
"body": "@RightmireM https://www.google.com/search?q=visual+studio+spell+checker"
}
] |
[
{
"body": "<p>In this post let me focus on the project structure.</p>\n<h3>Project vs Projects</h3>\n<p>Most of the time when we implement a n-tier application we separate each tier into its own project. We also separate implementation and abstraction. Some like this:</p>\n<ul>\n<li><code>{Project}.Presentation</code></li>\n<li><code>{Project}.Service.Abstractions</code></li>\n<li><code>{Project}.Service</code></li>\n<li><code>{Project}.Repository.Abstractions</code></li>\n<li><code>{Project}.Repository</code></li>\n</ul>\n<p>Each tier has its own responsibility and scope. For example the <code>Presentation</code> (or sometimes called <code>Web</code>) tier will handle the incoming requests (via <code>Middleware</code>s and <code>Controller</code>s) by</p>\n<ul>\n<li>performing preliminary checks (like: is xyz present, is xyz an int, etc.)</li>\n<li>calling the business layer (service tier)</li>\n<li>transforming the result (to align to the presentation framework)</li>\n</ul>\n<p>In a simple project like this the above showed separation might be an overkill, but as your application scope grows you might need to perform this kind of restructuring.</p>\n<p>I also want to mention that for more complex Microservices n-tier architecture might not be the best choice. <a href=\"https://www.sam-solutions.com/blog/building-microservice-with-onion-architecture\" rel=\"nofollow noreferrer\">Onion</a> or <a href=\"https://netflixtechblog.com/ready-for-changes-with-hexagonal-architecture-b315ec967749\" rel=\"nofollow noreferrer\">Hexagonal</a> architecture might be a better fit.</p>\n<h3>Controller</h3>\n<ul>\n<li><code>DefaultController</code>: Try to name your controllers based on the resources on which they are performing some kind of operations. In case of REST APIs the primary building blocks are the <strong>resources</strong>. So, organizing your code around them is the suggested way.</li>\n<li><code>ErrorController</code>: Without knowing the implementation it is kinda hard to make any suggestions. But nowadays we usually handle application errors via a custom <a href=\"https://docs.microsoft.com/en-us/aspnet/core/fundamentals/error-handling?view=aspnetcore-5.0#exception-handler-lambda\" rel=\"nofollow noreferrer\">error handler middleware</a> in WebApis.</li>\n<li><code>TestCSVController</code>: It is really weird to use verbs inside the controller names. Resources are usually nouns.</li>\n</ul>\n<p>I also want to mention that there is an assessment process to evaluate the maturity of your REST API. It called <a href=\"https://restfulapi.net/richardson-maturity-model/\" rel=\"nofollow noreferrer\">Ricardson's maturity model</a> (<a href=\"https://blog.restcase.com/4-maturity-levels-of-rest-api-design/\" rel=\"nofollow noreferrer\">1</a>).</p>\n<h3>CSVParsers</h3>\n<p>I can see two implementation classes here and no abstraction. Based on the image it is impossible to tell how they relate to each other. Do they provide the same API (then define an <code>ICSVParser</code>)? Are they in a parent-child relationship? ...</p>\n<h3>Data</h3>\n<p>Personally I don't like the following naming conventions: <code>XYZManager</code>, <code>Utils</code>, <code>Data</code>, <code>Helpers</code>, etc. They simply do not provide any value. Based on these names you still don't know anything.</p>\n<p>Naming is hard. So, I'm not saying that Data is bad rather I would like to suggest to evaluate your naming whenever you add/remove/alter some file in this directory.</p>\n<p>Nowadays refactoring tools make the renaming quite painless.</p>\n<h3>Entities</h3>\n<p>In your <code>Data</code> folder you have <code>Context</code> class definitions. In your <code>Entities</code> folder you have (most probably) POCO definitions to hold <em>data</em>. As you can see the naming is kinda weird from this aspect.</p>\n<p><code>Databases</code> and <code>DataModels</code> might be better names in my opinion.</p>\n<h3>Repositories</h3>\n<p>Without the concrete implementation it is hard to tell but based on the naming the <code>FileChecksum</code> is not a repository. I do think it should not belong here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T09:56:55.073",
"Id": "512430",
"Score": "0",
"body": "Thanks for the detailed response. I'm making some changes based on your suggestions. I'm interested in input on other parts of the code (not really related to this answer.) Is it more appropriate to update this question and code, or should I accept an answer and repost a new question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T10:07:54.163",
"Id": "512434",
"Score": "1",
"body": "@RightmireM Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T12:44:54.897",
"Id": "512443",
"Score": "1",
"body": "@RightmireM Before any review is posted you can amend your code in your question. But after that you should not. If you have further questions or want to receive further reviews for the revised code then you advised to create a new question and refer to the original one."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T08:55:19.610",
"Id": "259751",
"ParentId": "259715",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259751",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T08:55:25.890",
"Id": "259715",
"Score": "2",
"Tags": [
"c#",
"design-patterns",
"asp.net",
"dependency-injection"
],
"Title": "Asp.Net overall design pattern integrating REST, dependency injection, and Hosted Services (See full project at Github)"
}
|
259715
|
<p>I recently needed to create a function to approximate a complex trigonometric function on an embedded system without a floating point unit and without a fast trigonometric library. So I pulled out my ancient copy of "Numerical Recipes in C, Second Edition" by Press, Teukolsky, Vetterling and Flannery, and updated the <a href="https://en.wikipedia.org/wiki/Chebyshev_polynomials" rel="noreferrer">Chebyshev polynomial</a> approximation functions to use modern C++.</p>
<p>For an approximation of order <span class="math-container">\$N\$</span> within the range <span class="math-container">\$[-1,1]\$</span>, the code calculates the Chebyshev approximation coefficients of the passed function <span class="math-container">\$f\$</span> as:
<span class="math-container">$$ c_j = \frac{2}{N}\sum_{k=1}^{N} f\left[ \cos\left(\frac{\pi(k - \frac{1}{2})}{N}\right)\right] \cos\left(\frac{\pi j (k - \frac{1}{2})}{N}\right) $$</span></p>
<p>To make the code more general, we map any arbitrary input range <span class="math-container">\$[a, b]\$</span> to <span class="math-container">\$[-1, 1]\$</span> using
<span class="math-container">$$ x' = \frac{x - \frac{1}{2}(b + a)}{\frac{1}{2}(b - a)} $$</span></p>
<p>This code then uses <a href="https://en.wikipedia.org/wiki/Clenshaw_algorithm" rel="noreferrer">Clenshaw's algorithm</a> to evaluate the approximation.</p>
<p>The <code>demo</code> function takes a function to be approximated, low and high limits and the order of the approximation as inputs and calculates the coefficients and prints 100 values and the error value of the approximation at each of those points, and the maximum of the absolute error. It then exercises the checked evaluation of the approximation (which does range checking) to provoke a thrown <code>std::range_error</code>. The checked evaluation uses an unchecked evaluation to actually perform the Clenshaw algorithm and evaluate the approximation.</p>
<p>A plot of the error values for a 7th order approximation of the cosine function in the range <span class="math-container">\$[0, \frac{\pi}{2}]\$</span> is shown below. It has the characteristic undulating error value of a Chebyshev approximation.
<a href="https://i.stack.imgur.com/EpaWZ.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/EpaWZ.gif" alt="error plot of 7th order Chebyshev approximation of cosine function" /></a></p>
<pre class="lang-cpp prettyprint-override"><code>#include <cmath>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <limits>
#include <numbers>
#include <stdexcept>
#include <vector>
template <typename T>
class ChebApprox {
public:
// given a function implementation, create a Chebyshev polynomial approximation
ChebApprox(T lowerbound, T upperbound, unsigned n, T (*func)(T));
// range-check evaluation of Chebyshev approximation
T operator()(T x) const;
// unchecked evaluation of Chebyshev approximation
T chebeval(T x) const;
// returns beginning iterator of coefficients list
auto begin() const { return coefficients.cbegin(); }
// returns ending iterator of coefficients list
auto end() const { return coefficients.cend(); }
private:
T lowerbound;
T upperbound;
std::vector<T> coefficients;
};
template <typename T>
ChebApprox<T>::ChebApprox(T lowerbound, T upperbound, unsigned n, T (*func)(T))
: lowerbound{lowerbound}
, upperbound{upperbound}
{
const auto bma{(upperbound - lowerbound)/2};
const auto bpa{(upperbound + lowerbound)/2};
std::vector<T> f;
f.reserve(n);
coefficients.reserve(n);
for (unsigned k = 0; k < n; ++k) {
T y{std::cos(std::numbers::pi * (k + 0.5) / n)};
f.push_back((*func)(y * bma + bpa));
}
const T fac = 2.0/n;
for (unsigned j=0; j < n; ++j) {
T sum{0};
for (unsigned k=0; k < n; ++k) {
sum += f[k] * std::cos(std::numbers::pi * j * (k+0.5) / n);
}
coefficients.push_back(fac*sum);
}
}
template <typename T>
T ChebApprox<T>::operator()(T x) const {
if (x < lowerbound || x > upperbound) {
throw std::range_error("Approximation function input out of allowed range");
}
return chebeval(x);
}
template <typename T>
T ChebApprox<T>::chebeval(T x) const {
T y{(2 * x - lowerbound - upperbound) / (upperbound - lowerbound)};
T y2{2 * y};
T d{0};
T dd{0};
for (auto j{coefficients.size()-1}; j; --j) {
auto sv{d};
d = y2 * d - dd + coefficients[j];
dd = sv;
}
return y * d - dd + coefficients[0] / 2;
}
void demo(double (*func)(double), double lo, double hi, unsigned n)
{
ChebApprox<double> ch{lo, hi, n, func};
std::cout << "Coefficients:\n" << std::setprecision(std::numeric_limits<double>::digits10 + 1);
std::copy(ch.begin(), ch.end(), std::ostream_iterator<double>(std::cout, ", "));
std::cout << "\nEvaluation\n";
auto delta{(hi-lo)/100};
double maxerror{0};
for (auto x{lo}; x < hi; x += delta) {
auto calc{ch(x)};
auto error{calc - func(x)};
if (std::fabs(error) > std::fabs(maxerror)) { maxerror = error; }
std::cout << x << '\t' << calc << '\t' << error << '\n';
}
std::cout << "Maximum absolute error was " << maxerror << '\n';
try {
auto bad{ch(hi + 1)}; // outside defined range
} catch (std::range_error &err) {
std::cout << err.what() << '\n';
}
}
int main() {
demo(std::cos, 0, std::numbers::pi/2, 7);
demo(std::sqrt, 0, 100, 5);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T15:14:12.090",
"Id": "512336",
"Score": "0",
"body": "What were the memory restrictions like?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T15:24:06.657",
"Id": "512337",
"Score": "5",
"body": "Memory restrictions were fairly tight. The target processor was a Renesas μPD78P078Y with 60K total PROM and 1K RAM. Computations on the target were actually performed using 48-bit fixed-point."
}
] |
[
{
"body": "<h1>Naming things</h1>\n<p>You have a bounds checking evaluation function, <code>operator()</code>, and one that doesn't do bounds checking named <code>chebeval()</code>. If the idea is to have this mimic an STL containers <code>operator[]</code> vs. <code>at()</code>, then perhaps make it more like that: have <code>operator()</code> do the unchecked evaluation, and have a member function named <code>at()</code> that does the bounds checks. Alternatively, keep the safe <code>operator()</code> as it is, but perhaps rename <code>chebeval()</code> to something else that makes it clear that this is not doing bounds checks (<code>eval_unchecked()</code>?).</p>\n<p>You use a lot of one-letter variables, making the code hard to read. Consider making them more descriptive. Alternatively, add a comment with a link to a page/paper with the formulas and algorithms you are using, and stay as close to the notation as used in that page/paper as possible.</p>\n<h1>Consider replacing <code>begin()</code>/<code>end()</code> with <code>coefficients()</code></h1>\n<p>What is the begin and end of a Chebyshev approximation? Not everyone would assume that <code>begin()</code> and <code>end()</code> would give you access to the coefficients. So I would make it more explicit, and just have a member function returning a <code>const</code> reference:</p>\n<pre><code> auto &coefficients() const { return m_coefficients; }\nprivate:\n std::vector<T> m_coefficients;\n</code></pre>\n<p>And then you can use the ranges library to write for example:</p>\n<pre><code>std::ranges::copy(ch.coefficients(), std::ostream_iterator<double>(std::cout, ", "));\n</code></pre>\n<h1>Consider replacing <code>std::vector</code> with a <code>std::array</code></h1>\n<p>You know the number of coefficients up front at construction time, and it will never change. And since <code>class ChebApprox</code> is already a <code>template</code>, you can just add a template parameter for the number of coefficients instead, and then use <code>std::array<T, n> coefficients</code> for a small performance improvement.</p>\n<h1>Allow function objects</h1>\n<p>You are using a raw function pointer for <code>func</code>, but this precludes you from passing function objects and lambdas to the constructor. In particular, you cannot create a new <code>ChebApprox</code> using a previously created <code>ChebApprox</code> as the input function. One way to do this is to use <a href=\"https://en.cppreference.com/w/cpp/utility/functional/function\" rel=\"nofollow noreferrer\"><code>std::function</code></a>, like so:</p>\n<pre><code>template <typename T>\nclass ChebApprox {\npublic:\n ChebApprox(T lowerbound, T upperbound, unsigned n, std::function<T(T)> func);\n</code></pre>\n<p>However, as pointed out by Ray Hamel, <code>std::function</code> <a href=\"https://stackoverflow.com/questions/13307090/do-stdfunction-and-stdbind-do-dynamic-memory-allocation\">might allocate memory</a>, although a decent implementation will not do so if it only needs to store a raw function pointer. But we can avoid this issue by not using <code>std::function</code>, but instead adding a template parameter for the function type:</p>\n<pre><code>template <typename T, typename Func>\nclass ChebApprox {\n using \npublic:\n ChebApprox(T lowerbound, T upperbound, unsigned n, Func &&func);\n</code></pre>\n<p>The drawback of the latter method is that <code>Func</code> is now no longer constrained, and passing it an overloaded function such as <code>std::sqrt</code> will be problematic, and would require you to explicitly cast it to something unambiguous first.</p>\n<h1>Consider using <code>std::midpoint()</code></h1>\n<p>When calculating <code>bma</code> and <code>bpa</code>, use <a href=\"https://en.cppreference.com/w/cpp/numeric/midpoint\" rel=\"nofollow noreferrer\"><code>std::midpoint()</code></a>. While unlikely to give problems, it is nonetheless safer to use than what you wrote, especially if the bounds are close to being denormal or infinity.</p>\n<p>It might also be possible to use <a href=\"https://en.cppreference.com/w/cpp/numeric/lerp\" rel=\"nofollow noreferrer\"><code>std::lerp()</code></a> instead:</p>\n<pre><code>for (unsigned k = 0; k < n; ++k) {\n T y{1 + 0.5 * std::cos(std::numbers::pi * (k + 0.5) / n)};\n f.push_back(func(std::lerp(lowerbound, upperbound, y));\n}\n</code></pre>\n<h1>Avoid an expensive division in <code>chebeval()</code></h1>\n<p>Divisions are one of the most expensive CPU instructions. If you have a small number of coefficients, the calculation of <code>y</code> might take a significant fraction of the CPU time in <code>chebeval()</code>. Instead of storing <code>lowerbound</code> and <code>upperbound</code> as member variables, consider storing <code>lowerbound + upperbound</code> and <code>1 / (upperbound - lowerbound)</code> instead, so the calculation of <code>y</code> gets sped up.</p>\n<p>The range check can be done by first calculating <code>y</code>, then checking if it is in the range <span class=\"math-container\">\\$-1\\dots 1\\$</span>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:49:51.990",
"Id": "512344",
"Score": "0",
"body": "Regarding `chebeval` - it's not intended to be used outside the range; it just doesn't check for that. It is to `operator()` as `std::vector::operator[]()` is to `std::vector::at()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:50:33.100",
"Id": "512345",
"Score": "0",
"body": "Ah, shouldn't it be made `private` then?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:51:33.847",
"Id": "512346",
"Score": "0",
"body": "I considered that, but followed the same rationale that leads to `std::vector::operator[]()` being unchecked but also `public`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T04:27:38.797",
"Id": "512397",
"Score": "0",
"body": "Using single-letter variables is absolutely standard in mathematics. It makes no sense to change them to something that purports to be \"more meaningful\" in computer code. For a standard well known algorithm like this, there is no point including a reference, but a comment identifying it as \"Clenshaw's algorithm\" would be useful."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T06:27:08.610",
"Id": "512400",
"Score": "1",
"body": "@alephzero It is indeed absolutely standard in mathematics, but if you've ever read a paper, you know that they contain an explanation for every variable name used in a formula. It is missing in this code. And while you and I might know how to find a description of Clenshaw's algorithm, not everyone does, and adding a proper reference doesn't cost you anything but might greatly help someone else."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T14:00:05.670",
"Id": "512450",
"Score": "1",
"body": "I disagree with your suggestion to use `std::function` in place of function pointers. In particular, it seems incongruous with your suggestion to replace `std::vector` with a `std::array` (`std::function` performs a dynamic allocation). Instead I would make a second template parameter `F` and replace the parameter `T (*func)(T)` with `F &&func` and the line `f.push_back(func(y*bma + bpa))` with `f.push_back(std::invoke(func, y*bma + bpa))`. This allows any appropriate invocable object to be passed to the function without any overhead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T14:31:52.453",
"Id": "512453",
"Score": "1",
"body": "And, speaking of, I also disagree with replacing `std::vector` with a `std::array`. What about the cases where `n` is not known at compile-time, or is large enough that the `coefficients` array would overflow the stack? If avoiding an unnecessary dynamic allocation is important, then in C++20 perhaps `coefficients` could be a `std::span<T>` with the function that constructs `ChebApprox` passing it as a parameter and owning the associated memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T15:07:48.350",
"Id": "512454",
"Score": "0",
"body": "@RayHamel I wouldn't worry about `std::function` here because it is only used once in the constructor, whereas the coefficients are accessed each time you want to evaluate the approximation at a given point. But making the whole function type a template parameter is a good approach too, except maybe for a bit more boilerplate in getting the value type out of it. It is also reasonable to assume that the number of coefficients is not very large, since the whole point of this is to have a way to cheaply approximate the original function."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T15:43:51.797",
"Id": "512456",
"Score": "0",
"body": "OP says this was to run on an embedded device with 60KB of memory, so I'm not sure we can afford to be blasé about the dynamic allocation `std::function` performs. And it might be reasonable to assume the number of coefficients is small, but if we're assuming something, especially something having to do with low-level memory allocation, we ought to make that assumption explicit with, e.g., an assertion."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T16:08:41.157",
"Id": "512458",
"Score": "0",
"body": "@RayHamel I'm confused, you don't like the potential dynamic allocation of `std::function`, but you do recommend using `std::vector` for the coefficients, which is almost certainly going to allocate memory dynamically? Note that a decent implementation of `std::function` will not allocate memory if it is not necessary, for example if it only needs to store a raw function pointer, like in OP's example, and even if it allocates, it is only a temporary allocation. And with `std::array`, the caller can choose to make it dynamic by just using `new` to create a `ChebApprox`."
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:45:54.587",
"Id": "259735",
"ParentId": "259725",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "259735",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T14:33:36.613",
"Id": "259725",
"Score": "14",
"Tags": [
"c++",
"mathematics",
"numerical-methods",
"c++20"
],
"Title": "C++ class to create and evaluate Chebyshev approximations of arbitrary functions"
}
|
259725
|
<p>I have a simple web api where each request "item" is stored in a list and thus a list is built without creating a new list per request. I have achieved this via dependency injection , but I want to know if there is a better way to do it?</p>
<pre><code>[ApiController]
[Route("[controller]")]
public class MyController: ControllerBase
{
private readonly List<string> _items;
public WeatherForecastController(List<string> items)
{
_items = items;
}
[HttpPost]
public ActionResult GetList([FromBody] CustomRequestObject request)
{
_items.Add(request.Item);
return Ok(new CustomResponseObject(){Items = _items});
}
}
public class CustomRequestObject
{
public string Item { get; set; }
}
public class CustomResponseObject
{
public IList<string> Items { get; set; }
}
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSingleton<List<string>>(); //items stored after each request
}
//rest of startup methods left for simplicity
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T09:23:03.517",
"Id": "512427",
"Score": "0",
"body": "What is the expected lifetime of your data?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T14:09:48.230",
"Id": "512451",
"Score": "0",
"body": "Are you not interested in retaining this data when the server reboots? How about after a period of not having received any web requests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T14:29:18.393",
"Id": "512452",
"Score": "0",
"body": "Why not simply use a DB?"
}
] |
[
{
"body": "<p>It really depends, how far you want to go with this.</p>\n<p>Maybe the most common suggestion that I can give is that what you are doing is called Memory Caching. It's good to call things with a name that is widely understood.</p>\n<p>Read this article about <a href=\"https://docs.microsoft.com/en-us/aspnet/core/performance/caching/memory\" rel=\"nofollow noreferrer\">In memory caching in Asp.net core</a>.</p>\n<p>Just to give you an example, what can be a possible issue with your code. Let's say you will have 2 instances of the same API, for scaling purposes. Guess what is going to happen? Every instance is going to work with its own in-memory list.</p>\n<p>A side issue (not related to your question): you never except for function <code>GetList</code> to add something to the list. :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T00:00:14.290",
"Id": "259743",
"ParentId": "259728",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T15:32:16.917",
"Id": "259728",
"Score": "-1",
"Tags": [
"c#",
".net",
"api",
"dependency-injection"
],
"Title": "Better way to keep a list of items from a Http Request?"
}
|
259728
|
<p>I made a snake game in c, it runs pretty well, everything is working, I think, I'm just wondering if there are any bugs I'm not aware of or if there is anything I can do better.</p>
<pre class="lang-c prettyprint-override"><code>#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
#include <math.h>
#include <time.h>
int gameOver = 0, width = 20, height = 20, x, y, fruitX, fruitY, score;
int s;
int totalTail;
int tailX[100], tailY[100];
void Setup(){
srand(time(NULL));
x = height/2;
y = width/2;
score = 0;
Start:
fruitX = 1 + rand()%width;
fruitY = 1+ rand()%height;
if(fruitX <= 0||fruitY <= 0||fruitX == x||fruitY == y||fruitX>height||fruitY>width){
goto Start;
}
}
void Draw(){
system("cls");
for(int i = 0; i<height;i++){
for(int j = 0; j<width; j++){
if(i == 0||j == 0||i == width-1|| j == height-1){
printf("#");
}
else if(i == x&&j == y){
printf("O");
} else if(fruitX == i && fruitY == j){
printf("F");
} else{
int print = 0;
for(int k = 0; k <totalTail; k++){
if(tailX[k] == i&& tailY[k] == j){
printf("o");
print = 1;
}
}
if(print == 0){
printf(" ");
}
}
}
printf("\n");
}
printf("Score: %d", score);
}
void Input(){
if(kbhit()){
switch(getch()){
case 'w':
s = 1;
break;
case 's':
s = 2;
break;
case 'a':
s = 3;
break;
case 'd':
s = 4;
break;
}
}
}
void Logic(){
int prevX = tailX[0];
int prevY = tailY[0];
int prev2X, prev2Y;
tailX[0] = x;
tailY[0] = y;
for (int i = 1; i < totalTail; i++)
{
prev2X = tailX[i];
prev2Y = tailY[i];
tailX[i] = prevX;
tailY[i] = prevY;
prevX = prev2X;
prevY = prev2Y;
}
switch(s){
case 1:
x--;
break;
case 2:
x++;
break;
case 3:
y--;
break;
case 4:
y++;
break;
default:
break;
}
if(s == 1||s==2){Sleep(25);}
for(int i = 0; i <totalTail; i++){
if(tailX[i] == x&&tailY[i] == y){
gameOver = 1;
}
}
if(x > width-1||y>height-1||x<0||y<0){
gameOver = 1;
}
if(x == fruitX && y == fruitY){
score += 1;
totalTail++;
start2:
fruitX = rand()%height;
fruitY = rand()%width;
if(fruitX <= 0||fruitY <= 0||fruitX == x||fruitY == y||fruitX>height||fruitY>width){
goto start2;
}
}
}
int main()
{
Setup();
while(gameOver != 1){
Draw();
Logic();
Input();
Sleep(10);
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T20:46:52.977",
"Id": "512376",
"Score": "1",
"body": "dareesome, what is the reason for the `fruitX == x||fruitY == y` test?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T20:55:57.923",
"Id": "512378",
"Score": "0",
"body": "Where it says ``if(x == fruitX && y == fruitY){`` or ``if(fruitX <= 0||fruitY <= 0||fruitX == x||fruitY == y||fruitX>height||fruitY>width){``"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T16:09:58.400",
"Id": "512459",
"Score": "2",
"body": "This isn't a big enough comment for a full answer, but I would think that Snake is a perfect use-case for a Linked List rather than an array. Your implementation requires you to iterate over the whole snake every time it moves, while a LL would be just a matter of adding one to the head and removing one from the tail. This would also be more memory efficient as the snake would only occupy as much memory as it needs, and could work efficiently at any length, rather than having an arbitrary cap of 100."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T04:06:49.293",
"Id": "512638",
"Score": "1",
"body": "@DarrelHoffman I agree with the linked list idea, but I'd add that the best implementation thereof would not be to allocate each link node's memory on the heap; but instead to pre-allocate a 2d array representing the playing field, and have each link node pointer point to the array element representing the node position. That way you never have to malloc()/free() anything, plus instead of using 8 byte pointers you can further save memory by using uint16_t (or uint32_t) indeces. Furthermore, if you turn each array element into a (bit-packed) struct, the same array can double as a fruit tracker."
}
] |
[
{
"body": "<p>You should keep your game loop as simple as possible with only an <code>update</code> and <code>draw</code> method and specifically in that order.</p>\n<hr />\n<p>To ensure your game loop is iterating at the same speed everytime, you should calculate the duration of your <code>update</code> and <code>draw</code> methods and then subtract that from how long each iteration should last.</p>\n<p>i.e.:</p>\n<pre><code>MD = 10ms // max duration for an iteration\nD = 2ms // actual duration of a draw and update\nMD - D = 10ms - 2ms = 8ms // calculated duration of sleep\n</code></pre>\n<hr />\n<p>You should not be redrawing the whole snake game every iteration. That is extrememly inefficient. You should instead move the console cursor to the coordinates that require something to be changed.</p>\n<p><em>drawing (in any context) is extremely expensive, so only draw what you need</em></p>\n<p>Also, a nice trick in console games is that you don't need to redraw the whole snake to show that it moved.</p>\n<p>i.e.: steps in one iteration on how to make the snake move.</p>\n<p>Step 0: Snake in default position</p>\n<pre><code>###@\n</code></pre>\n<p>Step 1: Snake with head advanced by 1</p>\n<pre><code>###@@\n</code></pre>\n<p>Step 2: Draw a space <code> </code> at the snake's last body position\n<em>note: this represents deletion</em></p>\n<pre><code> ##@@\n</code></pre>\n<p>Step 3: Snake with body part placed right behind the head\n<em>note: this deletes the old <code>@</code> symbol</em></p>\n<pre><code> ###@\n</code></pre>\n<p>So no matter how long your snake is, it will only require 3 actions to move the snake.</p>\n<hr />\n<p>The fruit should only appear in areas where the snake does not exist. The amount of possible coordinates is finite in your game. So I would just have a list of values to store all the unused coordinates and randomely take a value from that list to determine the location of the next food. (less guessing required).</p>\n<pre><code>start2:\nfruitX = rand()%height;\nfruitY = rand()%width;\n\nif(fruitX <= 0||fruitY <= 0||fruitX == x||fruitY == y||fruitX>height||fruitY>width){\n goto start2;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T01:30:10.527",
"Id": "512389",
"Score": "1",
"body": "Second opinion. Painting only part of the screen can cause flicker. In many contexts, the most efficient way to update the screen is to draw to a back buffer and swap buffers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T08:06:53.207",
"Id": "512414",
"Score": "0",
"body": "I don't think sleep is the best method, since sleep could take a variable amount of time. Better is a busy loop or interrupt based timing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T08:13:06.980",
"Id": "512417",
"Score": "0",
"body": "@qwr I actually quite like sleep for simple console games that don't require many updates. What do you mean by \"sleep could take a variable amount of time\" ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T08:27:17.867",
"Id": "512420",
"Score": "1",
"body": "Sleep only guarantees to suspend the process for at least the specified time. The execution of other processes can delay resumption. See e.g. https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-sleep#remarks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T11:34:05.507",
"Id": "512439",
"Score": "0",
"body": "@Davislor The flicker would be caused by calling `cls`, not as an inherent problem of partial screen updates on a text console. I've never seen any appreciable flicker in a game, from a telnet/bbs ANSI game to local term games (e.g. rogue). Assuming you're trying to keep a sane framerate, the screen updates should be just fine as suggested."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T19:33:05.303",
"Id": "512597",
"Score": "0",
"body": "\"You should not be redrawing the whole snake game every iteration.\" It is important to note that this is only true for drawing to the console. Most video games re-render the entire screen every frame."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:41:26.427",
"Id": "259734",
"ParentId": "259730",
"Score": "23"
}
},
{
"body": "<h2>Enums</h2>\n<p>In the code <code>s</code> is used to indicate the movement direction. From the code it's not easy to tell what <code>s</code> or <code>s == 2</code> means. An enum would improve readability and maintainability of the code.</p>\n<pre><code>typedef enum {\n Up,\n Down,\n Left,\n Right\n} Direction;\n</code></pre>\n<p>Which would lead to something like this:</p>\n<pre><code>Direction direction;\n\nif (kbhit()) {\n switch (getch()) {\n case 'w':\n direction = Up;\n break;\n case 's':\n direction = Down;\n break;\n case 'a':\n direction = Left;\n break;\n case 'd':\n direction = Right;\n break;\n }\n}\n</code></pre>\n<h2>Styling</h2>\n<p>The code contains some inconsistent styling in terms of spacing around operators, brackets and parentheses. It would be best to make the styling consistent to increase readability. Using a style guide, formatter and/or linter could help with this.</p>\n<h2>Avoid the use of goto</h2>\n<p>Opinions may differ on this one, but the <code>goto</code> statement can increase the likelihood of spaghetti code. It has some proper use cases, but most of the time there are better ways to structure code to avoid it's usage. More information on this can be found here: <a href=\"https://stackoverflow.com/questions/46586/goto-still-considered-harmful\">https://stackoverflow.com/questions/46586/goto-still-considered-harmful</a>.</p>\n<pre><code>start:\n fruitX = rand() % height;\n fruitY = rand() % width;\n\n if (fruitX <= 0 || fruitY <= 0 || fruitX == x|| fruitY == y || fruitX > height || fruitY > width) {\n goto start;\n }\n</code></pre>\n<p>Could be written as:</p>\n<pre><code> do {\n fruitX = rand() % height;\n fruitY = rand() % width;\n } while (fruitX <= 0 || fruitY <= 0 || fruitX == x|| fruitY == y || fruitX > height || fruitY > width)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T12:35:37.427",
"Id": "259759",
"ParentId": "259730",
"Score": "9"
}
},
{
"body": "<p>A couple of things.</p>\n<p>It’s a good idea to future-proof your program by declaring which version of the Windows SDK you’re using. This way, a future version of the compiler knows what version to stay compatible with and not to deprecate any functions you use. You can do this with the macros in <code><SdkDdkVer.h></code>, typically:</p>\n<pre><code>#define _WIN32_WINNT _WIN32_WINNT_WIN10\n#define NTDDI_VERSION NTDDI_WIN10_19H1\n#include <SdkDdkVer.h>\n</code></pre>\n<p>In your <code>Setup</code> function, you use a <code>goto</code>, which is a shoot-yourself-in-the-foot feature of the language. You aren’t trying to break out of multiple nested loops or send all possible code branches to a single exit point. What you want here is to retry the randomization until it gives you good values. This is a <code>do</code> ... <code>while</code> loop. That is, without refactoring anything else, you would want to rewrite that control structure as something like this:</p>\n<pre><code>#if 0\nStart:\nfruitX = 1 + rand()%width;\nfruitY = 1+ rand()%height;\n\nif(fruitX <= 0||fruitY <= 0||fruitX == x||fruitY == y||fruitX>height||fruitY>width){\n goto Start;\n}\n#endif\n\ndo {\n fruitX = 1 + rand()%width;\n fruitY = 1 + rand()%height;\n} while ( fruitX <= 0 ||\n fruitY <= 0 ||\n fruitX == x ||\n fruitY == y ||\n fruitX>height ||\n fruitY>width\n );\n</code></pre>\n<p>Note that it is impossible for <code>fruitX</code> and <code>fruitY</code> to exceed <code>width</code> and <code>height</code>, respectively, as you have defined them with <code>% width</code> and <code>% height</code>, but defensive coding is a good idea. (If the invalid values should be impossible, you might even want to abort with a descriptive error message, rather than silently handle them.) You might also define them as unsigned values.</p>\n<p>There appears to be a significant logic error here as well: you generate a new position for the fruit whenever it is on <strong>either</strong> the same row or the same column as the head of the snake, and you probably meant to regenerate it only if it is in the exact same location.</p>\n<p>This would get you something like</p>\n<pre><code>do {\n fruitX = 1 + rand()%width;\n fruitY = 1 + rand()%height;\n} while ( fruitX == x && fruitY == y );\n</code></pre>\n<p>It would also be possible to subtract 1 from the range of the x and y coordinates of the fruit, and add 1 to either if it is greater than or equal to the coordinate of the head. This gets you a uniform pseudo-random distribution, on the first try, guaranteed not to be on the same row or column as the head.</p>\n<p>This code is probably identical to the code that will place new fruits on the screen, so you can factor it out into a separate function that returns a coordinate-pair, instead of repeating yourself.</p>\n<p>If you’re using a Boolean value, you might as well use <code>bool</code> from <code><stdbool.h></code>.</p>\n<p>The recommended way to clear the screen in Windows is not with <code>system("cls")</code>, but by <a href=\"https://docs.microsoft.com/en-us/windows/console/clearing-the-screen\" rel=\"nofollow noreferrer\">setting the console to accept ANSI virtual terminal control codes, as demonstrated here.</a> The virtual console (which emulates a DEC VT102 from the 1970s) is documented in more detail <a href=\"https://docs.microsoft.com/en-us/windows/console/console-virtual-terminal-sequences\" rel=\"nofollow noreferrer\">here.</a> The terminal also supports painting only the part of the screen that has changed, or drawing to a back buffer and swapping buffers, to avoid flicker. Either is much closer to how you would render modern graphics in a game or app than clearing the screen and then printing every character in order, although the API is very different.</p>\n<p>If you use this interface, you would also want to <a href=\"https://docs.microsoft.com/en-us/windows/console/reading-input-buffer-events\" rel=\"nofollow noreferrer\">read console input events, as documented here.</a> Unfortunately, if you wanted to have your game advance by clock ticks, and not update when you press a key, you would need to fall back on deprecated APIs (which, however, are still going to be supported for the indefinite future).</p>\n<p>Here’s a very simple test program that refactors the global game state into a <code>struct</code> and passes a reference to it around. (I’m trying to compromise here between not writing a new program in a code review, and providing a minimal working example of the concepts, not just links to documentation.) I left out the input handling, since I could see several different approaches you could take, but you probably would end up using <code>ReadConsoleInput</code> rather than <code>getch</code>.</p>\n<pre><code>#define _WIN32_WINNT _WIN32_WINNT_WIN10\n#define NTDDI_VERSION NTDDI_WIN10_19H1\n#include <SdkDdkVer.h>\n\n#include <assert.h>\n#include <stdbool.h>\n#include <stddef.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n\n#include <windows.h>\n\n#define HEIGHT 20U\n#define WIDTH 20U\n\ntypedef struct GameState {\n unsigned fruitX; // The x coordinate of the fruit, with the origin in the top left corner.\n unsigned fruitY; // And its y coordinate.\n long score;\n bool isGameOver;\n ptrdiff_t snakeLen; // The number of snake segments, including the head.\n unsigned snakeXs[HEIGHT*WIDTH]; // The x-coordinates of each snake segment, from tail to head\n // (The x-coordinate of the head is snakeXs[snakeLen-1]).\n unsigned snakeYs[HEIGHT*WIDTH]; // The y-coordinate\n} GameState;\n\nint clear_screen(const HANDLE hStdOut) {\n // Write the sequence for clearing the display.\n DWORD written = 0;\n static const wchar_t sequence[] = L"\\x1b[2J\\x1b[3J";\n\n if ( !WriteConsoleW( hStdOut, sequence, ARRAYSIZE(sequence), &written, NULL )) {\n return GetLastError();\n } else {\n return 0;\n }\n}\n\nvoid game_init(GameState* const state)\n{\n static const unsigned x = WIDTH/2U;\n static const unsigned y = HEIGHT/2U;\n\n do {\n state->fruitX = rand() % WIDTH;\n state->fruitY = rand() % HEIGHT;\n } while ( state->fruitX == x && state->fruitY == y );\n\n memset( state, sizeof(*state), 0 );\n state->score = 0;\n state->isGameOver = false;\n state->snakeXs[0] = x;\n state->snakeYs[0] = y;\n state->snakeLen = 1;\n}\n\nvoid draw_screen( const GameState* const state,\n const HANDLE hStdOut )\n{\n char playfield[HEIGHT][WIDTH+1];\n char scoreline[32] = {0};\n\n clear_screen(hStdOut);\n\n for ( unsigned i = 0; i < HEIGHT; ++i ) {\n for ( unsigned j = 0; j < WIDTH; ++j ) {\n playfield[i][j] = '.';\n }\n playfield[i][WIDTH] = '\\n';\n }\n\n const ptrdiff_t headPos = state->snakeLen - 1;\n assert( headPos >= 0 );\n\n for ( ptrdiff_t i = 0; i < headPos; ++i ) {\n assert(state->snakeXs[i] < WIDTH);\n assert(state->snakeYs[i] < HEIGHT);\n playfield[state->snakeYs[i]][state->snakeXs[i]] = '#';\n }\n\n playfield[state->snakeYs[headPos]][state->snakeXs[headPos]] = '@';\n playfield[state->fruitY][state->fruitX] = '*';\n\n WriteConsole( hStdOut, playfield, sizeof(playfield), NULL, NULL );\n const DWORD scorelen = snprintf( scoreline,\n sizeof(scoreline),\n "Score: %ld\\n",\n state->score );\n WriteConsole( hStdOut, scoreline, scorelen, NULL, NULL );\n}\n\nDWORD get_console_mode( const HANDLE h )\n{\n DWORD mode;\n if (!GetConsoleMode( h, &mode )) {\n exit(GetLastError());\n }\n\n return mode;\n}\n\nint main(void)\n{\n srand(time(NULL));\n const HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);\n\n const DWORD originalMode = get_console_mode(hStdOut);\n\n const DWORD newMode = originalMode | \n ENABLE_VIRTUAL_TERMINAL_PROCESSING;\n\n if (!SetConsoleMode( hStdOut, newMode ))\n {\n return GetLastError();\n }\n\n GameState game_state;\n game_init(&game_state);\n\n draw_screen( &game_state, hStdOut );\n\n // Restore the mode on the way out to be nice to other command-line applications.\n SetConsoleMode( hStdOut, originalMode );\n\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p>I admit that I inconsistently switched between <code>WriteConsoleW</code> and <code>WriteConsole</code> there. This is primarily because I buffer the entire playfield and write it out in one system call. Most real-world apps should use Unicode consistently for character I/O, but do not necessarily have to waste memory storing wide-character strings.</p>\n<p>It’s generally considered a bad idea to have global variables that aren’t <code>const</code>. They’re bug-attractors, because it’s impossible to reason about which part of the program might have modified them and how. You’ll especially appreciate being able to use the receive-copy-update pattern on state objects if you ever want to make your game multi-threaded—for example, if you turn it into a TRON game, the AI thread could be examining the current game state safely, and another thread could be rendering the next frame and selecting appropriate sound effects, while the physics engine is preparing the new game state.</p>\n<p>I would probably turn the <code>case</code> blocks into a finite state machine, which either becomes a loop similar to <code>while(!state->isGameOver)</code> or a tail-recursive call similar to <code>return update_state( &game_state, player_move );</code>. These optimize to equally-efficient code on a modern compiler.</p>\n<p>Hope that helps!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T15:31:12.170",
"Id": "259762",
"ParentId": "259730",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>You aren't ever interested in where the n<sup>th</sup> part of your snake is, but whether one (or sometimes any other obstacle) is at a specific place.<br />\nLay out your data-structures accordingly!</p>\n<p>Have a single array representing the whole playing field, with codes reserved for space, edibles, walls, snake-head, and 4 types of snake-body (depending on where the body went). If you later decide on adding multi-player, add the same for new snakes.</p>\n<p>Add a function to translate from linear coordinate to x/y and back.</p>\n<p>That does imply that a snake only stores the the head-coordinate, the length (current and wanted), and the ultimate tail-coordinate. The rest is inferred from the playing-field as and when needed.</p>\n</li>\n<li><p>You know that <code>srand()</code> and <code>rand()</code> are a bad PRNG? Oh well, it should be enough to get you going at least.</p>\n</li>\n<li><p>Others already commented on structured do-while loops being superior to hand-rolling your own with goto. I just wanted to add that <code>assert()</code> is there for testing whether your program's invariants hold. Always retesting them in the general code clutters it up, makes readers double-check and detracts from the point.</p>\n</li>\n<li><p>You are using <code>gameOver</code> as a boolean variable. Except that you disregard the conventions baked into the very language.<br />\nIn C, zero is false, all else is truthy. (Let's disregard NaN for now.)</p>\n<p>Anyway, <code>running</code> with inverted logic would have been my preference. Which can be upgraded to <code>lifes</code> without trouble.</p>\n</li>\n<li><p>Doing the update-step after drawing and before processing input is most peculiar. There is no reason to adding gratuitious lag. Anyway, calling it <code>Logic()</code> instead of <code>Update()</code> is surprising.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:57:43.777",
"Id": "259810",
"ParentId": "259730",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:05:00.473",
"Id": "259730",
"Score": "20",
"Tags": [
"c",
"snake-game"
],
"Title": "A Snake Game in C"
}
|
259730
|
<p>I am trying to create a doc file which contains the list of folders in a given folder path. The <code>Main</code> function is the entry point.</p>
<pre><code>// This function performs the operation of creating the file of the list of folders in the specific folder.
// Usage: Set the ListDocName, the ListDocFullPath, and the SpecificFolder, then just run Main function.
function Main() {
// Set Doc (output) file name
var ListDocName = "RootFolderList";
// Set Doc (output) file path
var ListDocFullPath = "/";
// Set specific folder, and this program would list its subfolders to Doc file.
var SpecificFolder = "/";
CreateGoogleDocInSpecificFolder(ListDocName, ListDocFullPath);
var DocFiles = GoogleDocsInSpecificFolder(ListDocName, ListDocFullPath);
while(DocFiles.hasNext())
{
var docFile = DocFiles.next();
var docID = docFile.getId();
var doc = DocumentApp.openById(docID);
var Folders = FoldersInSpecificFolder(SpecificFolder);
while(Folders.hasNext())
{
var Folder = Folders.next();
// Access the body of the document, then add a paragraph.
doc.getBody().appendParagraph(SpecificFolder + '/' + Folder.getName() + '\t' + Folder.getId());
}
doc.saveAndClose();
}
}
// FoldersInSpecificFolder function would return a FileIterator
function FoldersInSpecificFolder(FolderFullPath)
{
if(FolderFullPath == '/')
{
// Return the FolderIterator in Root.
return getFolder(FolderFullPath);
}
else
{
// getFolder return the FolderIterator
var TargetFolders = getFolder(FolderFullPath);
while (TargetFolders.hasNext())
{
var folder = TargetFolders.next();
return folder.getFolders();
}
}
}
// GoogleDocsInSpecificFolder function would return a FileIterator
function GoogleDocsInSpecificFolder(docName, FolderFullPath)
{
if(FolderFullPath == '/')
{
// Read files in Root, getFilesByName return the FileIterator
var RootDocs = DriveApp.getRootFolder().getFilesByName(docName);
return RootDocs;
}
else
{
// getFolder return the FolderIterator
var TargetFolders = getFolder(FolderFullPath);
while (TargetFolders.hasNext())
{
var folder = TargetFolders.next();
var docFiles = folder.getFilesByName(docName);
return docFiles;
}
}
}
function CreateGoogleDocInSpecificFolder(docName, FolderFullPath)
{
var docID;
if(FolderFullPath == '/')
{
// Create a new Google Doc in Root
var docRoot = DocumentApp.create(docName);
var docRootID = docRoot.getId();
docRoot.saveAndClose();
return docRootID;
}
else
{
// Create a new Google Doc in Root
var docRoot = DocumentApp.create(docName);
var docRootID = docRoot.getId();
docRoot.saveAndClose();
// Get new Google Doc file ID (Use in copy)
var docRootFile = DriveApp.getFileById(docRootID);
var TargetFolders = getFolder(FolderFullPath);
while (TargetFolders.hasNext())
{
var folder = TargetFolders.next();
// Copy Google Doc to correct file path
var docFile = docRootFile.makeCopy(docName, folder);
docID = docFile.getId();
}
// Delete Google Doc in Root
DriveApp.removeFile(docRootFile);
return docID;
}
}
// getFolder function would return the FolderIterator which is locate at Path.
function getFolder(Path)
{
var SubFolder;
var arr = Path.split("/");
for (var i = 1; i < arr.length; i = i + 1)
{
var FolderName = arr[i];
if(i == 1)
{
SubFolder = DriveApp.getRootFolder().searchFolders("title contains '"+FolderName+"'");
}
else
{
if (SubFolder.hasNext())
{
var folderTemp = SubFolder.next();
SubFolder = folderTemp.searchFolders("title contains '"+FolderName+"'");
}
}
}
return SubFolder;
}
</code></pre>
<p>If there is any possible improvement about potential drawback, please let me know.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:10:00.053",
"Id": "259731",
"Score": "0",
"Tags": [
"javascript",
"file-system",
"web-services",
"google-apps-script",
"google-drive"
],
"Title": "List sub-folders and its ID in the given path in Google Drive with Google App Script"
}
|
259731
|
<p>PHP 7 is the next version of <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a>. It succeeds PHP-5.6, which is the last release of the PHP 5.X version. PHP 7.0.0 was <a href="https://php.net/archive/2015.php#id2015-12-03-1" rel="nofollow noreferrer">released on Dec 3, 2015</a></p>
<h2>PHP 6</h2>
<p>Several years ago there was a major push to make PHP Unicode compatible and this push focused around what was then slated to be PHP 6. An internal version was developed and a lot of material was published (including some books) about this new version. Serious problems with the implementation arose, however, and the project was abandoned, with most of the surviving code being implemented in PHP 5.4. To avoid confusion with this discussion <a href="https://wiki.php.net/rfc/php6" rel="nofollow noreferrer">the decision was made to skip version 6</a>.</p>
<h2>Development</h2>
<p>You can download the <a href="https://github.com/php/php-src/tree/PHP-7.0" rel="nofollow noreferrer">PHP 7 source</a> and compile it yourself. Official builds are <a href="https://www.php.net/downloads.php" rel="nofollow noreferrer">available on the PHP website</a>.</p>
<h2>Features</h2>
<p>New features of PHP 7 include (See <a href="https://wiki.php.net/rfc#php_70" rel="nofollow noreferrer">all accepted features</a>):</p>
<ul>
<li>Zend Engine 3 (aka <a href="https://wiki.php.net/phpng" rel="nofollow noreferrer">phpng</a>, performance improvements and 64bit integer support on Windows)</li>
<li><a href="https://wiki.php.net/rfc/return_types" rel="nofollow noreferrer">return type declarations</a></li>
<li><a href="https://wiki.php.net/rfc/isset_ternary" rel="nofollow noreferrer">?? (null coalesce) operator</a></li>
<li><a href="https://wiki.php.net/rfc/scalar_type_hints_v5" rel="nofollow noreferrer">scalar type declarations</a></li>
<li>Anonymous classes</li>
<li>Generator Return Expressions</li>
<li>Generator delegation</li>
<li>Session options</li>
<li>CSPRNG (Cryptographically Secure PseudoRandom Number Generator)</li>
<li>Spaceship Operator (i.e. <code><=></code> )</li>
</ul>
<h2>PHP7 migration guide</h2>
<p>There's a whole section on <a href="https://php.net/migration70" rel="nofollow noreferrer">Migrating from PHP 5.6.x to PHP 7.0.x</a> in the manual:</p>
<blockquote>
<ul>
<li><a href="https://php.net/migration70.incompatible" rel="nofollow noreferrer">Backward incompatible changes</a></li>
<li><a href="https://php.net/migration70.new-features" rel="nofollow noreferrer">New features</a></li>
<li><a href="https://php.net/migration70.sapi-changes" rel="nofollow noreferrer">Changes in SAPI Modules</a></li>
<li><a href="https://php.net/migration70.deprecated" rel="nofollow noreferrer">Deprecated features in PHP 7.0.x</a></li>
<li><a href="https://php.net/migration70.changed-functions" rel="nofollow noreferrer">Changed functions</a></li>
<li><a href="https://php.net/migration70.new-functions" rel="nofollow noreferrer">New functions</a></li>
<li><a href="https://php.net/migration70.classes" rel="nofollow noreferrer">New Classes and Interfaces</a></li>
<li><a href="https://php.net/migration70.constants" rel="nofollow noreferrer">New Global Constants</a></li>
<li><a href="https://php.net/migration70.removed-exts-sapis" rel="nofollow noreferrer">Removed Extensions and SAPIs</a></li>
<li><a href="https://php.net/migration70.other-changes" rel="nofollow noreferrer">Other Changes</a></li>
</ul>
<p><sup>© 1997-2015, The PHP Documentation group, <a href="https://php.net/manual/en/copyright.php" rel="nofollow noreferrer">CC-BY 3.0</a></sup></p>
</blockquote>
<h2>Information</h2>
<ul>
<li>For global question on PHP, please use the generic tag: <a href="/questions/tagged/php" class="post-tag" title="show questions tagged 'php'" rel="tag">php</a></li>
<li>If you want to talk about PHP or if you have a question, you can come to <a href="https://chat.stackoverflow.com/rooms/11/php">the PHP chat room</a></li>
</ul>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:39:48.180",
"Id": "259732",
"Score": "0",
"Tags": null,
"Title": null
}
|
259732
|
PHP 7 is the successor to PHP 5.6, it was released on December 3, 2015. Use this tag for issues relating to development using PHP 7
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T16:39:48.180",
"Id": "259733",
"Score": "0",
"Tags": null,
"Title": null
}
|
259733
|
<p>I’m learning a lot of from Combine thanks to an amazing book in raywenderlich.
Currently i’m writing an app and following the clean MVVM architecture.</p>
<p>Then I have the following layers:</p>
<ul>
<li>Domain(UseCases and RepositoryProtocols)</li>
<li>Data(RepositoryImplementations)</li>
<li>Presentation(ViewController and ViewModels)</li>
</ul>
<p>So this is what I have by now:</p>
<p>LoginUseCase.swift</p>
<pre><code>import Foundation
import Combine
public enum LoginState {
case idle
case inProgress
case success
case emailValidationPending
case wrongPassword
case invalidEmail
case invalidPassword
case error
}
public protocol LoginUseCase {
func login(email: String, password: String) -> AnyPublisher<LoginState, Never>
}
public class LoginUseCaseImp: LoginUseCase {
let repository: RegistroRepository
public init(repository: RegistroRepository) {
self.repository = repository
}
public func login(email: String, password: String) -> AnyPublisher<LoginState, Never> {
return Future<LoginState, Never> { [weak self] promise in
self?.repository.login(email: email, password: password) { (result: Result<Bool, LoginRepositoryError>) in
switch result {
case .success(_):
return promise(.success(.success))
case .failure(let error):
switch error {
case .wrongPassword:
return promise(.success(.wrongPassword))
case .userNotExist:
return promise(.success(.error))
case .emailValidationPending:
return promise(.success(.emailValidationPending))
}
}
}
}.eraseToAnyPublisher()
}
}
</code></pre>
<p>LoginViewModel.swift</p>
<pre><code>import Foundation
import DomainRadarAir
import Combine
public final class LoginViewModel: ObservableObject {
private let loginUseCase: LoginUseCase
public init(loginUseCase: LoginUseCase) {
self.loginUseCase = loginUseCase
}
public func login(email: String?, password: String?) -> AnyPublisher<LoginState, Never> {
guard let email=email, !email.isEmpty else {
return Just<LoginState>(.invalidEmail).eraseToAnyPublisher()
}
guard let password=password, !password.isEmpty else {
return Just<LoginState>(.invalidPassword).eraseToAnyPublisher()
}
return loginUseCase.login(email: email, password: password)
}
}
</code></pre>
<p>Then in the LoginViewController.swift</p>
<pre><code> @IBAction func loginClick(_ sender: Any) {
viewModel.login(email: emailTF.text, password: passwordTF.text)
.print("State: ")
.sink { [weak self] state in
guard let self = self else { return }
switch state {
// handle all cases
}
.store(in: &cancellables)
}
</code></pre>
<p>What do you think of this approach, passing AnyPublisher object from UseCase to ViewController through ViewModel?</p>
<p>Thanks in advance for your opinions.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T19:15:04.313",
"Id": "259736",
"Score": "0",
"Tags": [
"swift",
"ios",
"mvvm"
],
"Title": "iOS: Combine and Clean Architecture"
}
|
259736
|
<p>I'm making a terrain-deformation system in Unity that utilizes the common marching-cubes algorithm. So far I've gotten the system working, employed Unity's job system and burst compiler, and managed to cut down frame calculation time from ~100ms per job to ~25ms. That's great, and I'm getting around 20 FPS during the worst performance drops when two jobs have to run end-to-end, so I'm super proud of that. However 20 FPS is still pretty choppy and I would like to cut it down further, but I've been looking at this so long I'm probably missing some easy performance gains. Does anyone have any insight into wasteful practices I'm overlooking in my mesh deformation script?</p>
<pre><code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Unity.Jobs;
using Unity.Collections;
using Unity.Burst;
public class Chunk
{
// Chunk data
public GameObject chunkObject;
MeshFilter meshFilter;
MeshCollider meshCollider;
MeshRenderer meshRenderer;
Vector3Int chunkPosition;
// Job system data
private NativeList<Vector3> marchVerts;
private NativeList<int> marchTris;
MarchCubeJob instanceMarchCube;
public JobHandle jobHandler;
// Density map of terrain
// [x + (chunkWidth+1) * (y + (ChunkHeight+1) * z)] is the formula to retrieve [x, y, z]
private NativeArray<float> passMap;
// World settings
int chunkWidth { get { return Terrain_Data.chunkWidth;}}
int ChunkHeight { get { return Terrain_Data.chunkHeight;}}
static float terrainSurface { get { return Terrain_Data.terrainSurface;}}
// Constructor
public Chunk (Vector3Int _position){
passMap = new NativeArray<float>((chunkWidth+1)*(chunkWidth+1)*(ChunkHeight+1), Allocator.Persistent);
chunkObject = new GameObject();
chunkObject.name = string.Format("Chunk x{0}, y{1}, z{2}", _position.x, _position.y, _position.z);
chunkPosition = _position;
chunkObject.transform.position = chunkPosition;
meshRenderer = chunkObject.AddComponent<MeshRenderer>();
meshFilter = chunkObject.AddComponent<MeshFilter>();
meshCollider = chunkObject.AddComponent<MeshCollider>();
chunkObject.transform.tag = "Terrain";
meshRenderer.material = Resources.Load<Material>("Materials/Terrain");
// Generate chunk
PopulateTerrainMap();
CreateMeshData();
FinishMesh();
}
// Get natural layout of terrainMap based on random generation
void PopulateTerrainMap(){
for (int x = 0; x < chunkWidth + 1; x++) {
for (int y = 0; y < ChunkHeight + 1; y++) {
for (int z = 0; z < chunkWidth + 1; z++) {
passMap[x + (chunkWidth+1) * (y + (ChunkHeight+1) * z)] = Terrain_Data.GetTerrainPoint(x + chunkPosition.x, y + chunkPosition.y, z + chunkPosition.z);
}
}
}
}
// Setup job system for marching cubes to get vertex data
void CreateMeshData(){
// Set up memory pointers
marchVerts = new NativeList<Vector3>(1, Allocator.TempJob);
marchTris = new NativeList<int>(1, Allocator.TempJob);
// Call marchcubes job
instanceMarchCube = new MarchCubeJob(){
marchVerts = marchVerts,
marchTris = marchTris,
mapSample = passMap
};
// Run job for this chunk
jobHandler = instanceMarchCube.Schedule();
}
// Finish meshes on affected chunks
public void FinishMesh(){
// Make sure chunk job is complete
jobHandler.Complete();
// Build mesh for this chunk
BuildMesh();
// Dispose of memory pointers
marchVerts.Dispose();
marchTris.Dispose();
}
// Increase/decrease terrain density in a sphere
public void ModifyTerrain (Vector3 pos, int radius, float speed){
Vector3Int v3Int = new Vector3Int(Mathf.RoundToInt(pos.x), Mathf.RoundToInt(pos.y), Mathf.RoundToInt(pos.z));
v3Int -= chunkPosition;
// Set bounds
int xlow = Mathf.Clamp(v3Int.x - radius, 0, chunkWidth);
int ylow = Mathf.Clamp(v3Int.y - radius, 0, ChunkHeight);
int zlow = Mathf.Clamp(v3Int.z - radius, 0, chunkWidth);
int xhigh = Mathf.Clamp(v3Int.x + radius, 0, chunkWidth + 1);
int yhigh = Mathf.Clamp(v3Int.y + radius, 0, ChunkHeight + 1);
int zhigh = Mathf.Clamp(v3Int.z + radius, 0, chunkWidth + 1);
// Set new terrainMap values
for (int x = xlow; x < xhigh; x++){
for (int y = ylow; y < yhigh; y++){
for (int z = zlow; z < zhigh; z++){
float dist = Vector3.Distance(new Vector3(x, y, z), v3Int);
if (dist < radius){
passMap[x + (chunkWidth+1) * (y + (ChunkHeight+1) * z)] += speed;
}
}
}
}
// Call marchcubes and draw mesh
CreateMeshData();
}
// Draw mesh using vertex values
void BuildMesh(){
Mesh mesh = new Mesh();
mesh.vertices = instanceMarchCube.marchVerts.ToArray();
mesh.triangles = instanceMarchCube.marchTris.ToArray();
mesh.RecalculateNormals();
meshFilter.mesh = mesh;
meshCollider.sharedMesh = mesh;
}
// Dispose native data on destroy
private void OnDestroy(){
marchVerts.Dispose();
marchTris.Dispose();
passMap.Dispose();
}
// Build a chunk using marching cubes as a job
[BurstCompile]
public struct MarchCubeJob: IJob{
int chunkWidth { get { return Terrain_Data.chunkWidth;}}
int ChunkHeight { get { return Terrain_Data.chunkHeight;}}
static float terrainSurface { get { return Terrain_Data.terrainSurface;}}
public NativeList<Vector3> marchVerts;
[WriteOnly] public NativeList<int> marchTris;
[ReadOnly] public NativeArray<float> mapSample;
public void Execute(){
for (int x = 0; x < chunkWidth; x++) {
for (int y = 0; y < ChunkHeight; y++) {
for (int z = 0; z < chunkWidth; z++) {
// Instantiate position var
Vector3Int position = new Vector3Int(x, y, z);
//Sample terrain values to get density at each corner of cube
float[] cube = new float[8];
for (int i = 0; i < 8; i++){
cube[i] = SampleTerrainMap(position + Terrain_Data.CornerTable[i]);
}
// Get configuration index of cube by comparing corner density to terrainSurface value
int configIndex = GetCubeConfiguration(cube);
// If cube is empty (-1 in all vertices means there is no cube here)
if (configIndex == 0 || configIndex == 255){
continue;
}
// Start mesh vertex calculations
int edgeIndex = 0;
for (int i = 0; i < 5; i++){ // Triangles
for (int p = 0; p < 3; p++){ // Tri Vertices
int indice = Terrain_Data.TriangleTable[configIndex, edgeIndex];
if (indice == -1){
continue;
}
// Get 2 points of edge
Vector3 vert1 = position + Terrain_Data.CornerTable[Terrain_Data.EdgeIndexes[indice, 0]];
Vector3 vert2 = position + Terrain_Data.CornerTable[Terrain_Data.EdgeIndexes[indice, 1]];
Vector3 vertPosition;
// Smooth terrain
// Sample terrain values at either end of current edge
float vert1Sample = cube[Terrain_Data.EdgeIndexes[indice, 0]];
float vert2Sample = cube[Terrain_Data.EdgeIndexes[indice, 1]];
// Calculate difference between terrain values
float difference = vert2Sample - vert1Sample;
if (difference == 0){
difference = terrainSurface;
}
else{
difference = (terrainSurface - vert1Sample) / difference;
}
vertPosition = vert1 + ((vert2 - vert1) * difference);
marchVerts.Add(vertPosition);
marchTris.Add(marchVerts.Length - 1);
edgeIndex++;
}
}
}
}
}
}
static int GetCubeConfiguration(float[] cube){
int configurationIndex = 0;
for (int i = 0; i < 8; i++){
if (cube[i] > terrainSurface){
configurationIndex |= 1 << i;
}
}
return configurationIndex;
}
public float SampleTerrainMap(Vector3Int point){
return mapSample[point.x + (chunkWidth+1) * (point.y + (ChunkHeight+1) * point.z)];
}
}
}
</code></pre>
<p>A short summary of the execution order:</p>
<p>It starts by having a separate object call <strong>ModifyTerrain()</strong> for each affected chunk in the gameworld.</p>
<p><strong>ModifyTerrain()</strong> then scrolls through each point in the chunk and updates the NativeArray(float) <strong>passMap</strong>, a representation of the density of the ground at that point.</p>
<p>It then calls <strong>CreateMeshData()</strong>, which allocates the NativeList(Vector3) <strong>marchVerts</strong> and NativeList(int) <strong>marchTris</strong> before creating a <strong>MarchCubeJob()</strong> job to calculate the chunk mesh.</p>
<p>The same outside object then calls <strong>FinishMesh()</strong> in <strong>LateUpdate()</strong> for the same affected chunks, which completes all jobs as a priority, copies the <strong>marchVerts</strong> and <strong>marchTris</strong> NativeLists into the mesh construction method <strong>BuildMesh()</strong>.</p>
<p>If you have any useful critique on my code I'd be happy to hear it! I don't have much experience with optimization so every little bit helps. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T03:48:07.367",
"Id": "512391",
"Score": "0",
"body": "Welcome to the Code Review Community. The question would be better if the title just stated what the code does, and you addressed your concerns about the code within the body of the question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T05:01:19.193",
"Id": "512399",
"Score": "0",
"body": "Thanks @pacmaninbw, I changed my title to the main topic I'm trying to get information on - that is to say optimizing c# procedural mesh generation. Do you have any insight into the matter? I would guess eliminating for loops would be the biggest time save, but I'm not sure that's possible with how I'm executing the methods as of now. Perhaps how to make marchVerts write-only? I'm kinda stumped."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T17:14:06.840",
"Id": "512463",
"Score": "0",
"body": "I've since made a big improvement by moving the position and cube allocators to the beginning of the job execution and instead modifying their values. Job timing is down to ~8ms."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T22:47:29.540",
"Id": "259740",
"Score": "3",
"Tags": [
"c#",
"performance",
"game",
"multithreading",
"unity3d"
],
"Title": "C# Procedural Mesh Generation Optimization"
}
|
259740
|
<p>I've been playing around with <a href="https://dotty.epfl.ch/docs/reference/contextual/derivation.html#how-to-write-a-type-class-derived-method-using-low-level-mechanisms" rel="nofollow noreferrer">this example</a> from the Scala 3 documentation, and I noticed that certain things duplicate functionality already present in the standard API; In particular, the <code>summonAll</code> (which was working for <code>Eq[_]</code> only) seemed to be a combination of</p>
<ul>
<li><code>Tuple.Map[Tup, F]</code> type constructor, which recursively deconstructs a tuple <code>Tup</code> and modifies each entry by wrapping it in <code>F</code></li>
<li><code>compiletime.summonAll</code>, which already knows how to summon elements for each entry of a tuple-type.</li>
</ul>
<p>I think it was either done this way for didactic purposes, or maybe the API changed after the example was written.</p>
<p>Anyway, I've attempted to modify it, and to use the above mentioned definitions from the API, that's what I obtained:</p>
<pre><code>import deriving.Mirror
import compiletime.{ erasedValue, summonAll }
trait Eq[T]:
def eqv(x: T, y: T): Boolean
object Eq:
inline given derived[T](using m: Mirror.Of[T]): Eq[T] =
val elemInstances = summonAll[Tuple.Map[m.MirroredElemTypes, Eq]]
inline m match
case s: Mirror.SumOf[T] => eqSum(s, elemInstances)
case p: Mirror.ProductOf[T] => eqProduct(p, elemInstances)
def eqSum[T](s: Mirror.SumOf[T], elems: Tuple): Eq[T] =
new Eq[T]:
def eqv(x: T, y: T): Boolean =
val ordx = s.ordinal(x)
(s.ordinal(y) == ordx) && check(elems.productElement(ordx))(x, y)
def eqProduct[T](p: Mirror.ProductOf[T], elems: Tuple): Eq[T] =
new Eq[T]:
def eqv(x: T, y: T): Boolean =
iterator(x).zip(iterator(y)).zip(elems.productIterator).forall{
case ((x, y), elem) => check(elem)(x, y)
}
def iterator[T](p: T) = p.asInstanceOf[Product].productIterator
def check(elem: Any)(x: Any, y: Any): Boolean = elem.asInstanceOf[Eq[Any]].eqv(x, y)
given Eq[Int] with
def eqv(x: Int, y: Int) = x == y
end Eq
case class Foo(a: Int, b: Int) derives Eq
</code></pre>
<p>Questions:</p>
<ul>
<li>I had to introduce more <code>Any</code>s, in <code>check</code> in particular. Is there some way to specify that it's coming from a product type where each entry is a subtype of <code>Eq[_]</code>? Should one attempt to tighten some other types?</li>
<li>Is there anything else that could be shortened or simplified using the API methods?</li>
<li>Is <code>p.asInstanceOf[Product]</code> actually safe? Or should there be some additional conversion step that transforms the type <code>T</code> into <code>Product</code>?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T14:53:09.700",
"Id": "512862",
"Score": "0",
"body": "I think `p.asInstanceOf[Product]` is safe, since there wouldn't be a given `Mirror.ProductOf[T]` otherwise. Also, it looks like casting is unavoidable for `eqSum`, although you might want to make these methods private."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-19T23:26:05.597",
"Id": "259742",
"Score": "2",
"Tags": [
"scala"
],
"Title": "Scala 3 Typeclass derivation using low-level mechanisms: The `Eq`-example"
}
|
259742
|
<h3>Exercise 1</h3>
<p>Please implement code and data structures that read the files:</p>
<ul>
<li><code>src/test/java/resources/people.csv</code></li>
<li><code>src/test/java/resources/relationships.csv</code></li>
</ul>
<p>and use them to build an in-memory data structure that represents the people in the file and their relationships with each other.</p>
<h3>Exercise 2 - Validate correct people loaded</h3>
<p>Write a test to validate that you have loaded the expected number of people.</p>
<h3>Exercise 3 - Validate correct relationships loaded</h3>
<p>Write a test to validate that the following people have the correct expected number of connections to other people</p>
<ul>
<li>Bob (4 relationships)</li>
<li>Jenny (3 relationships)</li>
<li>Nigel (2 relationships)</li>
<li>Alan (0 relationships)</li>
</ul>
<h3>Exercise 4 - Write a method that calculates the size of the extended family</h3>
<p>Write a method which, when passed the object representing a particular person, returns an int representing the size of their extended family including themselves. Their extended family includes anyone connected to them by a chain of family relationships of any length, so your solution will need to work for arbitrarily deep extended families. It should not count their friends. Write tests that validate this returns the correct result for the families of:</p>
<ul>
<li>Jenny (4 family members)</li>
<li>Bob (4 family members)</li>
</ul>
<h2>Solution</h2>
<pre><code> package com.graph;
import java.util.ArrayList;
import java.util.List;
public class People {
private String name;
private String email;
private int age;
boolean visited = false;
private List<Relatives> relations = new ArrayList<>();
public People(String name, String email, int age) {
this.name = name;
this.email = email;
this.age = age;
}
public int getRelationShipCount() {
return this.relations.size();
}
public void addRelationShip(People people, String relationShip) {
if (this.getRelationShipCount() > 0) {
this.getRelations().forEach(rel -> {
// if user already in the relationship list then don't add the user in the
// relations
if (rel.getPerson().getEmail().equals(people.getEmail())) {
return;
}
});
}
Relatives newRelationShip = new Relatives(Relation.valueOf(relationShip), people);
this.relations.add(newRelationShip);
// Relation is bi-directional so add this to the relation of person
newRelationShip = new Relatives(Relation.valueOf(relationShip), this);
people.getRelations().add(newRelationShip);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Relatives> getRelations() {
return relations;
}
public void setRelations(List<Relatives> relations) {
this.relations = relations;
}
public boolean isVisited() {
return visited;
}
public void setVisited(boolean visited) {
this.visited = visited;
}
@Override
public String toString() {
return "name: " + this.getName() + " email: " + this.getEmail() + " age: " + this.getAge();
}
}
package com.graph;
public enum Relation {
FAMILY,
FRIEND
}
package com.graph;
public class Relatives {
private Relation relationShip;
private People person;
public Relatives(Relation relationShip, People person) {
super();
this.relationShip = relationShip;
this.person = person;
}
public Relation getRelationShip() {
return relationShip;
}
public void setRelationShip(Relation relationShip) {
this.relationShip = relationShip;
}
public People getPerson() {
return person;
}
public void setPerson(People person) {
this.person = person;
}
}
package com.graph;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class ReadPersonAndRelationship {
public List<People> getAllPeople() {
List<People> peopleList = new ArrayList<>();
try (FileReader fr = new FileReader("src/test/resources/people.csv");
BufferedReader br = new BufferedReader(fr);) {
// read line by line
String line;
while ((line = br.readLine()) != null) {
String[] peoples = line.split(",");
People p = new People(peoples[0], peoples[1], Integer.valueOf(peoples[2]));
peopleList.add(p);
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
return peopleList;
}
public List<Relatives> getAllPeopleRelationShip(List<People> listPeople) {
List<Relatives> relationshipsList = new ArrayList<>();
try (FileReader fr = new FileReader("src/test/resources/relationships.csv");
BufferedReader br = new BufferedReader(fr);) {
// read line by line
String line;
while ((line = br.readLine()) != null) {
if (line.trim().length() == 0) {
continue; // Skip blank lines
}
String[] rr = line.split(",");
People currentPerson = getPersonByEmail(listPeople, rr[0]);
People nextPerson = getPersonByEmail(listPeople, rr[2]);
if (null != nextPerson && null != currentPerson) {
currentPerson.addRelationShip(nextPerson, rr[1]);
}
}
} catch (IOException e) {
System.err.format("IOException: %s%n", e);
}
return relationshipsList;
}
private People getPersonByEmail(List<People> peopleList, String email) {
List<People> listPeople = peopleList.stream().filter(people -> people.getEmail().equals(email))
.collect(Collectors.toList());
if (null != listPeople && !listPeople.isEmpty()) {
return listPeople.get(0);
}
return null;
}
public static void main(String[] args) throws IOException {
ReadPersonAndRelationship r = new ReadPersonAndRelationship();
List<People> allPeople = r.getAllPeople();
System.out.println(allPeople.toString());
allPeople.forEach(people -> {
System.out.println(r.getRelationShipCount(people.getName()));
System.out.println(people.getName() + " : " + r.getExtendedFamilyCount(people.getName()));
});
}
public int getRelationShipCount(String name) {
List<People> peopleList = getAllPeople();
getAllPeopleRelationShip(peopleList);
// should be based on the unique key as email
List<People> peoples = peopleList.stream().filter(people -> people.getName().equalsIgnoreCase(name))
.collect(Collectors.toList());
if (null == peoples || peoples.size() > 1 || peoples.isEmpty()) {
return 0;
}
return peoples.get(0).getRelationShipCount();
}
public int getExtendedFamilyCount(String name) {
List<People> peopleList = getAllPeople();
getAllPeopleRelationShip(peopleList);
Deque<People> stack = new LinkedList<>();
People start = peopleList.stream().filter(people -> people.getName().equalsIgnoreCase(name))
.collect(Collectors.toList()).get(0);
if (null != start) {
stack.push(start);
start.setVisited(true);
}
int extendedFamilyCount = 0;
while (!stack.isEmpty()) {
People poped = stack.pop();
extendedFamilyCount++;
poped.getRelations().forEach(rel -> {
if (!rel.getPerson().isVisited() && rel.getRelationShip().equals(Relation.FAMILY)) {
stack.push(rel.getPerson());
rel.getPerson().setVisited(true);
}
});
}
return extendedFamilyCount;
}
}
</code></pre>
<h2>Files</h2>
<h3>People.csv</h3>
<pre><code>Bob,bob@example.com,31
Derek,derek@example.com,25
Anna,anna@example.com,25
Jenny,jenny@example.com,52
Pete,pete@example.com,57
Kerry,kerry@example.org,29
Joe,joe@example.net,28
Nigel,nigel@example.com,40
Amber,amber@example.com,12
Finn,finn@example.com,15
Alan,alan@example.org,23
Dave,dave@example.com,49
.....................................
</code></pre>
<h3>relationships.csv</h3>
<pre><code>bob@example.com,FAMILY,finn@example.com
bob@example.com,FAMILY,amber@example.com
bob@example.com,FAMILY,anna@example.com
anna@example.com,FAMILY,finn@example.com
anna@example.com,FAMILY,amber@example.com
amber@example.com,FAMILY,finn@example.com
anna@example.com,FRIEND,jenny@example.com
jenny@example.com,FAMILY,pete@example.com
jenny@example.com,FAMILY,kerry@example.org
pete@example.com,FAMILY,kerry@example.org
dave@example.com,FAMILY,pete@example.com
kerry@example.org,FRIEND,joe@example.net
joe@example.net,FAMILY,nigel@example.com
nigel@example.com,FRIEND,derek@example.com
derek@example.com,FRIEND,bob@example.com
derek@example.com,FRIEND,pete@example.com
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T08:01:20.880",
"Id": "512413",
"Score": "1",
"body": "Welcome to Code Review, please divide the code in separated classes to improve readibility of your question. You used `kotlin` and `gradle` tags, are these tags really necessary?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T08:14:54.087",
"Id": "512418",
"Score": "0",
"body": "Yes, I used kotlin plugin. kotlin(\"jvm\") version \"1.3.21\"\nand Gradle to build it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T10:06:48.770",
"Id": "512433",
"Score": "1",
"body": "You might have used `kotlin(\"jvm\")` and Gradle to build it, but I don't see any traces of either Kotlin or Gradle in the code so I'm removing those tags. This is Java code, not Kotlin. And just because you're using Gradle doesn't mean that your code is *about* Gradle."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T04:44:57.037",
"Id": "512520",
"Score": "1",
"body": "Please note that the \"example.com\" domain is reserved for the sole purpose of allowing you to create addresses for testing purposes that are guaranteed to not exist in real life. Please do not create random e-mail addresses with valid domain name like gmail.com because you will either accidentally e-mail to them or you will publish them and they will end up on spam lists. This will be a major annoyment to the people who own those addresses and do not want unsolicited e-mails. (I have edited the question to hide the addresses)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T06:18:16.883",
"Id": "512523",
"Score": "0",
"body": "Hi @TorbenPutkonen : http://example.com/,https://example.com/ is not a valid domain"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T07:22:18.877",
"Id": "512527",
"Score": "1",
"body": "@RaushanKumar Yes, that is the point. You can safely use it in tests and be sure that it does not represent anything that occurs in real life."
}
] |
[
{
"body": "<p>Nice implementation, find below my suggestions.</p>\n<hr />\n<blockquote>\n<p>Exercise 1 Please implement code and data structures that read the\nfiles</p>\n</blockquote>\n<p>The data structure (that represents the graph) in your implementation is <code>List<People></code>, which is a bit confusing. Creating a class <code>Graph</code> to hold and manage the people would be more appropriate in my opinion.</p>\n<hr />\n<blockquote>\n<p>Exercise 2 - Validate correct people loaded</p>\n</blockquote>\n<pre><code>ReadPersonAndRelationship r = new ReadPersonAndRelationship();\nList<People> allPeople = r.getAllPeople();\nSystem.out.println(allPeople.toString());\n</code></pre>\n<p>This is one way to test. However, it's hard to know how many people are in the list. It prints a long line to the console and we need to count manually the people to see if they are 12 (like in the file). If there are more people, it would be unfeasible.</p>\n<p>In Java, you can use <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">Junit</a> to unit test the code. For example:</p>\n<pre><code>@Test\npublic void testGetAllPeople() {\n ReadPersonAndRelationship r = new ReadPersonAndRelationship();\n\n List<People> allPeople = r.getAllPeople();\n\n assertEquals(12, allPeople.size());\n}\n</code></pre>\n<p>Running this test will immediately tell if the 12 people in the file are actually in the list.</p>\n<hr />\n<blockquote>\n<p>Exercise 3 - Validate correct relationships loaded</p>\n</blockquote>\n<blockquote>\n<p>Exercise 4 - Write a method that calculates the size of the extended\nfamily</p>\n</blockquote>\n<pre><code>allPeople.forEach(people -> {\n System.out.println(r.getRelationShipCount(people.getName()));\n System.out.println(people.getName() + " : " + r.getExtendedFamilyCount(people.getName()));\n});\n</code></pre>\n<p>Similarly, instead of printing the result to the console, two more tests can be created. One example for testing <code>getRelationShipCount</code>:</p>\n<pre><code>@Test\npublic void testGetRelationshipCount() {\n ReadPersonAndRelationship r = new ReadPersonAndRelationship();\n\n int bobRelationshipsCount = r.getRelationShipCount("Bob");\n int jennyRelationshipsCount = r.getRelationShipCount("Jenny");\n\n assertEquals(4, bobRelationshipsCount);\n assertEquals(3, jennyRelationshipsCount);\n}\n</code></pre>\n<h2>Responsibility</h2>\n<p>The class <code>ReadPersonAndRelationship</code> seems to have a lot of responsibility. Besides reading the files, it goes through the "graph" and returns statistics like the relationships count and the extended family count for a person. This logic should be delegated to another class, perhaps to a class <code>Graph</code> that I mentioned earlier.</p>\n<h2>Performance</h2>\n<p>The methods <code>getRelationShipCount</code> and <code>getExtendedFamilyCount</code> need to read the file every time. In your <code>main</code> method:</p>\n<pre><code> allPeople.forEach(people -> {\n System.out.println(r.getRelationShipCount(people.getName()));\n System.out.println(people.getName() + " : " + r.getExtendedFamilyCount(people.getName()));\n });\n</code></pre>\n<p>Because there are 12 people, this part reads the file <code>people.csv</code> <strong>24 times</strong>. And the file <code>relationships.csv</code> <strong>12 times</strong>.</p>\n<p>Consider this workflow:</p>\n<ol>\n<li>Read the files once and create a graph</li>\n<li>Call the methods on the graph (which works on the people in memory)</li>\n</ol>\n<h2>Naming</h2>\n<p>The class <code>People</code> should be <code>Person</code> since it stores the information for only one person. Same for the class <code>Relatives</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T08:56:07.433",
"Id": "512421",
"Score": "1",
"body": "Thank you for your suggestion @Marc"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T08:43:25.150",
"Id": "259750",
"ParentId": "259746",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T04:06:38.427",
"Id": "259746",
"Score": "1",
"Tags": [
"java"
],
"Title": "Building a graph of people, and their relationships with each other"
}
|
259746
|
<p>In a few hours I threw together this little text-based java game. Pretty much you're managing a forest and have to try and keep it together while keeping enough of a profit to move forward.</p>
<pre class="lang-java prettyprint-override"><code>package com.company;
import java.util.Arrays;
import java.util.Scanner;
import java.util.concurrent.ThreadLocalRandom;
import static java.lang.Integer.parseInt;
public class Main {
static int gold = 60, trees = 15, unr_trees = 0, r_trees = 0, fertilizer = 1, animal_protection = 0;
static int refinesLeftThisTurn;
static int turn = 1, actionsUsedThisTurn = 0;
static int wildlifeProtection;
public static void main(String[] args) {
cls();
System.out.println("Treemnger:\n\n");
game();
}
public static void game() {
boolean endCommand = false;
Scanner s = new Scanner(System.in);
while (true) {
endCommand = false;
refinesLeftThisTurn = 10;
actionsUsedThisTurn = 0;
System.out.println("Turn: " + turn);
System.out.println("\n");
while (!endCommand) {
System.out.println("Enter a command (type 'help' for list)");
String commandEntered = s.nextLine();
String[] splitCommand = commandEntered.split(" ");
String command = splitCommand[0];
String[] subcommands = Arrays.copyOfRange(splitCommand, 1, commandEntered.length());
switch (command.toLowerCase()) {
case "help":
System.out.println("Commands: 'help', 'resources', 'chop', 'sell', 'refine', 'buy', 'use', 'clear', 'end'");
endCommand = false;
break;
case "resources":
printResources();
endCommand = false;
break;
case "chop":
if (subcommands[0] != null) {
if (trees - parseInt(subcommands[0]) >= 0) {
trees -= parseInt(subcommands[0]);
unr_trees += parseInt(subcommands[0]);
if (rng(1, 30) == 1) {
System.out.println("Lucky! You got 5 extra wood!");
unr_trees += 5;
}
} else {
System.out.println("You need more trees!");
break;
}
} else {
System.out.println("Please provide number of trees to be cut, e.g. 'chop 3'.");
break;
}
endCommand = false;
actionsUsedThisTurn++;
break;
case "sell":
if (subcommands[0] == null) {
System.out.println("Please provide the type of wood to sell!");
break;
}
if (subcommands[1] == null || NotIntString(subcommands[1])) {
System.out.println("Please provide the amount of wood to sell!");
break;
}
switch (subcommands[0]) {
case "unrefined":
if (unr_trees - parseInt(subcommands[1]) >= 0) {
unr_trees -= parseInt(subcommands[1]);
gold += rng(4, 6) * parseInt(subcommands[1]);
} else {
System.out.println("You need more unrefined logs!");
}
break;
case "refined":
if (r_trees - parseInt(subcommands[1]) >= 0) {
r_trees -= parseInt(subcommands[1]);
gold += rng(13, 17) * parseInt(subcommands[1]);
} else {
System.out.println("You need more refined logs!");
}
break;
default:
System.out.println("Please specify either 'unrefined' or 'refined' logs.");
break;
}
actionsUsedThisTurn++;
break;
case "refine":
if (refinesLeftThisTurn < 0) {
System.out.println("You cannot refine any more times this turn! Wait till next turn to regain your 10 refines!");
}
if (subcommands[0] == null) {
System.out.println("Please provide the amount of wood to refine!");
break;
}
if (unr_trees - parseInt(subcommands[0]) >= 0 || gold - (parseInt(subcommands[0]) * 5) >= 0) {
unr_trees -= parseInt(subcommands[0]);
r_trees += parseInt(subcommands[0]);
gold -= parseInt(subcommands[0]) * 5;
refinesLeftThisTurn -= parseInt(subcommands[0]);
}
actionsUsedThisTurn++;
break;
case "buy":
if (subcommands[0] == null) {
System.out.println("Please provide what you would like to buy!");
break;
}
if (subcommands[1] == null || NotIntString(subcommands[1])) {
System.out.println("Please provide the amount you would like to buy!");
break;
}
switch (subcommands[0]) {
case "fertilizer":
if ((gold - parseInt(subcommands[1])) * 50 >= 0) {
fertilizer += parseInt(subcommands[1]);
gold -= parseInt(subcommands[1]) * 50;
if (rng(1, 20) == 1) {
System.out.println("Lucky! You got 2 extra fertilizer!");
fertilizer += 2;
}
}
break;
case "wildlifeprotection":
if ((gold - parseInt(subcommands[1])) * 50 >= 0) {
animal_protection += parseInt(subcommands[1]);
gold -= parseInt(subcommands[1]) * 40;
break;
}
default:
System.out.println("Please specify either 'fertilizer' or 'wildlifeprotection'");
break;
}
actionsUsedThisTurn++;
break;
case "use":
if (subcommands[0] == null) {
System.out.println("Please provide what you would like to use!");
break;
}
if (subcommands[1] == null || NotIntString(subcommands[1])) {
System.out.println("Please provide how many of that item you would like to use!");
break;
}
switch (subcommands[0]) {
case "fertilizer":
if (fertilizer - parseInt(subcommands[1]) >= 0) {
fertilizer -= parseInt(subcommands[1]);
trees += rng(2, 4);
if (rng(1, 10) == 1) {
System.out.println("Lucky you! You get 5 extra trees!");
trees += 5;
}
} else {
System.out.println("You need more fertilizer!");
}
break;
case "wildlifeprotection":
if (animal_protection - parseInt(subcommands[1]) >= 0) {
animal_protection -= parseInt(subcommands[1]);
wildlifeProtection++;
} else {
System.out.println("You need more wildlife protection!");
}
break;
default:
System.out.println("Please specify either 'fertilizer' or 'wildlifeprotection'");
}
actionsUsedThisTurn++;
break;
case "clear":
cls();
break;
case "end":
cls();
System.out.println("Thank's for playing!");
System.exit(0);
default:
System.out.println("Invalid command!");
break;
}
if (actionsUsedThisTurn >= 5) {
turn++;
endCommand = true;
}
}
if (wildlifeProtection == 0) {
trees -= rng(2, 4);
}
if (trees < 0) {
cls();
System.out.println("You lost, making it to " + turn + " turns! Make it longer next time!");
System.exit(0);
}
}
}
public static void cls() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
public static void printResources() {
String s = "Trees: " +
trees +
"\nGold: " +
gold +
"\n\nUnrefined Trees: " +
unr_trees +
"\nRefined Trees: " +
r_trees +
"\n\nFertilizer: " +
fertilizer +
"\nAnimal Protection: " +
animal_protection;
System.out.println(s);
}
private static boolean NotIntString(String string) {
try {
parseInt(string);
return false;
} catch (NumberFormatException e) {
return true;
}
}
private static int rng(int min, int max) {
return ThreadLocalRandom.current().nextInt(min, max + 1);
}
}
</code></pre>
<p><a href="https://github.com/CATboardBETA/treemngr" rel="nofollow noreferrer">GitHub</a></p>
|
[] |
[
{
"body": "<ul>\n<li>naming should be consistent, choose either snake case or camel case, but not both.</li>\n<li>variables/fields should be declared one per line.</li>\n<li>all the fields should be <code>private</code></li>\n<li>name methods in a more meaningful way and do not shorten their names (for example, <code>rng</code> -> <code>randomInt</code> and <code>cls</code> -> <code>clearScreen</code>)</li>\n<li>Using <code>System.exit(0)</code> is bad practice, you should use a condition in your main loop, like <code>while(playing) {...}</code> to exit it properly.</li>\n<li><code>game()</code> is too big and unreadable, consider splitting it into multiple methods. Having separate methods for commands is a good start.</li>\n<li>you have a method to check if string is an integer, but in some places you just parse using <code>parseInt</code> without any validation</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T10:12:23.793",
"Id": "259789",
"ParentId": "259747",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T04:27:58.770",
"Id": "259747",
"Score": "4",
"Tags": [
"java",
"game"
],
"Title": "Basic java text-based management game"
}
|
259747
|
<p>I am writing an API function using Django Rest Framework where it accesses many resources like AWS, Database, External APIs etc., I want the API execution to stop if it fails in any of the steps and return an appropriate response.</p>
<p>I initially used ValueError to raise exceptions manually when something failed, but this resulted in traceback being printed in logs for manually raised exceptions, and the logs became messy.</p>
<p>Later, I used separate except statement for "ValueError" and "Exception" but this led to traceback not being printed for naturally occuring (not manually raised) exceptions and debugging them were hard.</p>
<p>So I created a custom exception which takes an error code, and an error message like below.</p>
<pre><code>class CustomException(Exception):
def __init__(self, status, msg):
self.status = status
self.message = msg
super().__init__(self.message + ': ' + str(self.status))
def __str__(self):
return 'ErrorCode: ' + str(self.status) + ' ErrorMessage:' + str(self.message)
</code></pre>
<p>And I came up with the below code structure for the API function,</p>
<pre><code>def place_order(request):
err_msg = 'Problem in placing order. Please contact us'
try:
response = get_product_details_from_db()
if response.status == 0:
err_msg = 'Failed to get product details from DB'
raise CustomException(0, err_msg)
# Do something...
response = access_aws_s3_files()
if response.status == 0:
err_msg = 'Failed trying to access s3'
raise CustomException(0, err_msg)
# Do something...
response = call_external_api()
if response.status == 0:
err_msg = 'Failed in accessing external API'
raise CustomException(0, err_msg)
# Do something...
response_data = {
'status': 1,
'order_id': '1235'
}
except CustomException as e:
response_data = {
'status': e.status,
'error_message': e.message
}
except Exception as e:
traceback.print_exc()
print(e)
response_data = {
'status': 0,
'error_message': err_msg
}
return Response(data=json.dumps(response_data), status=status.HTTP_200_OK)
</code></pre>
<p>Is this the standard way of handling such things? Is there any better/alternative way we can handle this ?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T07:11:10.903",
"Id": "259749",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"error-handling",
"django"
],
"Title": "Stop Django Rest Framework API execution and return appropriate response"
}
|
259749
|
<p>I'm working on a simple method that would censor emails (GPDR stuff) so they won't show the full name of a user, with 1st character, optional dot, 1st character after the dot and whatever is left after the @ to be left uncensored. So, the intent is like this:</p>
<p>Email to be censored: <code>name.lastname@email.com</code></p>
<p>Desired effect: <code>n***.l*******@email.com</code></p>
<p>I've written this:</p>
<pre><code>public static String getCensoredUsername(String username) {
if (username.contains("@")) {
char[] chars = username.toCharArray();
for (int i = 1; i < chars.length; i++) {
boolean isCurrentCharacterADot = chars[i] == '.';
boolean isPreviousCharacterADot = chars[i - 1] == '.';
if (chars[i] == '@') {
break;
}
if (chars[i] == '.') {
chars[i] = '.';
} else if (!isCurrentCharacterADot && !isPreviousCharacterADot) {
chars[i] = '*';
}
}
return String.valueOf(chars);
}
return username;
}
</code></pre>
<p>It feels to me very Java 6. What would make it look better?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T13:06:02.383",
"Id": "512447",
"Score": "1",
"body": "Please take into account that here on Code Review answers won't come as quick as on [SO], hence you should really wait at least a day before you accept an answer althought it is mine ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T13:20:23.903",
"Id": "512448",
"Score": "0",
"body": "ok, noted. thank you for your help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T13:22:00.430",
"Id": "512449",
"Score": "0",
"body": "Feel free to unaccept my answer this could help to get more answers which may be better as well."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T04:33:01.977",
"Id": "512518",
"Score": "0",
"body": "I get the feeling that you're hiding information but you want to retain some information in them so that the addresses can still be identified. This doesn't seem to comply with GDPR too well. If you want to protect privacy, just replace the shown e-mail addresses with an UUID and keep the e-mail -> UUID mapping in a protected database. As Fabio F. showed, your approach fails with common e-mail addresses leaving you vulnerable to GDPR violations so that too speaks against \"e-mail address sanitation.\" (Instead of UUID you can use any shorter non-reversible and non-guessable random unique token.)"
}
] |
[
{
"body": "<p>Just a few remarks....</p>\n<ul>\n<li>if <code>username</code> doesn't contain a <code>@</code> the code should return early which saves one level of indentation.</li>\n<li>The condition <code>if (chars[i] == '.')</code> should better be <code>if (isCurrentCharacterADot)</code> but you could omit this as well because you won't need to assign anything to <code>chars[i]</code> if it is a dot.</li>\n</ul>\n<p>This could look like so</p>\n<pre><code>public static String getCensoredUsername(String username) {\n if (!username.contains("@")) { return username; }\n\n char[] chars = username.toCharArray();\n for (int i = 1; i < chars.length; i++) {\n boolean isCurrentCharacterADot = chars[i] == '.';\n boolean isPreviousCharacterADot = chars[i - 1] == '.';\n\n if (chars[i] == '@') {\n break;\n }\n else if (!isCurrentCharacterADot && !isPreviousCharacterADot) {\n chars[i] = '*';\n }\n }\n return String.valueOf(chars);\n}\n</code></pre>\n<p>As a side note, because this is a <code>public</code> method there should be some parameter-validation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T12:17:25.830",
"Id": "259757",
"ParentId": "259756",
"Score": "3"
}
},
{
"body": "<p>There is nothing wrong about being "too Java 6"!</p>\n<p>First few notes about naming and naming convention:</p>\n<ol>\n<li><code>username</code> is, in fact, the email, so should be <code>email</code></li>\n<li><code>getCensoredUsername</code> for the same reason should be <code>getCensoredEmail</code> <strong>but</strong> in Java <code>get</code>, by convention, is used only for getter or when you're applying very little logic; thus is better to use an "action-subject" type of name like <code>censorEmail</code></li>\n<li>Being Java a type language, calling a variable <code>chars</code> is not helpful, that should be <code>emailChars</code> or even just <code>email</code> if that is not colliding with other variables, the compiler will tell you the type.</li>\n</ol>\n<p>Biggest problem though, is the data validation, you should check at least that email is not <code>null</code>.</p>\n<p>Normally you would check that the email is "valid" but if you take a look at the <a href=\"https://en.wikipedia.org/wiki/Email_address#Examples\" rel=\"noreferrer\">email syntax</a> you might notice that's almost impossible to do it without writing a formal parser (or using some library). So let's say we want just censor the "reasonably valid" emails.</p>\n<p>Your approach to go char by char in the username part is not very flexible: what if tomorrow you want to have <code>f****o.f*****i@gmail.com?</code> You need to add other flags, and wouldn't be very enjoyable.</p>\n<p>I suggest you to start from the censor method and build bottom up from that.</p>\n<p>Here is my solution</p>\n<pre><code> public static String hideLastChars(String name) {\n Objects.requireNonNull(name, "String should not be null");\n if (name.length() <= 1) {\n return name;\n } else {\n return name.charAt(0) + IntStream.range(1, name.length()).mapToObj(i -> "*").collect(Collectors.joining());\n }\n }\n</code></pre>\n<p>Now that we have our "logic" we need to do a bit of input validation.</p>\n<pre><code> public static String censorEmail(String email) {\n Objects.requireNonNull(email, "Email should not be null");\n String[] splitEmail = email.split("@");\n if (splitEmail.length > 1 && splitEmail[0].length() > 0) {\n return censorUsername(splitEmail[0]) + "@" + splitEmail[1];\n }\n throw new IllegalArgumentException("Please provide a valid email");\n }\n</code></pre>\n<p>Now we know that the email is not null, it does contain a '@' and user is there.\nWe just need to apply our <code>hideLastChars</code> to each piece.</p>\n<p>We have a little problem here because if you just split on each <code>.</code> you will end up losing trailing dots, for example in an email like <code>john.doe....@gmail.com</code>.\nA solution is to use <a href=\"https://stackoverflow.com/questions/2206378/how-to-split-a-string-but-also-keep-the-delimiters\">Lookahead regexp</a> to split on each <code>.</code> but keeping it in the split result, this is the regexp: <code>((?<=\\.)|(?=\\.))</code>, for example <code>"john.doe...".split("((?<=\\.)|(?=\\.))")</code> will return <code>{ "john", ".", "doe", ".", ".", "." }</code></p>\n<p>Now we know how to map each piece and how to extract it.</p>\n<pre><code> private static String censorUsername(String username) {\n return Arrays\n .stream(username.split("((?<=\\\\.)|(?=\\\\.))"))\n .map(scratch_1::hideLastChars)\n .collect(Collectors.joining(""));\n }\n</code></pre>\n<p>I suggest you to create a unit test to test the logic so every time you find a new email that creates problem you can add in the test and see what happens (What about <code>p.g@curry.com</code>?).\nI've run few examples using your code and mine. Here's the result</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>INPUT</th>\n<th>ORIGINAL</th>\n<th>REVIEWED</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code>name.surname@gmail.com</code></td>\n<td><code>n***.s******@gmail.com</code></td>\n<td><code>n***.s******@gmail.com</code></td>\n</tr>\n<tr>\n<td><code>name.surname.p99@gmail.com</code></td>\n<td><code>n***.s******.p**@gmail.com</code></td>\n<td><code>n***.s******.p**@gmail.com</code></td>\n</tr>\n<tr>\n<td><code>name.surname.p99.@gmail.com</code></td>\n<td><code>n***.s******.p**.@gmail.com</code></td>\n<td><code>n***.s******.p**.@gmail.com</code></td>\n</tr>\n<tr>\n<td><code>@gmail.com</code></td>\n<td><code>@*****.c**</code></td>\n<td><code>Exception: Please provide a valid email</code></td>\n</tr>\n<tr>\n<td><code>user.com</code></td>\n<td><code>user.com</code></td>\n<td><code>Exception: Please provide a valid email</code></td>\n</tr>\n<tr>\n<td><code>user%example.com@example.org</code></td>\n<td><code>u***********.c**@example.org</code></td>\n<td><code>u***********.c**@example.org</code></td>\n</tr>\n<tr>\n<td><code>"john..doe..."@example.org</code></td>\n<td><code>"****..d**..."@example.org</code></td>\n<td><code>"****..d**..."@example.org</code></td>\n</tr>\n<tr>\n<td><code>" "@example.org</code></td>\n<td><code>"**@example.org</code></td>\n<td><code>"**@example.org</code></td>\n</tr>\n<tr>\n<td><code>null</code></td>\n<td><code>Exception: Cannot invoke "String.contains(java.lang.CharSequence)" because "username" is null</code></td>\n<td><code>Exception: Email should not be null</code></td>\n</tr>\n<tr>\n<td><code>...p...g...@gmail.com</code></td>\n<td><code>...p...g...@gmail.com</code></td>\n<td><code>...p...g...@gmail.com</code></td>\n</tr>\n<tr>\n<td><code>p.g@curryfication.com</code></td>\n<td><code>p.g@curryfication.com</code></td>\n<td><code>p.g@curryfication.com</code></td>\n</tr>\n</tbody>\n</table>\n</div>",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T04:39:03.750",
"Id": "512519",
"Score": "2",
"body": "The \"p.g@example.com\" is a great example of how this approach is not going to work too well in practise. The sanitation scheme also leaves unique addresses fully exposed. I know people who own theirown domains and have \"firstname@lastname.tld\" addresses. Removing the first name does not make the address any less unique."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T18:43:18.700",
"Id": "259770",
"ParentId": "259756",
"Score": "7"
}
},
{
"body": "<p>If <code>username</code> is not an email, <code>getCensoredUsername(username)</code> does nothing, which is a little bit confusing.</p>\n<p>Two possible approaches:</p>\n<ol>\n<li>Call the method <code>censorLocalPart(String email)</code> and use it only if the username is an email. (this suggestion is on the lines of @Fabio F.'s review)</li>\n<li>Add a comment (or Javadoc) to specify that a username will be censored only if it is an email.</li>\n</ol>\n<p>An alternative is to use <a href=\"https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)\" rel=\"nofollow noreferrer\">replaceAll</a> with a regex:</p>\n<pre><code>public static String censorUsername(String username){\n return username.replaceAll("(?<=[^\\\\.])[^\\\\.](?=.*@)","*");\n}\n</code></pre>\n<p><a href=\"https://regex101.com/r/yVbaKH/1\" rel=\"nofollow noreferrer\">Regex demo</a></p>\n<p>A brief explanation of the regex:</p>\n<ul>\n<li><code>(?<=[^\\.])</code>: lookbehind for a character that is not <code>.</code></li>\n<li><code>[^\\.]</code>: match a character that is not <code>.</code></li>\n<li><code>(?=.*@)</code>: make sure that there is an <code>@</code> on the right. This is to exclude the domain of the email and usernames that are not emails.</li>\n</ul>\n<p>Some tests (borrowed from @Fabio F.):</p>\n<pre><code>@Test\npublic void testCensorUsername() {\n assertEquals("simpleUsername", censorUsername("simpleUsername"));\n assertEquals("n***.s******@gmail.com", censorUsername("name.surname@gmail.com"));\n assertEquals("n***.s******.p**@gmail.com", censorUsername("name.surname.p99@gmail.com"));\n assertEquals("n***.s******.p**.@gmail.com", censorUsername("name.surname.p99.@gmail.com"));\n assertEquals("u***********.c**@example.org", censorUsername("user%example.com@example.org"));\n assertEquals("\\"****..d**...\\"@example.org", censorUsername("\\"john..doe...\\"@example.org"));\n assertEquals("p.g@test.com", censorUsername("p.g@test.com"));\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T08:21:51.067",
"Id": "259786",
"ParentId": "259756",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259757",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T11:43:13.610",
"Id": "259756",
"Score": "4",
"Tags": [
"java",
"strings"
],
"Title": "Censoring emails in Java"
}
|
259756
|
<p>I want to write the test case for Service class.</p>
<p>My Service Class dynamic-form.service.ts</p>
<pre><code>import { HttpClient, HttpBackend } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class DynamicFormService {
private http: HttpClient;
constructor(private handler: HttpBackend
) {
this.http = new HttpClient(handler);
}
async getDynamicFormData(paramName: any, data?: any): Promise<any> {
return await this.http.get(this.HostUrl + paramName).toPromise();
}
async getTaskByWorkflowId(paramNameWithId): Promise<any> {
return await this.http.get(this.HostUrl + paramNameWithId).toPromise();
}
async getAccontType(paramNameWithId): Promise<any> {
return await this.http.get(this.HostUrl + paramNameWithId).toPromise();
}
}
</code></pre>
<p>My dynamic-form.spec.ts are as follows</p>
<pre><code>import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { TestBed} from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { of } from 'rxjs';
import { DynamicFormServiceService } from './dynamic-form-service.service';
describe('DynamicFormServiceService', () => {
let service: DynamicFormServiceService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [HttpClientTestingModule, RouterTestingModule.withRoutes([])]
});
service = TestBed.inject(DynamicFormServiceService);
httpMock= TestBed.inject(HttpTestingController);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});
</code></pre>
<p>I have written one of service method test case as follows</p>
<pre><code>it('should call getAccontType', ()=>{
const data = [
{
"id": 4,
"name": "24hrs"
},
{
"id": 5,
"name": "48hrs"
}];
service.getAccontType(`account-type`).then(res=> expect(res.length).toBeGreaterThan(0));
const request = httpMock.expectOne(`http://localhost:8080/account-type`);
expect(request.request.method).toBe('GET');
request.flush(data);
httpMock.verify();
});
</code></pre>
<p>I want to know it is good way to write test-case this way or I can do better. Any suggestion.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T15:29:11.820",
"Id": "512455",
"Score": "0",
"body": "Welcome to the Code Review Community. What we do here is review working code from one of your projects and make suggestions about how to improve the code. `I want to know it is good way to write test-case this way or I can do better.` is difficult to answer. Before you post a question here, the code should be working and getting the expected answers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:17:51.973",
"Id": "512479",
"Score": "0",
"body": "To add: https://codereview.stackexchange.com/help/on-topic"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T04:00:41.007",
"Id": "512517",
"Score": "0",
"body": "My Test case is running fine. I want my code-coverage to be good."
}
] |
[
{
"body": "<p>Personally i would create an interface for the expected data from the backend. <code>any</code> is something i try to avoid, because then my IDE can´t help me finding my stupid mistakes.</p>\n<p>For example</p>\n<pre><code>interface DynamicFormData {\n aValue: string,\n anotherValue: number,\n}\n\nasync getDynamicFormData(paramName: string, data?: SomeDataType): Promise<DynamicFormData > {\n return await this.http.get(this.HostUrl + paramName).toPromise();\n}\n</code></pre>\n<p>It gives you the benefit, that whereever you call that method, the IDE will know how the data will look like and what methods could be performed on it.</p>\n<p>Also personally i like working with RxJS more than Promises, but thats a personal habit. But it allows to filter, modify, do stuff on the response. And i stay away from "async/await", because i do not like blocking tasks in my frontend if i can avoid them. But as i said, personal style.</p>\n<p>About the init of the testcases, why do you need to import the RouterTestingModule? Its not used in the service at all.</p>\n<p>About the test coverage:<br />\nWhen i see a method interface like <code>getDynamicFormData(paramName: any, data?: any)</code> then i would ask myself if "paramName" is mandatory or not. Also test cases are a kind of documentation, therefore i would add a testcase with an empty paramName (for example <code>null</code>).</p>\n<p>From a Unit-testing perspective i would avoid hard coded strings like <code>"account-type"</code>. You will surely use this strings also at other places in the regular code when you want to call the service. If those strings change, you have to find all places where they are used and replace them. Therefore i would create constants for those and us those constants. Then if the API changes ( e.g. <code>"account-type"</code> changes to <code>"type-of-account"</code>) you just have to change it at one place and all (code and unit test) will adept automaticly.</p>\n<p>You specificly asked in the comment for "code-coverage".<br />\nFor that we have to think about what could be the possible results of each method. The Promise could be resolved or fail. Quite easy.</p>\n<p>BUT your service is instantiated with a parameter</p>\n<pre><code>constructor(private handler: HttpBackend) {\n this.http = new HttpClient(handler);\n }\n</code></pre>\n<p>If you do not provide any input (as you do in your unit test), then its instantiated with <code>this.http = new HttpClient();</code>. I always use the HTTPClient provided directly by Angular, therefor i do not really know the effect of this. From the documentation it seems that this would circumvent the interceptors. But be it as it be, as its an input that may alter the behavior of your service, its something that should be covered by your testcases.</p>\n<p>Hope you could use some of the mentioned things. :-)</p>\n<p>warm regards\nJan</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T12:10:32.957",
"Id": "259899",
"ParentId": "259760",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259899",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T12:46:31.993",
"Id": "259760",
"Score": "0",
"Tags": [
"unit-testing",
"typescript",
"angular-2+"
],
"Title": "Unit Test case for services method in angular"
}
|
259760
|
<p>I often come around a requirement where we have to perform a repetitive task on the user's screen (for eg, updating a counter like flash sale/ live class timer, autoscrolling the banner, etc) .
I have written this small file which performs a basic task of pressing a button every 2 seconds for a total of 4 times as a general example and my approach to this problem
Please review and provide your inputs about weather this would be a correct approach or not.</p>
<pre class="lang-kotlin prettyprint-override"><code>class AVCActivity : AppCompatActivity() {
private var scrollInterval = 0
private var run4Times = false
private val handler = Handler()
private var count = 0
override fun onCreate(b:Bundle) {
scrollInterval = 2000
run4Times = api.runRepetitiveTask()
// task will start in onResume
}
override fun onPause() {
super.onPause()
handler.clearStack()
}
override fun onResume() {
super.onResume()
if(run4Times){
handler.clearStack().postDelayed(scrollTask,scrollInterval.toLong())
}
}
private fun Handler.clearStack():Handler{
this.removeCallbacksAndMessages(null)
return this
}
private val scrollTask = object : Runnable{
override fun run() {
if(count < 4){
count + =1
btHello?.performOnClick()
handler.clearStack().postDelayed(this,scrollInterval.toLong())
}
else{
run4Times = false
handler.clearStack()
}
}
}
}
</code></pre>
<hr />
<p>Some details:</p>
<ol>
<li>handler fires the runnable <strong>every 2 seconds via recursion for 3 times</strong> . on the 4th time, the <strong>runnable clears the handler and closes handler recursion</strong></li>
<li><strong>handler gets started in onResume and stopped in onPause</strong> to handle case where user has closed the screen before completion of the original task. <strong>The condition to weather make the handler fire the runnable is handled via a global variable, initialised in onCreate()</strong> .i,e only once .</li>
<li><strong>handler is NOT started in onCreate</strong> because this will cause the handler to run same runnable twice(since onCreate->onResume) . this usually causes a bug where we assume the runnable to run once every 2 seconds, but ends up with 2 runnables running every 2 seconds</li>
<li><strong>every postCall is made after handler.removeCallbacksAndMessages(null)</strong> (via extension function <code>clearStack()</code> ) , thereby removing any unprocessed runnables. this is especially required in a case of onResume() , <strong>since onResume can be called multiple times</strong> and this could lead to same problem as point 3. using this function prevents this case from occurring.</li>
<li><strong>variables like handler and runnable are global</strong> to prevent duplication/re assigning.</li>
<li>i<strong>t is safe to access ui views</strong> in runnable because the handler is going to run the runnable in main thread (my assumption)</li>
</ol>
<hr />
<p>Anything else should i be considering? Is it a good general approach? any memory leaks in this approach?</p>
<p>PS : I think this question might have been asked before, but i am not sure if this has been asked in context to Android/kotlin. Kindly point me to an already asked question with better approach if this is repetitive</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T15:40:42.710",
"Id": "259763",
"Score": "1",
"Tags": [
"multithreading",
"android"
],
"Title": "running a task on UI every x seconds"
}
|
259763
|
<p>My code is working fine...</p>
<p>but I want to remove <strong>below those(1)</strong> lines of code from my <strong>example code(2)</strong> (JS Code). If I remove those code then a tag is not working. (a tag do not open link or href is not working).</p>
<p><strong>Is it a good approach to done it by writing those code? ( if any problem will occur for ajax request for this ) ? & Is there any way to work a tag by removing those line of code ? Please help me.</strong></p>
<p><strong>Wanna Remove Those Code(1)</strong></p>
<pre><code> if (e.target.nextElementSibling == null) {
if (e.target.getAttribute('target') != null) {
window.open(e.target.getAttribute('href'), e.target.getAttribute('target'));
} else {
window.location.href = e.target.getAttribute('href');
}
</code></pre>
<p><strong>Example Code(2)</strong></p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const lists = document.querySelectorAll('.sidenav nav ul ul')
lists.forEach(function (el) {
el.className = 'sub-menu';
el.style.height = 0 + "px";
})
document.querySelectorAll(".sidenav nav ul li a ").forEach(el => el.addEventListener('click', function (e) {
e.preventDefault();
e.stopPropagation();
if (e.target.nextElementSibling == null) {
if (e.target.getAttribute('target') != null) {
window.open(e.target.getAttribute('href'), e.target.getAttribute('target'));
} else {
window.location.href = e.target.getAttribute('href');
}
}
let el = e.target.parentElement.children[1];
let ul = e.target.parentElement.closest('ul');
if (ul) {
ul.querySelectorAll('ul').forEach(function (item) {
item.style.height = 0 + 'px';
})
}
if (typeof el == 'undefined') return;
if (parseInt(getComputedStyle(el).height) > 0) {
el.style.height = 0 + "px";
} else {
el.style.height = el.scrollHeight + "px";
}
return false;
}));</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>*,*::after,*::before{
box-sizing: border-box;
}
html,body{
margin: 0;
padding: 0;
}
nav{
padding: 20px;
height: 4rem;
width: 250px;
}
nav ul {
margin: 0;
padding: 0;
list-style: none;
display: flex;
flex-direction: column;
}
nav ul li {
background: tomato;
width: 100%;
}
nav ul li a{
display: block;
padding: 10px;
text-decoration: none;
}
nav ul ul {
margin-left: 20px;
height: 0;
transition: all .2s ease-in ;
}
nav ul ul li {
width: 100%;
background: aqua;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><aside class="sidenav">
<nav>
<ul>
<li><a href="https://dev.to/">Home</a></li>
<li><a href="">Cat </a>
<ul>
<li><a href="https://dev.to/" >Cat 1</a></li>
<li><a href="https://dev.to/" target="_blank">Cat 1 </a></li>
</ul>
</li>
<li><a href="https://dev.to/">about</a></li>
<li><a href="https://dev.to/">about</a></li>
<li><a href="https://dev.to/">about</a></li>
</ul>
</nav>
</aside></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<pre><code>e.preventDefault();\ne.stopPropagation();\n\nif (e.target.nextElementSibling == null) {\n\n if (e.target.getAttribute('target') != null) {\n window.open(e.target.getAttribute('href'), e.target.getAttribute('target'));\n } else {\n window.location.href = e.target.getAttribute('href');\n }\n}\n</code></pre>\n<p>Change that part to:</p>\n<pre><code>if (e.target.nextElementSibling == null) {\n return;\n}\n\ne.preventDefault();\ne.stopPropagation();\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T03:09:49.493",
"Id": "260098",
"ParentId": "259764",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260098",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T16:35:00.417",
"Id": "259764",
"Score": "1",
"Tags": [
"javascript",
"event-handling"
],
"Title": "dispatch event listener problem after click"
}
|
259764
|
<p>I have a text adventure game and I need to use OOP so I've chosen to use it when getting the player's name and age. I need to keep the OOP; but was wondering if there are any ways to clean up the code or simplify it while still getting the overall output.</p>
<pre><code>
class Player:
def __init__(self):
self.get_name()
self.verify_age()
def get_name(self):
print("If you are ready lets begin!")
while True:
print("What is your name?")
name = input(":> ")
if not name.istitle():
print("Please enter a name starting with a capital letter; try again.")
else:
self.name = name
print("Hello " + name + " prepare for battle.")
break
def verify_age(self):
while True:
print("Before we begin please verify your age. \nWhat is your age?")
age = input(":> ")
try:
if 8 < int(age) <= 110:
self.age = age
break
elif int(age) <= 8:
print("You are not old enough to play the game! Try again.")
else:
print("You can't be that old, come on! Try again.")
except:
print("That is not a valid number! Try again.")
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T16:57:26.253",
"Id": "512461",
"Score": "2",
"body": "This is just the class. How will you be actually using this in your game?"
}
] |
[
{
"body": "<p>The methods in this class are not really Player methods. They are a combination of game flow, user input and value verification methods. I'd organize it more like this.</p>\n<pre><code>class Game:\n def __init__(self):\n io.show("If ready, let's begin")\n name = self.get_valid_name()\n age = self.get_valid_age()\n self.player = Player(name, age)\n io.show("Hello {}, prepare for battle".format(self.player.get_name()))\n</code></pre>\n<p>The <code>Game</code> object owns the flow of control. The I/O is encapsulated in an object which can be a simple stdio wrapper for now, but may eventually include non-blocking input or html output or whatever - don't tie the game logic to the display method. The <code>Player</code> object contains player state.</p>\n<p>The <code>get_valid_x</code> methods can basically be what you have now. If you are using that pattern over and over, you could get fancy and write a parameterized validator:</p>\n<pre><code>def get_valid_input(prompt, validation_func):\n while True:\n input = io.prompt(prompt)\n guidance = validation_func(input)\n if not guidance:\n return input\n io.show(guidance)\n\ndef validate_name(str):\n if not str.istitle():\n return "Please enter name beginning with capital Letter" \n return None\n\n ...\n \n name = get_valid_input("What is your name?", validate_name)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T18:41:37.053",
"Id": "259769",
"ParentId": "259765",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T16:37:56.453",
"Id": "259765",
"Score": "1",
"Tags": [
"object-oriented",
"pygame"
],
"Title": "Asking for player name and age using OOP"
}
|
259765
|
<p>For example, given <code>[10, 15, 3, 7]</code> and a number <code>k</code> of <code>17</code>, return <code>True</code> since <code>10 + 7</code> is <code>17</code>.</p>
<p>How can I improve the below solution?</p>
<pre><code>from itertools import combinations
def add_up_to(numbers, k):
c_k_2 = list(combinations(numbers, 2))
return any([True for pair in c_k_2 if sum(pair) == k])
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:03:47.947",
"Id": "512470",
"Score": "0",
"body": "consider sorting and using two pointers for quick performance"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:17:16.707",
"Id": "512478",
"Score": "2",
"body": "@HereToRelax Consider writing an answer and providing some more explanation for contributors that are looking to learn and improve"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:25:12.570",
"Id": "512480",
"Score": "0",
"body": "I have an answer on two pointers here https://codereview.stackexchange.com/a/219139/62030"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T20:17:53.927",
"Id": "512489",
"Score": "0",
"body": "Thanks for sharing. I implemented your proposed approach (my interpretation of course, as there's not a lot of information provided), sorted the list and used two pointers to run across the array. I used a numpy array to get good sorting performance. While there was a sweet spot (list length around 1.000) where this approach slightly outperformed my proposed algortihm using a `set`, it was significantly slower for long lists. If you actually know of a faster approach, I'd be interested to learn, so please do share!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T20:33:54.413",
"Id": "512491",
"Score": "0",
"body": "How do you get a list of 10^10 elements and how long does it take once the list is loaded?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T20:43:52.210",
"Id": "512492",
"Score": "0",
"body": "it takes me considerably longer to generate a suitable list or read one for the sizes that fit on my ram."
}
] |
[
{
"body": "<hr />\n<p><strong>Indents</strong></p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">PEP 8: <em>Use 4 spaces per indentation level.</em></a></p>\n<hr />\n<p><strong><code>True if condition else False</code></strong></p>\n<p>The pattern <code>True if condition else False</code> can be replaced by <code>condition</code> if it evaluates to a <code>bool</code>. If you are checking for <a href=\"https://www.freecodecamp.org/news/truthy-and-falsy-values-in-python/\" rel=\"nofollow noreferrer\">truthy and falsey values</a> you can replace the pattern by <code>bool(condition)</code>.</p>\n<p>While this lets us simplify the <code>return</code> statement</p>\n<pre><code>return any([sum(pair) == k for pair in c_k_2])\n</code></pre>\n<p>it actually performs worse (as pointed out by Manuel in the comments) without implementing further improvements (see the next point). While you originally create a list of only <code>True</code> values, this simplification will create a list that also includes all the <code>False</code> values, which we do not need at all.</p>\n<hr />\n<p><strong>Drop the <code>list</code></strong></p>\n<p>You convert to a list twice in your code, once explicitly by calling the <code>list(...)</code> constructor and once implicitly by wrapping a generator expression with <code>[...]</code>. In your particular use case, both are unnecessary.</p>\n<p>When dropping the call to the <code>list</code> constructor, <code>combinations(numbers, 2)</code> will provide an <code>itertools.combinations</code> object, which I would assume behaves similiarly to a generator, which is a lazily evaluated iterable. This way we don't compute and store all possible combinations of numbers in advance, which is perfect for us because we</p>\n<ol>\n<li>only need one pair of numbers at a time</li>\n<li>want to stop evaluating the expression once we find a pair that matches our criteria</li>\n</ol>\n<p>Dropping the brackets <code>[]</code> around our generator expression follows the same logic.</p>\n<p><a href=\"https://stackoverflow.com/questions/47789/generator-expressions-vs-list-comprehensions\">Generator expressions vs. list comprehensions on StackOverflow</a></p>\n<hr />\n<p>Applying these improvements will make the code more efficient, more readable and more concise:</p>\n<pre><code>def any_two_elements_add_up_to(numbers, k):\n pairs = combinations(numbers, 2)\n return any(sum(pair) == k for pair in pairs)\n\n# or as a one-liner\n\ndef any_two_elements_add_up_to(numbers, k):\n return any(sum(pair) == k for pair in combinations(numbers, 2))\n</code></pre>\n<hr />\n<p><strong>EDIT: Algorithm</strong></p>\n<p>I've tried my hand at a faster approach, this is the first solution I came up with. Although it's really simple it still outperforms the above solution by orders of magnitude as it runs in O(n).</p>\n<p>Here's the code:</p>\n<pre><code>def new_approach(numbers, target):\n counterparts = set()\n\n for num in numbers:\n if num in counterparts:\n return True\n\n counterparts.add(target - num)\n\n return False\n</code></pre>\n<p>Since every number only has one counterpart <code>k - x</code> that would make it add up to <code>k</code>, we can keep a <code>set</code> of all possible counterparts that we've identified so far. Once we come across a number that is in our <code>set</code> of counterparts (i.e. adds up to <code>k</code> with a previous number) we return <code>True</code>. If we don't come across one such number, we simply return <code>False</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T11:06:58.047",
"Id": "512534",
"Score": "0",
"body": "They don't have the pattern `True if condition else False`, though, and that first simplification of yours actually makes the code slower when there are a lot of `False` values that then get added to the list (for example in my answer's \"worst case\" input). You also make it sound too general, for example if `condition` is a string, then it doesn't evaluate to `True` or `False`, so it's not equivalent to the `True if condition else False` pattern."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T11:32:20.497",
"Id": "512536",
"Score": "0",
"body": "Very good points, thank you! I will update my answer accordingly"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T17:08:55.060",
"Id": "259767",
"ParentId": "259766",
"Score": "9"
}
},
{
"body": "<p>We can take your approach even further than riskypenguin did by pushing the work pretty much entirely into C-code:</p>\n<pre><code>def add_up_to(numbers, k):\n return k in map(sum, combinations(numbers, 2))\n</code></pre>\n<p>Takes <span class=\"math-container\">\\$O(1)\\$</span> space instead of your <span class=\"math-container\">\\$O(n^2)\\$</span>, and best case time is <span class=\"math-container\">\\$O(1)\\$</span> instead of your <span class=\"math-container\">\\$O(n^2)\\$</span>. And it's nice and short. Plus the C code is faster.</p>\n<p>Benchmark with a worst case, <code>numbers, k = [0] * 1000, 1</code>:</p>\n<pre><code>546.63 ms original\n386.11 ms riskypenguin\n229.90 ms Manuel\n</code></pre>\n<p>Benchmark with a "best case", <code>numbers, k = [0] * 1000, 1</code>:</p>\n<pre><code>594.35 ms original\n 0.02 ms riskypenguin\n 0.02 ms Manuel\n</code></pre>\n<p>Why did I put quotes around "best case"? Because for you it's a worst case. Note your increased time. You treat all pairs in any case, and you do the most work when they all have the desired sum: then you build the longest possible list, full of <code>True</code> values. The other solutions see the first pair and right away stop, hence their tiny times.</p>\n<p>Those are of course all <a href=\"https://www.youtube.com/watch?v=62necDwQb5E\" rel=\"nofollow noreferrer\">moo points</a>, as this problem should be solved in <span class=\"math-container\">\\$O(n)\\$</span> time (as riskypenguin did later) or at most <span class=\"math-container\">\\$O(n \\log n)\\$</span> time. Unless you're only allowed <span class=\"math-container\">\\$O(1)\\$</span> space and forbidden to modify the given list, which is rather unrealistic.</p>\n<p>Benchmark code:</p>\n<pre><code>from timeit import repeat\nfrom functools import partial\nfrom itertools import combinations\n\ndef original(numbers, k):\n c_k_2 = list(combinations(numbers, 2))\n return any([True for pair in c_k_2 if sum(pair) == k])\n\ndef riskypenguin(numbers, k):\n return any(sum(pair) == k for pair in combinations(numbers, 2))\n\ndef Manuel(numbers, k):\n return k in map(sum, combinations(numbers, 2))\n\ndef benchmark(numbers, k, reps):\n print(f'{len(numbers)=} {k=} {reps=}')\n funcs = original, riskypenguin, Manuel\n for _ in range(3):\n for func in funcs:\n t = min(repeat(partial(func, numbers, k), number=reps))\n print('%6.2f ms ' % (t * 1e3), func.__name__)\n print()\n\n# benchmark([10, 15, 3, 7], 17, 10**5)\nbenchmark([0] * 1000, 1, 5)\nbenchmark([0] * 1000, 0, 5)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T11:37:30.990",
"Id": "512537",
"Score": "0",
"body": "That's a really clean solution compared to my first version, +1! Could you include my proposed approach using a `set` in your benchmarks? I would hope it performs pretty well, especially in worst case scenarios"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:07:48.900",
"Id": "512539",
"Score": "0",
"body": "@riskypenguin Hmm, I left it out intentionally, as I don't find it interesting to confirm the obvious :-P. I really just wanted to compare the `combinations`+`sum` versions, didn't even include another O(1) space non-modifying solution of mine that's about four times faster. But I ran your set solution now, takes about 0.4 to 0.5 ms for that \"worst case\", although that's not quite fair as it additionally unrealistically benefits from its set remaining a single element."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:13:57.923",
"Id": "512541",
"Score": "0",
"body": "I see your point, no worries. Do you have an idea where your performance improvement comes from exactly? Is it just the replacement of `==` by `in` or the presumably reduced overhead of not calling `any`? Or does `map` simply outperform user-written generator expressions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:29:16.817",
"Id": "512544",
"Score": "1",
"body": "@riskypenguin I think it's the `map` vs the generator expression. With the latter, you're still interpreting Python code all the time. And maybe all the \"context switches\" between `any` and the generator also hurt. I'm kinda disappointed the speed difference isn't bigger :-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:45:06.897",
"Id": "512548",
"Score": "1",
"body": "@TobySpeight Bah, [that was intentional](https://www.youtube.com/watch?v=62necDwQb5E) :-("
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:33:12.693",
"Id": "512559",
"Score": "1",
"body": "\"Bah\" - or \"Baa\"? ;-)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:38:35.840",
"Id": "512652",
"Score": "0",
"body": "I tried to edit it myself, but turns out there's a minimum number of characters you can edit; the best case scenario should have `k == 0`, not `k == 1`, there's a typo in the benchmark example!"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T10:56:15.720",
"Id": "259790",
"ParentId": "259766",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259790",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T16:38:58.630",
"Id": "259766",
"Score": "7",
"Tags": [
"python"
],
"Title": "Given a list of numbers and a number, return whether any two numbers from the list add up to"
}
|
259766
|
<p>This is a follow up to <a href="https://codereview.stackexchange.com/questions/259438/a-simple-encryption-scheme-similar-to-otp">my previous post</a>.</p>
<p>I've used a BCrypt library to create a key from the passed in password. I then separated out the salt from the hash. The encryption is done using the salt concatenated to the hash, but only the hash is returned to the user. The salt is prepended to the encrypted data.</p>
<p>The key(salt + hash) is used to create a 512 bit hash using SHA3512. Each byte of data is XOR'ed with a byte of the key and a byte of the new hash. This byte of the hash is replaced by being XOR'ed with the byte of the key. When the end of the hash is reached, this byte array with all new values is then hashed and used for the next 64 bytes of data.</p>
<p>The Decryption separates out the salt and combines it with the passed in key to create the original hash and continue with the original encryption steps.</p>
<pre><code>using System.Text;
using System.Linq;
using System.Collections.Generic;
using SHA3.Net;
using BCrypt.Net;
class Cipher
{
public static IEnumerable<byte> Encrypt(string password, IEnumerable<byte> data,out string key)
{
if (password == null)
{
password = "";
}
if (data == null)
{
data = new byte[] { 0 };
}
var hash = MakeKey(password);
key = new string(hash, 22, 31);
string salt = new string(hash, 0, 22);
return GetBytes(data, key,salt);
}
public static IEnumerable<byte> Decrypt(IEnumerable<byte> data, string key)
{
if (data == null)
{
data = new byte[] { 0 };
}
return GetBytes(data, key);
}
static IEnumerable<byte> GetBytes(IEnumerable<byte> data, string key, string salt = "")
{
int saltLength = 0;
if(salt == "")
{
salt = new string(data.Take(22).Select(x => (char)x).ToArray());
saltLength = 22;
}
else
{
foreach(char c in salt)
{
yield return (byte)c;
}
}
key = $"{salt}{key}";
var hash = Sha3.Sha3512().ComputeHash(Encoding.UTF8.GetBytes(key));
int i = 0;
foreach (var b in data.Skip(saltLength))
{
//modulo 64
int hashIndex = (int)(((uint)i << 26) >> 26);
if (i > 0 && hashIndex == 0)
{
hash = Sha3.Sha3512().ComputeHash(hash);
}
byte offset = (byte)key[i % key.Length];
var retVal = (byte)(b ^ offset ^ hash[hashIndex]);
hash[hashIndex] ^= offset;
++i;
yield return retVal;
}
}
static char[] MakeKey(string password) => BCrypt.Net.BCrypt.HashPassword(password).Skip(7).ToArray();
}
</code></pre>
<p>Here's what the encrypted data can look like:</p>
<p>{86, 110, 68, 77, 68, 75, 46, 116, 73, 99, 50, 53, 114, 57, 89, 47, 109, 70, 88, 105, 114, 117, 233, 83, 221, 231, 216, 45, 118, 223, 227, 185, 170, 177, 131, 154, 240, 170, 72, 192, 182, 112, 149, 208, 102, 235, 252, 156, 127, 189, 255, 240, 203, 152, 142, 189, 140, 64, 166, 196, 13, 254, 138, 159, 229, 199, 80, 80, 113, 162, 137, 87, 216, 59, 81, 140, 123, 199, 211, 75, 43, 62, 11, 3}</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:05:22.010",
"Id": "512553",
"Score": "0",
"body": "Could you provide the link to NuGet package you're using to run this code? I can't find the package containing `Sha3` class. You well described how it works but it doesn't clear what's its purpose? What do you expect from a Review?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:24:04.277",
"Id": "512555",
"Score": "0",
"body": "`(int)(((uint)i << 26) >> 26)` is that the same as `i & 63` and `i % 64`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:31:55.310",
"Id": "512558",
"Score": "0",
"body": "The shifts are a shortcut for modulo 64. I'm not home I'll add the using when I get back"
}
] |
[
{
"body": "<p>Too fancy, too hard to read. The whole code can be compressed into something like\n<code> BCrypt.Net.BCrypt.HashPassword(salt+password).ToArray()</code></p>\n<p>Take a look at how to use this function here: <a href=\"https://jasonwatmore.com/post/2020/07/16/aspnet-core-3-hash-and-verify-passwords-with-bcrypt\" rel=\"nofollow noreferrer\">https://jasonwatmore.com/post/2020/07/16/aspnet-core-3-hash-and-verify-passwords-with-bcrypt</a></p>\n<p>Most importantly: there's no point in using mighty hashing like SHA3 and BCrypt only to use some made-up XOR encryption scheme. <strong>Use a standard encryption algorithm from a reputable library</strong>. If you don't trust any library or algorithm, then encrypt 2 times with two different algorithms, different keys and maybe using libraries from different vendors.</p>\n<p>Beyond that, here are other issues I have with this code:</p>\n<ul>\n<li><p>Is <code>.Skip(7)</code> supposed to somehow remove the salt? You can't "remove" the salt, the string you get from that function is not your input anymore, it's a completely different string (aka hash).</p>\n</li>\n<li><p>All these IEnumerable aren't efficient. Just use byte[].</p>\n</li>\n<li><p>there's an attempt to be efficient with bitshifts. Just use <code>%</code> and leave it to the compiler. Given the rest of the code doesn't look like the most efficient implementation (IEnumerable, yield...) it makes no sense to sacrifice readability</p>\n</li>\n<li><p>to that end - add other comments. It's not clear what <code>GetBytes</code> is supposed to achieve, given its generic name and lack of comments.</p>\n</li>\n<li><p>if the password is null, empty, or string below a certain length - throw an exception. There's no point in encrypting something with an empty password</p>\n</li>\n<li><p>name things properly. <code>byte offset</code> is not an offset (that would have been <code>i % key.Length</code>), it's a byte from the key</p>\n</li>\n<li><p>use constants instead of magic values sprinkled across the code.</p>\n</li>\n<li><p>get familiarized with common encryption libraries and try to follow their patterns, don't reinvent wheels that need no reinventing</p>\n</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T22:59:02.273",
"Id": "259827",
"ParentId": "259768",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T17:41:28.067",
"Id": "259768",
"Score": "1",
"Tags": [
"c#",
"encryption"
],
"Title": "A simple encryption scheme 2.0"
}
|
259768
|
<p>I was seeing alot of machine learning applications calculate fitness via <code>1.0 / x</code>. Division in computers is slow so I came up with a version that is about ~36% fast on my architecture (<code>-march=x86-64</code>).</p>
<pre class="lang-cpp prettyprint-override"><code>#include <cmath> //std::exp2, std::log
#include <numbers> //std::numbers::log2e
#include <stdlib.h> //rand, srand
#include <iostream> //std::cout
float reciprical( float y )
{
//e^-ln(y)
//std::pow( log10e, -std::log(y) ) //~19s
return std::exp2(std::numbers::log2e * -std::log(y)); //~17s
}
float reciprical2( float y )
{
return 1/y; //~23s
}
int main(){
srand(1);
for(int i=0; i < 10000000000; ++i) std::cout << reciprical(rand());
}
</code></pre>
<p>I got inspiration from <a href="https://codegolf.stackexchange.com/a/114588">https://codegolf.stackexchange.com/a/114588</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:07:13.323",
"Id": "512471",
"Score": "3",
"body": "It is very unlikely that applying two transcedental functions is faster than a single division. The runtime is dominated by the output to `std::cout`. Also, why use `std::exp2(std::numbers::log2e * ...)` when you can just use `std::exp(...)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:11:54.860",
"Id": "512473",
"Score": "0",
"body": "Side note but I noticed that there's two different spellings of reciprocal/reciprical which could be confusing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:14:54.903",
"Id": "512475",
"Score": "1",
"body": "I also recommend you use a benchmarking library, like https://github.com/google/benchmark/blob/master/README.md, and also look at the generated assembly code with a tool like https://godbolt.org/."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:14:56.707",
"Id": "512476",
"Score": "0",
"body": "(1 all I can say is try it on your machine and see if it's faster and also (2 I didn't think about `std::exp(std::numbers::log10e * -std::log(y));`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:17:16.343",
"Id": "512477",
"Score": "0",
"body": "Thank you, I'll keep that in mind"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:37:08.203",
"Id": "512483",
"Score": "2",
"body": "You claim this is to accelerate an AI application. Have you actually tried it there?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T20:30:56.807",
"Id": "512490",
"Score": "1",
"body": "This feels a bit like saying that your merge sort implementation was a bit slow so you optimized it by replacing it with bubble sort."
}
] |
[
{
"body": "<p>Including IO in a benchmark is no good. I tried some <a href=\"https://quick-bench.com/q/onmsxwkyLVdK7PUs3v4rrk5xqtc\" rel=\"nofollow noreferrer\">different benchmarks on quick-bench</a> and the results were different: the versions with Expensive Functions (<code>log</code>, <code>exp</code>, etc) were much slower. Looking at the assembly, there was no "cheating" such as vectorizing the benchmark loop with the plain division - on the other hand, maybe that wouldn't be cheating, but a realistic representation of how it may work out in real situations. So you could even say that the division is likely to be <em>better than this result shows</em> in many (but not all) situations.</p>\n<p>Such results do depend on the specific micro-architecture though. As a specific example, <code>divss</code> on Intel Haswell and before had less than half the throughput than on Intel Broadwell and later. <code>log</code> and <code>exp</code> can be implemented without division, so the <em>relative cost</em> will be different on different processors. That may also explain part of the differences we observed, but that does not take away that benchmarks should not include significant sources of overhead that aren't the subject of the benchmark.</p>\n<p>On your architecture (and many others) there is a special hardware-accelerated approximate reciprocal. Indeed on some architectures, division is not a primitive at all and can only be implemented in terms of such an approximate reciprocal (<a href=\"https://projects.ncsu.edu/wcae//ISCA2004/submissions/cornea.pdf\" rel=\"nofollow noreferrer\">that's tricky</a>). For x86, you can write this, for a quite accurate but not perfect reciprocal:</p>\n<pre><code>float reciprocal(float y)\n{\n float r = _mm_cvtss_f32(_mm_rcp_ss(_mm_set_ss(y)));\n r = r * (2 - r * y);\n return r;\n}\n</code></pre>\n<p>The Newton-Raphson step is optional if you can accept a reduced precision, with a relative error of up to <span class=\"math-container\">\\$1.5 \\cdot 2^{-12}\\$</span>.</p>\n<p>Note than all the benchmarks that I linked before are for <em>throughput</em>, if you're in a situation where <em>latency</em> is important, an approximate reciprocal followed by a Newton-Raphson step <a href=\"https://quick-bench.com/q/4H_VK95_Wc7KoM3UIxijFdjVjXA\" rel=\"nofollow noreferrer\">is not actually good</a>. Pentium4 may have been an exception to that, since it had a much slower division, but Pentium4 is not very relevant today.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:55:01.330",
"Id": "512485",
"Score": "0",
"body": "if using intrinsiscs you can use `_mm_rcp_ss(__m128 a)` (SSE)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:58:35.570",
"Id": "512486",
"Score": "0",
"body": "@AlexAngel yes that's what I used above, unfortunately it's not as simple as just throwing it in there, since the function signature is inconvenient"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T20:01:56.337",
"Id": "512487",
"Score": "0",
"body": "Ya, I commented that before I looked at your benchmark/code"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T20:49:51.200",
"Id": "512493",
"Score": "0",
"body": "@harold, in your benchmark (1st link) there are two data type conversions in reciprocal2 function which, by quick-bench, takes ~27% of the execution time. Constant 1.44269504089 type is double so make it float... . Maybe not much speed up though ... ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T21:03:42.597",
"Id": "512497",
"Score": "0",
"body": "@JuhaP the original code has that feature, `std::numbers::log2e` is a `double` after all. I now [tested it with a float](https://quick-bench.com/q/JAdsDTC8d6aERWzihYLM9pfoPaI) and that didn't help (I agree that it *could* have, though). Btw I recommend interpreting line-based timing with several grains of salt, they tend to suffer from [skid](https://stackoverflow.com/questions/48369347/reliability-of-xcode-instruments-disassembly-time-profiling#comment84227298_48369347) and other imperfections"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T19:43:28.717",
"Id": "259773",
"ParentId": "259771",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T18:50:01.023",
"Id": "259771",
"Score": "0",
"Tags": [
"c++"
],
"Title": "fast reciprocal (1/x)"
}
|
259771
|
<p>Edit:</p>
<p>By adding the restrict keyword I was able to get my memcpy up to speed with the library implementation (and in this particular test, exceeding the library implementations speed). New results:</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Test case</th>
<th><code>mem_cpy</code></th>
<th><code>mem_cpy_naive</code></th>
<th><code>memcpy</code></th>
</tr>
</thead>
<tbody>
<tr>
<td>big string (1000 bytes)</td>
<td><strong>2.584988s</strong></td>
<td>3.936075s</td>
<td>3.952187s</td>
</tr>
<tr>
<td>small string (8 bytes)</td>
<td>0.025931s</td>
<td>0.051899s</td>
<td><strong>0.025807s</strong></td>
</tr>
</tbody>
</table>
</div>
<p>Note: I tested also it as a part of a bigger implementation I had been working on. Previously I gained about 20% performance by swapping the libc memcpy in place of my own, now there was no difference.</p>
<p>Updated code:</p>
<pre class="lang-c prettyprint-override"><code>static void
copy_words(void *restrict dst, const void *restrict src, size_t words)
{
const uint64_t *restrict src64;
uint64_t *restrict dst64;
uint64_t pages;
uint64_t offset;
pages = words / 8;
offset = words - pages * 8;
src64 = (const uint64_t *restrict)src;
dst64 = (uint64_t *restrict)dst;
while (pages--)
{
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
}
while (offset--)
*dst64++ = *src64++;
}
static void
copy_small(void *restrict dst, const void *restrict src, size_t size)
{
const uint64_t *restrict src64;
uint64_t *restrict dst64;
src64 = (const uint64_t *restrict)src;
dst64 = (uint64_t *restrict)dst;
*dst64 = *src64;
}
void
*mem_cpy(void *restrict dst, const void *restrict src, const size_t size)
{
const uint8_t *restrict src8;
uint8_t *restrict dst8;
size_t offset;
size_t words;
size_t aligned_size;
if (!src || !dst)
return (NULL);
if (size <= 8)
{
copy_small(dst, src, size);
return (dst);
}
words = size / 8;
aligned_size = words * 8;
offset = size - aligned_size;
copy_words(dst, src, words);
if (offset)
{
src8 = (const uint8_t *restrict)src;
src8 = &src8[aligned_size];
dst8 = (uint8_t *restrict)dst;
dst8 = &dst8[aligned_size];
while (offset--)
*dst8++ = *src8++;
}
return (dst);
}
</code></pre>
<hr />
<p>As a practice in optimization I'm trying to get my memcpy re-creation as close in speed to the libc one as I can. I have used the following techniques to optimize my memcpy:</p>
<ul>
<li>Casting the data to as big a datatype as possible for copying.</li>
<li>Unrolling the main loop 8 times.</li>
<li>For data <= 8 bytes I bypass the main loop.</li>
</ul>
<p>My results (I have added a naive 1 byte at a time memcpy for reference):</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>Test case</th>
<th><code>mem_cpy</code></th>
<th><code>mem_cpy_naive</code></th>
<th><code>memcpy</code></th>
</tr>
</thead>
<tbody>
<tr>
<td>big string (1000 bytes)</td>
<td>12.452919s</td>
<td>212.728906s</td>
<td><strong>0.935605s</strong></td>
</tr>
<tr>
<td>small string (8 bytes)</td>
<td>0.367271s</td>
<td>1.413559s</td>
<td><strong>0.149886s</strong></td>
</tr>
</tbody>
</table>
</div>
<p>I feel I have exhausted the "low hanging fruit" in terms of optimization. I understand that the libc function could be optimized on a level not accessible to me writing only C, but I wonder if there's still something to be done here or is the next step to write it in assembly. To give a bit more clarification as to my motive for this. I study programming in a school that has performance constrains on our projects, but as of now we are only able to use standard C, so I can't go optimizing on assembly level yet. We are also not allowed to use libc and have to create our own versions of the standard functions we want to use so making my memcpy as fast as possible helps me hitting the performance goals in my projects. And it's great for learning obviously. I welcome any ideas!</p>
<p>Here is the code including the tests, can be compiled as is:</p>
<pre class="lang-c prettyprint-override"><code>#include <time.h>
#include <stdint.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
const size_t iters = 100000000;
//-----------------------------------------------------------------------------
// Optimized memcpy
//
static void copy_words(void *dst, const void *src, size_t words)
{
const uint64_t *src64;
uint64_t *dst64;
uint64_t pages;
uint64_t offset;
pages = words / 8;
offset = words - pages * 8;
src64 = (const uint64_t *)src;
dst64 = (uint64_t *)dst;
while (pages--)
{
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
*dst64++ = *src64++;
}
while (offset--)
*dst64++ = *src64++;
}
static void copy_small(void *dst, const void *src, size_t size)
{
const uint64_t *src64;
uint64_t *dst64;
src64 = (const uint64_t *)src;
dst64 = (uint64_t *)dst;
*dst64 = *src64;
}
void *mem_cpy(void *dst, const void *src, const size_t size)
{
const uint8_t *src8;
uint8_t *dst8;
size_t offset;
size_t words;
size_t aligned_size;
if (!src || !dst)
return (NULL);
if (size <= 8)
{
copy_small(dst, src, size);
return (dst);
}
words = size / 8;
aligned_size = words * 8;
offset = size - aligned_size;
copy_words(dst, src, words);
if (offset)
{
src8 = (const uint8_t *)src;
src8 = &src8[aligned_size];
dst8 = (uint8_t *)dst;
dst8 = &dst8[aligned_size];
while (offset--)
*dst8++ = *src8++;
}
return (dst);
}
//-----------------------------------------------------------------------------
// Naive memcpy
//
void *mem_cpy_naive(void *dst, const void *src, size_t n)
{
const uint8_t *src8;
uint8_t *dst8;
if (src == NULL)
return (NULL);
src8 = (const uint8_t *)src;
dst8 = (uint8_t *)dst;
while (n--)
*dst8++ = *src8++;
return (dst);
}
//-----------------------------------------------------------------------------
// Tests
//
int test(int (*f)(), char *test_name)
{
clock_t begin = clock();
f();
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("%s: %f\n", test_name, time_spent);
return (1);
}
char *big_data()
{
char *out;
size_t i;
out = (char *)malloc(sizeof(char) * 1000);
i = 0;
while (i < 1000)
{
out[i] = 'a';
i++;
}
return (out);
}
int test1()
{
char *src;
char *dst;
size_t i;
src = big_data();
dst = (char *)malloc(sizeof(char) * 1000);
i = 0;
while (i < iters)
{
mem_cpy(dst, src, 1000);
i++;
}
return (1);
}
int test2()
{
char *src;
char *dst;
size_t i;
src = big_data();
dst = (char *)malloc(sizeof(char) * 1000);
i = 0;
while (i < iters)
{
mem_cpy_naive(dst, src, 1000);
i++;
}
return (1);
}
int test3()
{
char *src;
char *dst;
size_t i;
src = big_data();
dst = (char *)malloc(sizeof(char) * 1000);
i = 0;
while (i < iters)
{
memcpy(dst, src, 1000);
i++;
}
return (1);
}
int test4()
{
char *src;
char *dst;
size_t i;
src = "12345678";
dst = (char *)malloc(sizeof(char) * 8);
i = 0;
while (i < iters)
{
mem_cpy(dst, src, 8);
i++;
}
return (1);
}
int test5()
{
char *src;
char *dst;
size_t i;
src = "12345678";
dst = (char *)malloc(sizeof(char) * 8);
i = 0;
while (i < iters)
{
mem_cpy_naive(dst, src, 8);
i++;
}
return (1);
}
int test6()
{
char *src;
char *dst;
size_t i;
src = "12345678";
dst = (char *)malloc(sizeof(char) * 8);
i = 0;
while (i < iters)
{
memcpy(dst, src, 8);
i++;
}
return (1);
}
int main(void)
{
test(test1, "User memcpy (big string)");
test(test2, "User memcpy naive (big string)");
test(test3, "Libc memcpy (big string)");
test(test4, "User memcpy");
test(test5, "USer memcpy naive");
test(test6, "Libc memcpy");
}
</code></pre>
<p>I won't paste the assembly, since I think it's more convenient to just put a link to compiler explorer:</p>
<p><a href="https://godbolt.org/z/Yva9EaPrP" rel="nofollow noreferrer">https://godbolt.org/z/Yva9EaPrP</a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T20:53:16.317",
"Id": "512495",
"Score": "3",
"body": "One obvious optimization is you didn't declare the parameters `dest` and `src` with the qualifier `restrict` ( https://en.cppreference.com/w/c/language/restrict ), as in libc. Like so: `void *memcpy(void *restrict dest, const void *restrict src, size_t size)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T21:05:49.123",
"Id": "512498",
"Score": "0",
"body": "Great catch! Now my tests output as follows (suscpicious, I did add a print in the end to make sure compiler doesn't skip the loop):\n\nUser memcpy (big string): 1.639461\nLibc memcpy (big string): 2.749912"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T21:14:24.480",
"Id": "512500",
"Score": "1",
"body": "Could be yours is being inlined while libc's isn't. What about if you declare `mem_cpy` with `__attribute__((noinline))` (GCC/clang) / `__declspec(noinline)` (MSVC)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T21:22:26.807",
"Id": "512502",
"Score": "0",
"body": "I did as you suggested (first example, using gcc) and results were identical."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T21:25:52.253",
"Id": "512504",
"Score": "1",
"body": "Then I would guess the reason yours is faster is because of cache effects and/or static (your code) vs. dynamic (libc) linkage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T21:30:52.877",
"Id": "512505",
"Score": "1",
"body": "I tested it on a more \"real world\" example with a dynamic array implementation I have been working on (std::vector in C) and now I'm getting identical performance on my array tests using libc memcpy compared to my own. There used to be about a 20% difference in this particular test. So I'm pretty happy about the results as is!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:43:44.850",
"Id": "512763",
"Score": "0",
"body": "I hope the .h file declaration of `mem_cpy()` does **not** include `const` with `size_t size`. It is noise in the _declaration_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T18:09:53.267",
"Id": "512767",
"Score": "0",
"body": "Tests do not cover that cases where the buffers are not meeting max alignment. `malloc()` provides such, but `memcpy()` usage is not limited to that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:09:32.807",
"Id": "512941",
"Score": "1",
"body": "Adding the table was a good edit, but editing the code is not allowed after an answer has been posted because everyone should be able to see the code that was reviewed in the answer. Please read [What should I do when someone answers](https://codereview.stackexchange.com/help/someone-answers). You can ask a new question with a link to this question as a follow up question if you want a review of the new code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:15:42.907",
"Id": "512942",
"Score": "0",
"body": "I left the original code in the end though, is that not allowed?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:16:49.123",
"Id": "512944",
"Score": "0",
"body": "Or should I make an answer to this thread to show updated results and code, since there's not really a question to go with that but I feel it's relevant information?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:25:42.763",
"Id": "512946",
"Score": "0",
"body": "You could post your new code and the results as an answer, but only if the answer is a review of some sort. Tell us what you improved and why, why it's better than the original. That would work nicely."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:34:31.423",
"Id": "512947",
"Score": "0",
"body": "I have added the new results, tests and code and an overview of changes as an answer."
}
] |
[
{
"body": "<blockquote>\n<pre><code>const uint64_t *restrict src64;\n</code></pre>\n</blockquote>\n<p>Portability problem - <code>uint64_t</code> is only defined if the platform has a type of exactly 64 bits. Consider using <code>uint_fast64_t</code> (or perhaps <code>uintmax_t</code>) instead.</p>\n<blockquote>\n<pre><code>pages = words / 8;\noffset = words - pages * 8;\n</code></pre>\n</blockquote>\n<p>Another portability problem - assumes <code>CHAR_BIT</code> is 64/8 = 8. Use <code>sizeof *src64</code> instead.</p>\n<p>The terminology is strange and confusing. Why are we calling bytes "words" and words "pages"?</p>\n<blockquote>\n<pre><code>src64 = (const uint64_t *restrict)src;\ndst64 = (uint64_t *restrict)dst;\n</code></pre>\n</blockquote>\n<p>I don't see where this code guarantees that <code>src64</code> and <code>dst64</code> are suitably aligned for read and write as 64-bit quantities. This means that the code will work on some architectures (possibly with performance problems) and fail completely on others (perhaps raising <code>SIGBUS</code> if you're lucky).</p>\n<p>The explicit casts are unnecessary given that <code>src</code> and <code>dst</code> are both <code>void*</code>, which converts implicitly to any object pointer. And there's no need to declare separately from initialising.</p>\n<p>I don't see how <code>copy_small</code> honours its <code>size</code> argument. It always seems to copy a full <code>uint64_t</code>, potentially clobbering more than requested (and possibly writing outside its legitimate bounds).</p>\n<hr />\n<p>The tests have problems, too. Let's look at <code>test1()</code> as a representative example:</p>\n<blockquote>\n<pre><code>int test1()\n{\n char *src;\n char *dst;\n size_t i;\n</code></pre>\n</blockquote>\n<p>Again, declare where we initialise.</p>\n<blockquote>\n<pre><code> src = big_data();\n dst = (char *)malloc(sizeof(char) * 1000);\n</code></pre>\n</blockquote>\n<p>There's no need to write an explicit cast to convert from <code>void*</code>. The multiplication by 1 has no effect.</p>\n<p>Why do we continue if allocation gives us back a null pointer? That's very slapdash.</p>\n<p>More importantly, why are we including <code>malloc()</code> call in our timings? That's going to dominate the result.</p>\n<blockquote>\n<pre><code> i = 0;\n while (i < iters)\n {\n mem_cpy(dst, src, 1000);\n i++;\n }\n</code></pre>\n</blockquote>\n<p>That would be more readable as an ordinary <code>for</code> loop.</p>\n<blockquote>\n<pre><code> return (1);\n}\n</code></pre>\n</blockquote>\n<p>Why the pointless parens around the return value? <code>return 1;</code> is more readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T09:18:18.497",
"Id": "512529",
"Score": "0",
"body": "Can you elabroate on how `uint_fast64_t` would help? As for the compatibility, you are very correct. Just didn't get around to it yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T10:19:25.907",
"Id": "512531",
"Score": "0",
"body": "`uint_fast64_t` is defined even if there's not a type of exactly 64 bits. So it is more portable. Perhaps `uintmax_t` would be an even better choice?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T10:52:56.750",
"Id": "512533",
"Score": "0",
"body": "As for the copy small, I was thinking about that. Having all different types and checking it size is 6-8, 4-6 etc. seemed a bit overkill. As far as I understand malloc guarantees 64bit offset anyways. I played with the idea of still copying the data with a bit-mask though, to make extra sure only relevant data is copied, although I don't see a practical case in which that could become an issue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:09:36.203",
"Id": "512540",
"Score": "0",
"body": "What's wrong with a simple char-by-char approach for small copies? That's what most `memcpy()` implementations do. Yes, `malloc()` should return memory suitably aligned for any type, but that's no help when you need to copy (e.g.) a substring out of somewhere in the middle of a string, or from/to automatic (\"stack\") storage."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:00:26.317",
"Id": "512552",
"Score": "0",
"body": "You are probably right that I should do a byte by byte. I was thinking I could squeeze a cycle or two there with using the wider type, but I guess compiler would optimize it away anyways. Need to do a couple of tests for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T16:03:51.020",
"Id": "512582",
"Score": "0",
"body": "Oh and by the way I’m calling 64bit uints words and 8 * 64bits a page. As far as I understand that’s the naming of such things in the kernel, no?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T17:47:29.260",
"Id": "512588",
"Score": "0",
"body": "On most platforms a page is 4KB, i.e. 512x64 bits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T18:44:35.757",
"Id": "512594",
"Score": "0",
"body": "8 * 64 bits = 64 bytes is the typical size of a [cache line](https://stackoverflow.com/questions/3928995/how-do-cache-lines-work)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:48:13.750",
"Id": "512765",
"Score": "0",
"body": "@jkoskela \"As far as I understand malloc guarantees 64bit offset anyways.\" --> No."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:49:40.127",
"Id": "512766",
"Score": "0",
"body": "UV for stating a common hole: \"I don't see where this code guarantees that src64 and dst64 are suitably aligned for read and write as 64-bit quantities..\""
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T06:57:05.350",
"Id": "259784",
"ParentId": "259775",
"Score": "4"
}
},
{
"body": "<h2>Fix buffer overrun in <code>copy_small</code></h2>\n<p>As you've currently written it, and as Toby previously pointed out, <code>copy_small</code> always writes 8 bytes to <code>dest</code>, even when <code>size < 8</code>. This is a major memory safety bug as it writes past the end of the <code>dest</code> buffer.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void\ncopy_small(void *restrict dst, const void *restrict src, size_t size)\n{\n const uint64_t *restrict src64;\n uint64_t *restrict dst64;\n\n src64 = (const uint64_t *restrict)src;\n dst64 = (uint64_t *restrict)dst;\n *dst64 = *src64; // !DANGER WILL ROBINSON!\n}\n</code></pre>\n<p>Here is how I would write <code>copy_small</code>. This is safe and, I believe, optimal.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void copy_small(uint8_t *restrict dst, const uint8_t *restrict src, size_t size)\n{\n if (size & 8) {\n *(uint64_t *restrict)dst = *(const uint64_t *restrict)src;\n return;\n }\n if (size & 4) {\n *(uint32_t *restrict)dst = *(const uint32_t *restrict)src;\n dst += 4;\n src += 4;\n }\n if (size & 2) {\n *(uint16_t *restrict)dst = *(const uint16_t *restrict)src;\n dst += 2;\n src += 2;\n }\n if (size & 1)\n *dst = *src;\n}\n</code></pre>\n<h2>Don't time <code>malloc</code> in your tests</h2>\n<p>As Toby pointed out, you need to rewrite your tests so that any memory allocations are completed before the timer starts, otherwise you're contaminating your data by measuring <code>malloc</code> in addition to the copy routines.</p>\n<h2>Qualify pointer arguments with <code>restrict</code></h2>\n<p>As I said in the comments, your original code was missing the <code>restrict</code> qualifier (as with libc <code>memcpy</code>) on pointer arguments to <code>mem_cpy</code> and friends. This was the most significant missed optimization opportunity in your code, and as you say this change led to a significant speedup.</p>\n<p>For "fairness," if you haven't done so already, add <code>restrict</code> to the pointer arguments of <code>mem_cpy_naive</code>. Note that you will need to compile with the option <code>-fno-tree-loop-distribute-patterns</code> to prevent GCC from optimizing <code>mem_cpy_naive</code> to a call to libc <code>memcpy</code>.</p>\n<h2>Micro-optimizations</h2>\n<ul>\n<li>You declared <code>copy_words</code> and <code>copy_small</code> with <code>static</code> linkage, presumably because you want them to be inlined, but in that case you should also declare them <code>inline</code> (i.e. <code>static inline</code>). Contrary to popular myth, the <code>inline</code> specifier <em>does</em> make the compiler significantly more likely to inline the function.</li>\n<li>Passing a null pointer to <code>memcpy</code> is <em>undefined behavior,</em> meaning you don't have to handle it gracefully. So, this /<code>if (!src || !dst) return (NULL)</code>/ is unnecessary. I'd replace it with an assertion /<code>assert(src && dst)</code>/ and compile with <code>-DNDEBUG</code> for the benchmarks. You can also declare your functions with <code>__attribute__((nonnull))</code>, which tells GCC to 1) raise a warning if it detects a null pointer being passed to the function and 2) optimize under the assumption that the pointer arguments are never null.</li>\n<li>Divisions and multiplications by powers of 2 are equivalent to right or left bit shifts by that power (which are faster). So all the instances of <code>x / 8</code> in your code can be replaced with <code>x >> 3</code> and all the <code>x * 8</code> can be replaced by <code>x << 3</code>. The compiler is probably smart enough to do this itself, but you might as well make it explicit.</li>\n<li>The <code>if (offset)</code> branch is unnecessary, and the loop it contains can be replaced with a call to <code>copy_small</code>. And you can make this change while still only calling <code>copy_small</code> once in <code>mem_cpy</code>. Do you see how?</li>\n</ul>\n<h2>Style suggestions</h2>\n<ul>\n<li><code>copy_words</code> and <code>copy_small</code> don't have to follow the <code>memcpy</code> API exactly. It's a lot less verbose if their <code>dest</code> and <code>src</code> arguments are respectively <code>uint64_t*</code> and <code>uint8_t*</code> instead of <code>void*</code>.</li>\n<li>Declaring a bunch of uninitialized variables at the top of the function was necessary in ANSI C, but in modern C it's bad style and potentially dangerous if you forget to initialize one of them. As much as possible, variables should both be declared (as <code>const</code> when they aren't modified) and initialized directly before they're used.</li>\n<li>As Toby said, the unnecessary parentheses around return values are confusing to the reader.</li>\n<li>As Toby also said, the use of the term <code>pages</code> for something other than a page is confusing. I would replace that with <code>chunks</code> or similar.</li>\n</ul>\n<h2>Disagreements with Toby</h2>\n<ul>\n<li>I wouldn't worry about exotic/nonexistent platforms where <code>CHAR_BIT != 8</code> or <code>uint64_t</code> isn't supported. If you were actually implementing <code>memcpy</code> for GCC, you might have to worry about this. But otherwise, no.</li>\n<li>When I write C code, I try to make it compatible with C++ if possible. So, since C++ requires it, I'm in favor of casting calls to <code>malloc</code> to the type of pointer they're being assigned to.</li>\n</ul>\n<h2>Your code, as I would write it:</h2>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <assert.h>\n#include <stddef.h>\n#include <stdint.h>\n\n#if !defined(__GNUC__) && !defined(__attribute__) // no GCC attribute syntax\n#define __attribute__(X)\n#endif\n\n#ifdef __cplusplus // C++\nextern "C" {\n\n#if defined(__GNUC__) || defined(_MSC_VER) || defined(__restrict)\n#define restrict __restrict\n#elif !defined(restrict) // restrict or __restrict not supported in C++\n#define restrict\n#endif\n\n#endif\n\nstatic inline __attribute__((nonnull))\nvoid copy_small(uint8_t *restrict dst, const uint8_t *restrict src, size_t size)\n{\n if (size >= 8) {\n *(uint64_t *restrict)dst = *(const uint64_t *restrict)src;\n return;\n }\n if (size >= 4) {\n *(uint32_t *restrict)dst = *(const uint32_t *restrict)src;\n dst += 4;\n src += 4;\n }\n if (size & 2) {\n *(uint16_t *restrict)dst = *(const uint16_t *restrict)src;\n dst += 2;\n src += 2;\n }\n if (size & 1)\n *dst = *src;\n}\n\nstatic inline __attribute__((nonnull))\nvoid copy64(uint64_t *restrict dst, const uint64_t *restrict src, size_t n) {\n size_t chunks = n >> 3;\n size_t offset = n - (chunks << 3);\n\n while (chunks--) {\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n }\n while (offset--)\n *dst++ = *src++;\n}\n\n__attribute__((nonnull))\nvoid *mem_cpy(void *restrict dst, const void *restrict src, size_t size) {\n assert(dst && src);\n\n uint8_t *dst8 = (uint8_t*)dst;\n const uint8_t *src8 = (const uint8_t*)src;\n\n if (size > 8) {\n const size_t qwords = size >> 3;\n\n copy64((uint64_t*)dst, (const uint64_t*)src, qwords);\n\n const size_t aligned_size = qwords << 3;\n\n size -= aligned_size;\n dst8 += aligned_size;\n src8 += aligned_size;\n }\n\n copy_small(dst8, src8, size);\n\n return dst;\n}\n\n/* GCC optimizes this to a call to libc memcpy unless compiled with\n * -fno-tree-loop-distribute-patterns\n */\n__attribute__((nonnull))\nvoid *mem_cpy_naive(void *restrict dst, const void *restrict src, size_t size) {\n assert(dst && src);\n\n uint8_t *restrict dst8 = (uint8_t*)dst;\n const uint8_t *restrict src8 = (const uint8_t*)src;\n\n while (size--)\n *dst8++ = *src8++;\n\n return dst;\n}\n\n#ifdef __cplusplus\n}\n#endif\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T18:39:56.467",
"Id": "512592",
"Score": "2",
"body": "You shouldn't have to cast pointers in C++ either, since you should use `new` there, or perhaps a `std::vector`, instead of `malloc()`. If it's about compiling with a C++ compiler, then that shouldn't work here because `restrict` is not a valid C++ keyword."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T19:43:22.367",
"Id": "512598",
"Score": "1",
"body": "Did you look at the code I wrote at the bottom? I addressed the `restrict` issue (not difficult)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:06:08.593",
"Id": "512601",
"Score": "1",
"body": "The X32 ABI isn't really maintained, is likely to be deprecated in the near future and I don't think any distros support it. But, maybe it would be better to go with OP's idea and just use `uint64_t` to copy with, since it should still be close to optimal even on most platforms with a native word size less than 64 bits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T21:36:26.297",
"Id": "512616",
"Score": "1",
"body": "FWIW I dropped the `size_t` idea, if nothing else it makes my code easier to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:48:16.987",
"Id": "512733",
"Score": "0",
"body": "Would this be a cheapo lazy solution or could it work if I just bitmasked the < 8 byte chunk. Something like `mask = (1 << bytes) - 1; *dst = *src & mask` ??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:08:09.547",
"Id": "512749",
"Score": "0",
"body": "@jkoskela No because it will still write zero bytes out of bounds."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:46:32.287",
"Id": "512764",
"Score": "0",
"body": "`(const uint64_t *restrict)src` risks UB as casting to a stricter alignment is not guaranteed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T12:52:55.317",
"Id": "512939",
"Score": "0",
"body": "I have updated test and results. Now the results seem more aligned with expectations."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T16:36:21.197",
"Id": "259811",
"ParentId": "259775",
"Score": "6"
}
},
{
"body": "<p>If you try this in MacOS, you’ll have an extreme fight on your hands. MacOS will at boot time install code optimised for your particular processor in a fixed place, this is done for memcpy, memmove , memset plus memset for two, four or eight byte values, and for some atomic operations.</p>\n<p>The memcpy on my current computer uses vector instructions, uses caching instructions not available in C, and all the tricks in the book. You basically have no chance beating it. And if you beat it on one computer, it won’t work on another.</p>\n<p>As far as your code is concerned: You should try to align the pointers first.</p>\n<pre><code>If count >= 1 and dst is not two-byte aligned -> copy 1 byte. \nIf count >= 2 and dst is not four-byte aligned -> copy 2 byte.\nIf count >= 4 and dst is not eight-byte aligned -> copy 4 byte.\n</code></pre>\n<p>Then you copy eight bytes at a time, then another 4 if needed, another 2, and another byte.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:40:56.230",
"Id": "512728",
"Score": "0",
"body": "I tried it on a MacBook Pro i9 2019. My code was still faster although not by as big of a margin as in the OP. Mac OS uses clang though even if you type GCC so I had to compile on clang. Surely my compiler can vectorize and use all tricks in the book as well since I'm using -O3, restrict etc."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T09:09:42.043",
"Id": "259850",
"ParentId": "259775",
"Score": "0"
}
},
{
"body": "<h1>Updated results, tests and code</h1>\n<p>As per suggestions in this thread I have updated my code following several\nsuggestions from the answers. If I have incporporated your code in the result, I\nwant to note that I need to follow certain strict formatting rules so sorry if\nI've changed the formatting in places.</p>\n<h2>Test scenario</h2>\n<p>I have created the following test scenarion:</p>\n<ul>\n<li>Copy a constant amount of data, but changing the amount of bytes fed to memcpy\neach iteration and thus dividing the amount of iterations.</li>\n<li>Measure maximum throughput in MB/s to find a sweet spot. This could be\nconsidered the maximum theoretcial speed for the copy under optimal\nsituations.</li>\n</ul>\n<p>Test hardware:</p>\n<pre><code>AMD Ryzen 3 3100 4-Core Processor\ncpu MHz : 2199.410\ncache size : 512 KB\nbogomips : 7199.89\nTLB size : 3072 4K pages\nclflush size : 64\ncache_alignment : 64\naddress sizes : 43 bits physical, 48 bits virtual\n</code></pre>\n<p>Test (32 samples):</p>\n<p>total bytes per iteration = 4294MB</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>bytes / string</th>\n<th>lib (s)</th>\n<th>usr (s)</th>\n<th>lib (MB/s)</th>\n<th>usr (MB/s)</th>\n<th>lib / usr</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>1</td>\n<td>19.419099</td>\n<td>18.627787</td>\n<td>221.17</td>\n<td>230.57</td>\n<td>1.042480</td>\n</tr>\n<tr>\n<td>2</td>\n<td>10.235309</td>\n<td>9.164130</td>\n<td>419.62</td>\n<td>468.67</td>\n<td><strong>1.116888</strong></td>\n</tr>\n<tr>\n<td>4</td>\n<td>5.488895</td>\n<td>6.074278</td>\n<td>782.48</td>\n<td>707.07</td>\n<td>0.903629</td>\n</tr>\n<tr>\n<td>8</td>\n<td>2.734126</td>\n<td>2.450595</td>\n<td>1570.87</td>\n<td>1752.62</td>\n<td>1.115699</td>\n</tr>\n<tr>\n<td>16</td>\n<td>1.358260</td>\n<td>2.307924</td>\n<td>3162.11</td>\n<td>1860.97</td>\n<td>0.588520</td>\n</tr>\n<tr>\n<td>32</td>\n<td>0.533698</td>\n<td>1.219608</td>\n<td>8047.56</td>\n<td>3521.60</td>\n<td>0.437598</td>\n</tr>\n<tr>\n<td>64</td>\n<td>0.269884</td>\n<td>0.629097</td>\n<td>15914.12</td>\n<td>6827.19</td>\n<td><strong>0.429002</strong></td>\n</tr>\n<tr>\n<td>128</td>\n<td>0.231149</td>\n<td>0.376591</td>\n<td>18580.95</td>\n<td>11404.86</td>\n<td>0.613793</td>\n</tr>\n<tr>\n<td>256</td>\n<td>0.101361</td>\n<td>0.209152</td>\n<td>42372.98</td>\n<td>20535.15</td>\n<td>0.484628</td>\n</tr>\n<tr>\n<td>512</td>\n<td>0.098064</td>\n<td>0.146679</td>\n<td>43797.59</td>\n<td>29281.41</td>\n<td>0.668562</td>\n</tr>\n<tr>\n<td>1024</td>\n<td>0.091359</td>\n<td>0.122013</td>\n<td>47011.98</td>\n<td>35200.90</td>\n<td>0.748764</td>\n</tr>\n<tr>\n<td>2048</td>\n<td>0.088001</td>\n<td>0.124751</td>\n<td>48805.89</td>\n<td>34428.32</td>\n<td>0.705413</td>\n</tr>\n<tr>\n<td>4096</td>\n<td>0.092047</td>\n<td><strong>0.117869</strong></td>\n<td>46660.59</td>\n<td><strong>36438.48</strong></td>\n<td>0.780926</td>\n</tr>\n<tr>\n<td>8192</td>\n<td><strong>0.083935</strong></td>\n<td>0.121658</td>\n<td><strong>51170.16</strong></td>\n<td>35303.62</td>\n<td>0.689926</td>\n</tr>\n<tr>\n<td>16384</td>\n<td>0.089955</td>\n<td>0.132727</td>\n<td>47745.73</td>\n<td>32359.41</td>\n<td>0.677745</td>\n</tr>\n<tr>\n<td>32768</td>\n<td>0.122094</td>\n<td>0.177560</td>\n<td>35177.55</td>\n<td>24188.82</td>\n<td>0.687621</td>\n</tr>\n<tr>\n<td>65536</td>\n<td>0.132070</td>\n<td>0.175046</td>\n<td>32520.39</td>\n<td>24536.22</td>\n<td>0.754487</td>\n</tr>\n<tr>\n<td>131072</td>\n<td>0.132693</td>\n<td>0.155997</td>\n<td>32367.70</td>\n<td>27532.37</td>\n<td>0.850613</td>\n</tr>\n<tr>\n<td>262144</td>\n<td>0.158665</td>\n<td>0.172354</td>\n<td>27069.41</td>\n<td>24919.45</td>\n<td>0.920576</td>\n</tr>\n<tr>\n<td>524288</td>\n<td>0.192556</td>\n<td>0.197228</td>\n<td>22305.03</td>\n<td>21776.66</td>\n<td>0.976312</td>\n</tr>\n<tr>\n<td>1048576</td>\n<td>0.195232</td>\n<td>0.200701</td>\n<td>21999.30</td>\n<td>21399.83</td>\n<td>0.972751</td>\n</tr>\n<tr>\n<td>2097152</td>\n<td>0.199710</td>\n<td>0.206325</td>\n<td>21506.02</td>\n<td>20816.51</td>\n<td>0.967939</td>\n</tr>\n<tr>\n<td>4194304</td>\n<td>0.916251</td>\n<td>1.116313</td>\n<td>4687.54</td>\n<td>3847.46</td>\n<td>0.820783</td>\n</tr>\n<tr>\n<td>8388608</td>\n<td>1.867847</td>\n<td>1.933270</td>\n<td>2299.42</td>\n<td>2221.61</td>\n<td>0.966159</td>\n</tr>\n<tr>\n<td>16777216</td>\n<td>1.920515</td>\n<td>2.298106</td>\n<td>2236.36</td>\n<td>1868.92</td>\n<td>0.835695</td>\n</tr>\n<tr>\n<td>33554432</td>\n<td>1.905867</td>\n<td>2.115908</td>\n<td>2253.55</td>\n<td>2029.85</td>\n<td>0.900732</td>\n</tr>\n<tr>\n<td>67108864</td>\n<td>1.533392</td>\n<td>1.837277</td>\n<td>2800.96</td>\n<td>2337.68</td>\n<td>0.834600</td>\n</tr>\n<tr>\n<td>134217728</td>\n<td>1.530375</td>\n<td>1.882125</td>\n<td>2806.48</td>\n<td>2281.98</td>\n<td>0.813110</td>\n</tr>\n<tr>\n<td>268435456</td>\n<td>1.405044</td>\n<td>1.805629</td>\n<td>3056.82</td>\n<td>2378.65</td>\n<td>0.778147</td>\n</tr>\n<tr>\n<td>536870912</td>\n<td>1.485964</td>\n<td>1.877592</td>\n<td>2890.36</td>\n<td>2287.49</td>\n<td>0.791420</td>\n</tr>\n<tr>\n<td>1073741824</td>\n<td>1.434760</td>\n<td>1.869482</td>\n<td>2993.51</td>\n<td>2297.41</td>\n<td>0.767464</td>\n</tr>\n<tr>\n<td>2147483648</td>\n<td>1.442237</td>\n<td>1.838574</td>\n<td>2977.99</td>\n<td>2336.03</td>\n<td>0.784432</td>\n</tr>\n</tbody>\n</table>\n</div><h2>Updated code with tests</h2>\n<p>Improvements on the code since original:</p>\n<ul>\n<li>Usage of restrict keyword as suggested by @Ray Hamel</li>\n<li>Correction of the buffer overrun when copying a small string suggested by @Ray Hamel</li>\n<li>Corrections to tests such as not allocating memory inside the timed portion of\nthe tests as suggested by @Toby Spleight and several others.</li>\n<li>For my use case I can expwect that the results ar not NULL so I have\nincorporated <code>__attribute__((nonull))</code> as suggested by @Ray Hamel.</li>\n</ul>\n<pre class=\"lang-c prettyprint-override\"><code>\n#include <time.h>\n#include <math.h>\n#include <stdint.h>\n#include <assert.h>\n#include <string.h>\n#include <stdio.h>\n#include <stdlib.h>\n\nsize_t iters = 0; // 2^36\n\n//-----------------------------------------------------------------------------\n// Optimized memcpy\n//\n\nstatic inline void __attribute__((nonnull))\ncopy_small(uint8_t *restrict dst, const uint8_t *restrict src, size_t n)\n{\n if (n >= 8)\n {\n *(uint64_t *restrict)dst = *(const uint64_t *restrict)src;\n return;\n }\n if (n >= 4)\n {\n *(uint32_t *restrict)dst = *(const uint32_t *restrict)src;\n dst += 4;\n src += 4;\n }\n if (n & 2)\n {\n *(uint16_t *restrict)dst = *(const uint16_t *restrict)src;\n dst += 2;\n src += 2;\n }\n if (n & 1)\n *dst = *src;\n}\n\nstatic inline void __attribute__((nonnull))\ncopy512(uint64_t *restrict dst, const uint64_t *restrict src, size_t n)\n{\n size_t chunks;\n size_t offset;\n\n chunks = n >> 3;\n offset = n - (chunks << 3);\n while (chunks--)\n {\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n *dst++ = *src++;\n }\n while (offset--)\n *dst++ = *src++;\n}\n\nvoid __attribute__((nonnull))\n*mem_cpy(void *restrict dst, const void *restrict src, size_t n)\n{\n uint8_t *dst8;\n const uint8_t *src8;\n size_t qwords;\n size_t aligned_size;\n\n dst8 = (uint8_t*)dst;\n src8 = (const uint8_t*)src;\n qwords = n >> 3;\n if (n > 8)\n {\n copy512((uint64_t*)dst, (const uint64_t*)src, qwords);\n return (dst);\n }\n aligned_size = qwords << 3;\n n -= aligned_size;\n dst8 += aligned_size;\n src8 += aligned_size;\n copy_small(dst8, src8, n);\n return (dst);\n}\n\n//-----------------------------------------------------------------------------\n// Tests\n//\ndouble test(int (*f)(char *, char *, size_t),\n char *test_data,\n char *test_dst,\n char *test_name,\n size_t i)\n{ \n clock_t begin = clock();\n f(test_dst, test_data, i);\n clock_t end = clock();\n double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;\n return (time_spent);\n}\n\nchar *make_string(size_t size)\n{\n char *out;\n size_t i;\n\n out = (char *)malloc(sizeof(char) * size);\n i = 0;\n while (i < size)\n {\n out[i] = i % 128;\n i++;\n }\n return (out);\n}\n\nint test_usr(char *dst, char *src, size_t bytes)\n{\n size_t i;\n\n i = 0;\n while (i < iters)\n {\n mem_cpy(dst, src, bytes);\n assert(memcmp(dst, src, bytes) == 0);\n i++;\n }\n return (1);\n}\n\nint test_lib(char *dst, char *src, size_t bytes)\n{\n size_t i;\n\n i = 0;\n while (i < iters)\n {\n memcpy(dst, src, bytes);\n assert(memcmp(dst, src, bytes) == 0);\n i++;\n }\n return (1);\n}\n\nint test_different_sizes()\n{\n size_t power;\n size_t i;\n size_t size;\n double lib;\n double usr;\n double lmbs;\n double umbs;\n char *src;\n char *dst;\n\n i = 0;\n power = 32;\n iters = pow(2, power);\n printf("total bytes per iteration = %zuMB\\n", iters / (size_t)pow(10, 6));\n printf("| bytes / string | lib (s) | usr (s) | lib (MB/s) | usr (MB/s) | lib / usr |\\n");\n printf("|---|---|---|---|---|\\n");\n while (i < power)\n {\n size = pow(2, i);\n src = make_string(size);\n dst = make_string(size);\n lib = test(test_lib, src, dst, "LIB", size);\n usr = test(test_usr, src, dst, "USR", size);\n lmbs = ((size * iters) / pow(10, 6)) / lib;\n umbs = ((size * iters) / pow(10, 6)) / usr;\n printf("|%-10zu|%-10lf|%-10lf|%-10.2lf|%-10.2lf|%-10lf|\\n",\n size, lib, usr, lmbs, umbs, lib / usr);\n iters /= 2;\n free(src);\n free(dst);\n i++;\n }\n return (1);\n}\n\nint main(void)\n{\n test_different_sizes();\n}\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:33:38.597",
"Id": "259940",
"ParentId": "259775",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T20:45:29.667",
"Id": "259775",
"Score": "4",
"Tags": [
"performance",
"c",
"reinventing-the-wheel"
],
"Title": "User implementation of memcpy, where to optimize further?"
}
|
259775
|
<p>I am attempting to implement a <code>GetNeighborhood</code> function in order to get a specific region from <code>inputCells</code> by <code>sizeInput</code> and <code>centralLocation</code> parameters in 3D cells structure.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>GetNeighborhood</code> function is as below.</p>
<pre><code>function [output] = GetNeighborhood(inputCells, sizeInput, centralLocation)
% Get neighborhood of fixed size and centered at centralLocation
output = cell( sizeInput ,sizeInput ,sizeInput );
X = centralLocation(1);
Y = centralLocation(2);
Z = centralLocation(3);
for x = -sizeInput:sizeInput
for y = -sizeInput:sizeInput
for z = -sizeInput:sizeInput
if X + x < 1
xLocation = 1;
elseif X + x > size(inputCells, 1)
xLocation = size(inputCells, 1);
else
xLocation = X + x;
end
if Y + y < 1
yLocation = 1;
elseif Y + y > size(inputCells, 2)
yLocation = size(inputCells, 2);
else
yLocation = Y + y;
end
if Z + z < 1
zLocation = 1;
elseif Z + z > size(inputCells, 3)
zLocation = size(inputCells, 3);
else
zLocation = Z + z;
end
output{sizeInput + x + 1, sizeInput + y + 1, sizeInput + z + 1} = ...
inputCells{xLocation, yLocation, zLocation};
end
end
end
end
</code></pre>
<p><strong>Test cases</strong></p>
<p>For testing purpose, a simple test script is created as below.</p>
<pre><code>clear all;
clc;
close all;
set(groot,'defaultFigureVisible','on');
%% Create test cells
testCellsSize = 10;
test = cell(testCellsSize, testCellsSize, testCellsSize);
for x = 1:size(test, 1)
for y = 1:size(test, 2)
for z = 1:size(test, 3)
test{x, y, z} = [x * 100 + y * 10 + z];
end
end
end
%% Specify test parameters
NeighborhoodDist = 1;
centralLocation = [5 2 2];
%% Perform test
result = GetNeighborhood(test, NeighborhoodDist, centralLocation);
result
</code></pre>
<p>The output of the above testing code:</p>
<pre><code>
3×3×3 cell array
result(:,:,1) =
{[411]} {[421]} {[431]}
{[511]} {[521]} {[531]}
{[611]} {[621]} {[631]}
result(:,:,2) =
{[412]} {[422]} {[432]}
{[512]} {[522]} {[532]}
{[612]} {[622]} {[632]}
result(:,:,3) =
{[413]} {[423]} {[433]}
{[513]} {[523]} {[533]}
{[613]} {[623]} {[633]}
</code></pre>
<p>If there is any possible improvement about potential drawback or unnecessary overhead, please let me know.</p>
|
[] |
[
{
"body": "<p>I think the biggest gain in efficiency you can get is to not use a cell array. Each element of a cell array is an array. Each array has a header data structure that takes up 104 bytes (if I remember that number correctly). Storing only one number in an array means that there is a memory overhead of 104/(104+8)=92%. Access is also slower because of the double indirection. To store individual numbers you should always use a numeric array.</p>\n<p>This code:</p>\n<pre><code>if X + x < 1\n xLocation = 1;\nelseif X + x > size(inputCells, 1)\n xLocation = size(inputCells, 1);\nelse\n xLocation = X + x;\nend\n</code></pre>\n<p>has quite some redundancy. Every time you write the same expression twice, you should think about storing the result of the expression. Even if the computation is trivial and likely not to slow down your code, duplicated code still leads to maintenance issues. You could do instead:</p>\n<pre><code>xLocation = X + x;\nmaxLocation = size(inputCells, 1);\nif xLocation < 1\n xLocation = 1;\nelseif xLocation > maxLocation\n xLocation = maxLocation\nend\n</code></pre>\n<p>This can be further simplified using <code>max</code> and <code>min</code>:</p>\n<pre><code>xLocation = X + x;\nxLocation = max(xLocation, 1);\nxLocation = min(xLocation, size(inputCells, 1));\n</code></pre>\n<p>You could maybe even simplify this to a single line of code, though that doesn’t improve readability:</p>\n<pre><code>xLocation = min(max(X + x, 1), size(inputCells, 1));\n</code></pre>\n<p>Furthermore, this code is repeated three times, so you should make it into a function you can call three times.</p>\n<p>Once your input and output are numeric arrays, you can likely vectorize the operation, removing the loops and further simplifying the code.</p>\n<p><code>clear all</code> is not recommended. <code>clear</code> by itself clears the workspace, deleting all defined variables. Adding the <code>all</code> argument causes it to additionally remove from memory all parsed and pre-compiled functions, meaning that the next time you call those functions they’ll take longer to run. <code>clear all</code> is hardly ever needed, and should not be a part of your normal workflow.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T01:22:58.410",
"Id": "259884",
"ParentId": "259780",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259884",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-20T23:58:43.867",
"Id": "259780",
"Score": "1",
"Tags": [
"beginner",
"matrix",
"matlab"
],
"Title": "GetNeighborhood function for 3D cells structure in MATLAB"
}
|
259780
|
<p>I usually like to use <code>entr</code> when developing on my own hardware to run commands when a directory changes.</p>
<p>However, sometimes I'm working in an environment where I don't have much control over the availability of helpful programs so many of us take for granted.</p>
<p>I've been using Git Bash on Windows, and I've been getting tired of hunting down my build terminal, pressing up in my last history to get to the build command, and hitting enter to build my project. I want it to automatically run when I save a new change. But I don't have <code>entr</code> or any of the other usual suspects (like <code>inotifywait</code>) to assist me.</p>
<p>So to overcome this problem, with a bit of Internet searching to assist, I wrote a Bash function to watch the <code>src/</code> directory and build the project when anything in the directory changes (including timestamps, because <code>-l</code>):</p>
<pre class="lang-bsh prettyprint-override"><code>monitor_and_build () {
local sauce=$(ls -l $1)
while [ true ] ;
do
sleep 1
local newsauce=$(ls -l $1)
if [[ "$sauce" != "$newsauce" ]]; then
make
fi
local sauce="$newsauce"
done
}
</code></pre>
<p>to be invoked:</p>
<pre class="lang-bsh prettyprint-override"><code>$ monitor_and_build src/
</code></pre>
<p>I have a working directory <code>Makefile</code> that calls <code>make -C src/</code>.</p>
<p>Since I did it in such an ad-hoc way, I'm sure I missed a trick or there's some edge cases this has a problem with. Please review!</p>
<p>Bonus question: aside from the obvious "writing your own programs in Bash is error-prone and foolish" (I admit it took me a few drafts to get it working) - suppose I had <code>entr</code> available, and then what are the benefits of using a program like <code>entr</code> instead?</p>
|
[] |
[
{
"body": "<p>You're going to get false positives by comparing the output of <code>ls -l</code>. In many locales, this command gives date stamps in different formats for newer files (day+time) and older files (year+day). When any file transitions from "new" to "old" in this scheme, you'll get a spurious notification. If you have the GNU implementation of <code>ls</code>, you can make it use a specific timestamp format (e.g. <code>--time-style=full-iso</code>) which might alleviate that problem. Or just accept the false positives (<code>make</code> should be reasonably quick if nothing actually changed).</p>\n<p>The usual problem of failing to quote arguments (<code>$1</code> where you should have written <code>"$1"</code>) will mess up arguments that contain whitespace or shell pattern characters. Although that might be unlikely for your source directories, it's trivial to fix, and a good habit to have.</p>\n<p>Testing that the string <code>true</code> is non-empty (<code>[ true ]</code>) is an unusual approach to making an infinite loop - most shell programmers would simply use the <code>true</code> command. Actually, it's probably better to test the result of <code>sleep</code>, which returns non-zero if interrupted.</p>\n<p>Instead of polling, you should be able to block on filesystem notification events. Perhaps <code>inotifywait</code> meets your needs here?</p>\n<p>If we use plain <code>[</code> rather than <code>[[</code>, the code becomes portable (POSIX) shell, without needing Bash extensions, so is useful to more people.</p>\n<p>Is it right that you want to run <code>make</code> in the current directory? For some users, it might make more sense to <code>make -C "$1"</code>. You could be more flexible by allowing a command to be specified (here I've kept <code>make</code> as default):</p>\n<pre><code>monitor_and_build()\n{\n local d=${1:-.}; shift\n test -d "$d" || return 1\n local sauce=$(ls -l --time-style=full-iso "$d")\n while sleep 1\n do\n local newsauce=$(ls -l --time-style=full-iso "$d")\n if [ "$sauce" != "$newsauce" ]\n then "${@:-make}"\n fi\n local sauce="$newsauce"\n done\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:28:29.847",
"Id": "512557",
"Score": "0",
"body": "Ah, I'd not come across `entr` before, so didn't realise that `inotifywait` was similar. Thanks for the clarification. If you have the GNU version of `ls`, you can specify the timestamp format to use - that's probably useful for this."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:36:30.707",
"Id": "512562",
"Score": "0",
"body": "Already edited (I think it's a shame that SE doesn't notify the asker when answers get edited!) Yes, `--full-time` would be a good choice (and equivalent to what I suggested)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:58:36.267",
"Id": "512572",
"Score": "0",
"body": "The `-l` also becomes redundant when specifying `--full-time`, (but not for `--time-style`). Maybe we should just have `--full-time` in the code."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:33:16.017",
"Id": "259794",
"ParentId": "259781",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259794",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T04:08:39.023",
"Id": "259781",
"Score": "2",
"Tags": [
"bash"
],
"Title": "Bash: call make when directory changes"
}
|
259781
|
<p>So I got this short awk invocation wrapped in a bash script. unfortunately the bash script is kinda unreadable. Do you have any pointers?</p>
<pre><code>#!/bin/bash
action="printf \"$1 \" \$1 \" \""
awk {"$action"} $2
</code></pre>
<p>Invoking it like this <code>joinargs -s tmp</code> if the tmp file looks like:</p>
<pre><code>a
bb
ccc
</code></pre>
<p>would create this output <code>-s a -s bb -s ccc</code> and it's useful when assembling commands</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T10:51:16.633",
"Id": "512532",
"Score": "0",
"body": "Can't you use just `echo` for printing to stdout?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:07:59.230",
"Id": "512573",
"Score": "1",
"body": "`sed \"s/^/$1 /\" $2 | xargs` ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:35:51.800",
"Id": "512726",
"Score": "0",
"body": "@paladin how do you mean?"
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T08:36:27.710",
"Id": "259787",
"Score": "0",
"Tags": [
"bash"
],
"Title": "Short bash script to join arguments with dashoption, escaping quotes and $ dollar sign"
}
|
259787
|
<p>Here is a code for BST that I have written , that does not use pass by reference. Help me to find flaws in its design. Also I do not like the function <code>getReqNodes</code>, can it be made more elegant.</p>
<pre><code>#include <iostream>
using namespace std;
struct node {
int data;
node* left = nullptr;
node* right = nullptr;
node(int d , node *l = nullptr, node *r = nullptr){
data = d;
left = l;
right = r;
}
};
node* insertVal(node* n, int val) {
if (n == nullptr) {
n = new node(val);
n->data = val;
return n;
}
else if (val < n->data){
return new node(n->data, insertVal(n->left,val), n->right);
}
else if(val > n->data) {
return new node(n->data, n->left, insertVal(n->right, val));
}
else{
return new node(val, n->left, n->right);
}
}
int minVal(node* n) {
if (n == nullptr) return -10000;
else if (n->left == nullptr) return n->data;
else return minVal(n->left);
}
node* getReqNodes(node *t, node *q){
if(q == nullptr){return t;}
else{
t = insertVal(t,q->data);
t = getReqNodes(t,q->left);
t = getReqNodes(t,q->right);
return t;
}
}
node* removeVal(node *n, int v){
if (n == nullptr){return n;}
else if(v < n->data){
return new node(n->data, removeVal(n->left,v), n->right);
}
else if(v > n->data){
return new node(n->data, n->left, removeVal(n->right, v));
}
else{
node *j = n;
//attaching right subtree to the left subtree
node *p = getReqNodes(n->left, n->right);
delete j;
return p;
}
}
void printTree(node* n) {
if (n == nullptr) { return; }
printTree(n->left);
cout << n->data << " ";
printTree(n->right);
}
int main() {
node* p = nullptr;
for(int i = 0; i < 15; ++i){
p = insertVal(p, rand()%15);
}
printTree(p);cout<<endl;cout<<endl;
node *foo = removeVal(p, 149);
printTree(foo);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T23:04:58.657",
"Id": "512621",
"Score": "0",
"body": "This is C code. The only C++ thing is your usage of `std::cout`. You need to work on encapsulation and how classes work."
}
] |
[
{
"body": "<h1>General Observations</h1>\n<p>The code compiles and runs in Visual Studio 2019 on Windows 10.</p>\n<p>The vertical spacing is inconsistent and could be improved.</p>\n<p>The code could be reusable if the Binary Search Tree was made into a class.</p>\n<p>The unit testing in main could be more effective if know values were used first and then a second test with random number generated. The test of <code>removeVal()</code> currently only tests a value that is never in the BST, the function does work because I changed the value in the test.</p>\n<h1>Avoid <code>using namespace std;</code></h1>\n<p>If you are coding professionally you probably should get out of the habit of using the <code>using namespace std;</code> statement. The code will more clearly define where <code>cout</code> and other identifiers are coming from (<code>std::cin</code>, <code>std::cout</code>). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifier<code>cout</code> you may override within your own classes, and you may override the operator <code><<</code> in your own classes as well. This <a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\">stack overflow question</a> discusses this in more detail.</p>\n<h1>Function and Variable Naming</h1>\n<p>Generally the function names are fairly good, there is one exception, it isn't clear to me from the name what <code>getReqNodes()</code> is supposed to do. In main it might be better to have a variable called <code>bst</code> or <code>root</code> rather than <code>p</code>.</p>\n<h1>Random Number Generation</h1>\n<p>It would be better to use C++ random number generators rather than the old C library function <code>rand()</code> function, see <a href=\"https://stackoverflow.com/questions/13445688/how-to-generate-a-random-number-in-c\">EDIT 2 in the first answer to this stack overflow question</a>. Currently the random number generator is not random because it is never seeded with a value by calling <code>srand()</code>.</p>\n<h1>One Statement Per Line</h1>\n<p>The code contains multiple lines where there is more than one statement such as:</p>\n<pre><code> printTree(p); cout << endl; cout << endl;\n</code></pre>\n<p>This makes the code harder to read, understand and maintain, always remember that you may not be the only person that needs to edit the code.</p>\n<p>There are 2 other issues with that line, that <code>std::endl</code> flushes the output which affects the performance of the program so using:</p>\n<pre><code> std::cout << "\\n";\n</code></pre>\n<p>might be a better option. The second is that if a string such as <code>"\\n"</code> is used then the string <code>"\\n\\n"</code> can be used to output 2 new lines, decreasing the number of statements necessary, although this is also possible:</p>\n<pre><code> std::cout << std::endl << std::endl;\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:26:28.583",
"Id": "259808",
"ParentId": "259788",
"Score": "1"
}
},
{
"body": "<p>The <code>n->data = val;</code> statement in <code>insertVal</code> is unnecessary, because the constructor for <code>node</code> already populates the <code>data</code> field. With that line removed, you can remove the assignment to <code>n</code> and replace all 3 statements with <code>return new node(val);</code>.</p>\n<p>However, the bigger issue is a memory leak. <code>insertVal</code> should only allocate a new node at most once for any insert, but as it is it will allocate a new node for every level of the tree it passes. Even in the case of inserting a duplicate node, the existing node is leaked and a new node allocated.</p>\n<p>The code to insert on the left should replace the current left node with the value returned from the recursive call to <code>insertVal</code>:</p>\n<pre><code> if (val < n->data){\n n->left = insertVal(n->left, val);\n return n;\n }\n</code></pre>\n<p>With a similar changes to inserting on the right, and returning the current node when the you find the value being inserted, will get rid of the leak.</p>\n<p>You can also replace the recursive insertion with a loop based one.</p>\n<p>Similar change can be made to <span class=\"math-container\">`</span>removeVal, which should not be allocating any nodes at all, just reusing the existing ones in the tree.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T16:44:42.287",
"Id": "259813",
"ParentId": "259788",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T09:27:40.970",
"Id": "259788",
"Score": "1",
"Tags": [
"c++",
"binary-search-tree"
],
"Title": "Binary Search Tree without pass by reference"
}
|
259788
|
<p>I have written a simple program to represent the computer is doing an operation. It is suppose to show a rotating slash character to the user with every second passed however the program does not work as intended. It shows all the characters instead of cleaning the screen and show just the spinning slash character.</p>
<pre><code>#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int main(){
char wheel[3] = {'\\','|','/'};
int j=0;
int i = 0;
while(j<6){
printf("[%c]",wheel[i]);
sleep(1);
system("clear");
i++;
if(i>2) i=0;
j++;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T19:03:06.897",
"Id": "512595",
"Score": "0",
"body": "\"however the program does not work as intended\" That's a problem. Please take a look at the [help/on-topic]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:27:50.423",
"Id": "512719",
"Score": "0",
"body": "This question would really fit better on [SO]."
}
] |
[
{
"body": "<p>If you're running windows the command is "CLS" not "clear".\nLearning modulo will help you a lot in programming - here you could use <code>wheel[j%3]</code> and skip the variable <code>i</code>.\nAlso try to find a way to move the cursor instead of clearing the entire screen.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:31:16.187",
"Id": "512545",
"Score": "0",
"body": "No i am using standard librarys (nix*). Good suggestion about the modulo, however i do not know how to remove a character from standard output."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:42:40.170",
"Id": "512608",
"Score": "1",
"body": "Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:10:20.597",
"Id": "259792",
"ParentId": "259791",
"Score": "0"
}
},
{
"body": "<p>The problem was that before going to sleep i had to flush the contents of stdout manually and that is why i did get nothing on the screen since printf buffers the output i either have to have a new line character which tells the buffer to flush or use fflush(stdout) before i call the sleep function.</p>\n<p>This answer was useful.\n<a href=\"https://stackoverflow.com/questions/13568388/c-sleep-function-not-working\">https://stackoverflow.com/questions/13568388/c-sleep-function-not-working</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:45:19.567",
"Id": "259796",
"ParentId": "259791",
"Score": "0"
}
},
{
"body": "<p>The wheel array is missing the horizontal spoke of the wheel <code>-</code>.</p>\n<p>The wheel array does not need a number to initialize it.</p>\n<pre><code> char wheel[] = {'\\\\','|','/'};\n</code></pre>\n<p>The size of the array can be determined by:</p>\n<pre><code> size_t wheel_size = sizeof(wheel) / sizeof(*wheel);\n</code></pre>\n<p>Prefer <code>size_t</code> over int when indexing arrays. <code>size_t</code> is unsigned and can prevent a negative value being used as an index.</p>\n<p>The loop can then be written just in terms of the size of the wheel using modulo as suggested by another answer.</p>\n<pre><code>size_t j=0;\nwhile(j < (2 * wheel_size)){\n printf("[%c]",wheel[j % wheel_size]);\n sleep(1);\n system("clear");\n j++;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T13:09:57.937",
"Id": "259798",
"ParentId": "259791",
"Score": "0"
}
},
{
"body": "<p>Typically you'd want to use either <code>\\b</code> or <code>\\r</code> to let the new output overwrite the old output without clearing the whole screen.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <stdio.h>\n#include <unistd.h>\n\n#define elements(x) (sizeof(x)/sizeof(x[0]))\n\nint main(){\n char wheel[] = {'\\\\','|','/', '-'};\n\n for (int i=0; i<30; i++) {\n printf("\\r%c", wheel[i%elements(wheel)]);\n fflush(stdout);\n sleep(1);\n }\n}\n</code></pre>\n<p><code>\\r</code> is a carriage return, so it lets you re-print the entire current line of output.\n<code>\\b</code> is a backspace, so it lets you overwrite a single character. In this case, we only have one character on the line, so either on works the same. A backspace would be useful if you wanted to do something on this order:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <stdio.h>\n#include <unistd.h>\n\n#define elements(x) (sizeof(x)/sizeof(x[0]))\n\nint main(){\n char wheel[] = {'\\\\','|','/', '-'};\n\n // something written outside the processing loop that needs to be preserved\n printf("Please wait--processing ");\n\n for (int i=0; i<30; i++) {\n // just overwrite the one character for the spinner:\n printf("\\b%c", wheel[i%elements(wheel)]);\n fflush(stdout);\n sleep(1);\n }\n printf("\\n");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:07:21.333",
"Id": "512602",
"Score": "0",
"body": "Not that it changes much, but OP has the spinner in square brackets."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:42:28.923",
"Id": "512607",
"Score": "2",
"body": "Please note, questions involving code that's not working as intended, are off-topic on this site. If OP edits their post to address the problem and make their post on-topic, they make your answer moot. [It is advised not to answer such questions](https://codereview.meta.stackexchange.com/a/6389/120114). Protip: There are tons of on-topic questions to answer; you'll make more reputation faster if you review code in questions that will get higher view counts for being on-topic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T05:57:56.287",
"Id": "512645",
"Score": "1",
"body": "You voted to close the question, yet still answered it. I'm curious. Why?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:26:46.473",
"Id": "512718",
"Score": "0",
"body": "@Mast: Stack Overflow (and StackExchange in general) have a reputation for being a bunch of A-holes who care more about enforcing arbitrary rules than actually helping anybody. In particular, demanding that beginners learn lots about the structure of SO/SE, how questions should be asked, etc., before answering questions. This question clearly doesn't fit here so it should be closed. But demanding that the OP jump through (what they see as) flaming hoops to get help is bad too. IMO, the optimal route is to help them, then close the question (and advise them what to do next time)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T16:38:34.687",
"Id": "259812",
"ParentId": "259791",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T11:37:02.120",
"Id": "259791",
"Score": "-1",
"Tags": [
"c"
],
"Title": "Spinning slash wheel to represent an Ongoing operation"
}
|
259791
|
<p>I am creating a metaclass which ensures that instances of an actual class <code>A</code> are kind of singletons. But rather than having only single instance of <code>A</code>, I would like to have one instance per argument set given to <code>A</code>.</p>
<p>That is</p>
<pre><code>class A(metaclass=ArgumentSingleton):
pass
r = A()
s = A()
t = A(1)
u = A(1)
v = A('hi')
print(r is s) # True
print(r is t) # False
print(t is u) # True
print(v is u) # False
print(v is r) # False
</code></pre>
<p>Moreover, the property of 'being a singleton' must survive pickling.</p>
<p>That is</p>
<pre><code>a = A()
with open('tmp.pkl', 'wb') as f:
pkl.dump(a, f)
with open('tmp.pkl', 'rb') as f:
b = pkl.load(f)
print(a is b) # True
</code></pre>
<p>For example Sympy is capable of doing that with their constants (such as <code>pi</code>) and I tried similar approach.</p>
<pre><code>class ArgumentSingleton(type):
_instances = {}
def __new__(cls, name, bases, class_dict):
def __init__(self, *args):
self._args = args
print('Here in __init__')
def __reduce_ex__(self, protocol):
return type(self), (*self._args,)
init = '__init__'
reduce = '__reduce_ex__'
method_absence = [
init not in class_dict,
reduce not in class_dict
]
if all(method_absence):
class_dict[init] = __init__
class_dict[reduce] = __reduce_ex__
elif any(method_absence):
raise ArgumentSingletonException(
f"Either both methods '{init}', '{reduce}' are defined or "
f"none of them in class: {name}"
)
new_class = super().__new__(cls, name, bases, class_dict)
return new_class
def __call__(cls, *args, **kwargs):
key = (cls, *args, *kwargs.items())
if key not in ArgumentSingleton._instances:
ArgumentSingleton._instances[key] = super().__call__(*args, **kwargs)
return cls._instances[key]
</code></pre>
<p>The code depends quite deeply (at least to my standards) on inner workings of Python and I am afraid of any hidden bugs and hidden problems.</p>
<p>The purpose of controling presence of <code>__init__</code> and <code>__reduce_ex__</code> is to explicitly move responsibility for <code>__reduce_ex__</code> to the creators of the class <code>A</code> in case they decide to provide their <code>__init__</code>.</p>
<p>Any comments or suggestions appreciated!</p>
<p>So far, I am aware of the fact that the arguments must be hashable. That is not problem for me, as this construction is meant to speed up comparison of my complex hashable objects.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:19:17.240",
"Id": "512542",
"Score": "1",
"body": "Hey, welcome to the community! The 2nd code snippet, where you show the pickling and unpickling, makes use of a variable `b` that is not defined! For the sake of clarity and correctness you might want to add it there :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:21:44.147",
"Id": "512543",
"Score": "1",
"body": "Hi, thank you for welcome and pointing out the error. Fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:34:02.147",
"Id": "512560",
"Score": "1",
"body": "Welcome to Code Review. I have rolled back your edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<p>The point of having to define either neither or both of <code>__init__</code> and <code>__reduce_ex__</code> is to set <code>_args</code>.\nHowever you can just set <code>_args</code> in <code>__call__</code> and then use the one you've set in your <code>__reduce_ex__</code>.<br />\n<sub><strong>Note</strong>: untested</sub></p>\n<pre class=\"lang-py prettyprint-override\"><code>class ArgumentSingleton(type):\n __INSTANCES = {}\n\n def __new__(cls, name, bases, class_dict):\n def __reduce_ex__(self, protocol):\n return partial(type(self), *self.__args, **self.__kwargs), ()\n\n def __init__(self, *args, **kwargs):\n pass\n\n class_dict.setdefault('__init__', __init__)\n class_dict.setdefault('__reduce_ex__', __reduce_ex__)\n return super().__new__(cls, name, bases, class_dict)\n\n def __call__(cls, *args, **kwargs):\n key = (cls, args, frozendict(kwargs))\n if None is (self := cls.__INSTANCES.get(key)):\n self = cls.__INSTANCES[key] = super().__call__(cls, *args, **kwargs)\n self.__args, self.__kwargs = key[1:]\n return self\n</code></pre>\n<p>Now we should be able to see we can just stop defining a metaclass by;</p>\n<ol>\n<li>changing <code>__call__</code> to <code>__new__</code>, and</li>\n<li>defining a default <code>__reduce_ex__</code> on the base class.</li>\n</ol>\n<pre class=\"lang-py prettyprint-override\"><code>from frozendict import frozendict\nfrom functools import partial\n\nclass Singleton:\n __INSTANCES = {}\n\n def __new__(cls, *args, **kwargs):\n key = (cls, args, frozendict(kwargs))\n if None is (self := cls.__INSTANCES.get(key)):\n self = cls.__INSTANCES[key] = super().__new__(cls)\n self.__args, self.__kwargs = key[1:]\n return self\n\n def __reduce_ex__(self, protocol: int):\n return partial(type(self), *self.__args, **self.__kwargs), ()\n\nclass A(Singleton):\n pass\n\n\n# passes all your tests and the following one\na = A("hi")\nb = pickle.loads(pickle.dumps(a))\nassert a is b\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:21:46.707",
"Id": "512554",
"Score": "0",
"body": "Thanks for your answer. However it gets little problematic when allowing keyword arguments. Please, see my edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:26:22.033",
"Id": "512556",
"Score": "1",
"body": "@TomášHons My aim is to simplify your code not change how your code functions. Since your code didn't correctly handle kwargs my changes don't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:39:11.847",
"Id": "512566",
"Score": "0",
"body": "Well, I my solution explicitly forbid them, which I see as better than allow them and silently introduce weird behavior. I pointed that out for anyone who wants to use the solution (me and you included). My intention was not to complain but to raise awareness of the possible problem. Your solution has +1 from me, as it helped me a lot and probably will be accepted (I want let the question open for others for some time)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:43:33.333",
"Id": "512568",
"Score": "0",
"body": "@TomášHons Yeah using `frozendict` would be better here as you know. Additionally you are unlikely to have weird gotchas. For example if a subclass change the `__init__` in your code to include `**kwargs` your code has the same issue, without changing to use `frozendict`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:22:22.640",
"Id": "512574",
"Score": "0",
"body": "Right, that is true, it's not bullet proof (maybe forbid `__init__` completely). Similarly, I still ponder whether use the `Singleton` should be a class or metaclass. With metaclass it is possible to avoid invoking `__init__` completely when re-using an instance which is probably desirable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:40:05.783",
"Id": "512579",
"Score": "0",
"body": "@TomášHons My 2c with the code you've provided I currently see no benefits to using a metaclass that a normal class doesn't allow. However, ensuring `__init__` is only ever called once could be a benefit of using a metaclass, with different/more code. You could just move `__new__` to the metaclass and have like a mix between my two examples above. Additionally I'm confident you can make the right decision, worst case you can ask for another review :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:49:46.720",
"Id": "512581",
"Score": "0",
"body": "Right, I agree :) I will just add the `frozendict` to your solution, in order to mark it as accepted with a clear conscience (in case someone will use it in future). Thank you for your work!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:18:25.710",
"Id": "512715",
"Score": "0",
"body": "The edit intended to fix the error in the call `super().__call__(cls, *args, **kwargs)`. However, too short edits are forbidden, so I added a note there to fulfill the 'requirements' on edit. Also, the note itself makes sense for anyone who wants to use the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:19:16.783",
"Id": "512716",
"Score": "0",
"body": "@TomášHons The note is better served as a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:21:56.513",
"Id": "512717",
"Score": "0",
"body": "Yet, still the original intent to fix the code is valid. So please, remove the `cls` argument, as I do not have the ability."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:29:06.117",
"Id": "512720",
"Score": "0",
"body": "@TomášHons You're not following the etiquette of Stack Exchange sites. Everyone thinks their edits and opinions are right. And whilst you may be right, the proper course of action is to comment. Two people rejected your edit for misusing the edit button. Please leave your note as a comment."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:44:16.363",
"Id": "512730",
"Score": "0",
"body": "Now I am concerned about fixing the call on the line `self = cls.__INSTANCES[key] = super().__call__(cls, *args, **kwargs)`. I wrote the note **only** because I was not allow post such short edit (though I believe in the message of the note in itself). Now I send another edit to mark my point."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T13:02:09.577",
"Id": "259797",
"ParentId": "259793",
"Score": "5"
}
},
{
"body": "<p>Here is the solution that I will probably use.</p>\n<p>It's a bit more complicated, but</p>\n<ul>\n<li>Enables the class <code>A</code> to define its own signature of <code>__init__</code> (without introducing new problems).</li>\n<li>The signature is correctly handled even when it uses default arguments.</li>\n<li>The <code>__init__</code> method is truly invoked only once (which appears to me as more logical behavior).</li>\n</ul>\n<p>The first two properties are ensured via <code>inspect</code> module and manipulating with the actual signature of <code>A.__init__</code>.\nThe second property comes from the use of metaclass and modifying behavior of its <code>__call__</code> method.\nModifying <code>__new__</code> in the superclass of <code>A</code> is not enough for this purpose.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from frozendict import frozendict\nfrom functools import partial\nimport inspect\n\nclass ArgumentSingletonMeta(type):\n __instances = {}\n\n @staticmethod\n def __get_trimmed_signature(init_method):\n # Removes 'self' argument from the signature\n sig = inspect.signature(init_method)\n params = tuple(sig.parameters.values())\n return sig.replace(parameters=params[1:])\n\n @staticmethod\n def __get_normalized_arguments(cls, *args, **kwargs):\n sig = ArgumentSingletonMeta.__get_trimmed_signature(cls.__init__)\n bound = sig.bind(*args, **kwargs)\n bound.apply_defaults()\n return bound\n\n def __call__(cls, *args, **kwargs):\n normalized = ArgumentSingletonMeta.\\\n __get_normalized_arguments(cls, *args, **kwargs)\n key = (cls, normalized.args, frozendict(normalized.kwargs))\n if None is (self := cls.__instances.get(key)):\n self = cls.__instances[key] = super().__call__(*args, **kwargs)\n self._args, self._kwargs = key[1:]\n return self\n\nclass ArgumentSingleton(metaclass=ArgumentSingletonMeta):\n def __init__(self, *args, **kwargs):\n super().__init__()\n # self._args = args\n # self._kwargs = kwargs\n\n def __reduce_ex__(self, protocol: int):\n return partial(type(self), *self._args, **self._kwargs), ()\n\n</code></pre>\n<p>Note that it is probably more clear to assign the <code>self._args</code> and <code>self._kwargs</code> attributes in <code>ArgumentSingleton</code>'s <code>__init__</code>.\nHowever, setting them in <code>ArgumentSingletonMeta</code>'s <code>__call__</code> is more efficient, as the <code>args</code> and <code>kwargs</code> are shared between the <code>__instances</code> dict and the actual instances.</p>\n<p>Now try the following code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pickle as pkl\n\nclass A(ArgumentSingleton):\n def __init__(self, x, y, z=1):\n super().__init__(x, y, z)\n\na = A(x=0, y=1)\nb = A(0, 1)\nc = A(0, 1, z=1)\n\nprint(a is b)\nprint(a is c)\n\nwith open('tmp.pkl', 'wb') as f:\n pkl.dump(a, f)\n\nwith open('tmp.pkl', 'rb') as f:\n b = pkl.load(f)\n\nprint(a is b)\n</code></pre>\n<p>Please comment if you see any hidden problem (even from software engineering point of view).\nSo far, I can't see any, but I would like to know if there are any :)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:02:54.797",
"Id": "259863",
"ParentId": "259793",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259797",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T12:10:39.877",
"Id": "259793",
"Score": "6",
"Tags": [
"python",
"singleton"
],
"Title": "Singleton metaclass for each argument set compatible with Pickle"
}
|
259793
|
<p>I'm trying to develop a text-based game. Here is the concept-demo version.</p>
<pre><code>class Arena {
public static void battle(Hero h1, Hero h2){
h1.setHp(h1.getHp()-h2.getPhysical_attack());
h1.info();
}
public static void main(String[] args) {
System.out.println("Entering Arena ...");
Hero mike = new Hero();
mike.setUname("mike");
mike.info();
Hero tom = new Hero();
tom.setUname("tom");
tom.info();
battle(mike, tom);
}
}
class Hero{
private String uname;
private int hp;
private int physical_attack;
Hero(){
hp = 620;
physical_attack = 66;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public int getHp() {
return hp;
}
public void setHp(int hp) {
this.hp = hp;
}
public int getPhysical_attack() {
return physical_attack;
}
public void setPhysical_attack(int physical_attack) {
this.physical_attack = physical_attack;
}
void info() {
System.out.println("HP of "+uname+"'s hero = "+hp);
}
}
</code></pre>
<p>Is it common to use static void method to handle objects that way?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:39:56.637",
"Id": "512578",
"Score": "4",
"body": "This feels like it might be a bit early for a review. `static` can be ok, however there's questions I'd consider... are you going to support multiple Arena, with different Hero's fighting? How come Mike never hits Tom back? Does it make sense to have a Hero that doesn't have a name, or should this be a constructor parameter? Are you going to support equipment (to reduce damage / inflict more damage)? Get/Set pairings setup a race condition does that matter? Should Hero have a take damage method instead? etc..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:40:20.120",
"Id": "512605",
"Score": "1",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] |
[
{
"body": "<h3>Few suggestions</h3>\n<ol>\n<li><code>Arena.battle</code> can be changed to instance method rather than a static method. This will help in conducting matches in different arenas.</li>\n<li>Use constructor to set the uname, initial hp and initial physical_attack</li>\n<li>Its better to use camel case for variable names instead of underscore(_)</li>\n<li>Constructors can be overloaded to mandate <code>uname</code> and suitable default values for hp and physicalAttack.</li>\n<li><code>toString()</code> can be overloaded instead of <code>info()</code></li>\n<li><code>hashCode</code> and <code>equals</code> can be overridden to ensure that same player is not matched against himself</li>\n</ol>\n<p>Regarding the usage of <code>static</code> method to schedule games</p>\n<ol>\n<li>It's always better to have a separate scheduler class to schedule games.</li>\n<li>This will help in unit testing using dependency injection</li>\n<li>also, it will be easier to mock non-static methods than static methods in unit test</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:12:58.040",
"Id": "512686",
"Score": "0",
"body": "Thank you. Does \"Use constructor to set the uname\" refer to the constructor of class `Arena` or class `Hero`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T03:54:03.333",
"Id": "512816",
"Score": "1",
"body": "@JJJohn, The constructor suggestion was primarily for `Hero` class. Irrespective of this, if we have a mandatory parameter and if the value will be mostly available, then its better to pass it as constructor to enable easier understanding. Also, if the instance variable was never needed to be updated after construction, its better to mark the variable as `final` and use constructor parameter only."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T22:25:26.597",
"Id": "513063",
"Score": "0",
"body": "Thank you so much. Would you please give some examples for different arenas? For example, player1 vs. player2 at arena1 while player3 vs. player4 at arena2, so arena1 and arena2 are 2 instance of the class `Arena`, is my understanding correct?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T23:59:43.427",
"Id": "513204",
"Score": "1",
"body": "True. Your understanding is correct. Few more next steps, 1. an identifier for each arena 2. whether same player can play in different arenas at the same time? This requires some kind an event/game organizing strategy. It's better to separate responsibilities for game matching from Arena/Hero classes and evolve them as independent pluggable strategies. Adding reasonable unit tests will help in long run."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T23:13:20.340",
"Id": "259828",
"ParentId": "259800",
"Score": "1"
}
},
{
"body": "<p>Since the <code>Arena</code> class has no state, and what state it needs is passed in as arguments, it seems reasonable to me for the methods to be static. This is a common pattern for utility-like classes. To make it more explicit you can add the keyword <code>final</code> to the class to indicate that no-one should create an instance of this class (there would be no point).</p>\n<p>However the way you're accessing that method is not very standard. If you want it to be static you should really be accessing it like so:</p>\n<pre><code>Arena.battle(mike, tom);\n</code></pre>\n<p>If, as others have suggested, you want <code>Arena</code> to be a class from which instance objects are created, rather than a utility class, then I'd suggest giving it some state. Your battle method already takes two <code>Hero</code> instances. An alternative approach would be to set the Hero instances on your <code>Arena</code> object and then call <code>battle</code> like so:</p>\n<pre><code>class Arena {\n\n private Hero h1;\n private Hero h2;\n\n public void battle() {\n h1.setHp(h1.getHp()-h2.getPhysical_attack());\n h1.info();\n }\n\n public static void main(String[] args) {\n System.out.println("Entering Arena ...");\n\n Hero mike = new Hero();\n mike.setUname("mike");\n mike.info();\n\n Hero tom = new Hero();\n tom.setUname("tom");\n tom.info();\n\n Arena arena = new Arena();\n arena.hero1 = mike;\n arena.hero2 = tom;\n arena.battle();\n }\n}\n</code></pre>\n<p>That way you can call other methods on the <code>Arena</code> in the future and not have to remember which <code>Hero</code>s you passed to it. For example, a method that prints the result of the battle, or an average result of multiple battles over time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T04:26:00.677",
"Id": "512640",
"Score": "2",
"body": "The battle method should no longer be static since it works with instance properties h1 and h2..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T00:22:25.820",
"Id": "513207",
"Score": "0",
"body": "Opps. Thanks, @slepic"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T00:44:03.647",
"Id": "259831",
"ParentId": "259800",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T13:49:53.740",
"Id": "259800",
"Score": "-2",
"Tags": [
"java"
],
"Title": "Is it common to use static void method to handle objects, e.g. set some properties?"
}
|
259800
|
<p>A couple of weeks ago I had to do a coding challenge for a job interview. I did the challenge using Python, the code was working and I got the job. But I would like to know how (if possible) I can improve/refactor the code I've written.
The reviewer told my future employer there were too many if statements and that I could have written better code.
I guess this is an example of too many if statements:</p>
<pre class="lang-py prettyprint-override"><code>def get_row_tax_percentage(product_name: str):
exempt = is_exempt(product_name)
imported = is_imported(product_name)
if exempt and imported:
return Decimal(".05")
elif exempt and not imported:
return Decimal("0")
elif imported:
return Decimal(".15")
else:
return Decimal(".1")
</code></pre>
<p>Link to the task description: <a href="https://github.com/xpeppers/sales-taxes-problem" rel="noreferrer">https://github.com/xpeppers/sales-taxes-problem</a></p>
<p>Link to my solution: <a href="https://github.com/soulpaul/sales-taxes-solution" rel="noreferrer">https://github.com/soulpaul/sales-taxes-solution</a></p>
<p>I think this could be a chance to learn something new. I don't need you guys to write code for me, but please point me to the right direction.
Thanks to anyone who is going to spend some time on this.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:59:57.137",
"Id": "512657",
"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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T11:34:09.447",
"Id": "512679",
"Score": "2",
"body": "Welcome to the Code Review Community and congrats on the new job. In the future please copy the programming challenge into the question so that we understand the requirements. The full code that you want reviewed needs to be embedded in the question, we can use repositories for references, but we can't review code in them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T11:55:47.340",
"Id": "512849",
"Score": "0",
"body": "Just curious: Why `f\"{word.lower()}\"` instead of `word.lower()` [here](https://github.com/soulpaul/sales-taxes-solution/blob/bdb6f8f4ace0168224e1e402f86591492508b327/src/printer.py#L29)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:10:48.440",
"Id": "512881",
"Score": "1",
"body": "There's 2 things I don't like about the task, that would probably require it to be different in production code. First I wouldn't want to hard code the values into the code, they should be external to the code. Secondly the production code should probably be able to handle additional taxes (which is what I assume they are). That is their mistake and not your mistake. But if they expected you to ask about it, or they thought it was common sense, it could explain why they complained about the amount of ifs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T15:32:03.850",
"Id": "512953",
"Score": "0",
"body": "@Manuel honestly... it doesn't make sense to me as well. It's probably something due to some kind of refactoring. It's just bad code."
}
] |
[
{
"body": "<p>The reviewer was probably thinking that you can get the same result by adding together two independently-calculated surcharges:</p>\n<pre><code>def get_row_tax_percentage(product_name: str) -> Decimal:\n nonexempt = Decimal("0") if is_exempt(product_name) else Decimal(".05")\n imported = Decimal("0.10") if is_imported(product_name) else Decimal("0")\n return nonexempt + imported\n</code></pre>\n<p>There are other ways to write this, of course, but this seems clear to me: there is a surcharge for non-exempt items and another surcharge for imported items and the total percentage is the sum of both.</p>\n<p>Note that in your original code, <code>and not imported</code> is redundant.</p>\n<p>You annotated the type of <code>product_name</code> but not the return type of the function; <code>-> Decimal</code> should work.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:48:51.780",
"Id": "512569",
"Score": "4",
"body": "Tangentially: I encourage you not to take negative interview feedback *too* seriously. The standard interview process, especially for low-experience positions, is a process of elimination, and therefore strongly relies on finding and magnifying flaws rather than identifying excellence. Small mistakes become big ones, and an interviewer may ding you for purely stylistic choices or for interpreting an ambiguous spec in an unexpected way. I've had two interviewers give me exactly opposite advice. Do accept constructive criticism, but don't put undue weight on vaguely negative feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T17:12:52.070",
"Id": "512585",
"Score": "0",
"body": "As a grizzled veteran from the interviewing trenches, I endorse your comment about the software engineering hiring process -- although I would not restrict it to low-experience positions. It's an imperfect process, to say the least."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:45:51.643",
"Id": "512655",
"Score": "0",
"body": "I don't take interviews feedback too seriously but I want to understand If it could help me become a better coder. That's why, despite having had success in getting the job, I'm willing to work on this. I still have a long road of learning ahead :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:46:52.130",
"Id": "512740",
"Score": "0",
"body": "For real-world code, this would be pretty bad. Imagine, one of the values change, and then they cannot be added up that neatly."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:40:16.470",
"Id": "259803",
"ParentId": "259801",
"Score": "3"
}
},
{
"body": "<p><strong>Calcuating the result</strong></p>\n<p>The approach they might be looking for is the following:</p>\n<pre><code>def get_row_tax_percentage_calc(product_name: str):\n result = 0 if is_exempt(product_name) else 10\n result += 5 if is_imported(product_name) else 0\n\n return Decimal(result) / Decimal(100)\n</code></pre>\n<p>As you can see we're able to calculate the result without hardcoding all possible combinations of product characteristics. This approach is more maintainable: If we need to consider another characteristic of the product for our tax percentage, it's only a matter of adding a single line:</p>\n<pre><code>def get_row_tax_percentage_calc(product_name: str):\n result = 0 if is_exempt(product_name) else 10\n result += 5 if is_imported(product_name) else 0\n result += 7 if fits_new_characteristic(product_name) else 0\n\n return Decimal(result) / Decimal(100)\n</code></pre>\n<hr />\n<p>I would generally not recommend the following suggestions in an interview or at all, but they are some neat tricks to know:</p>\n<hr />\n<p>We can also multiply the <code>bool</code> values (<code>False -> 0</code> - <code>True -> 1</code>) with our surcharges to get this really simple implementation:</p>\n<pre><code>def get_row_tax_percentage_calc(product_name: str):\n result = 10 * (not is_exempt(product_name))\n result += 5 * is_imported(product_name)\n\n return Decimal(result) / Decimal(100)\n</code></pre>\n<hr />\n<p>We can also use the <code>bool</code> values from <code>is_exempt</code> and <code>is_imported</code> as indices (again, <code>False -> 0</code> - <code>True -> 1</code>).</p>\n<pre><code>def get_row_tax_percentage_calc(product_name: str):\n result = [10, 0][is_exempt(product_name)]\n result += [0, 5][is_imported(product_name)]\n\n return Decimal(result) / Decimal(100)\n</code></pre>\n<p>or</p>\n<pre><code>def get_row_tax_percentage_calc(product_name: str):\n result = [0, 10][not is_exempt(product_name)]\n result += [0, 5][is_imported(product_name)]\n\n return Decimal(result) / Decimal(100)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T02:33:12.323",
"Id": "512633",
"Score": "6",
"body": "i would strongly recommend against `10 * bool` in an interview or production either, it might be .1% faster but is a very unexpected and unusual use of `*`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T06:38:49.800",
"Id": "512649",
"Score": "8",
"body": "@cat: I guess it depends who reads it. If everyone else on the team has C experience, go for it! It feels natural, and exposes the logic well. I personally find `[0, 10][not is_exempt(product_name)]` harder to parse."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:32:58.323",
"Id": "512650",
"Score": "3",
"body": "+1 for suggesting the 10*bool approach."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:41:29.853",
"Id": "512653",
"Score": "0",
"body": "I didn't knew it was possible to multiply by booleans. Thanks for your answer and explanation! Anything else you could point me as improvable in the codebase?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:48:43.313",
"Id": "512656",
"Score": "4",
"body": "There is some clever code here but if readability is a key focus I would avoid your last few examples. The first one is good, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T09:36:31.920",
"Id": "512662",
"Score": "0",
"body": "@rshepp I agree, I tried to focus on readability first and then saw an opportunity to provide some related tricks, that might be handy to know although they rarely come up as useful =)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T13:12:54.510",
"Id": "512696",
"Score": "0",
"body": "@EricDuminil That's a false dichotomy, they're both terrible since they both mix semantics and implementation of the bool type. Implicit conversion between booleans and integers belongs relegated to assembly and numerical computing, it doesn't belong in high-level business logic."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:48:15.527",
"Id": "512741",
"Score": "0",
"body": "Do not use any of that in real-production code. Nice clever code golf, but terribly unmaintainable."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:51:41.713",
"Id": "512742",
"Score": "0",
"body": "@Dakkaron Do you actually mean *any of that*? I'd say my first (and only serious) suggestion is reasonable for production code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:54:14.980",
"Id": "512743",
"Score": "0",
"body": "@riskypenguin I really dislike the adding-up mechanic. What if one corner of the matrix changes so that it doesn't nicely add up any more?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:55:52.600",
"Id": "512744",
"Score": "3",
"body": "@Dakkaron The [problem statement](https://github.com/xpeppers/sales-taxes-problem) shows that the underlying logic is not a matrix of characteristics, but the summation of independent surcharges."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:57:19.907",
"Id": "512745",
"Score": "1",
"body": "Fair point, I redact my statement. I didn't see the link to the problem statement and thought that people were just inferring that from the code. You are right, the first variant is ok then."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:59:26.983",
"Id": "512746",
"Score": "0",
"body": "@Dakkaron You're actually right there, as the link to the problem statement was provided only after my (and some of the other) answers were posted."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:00:07.200",
"Id": "512748",
"Score": "2",
"body": "The only thing I'd change is the double negation. So `must_pay_taxes` instead of `not is_exempt`. Every piece of code would become more readable IMHO."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T20:58:06.937",
"Id": "512784",
"Score": "1",
"body": "@EricDuminil In general I dislike double negation, but here I think it's rather natural, and it's in the task description as well: \"except [products] that are exempt\"."
}
],
"meta_data": {
"CommentCount": "15",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T14:45:21.343",
"Id": "259804",
"ParentId": "259801",
"Score": "13"
}
},
{
"body": "<p>That really depends on how the task is stated. If it's stated like your code, just in English, with four different (and possibly independent) values, then I'd say your way is actually ok. Because then if one of them changes, you only need to change the value, not rewrite logic.</p>\n<p>But the task description says:</p>\n<blockquote>\n<p><strong>Basic sales tax</strong> is applicable at a rate of 10% on all goods, except books, food, and medical products that are exempt. <strong>Import duty</strong> is an additional sales tax applicable on all imported goods at a rate of 5%, with no exemptions.</p>\n</blockquote>\n<p>So it is in fact stated as two separate taxes that should be determined separately and just added. Make the code's logic reflect the real logic.</p>\n<p>For extra clarity, use the proper names as well. For example:</p>\n<pre><code>def get_row_tax_percentage(product_name: str):\n basic_sales_tax = 10 if not is_exempt(product_name) else 0\n import_duty = 5 if is_imported(product_name) else 0\n return Decimal(basic_sales_tax + import_duty) / 100\n</code></pre>\n<p>Or maybe with <code>0 if is_exempt(product_name) else 10</code>, I can't decide which I find clearer and/or closer to how the task says it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:33:52.477",
"Id": "512651",
"Score": "1",
"body": "I omitted to write the task description because it was way too long to include. I should have added a reference, you are right, especially since I was looking for more feedback on the other part of the code as well. Thanks for your time and your precious answer!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:04:08.633",
"Id": "259805",
"ParentId": "259801",
"Score": "21"
}
},
{
"body": "<p>I'm confused why all the answers are so fond of the ternary operator (Y if X else Z) rather than simple if statements:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def get_row_tax_percentage_calc(product_name: str):\n basic_sales_tax = Decimal('0.1')\n import_duty = Decimal('0.05')\n\n total = Decimal('0')\n if not is_exempt(product_name):\n total += basic_sales_tax\n if is_imported(product_name):\n total += import_duty\n return total\n</code></pre>\n<p>Coming from C++, I find python's ternary syntax particularly hard to parse, as the natural language order does not follow the flowchart logic.</p>\n<p>EDIT: thanks to @GregoryCurrie for the suggestion to make the magic numbers into named constants.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:27:57.050",
"Id": "512739",
"Score": "1",
"body": "Ternary statements are less code and arguably easier to read. That's not to say that IF statements are usually hard to read to begin with, but ternary is even easier to parse. Even in C#, I use ternary wherever it is applicable. It's an IF-THEN-ELSE all on one line if you please rather than what is usually going to be a minimum of four lines.\n`width = width == 0 ? 5 + 2 : width + 2` versus\n`if (width == 0) <New Line> width = 5 + 2 <New Line> else <New Line> width = width + 2`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:59:41.060",
"Id": "512747",
"Score": "3",
"body": "@Hashgrammer How is `result += 5 if is_imported(product_name) else 0` less code or easier to read than `if is_imported(product_name): result += 5`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:17:48.223",
"Id": "512753",
"Score": "3",
"body": "If I may suggest an improvement, pull out Decimal(\"0.1\") and Decimal(\"0.05\") into two constants with the name of the tax involved. In any case, this is certainly the clearest answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T22:20:23.257",
"Id": "512790",
"Score": "3",
"body": "@Hashgrammer I totally agree ternary operators are valuable and have their place, but in this case the `else` condition is a no-op and can be omitted, making the plain `if` statement both less verbose and in my opinion more readable"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:50:33.980",
"Id": "512891",
"Score": "1",
"body": "Useful to cite the discussion of pros and cons of using Python conditional expressions (aka 'the ternary operator') from [Does Python have a ternary conditional operator?](https://stackoverflow.com/a/394814/202229)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T20:05:12.140",
"Id": "513941",
"Score": "1",
"body": "@Manuel it's more verbose. Explicitly setting values is better than implicitly assuming they will be something if they are not something else. i.e. Setting 0 rather than just assuming it will still be 0 if the `+=` is not applied. It's easier to read because I don't have to read through the logic above to know that it will BE 0 because the `+=` was not applied to a previous assignment of 0, it is definitively set so on the same line. In this case, it is not necessarily less code although it could be if you figure removing the initial assignment `result = 0` since it wouldn't be needed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T20:08:34.830",
"Id": "513943",
"Score": "1",
"body": "@thegreatemu see my answer to Manuel above. It's more readable and verbose, and if you don't feel like repeating yourself in the code, it's less code: `result = 5 if is_imported(product_name) else 0` is 46 characters, while `result = 0; if is_imported(product_name): result += 5` is 53."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T23:37:02.657",
"Id": "259830",
"ParentId": "259801",
"Score": "14"
}
},
{
"body": "<p>Your code is simple, straightforward, easy to understand, and easy to change. It is absolutely fine and acceptable. Simple is good for code. It is not clever. I don’t want clever code.</p>\n<p>Apparently your reviewer wants more clever code. That is bad news as far as getting that job goes, but your code is just fine. Some examples of more clever code have been posted. But I always see for example the assumption that the taxes for “non-exempt” and “imported” are just added; that is not obvious and could quite obvious change at any time; your government might decide that 15 percent for non-exempt AND imported goods is too low or too high, and instead of changing one line you have to change your code completely.</p>\n<p>For example, the dictionary code is <em>very</em> clever. You could use it to impress that reviewer. I’d hate to see it in my codebase.</p>\n<p>Summary: Your code is fine as it is. I like it. And most people would not complain about it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T10:11:43.380",
"Id": "512670",
"Score": "1",
"body": "Maybe for some others it was an assumption. For me it wasn't. It's in the task description. And I don't think that mindlessly converting English to Python is \"clever\". It's rather the opposite. It's trying *not* to be clever. Takes *less* brainpower and is *less* error-prone than calculating the four values and fumbling them into four ifs."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T10:57:02.327",
"Id": "512675",
"Score": "0",
"body": "Actually... since the OP *also* just added the two taxes, you should complain about that just as much. Probably even *more*, since they *hide* it by having done that in the background and acting like those four values were given."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T11:04:35.740",
"Id": "512676",
"Score": "1",
"body": "I also don't find the OP's \"simple\". For example to figure out what the 10% is for, you need to read, negate, and combine three different if-conditions. The second of which is even confusing, because the `and not imported` seems superfluous, so makes one wonder why that was included, and why the third if-condition doesn't include `and not exempt `."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T08:56:37.507",
"Id": "259849",
"ParentId": "259801",
"Score": "0"
}
},
{
"body": "<p>Disclaimer: this answer was posted before the problem statement was posted. Only the code was there in the beginning. So the point of this answer was, if you see a possible pattern where there might not be a real pattern (e.g. the corners of the matrix add up, so use addition instead of four fields) is a bad idea, because what if the pattern breaks once requirements change</p>\n<p>The code is good as it is. It is simple, straight-forward and decidedly not clever. That's exactly how production code should be.</p>\n<p>The other answers here do indeed make the code shorter, but they make it a lot less maintainable and understandable. The only thing that could be reasonably improved is nested ifs, so that it's easier to see the matrix of results:</p>\n<pre><code>def get_row_tax_percentage(product_name: str):\n exempt = is_exempt(product_name)\n imported = is_imported(product_name)\n if exempt:\n if imported:\n return Decimal(".05")\n else:\n return Decimal("0")\n else:\n if imported:\n return Decimal(".15")\n else:\n return Decimal(".1")\n</code></pre>\n<p>That said, if the goal is to make a code golf like as-short-as-possible solution, I totally agree with the other answers. Code golf is fun, but has no reason to exist in production code.</p>\n<p>If you want that, you can go with this fun solution:</p>\n<pre><code>def get_row_tax_percentage(product_name: str):\n return [ Decimal(x) for x in ["0.1", "0.15", "0", "0.05"] ][is_imported(product_name) + is_exempt(product_name)*2]\n</code></pre>\n<p>This is a nifty one-liner that anyone that needs to maintain the code after you will hate you for.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:10:41.573",
"Id": "512751",
"Score": "1",
"body": "How is a direct translation from the task description to code *\"a lot less maintainable and understandable\"* than inventing new logic and hiding the calculation of those four numbers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:22:28.773",
"Id": "512755",
"Score": "0",
"body": "Your one-liner wants a whopping 50% tax for some products when it should be 5%."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:30:02.830",
"Id": "512759",
"Score": "0",
"body": "Since you started the golfing, here's mine, 49 characters shorter :-) `return Decimal(2-is_exempt(p:=product_name)*2+is_imported(p))/20`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T20:54:10.437",
"Id": "512783",
"Score": "1",
"body": "Btw if one of the two tax numbers does get changed then the solutions just following the specification simply need to update that number. You on the other hand will need to update *two* numbers and you'll have to calculate them. And if yet another tax is added, your style would add four more branches? In another indentation level? And all that is supposed to be *more* maintainable?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T20:29:59.007",
"Id": "512894",
"Score": "0",
"body": "A less evil version of your golf is to work with a 2D array so we don't need to double one of the booleans. This is more maintainable, especially with many extra conditions. One could even make an argument for such an approach if the effects aren't simply additive. (It's not an argument I'd make, though.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T07:23:29.147",
"Id": "512924",
"Score": "0",
"body": "@Manuel The problem statement was posted only after I posted my answer. Before that, it was only the code. And inferring from the code that you could reduce the thing to additions is evil. In this case it turns out to be right from the problem statement. But if you see code like that and infer that you could reduce it using mathematical tricks, that's not good."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:45:27.533",
"Id": "259871",
"ParentId": "259801",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T13:58:40.217",
"Id": "259801",
"Score": "15",
"Tags": [
"python",
"python-3.x"
],
"Title": "Having a string representing items in a cart, elaborate taxes and totals. Interview task in Python"
}
|
259801
|
<p>I wrote the following Chess logic in Kotlin and am looking for feedback to make the code cleaner and follow good software design principles. I tried to adhere to <strong>object-oriented design</strong>.</p>
<p>Some notes:</p>
<p>• I ignored special moves like "Castling" and "en pessant" for simplicity.</p>
<p>• I put the <strong>last <code>when</code> branch</strong> into a separate <code>when</code> statement so that the orthogonal and diagonal Queen moves can add up.</p>
<p>• To <strong>reset</strong> the game you initialize a new <code>ChessGame</code> object. Would it be better to add a <code>reset</code> method like this instead?</p>
<pre><code>fun resetGame() {
positionsArray = getStartingPositions()
currentPlayer = Player.White
removedPiecesList = mutableListOf()
}
</code></pre>
<p>The code itself:</p>
<pre><code>class ChessGame {
var currentPlayer: Player = Player.White
private var playingFieldArray = getStartingPositions()
val playingField: Array<Array<Piece>> = playingFieldArray
private fun getStartingPositions() = arrayOf<Array<Piece>>(
arrayOf(
Piece.Black.Rook1,
Piece.Black.Knight1,
Piece.Black.Bishop1,
Piece.Black.Queen,
Piece.Black.King,
Piece.Black.Bishop2,
Piece.Black.Knight2,
Piece.Black.Rook2
),
arrayOf(
Piece.Black.Pawn1,
Piece.Black.Pawn2,
Piece.Black.Pawn3,
Piece.Black.Pawn4,
Piece.Black.Pawn5,
Piece.Black.Pawn6,
Piece.Black.Pawn7,
Piece.Black.Pawn8
),
arrayOf(
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty
),
arrayOf(
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty
),
arrayOf(
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty
),
arrayOf(
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty,
Piece.Empty
),
arrayOf(
Piece.White.Pawn1,
Piece.White.Pawn2,
Piece.White.Pawn3,
Piece.White.Pawn4,
Piece.White.Pawn5,
Piece.White.Pawn6,
Piece.White.Pawn6,
Piece.White.Pawn8
),
arrayOf(
Piece.White.Rook1,
Piece.White.Knight1,
Piece.White.Bishop1,
Piece.White.Queen,
Piece.White.King,
Piece.White.Bishop2,
Piece.White.Knight2,
Piece.White.Rook2
),
)
private var removedPiecesList = mutableListOf<Piece>()
val removedPieces: List<Piece> = removedPiecesList
fun getAvailableMoves(x: Int, y: Int): List<Pair<Int, Int>> {
if (playingFieldArray[x][y] is Piece.White && currentPlayer == Player.Black ||
playingFieldArray[x][y] is Piece.Black && currentPlayer == Player.White ||
isGameOver()
) {
return emptyList()
}
val availableMoves = mutableListOf<Pair<Int, Int>>()
fun isValidPosition(x: Int, y: Int) = x in 0..7 && y in 0..7 && !tileHasPieceOfCurrentPlayer(x, y)
when (playingFieldArray[x][y]) {
Piece.Black.Rook1, Piece.Black.Rook2, Piece.White.Rook1, Piece.White.Rook2, Piece.Black.Queen, Piece.White.Queen -> {
var toXUp = x - 1
val toYUp = y
while (isValidPosition(toXUp, toYUp)
&& !tileHasPieceOfCurrentPlayer(toXUp, toYUp)
) {
availableMoves.add(Pair(toXUp, toYUp))
if (tileHasPieceOfOpponent(toXUp, toYUp)) break
toXUp--
}
var toXDown = x + 1
val toYDown = y
while (isValidPosition(toXDown, toYDown)
&& !tileHasPieceOfCurrentPlayer(toXDown, toYDown)
) {
availableMoves.add(Pair(toXDown, toYDown))
if (tileHasPieceOfOpponent(toXDown, toYDown)) break
toXDown++
}
val toXLeft = x
var toYLeft = y - 1
while (isValidPosition(toXLeft, toYLeft)
&& !tileHasPieceOfCurrentPlayer(toXLeft, toYLeft)
) {
availableMoves.add(Pair(toXLeft, toYLeft))
if (tileHasPieceOfOpponent(toXLeft, toYLeft)) break
toYLeft--
}
val toXRight = x
var toYRight = y + 1
while (isValidPosition(toXRight, toYRight)
&& !tileHasPieceOfCurrentPlayer(toXRight, toYRight)
) {
availableMoves.add(Pair(toXRight, toYRight))
if (tileHasPieceOfOpponent(toXRight, toYRight)) break
toYRight++
}
}
Piece.Black.Knight1, Piece.Black.Knight2, Piece.White.Knight1, Piece.White.Knight2 -> {
val toXUpLeft = x - 2
val toYUpLeft = y - 1
if (isValidPosition(toXUpLeft, toYUpLeft)) {
availableMoves.add(Pair(toXUpLeft, toYUpLeft))
}
val toXUpRight = x - 2
val toYUpRight = y + 1
if (isValidPosition(toXUpRight, toYUpRight)) {
availableMoves.add(Pair(toXUpRight, toYUpRight))
}
val toXDownLeft = x + 2
val toYDownLeft = y - 1
if (isValidPosition(toXDownLeft, toYDownLeft)) {
availableMoves.add(Pair(toXDownLeft, toYDownLeft))
}
val toXDownRight = x + 2
val toYDownRight = y + 1
if (isValidPosition(toXDownRight, toYDownRight)) {
availableMoves.add(Pair(toXDownRight, toYDownRight))
}
val toXLeftUp = x - 1
val toYLeftUp = y - 2
if (isValidPosition(toXLeftUp, toYLeftUp)) {
availableMoves.add(Pair(toXLeftUp, toYLeftUp))
}
val toXRightUp = x - 1
val toYRightUp = y + 2
if (isValidPosition(toXRightUp, toYRightUp)) {
availableMoves.add(Pair(toXRightUp, toYRightUp))
}
val toXLeftDown = x + 1
val toYLeftDown = y - 2
if (isValidPosition(toXLeftDown, toYLeftDown)) {
availableMoves.add(Pair(toXLeftDown, toYLeftDown))
}
val toXRightDown = x + 1
val toYRightDown = y + 2
if (isValidPosition(toXRightDown, toYRightDown)) {
availableMoves.add(Pair(toXRightDown, toYRightDown))
}
}
Piece.Black.King, Piece.White.King -> {
val toXUp = x - 1
val toYUp = y
if (isValidPosition(toXUp, toYUp)) {
availableMoves.add(Pair(toXUp, toYUp))
}
val toXDown = x + 1
val toYDown = y
if (isValidPosition(toXDown, toYDown)) {
availableMoves.add(Pair(toXDown, toYDown))
}
val toXLeft = x
val toYLeft = y - 1
if (isValidPosition(toXLeft, toYLeft)) {
availableMoves.add(Pair(toXLeft, toYLeft))
}
val toXRight = x
val toYRight = y + 1
if (isValidPosition(toXRight, toYRight)) {
availableMoves.add(Pair(toXRight, toYRight))
}
val toXUpLeft = x - 1
val toYUpLeft = y - 1
if (isValidPosition(toXUpLeft, toYUpLeft)) {
availableMoves.add(Pair(toXUpLeft, toYUpLeft))
}
val toXUpRight = x - 1
val toYUpRight = y + 1
if (isValidPosition(toXUpRight, toYUpRight)) {
availableMoves.add(Pair(toXUpRight, toYUpRight))
}
val toXDownLeft = x + 1
val toYDownLeft = y - 1
if (isValidPosition(toXDownLeft, toYDownLeft)) {
availableMoves.add(Pair(toXDownLeft, toYDownLeft))
}
val toXDownRight = x + 1
val toYDownRight = y + 1
if (isValidPosition(toXDownRight, toYDownRight)) {
availableMoves.add(Pair(toXDownRight, toYDownRight))
}
}
Piece.Black.Pawn1, Piece.Black.Pawn2, Piece.Black.Pawn3, Piece.Black.Pawn4, Piece.Black.Pawn5, Piece.Black.Pawn6, Piece.Black.Pawn7, Piece.Black.Pawn8 -> {
val toXDown = x + 1
val toY1Down = y
if (isValidPosition(toXDown, toY1Down) && !tileHasPieceOfOpponent(toXDown, toY1Down)) {
availableMoves.add(Pair(toXDown, toY1Down))
}
val toXDownRight = x + 1
val toYDownRight = y + 1
if (isValidPosition(toXDownRight, toYDownRight)
&& tileHasPieceOfOpponent(toXDownRight, toYDownRight)
) {
availableMoves.add(Pair(toXDownRight, toYDownRight))
}
val toXDownLeft = x + 1
val toYDownLeft = y - 1
if (isValidPosition(toXDownLeft, toYDownLeft)
&& tileHasPieceOfOpponent(toXDownLeft, toYDownLeft)
) {
availableMoves.add(Pair(toXDownLeft, toYDownLeft))
}
}
Piece.White.Pawn1, Piece.White.Pawn2, Piece.White.Pawn3, Piece.White.Pawn4, Piece.White.Pawn5, Piece.White.Pawn6, Piece.White.Pawn7, Piece.White.Pawn8 -> {
val toXUp = x - 1
val toYUp = y
if (isValidPosition(toXUp, toYUp) && !tileHasPieceOfOpponent(toXUp, toYUp)) {
availableMoves.add(Pair(toXUp, toYUp))
}
val toXUpRight = x - 1
val toYUpRight = y + 1
if (isValidPosition(toXUpRight, toYUpRight) && tileHasPieceOfOpponent(toXUpRight, toYUpRight)) {
availableMoves.add(Pair(toXUpRight, toYUpRight))
}
val toXUpLeft = x - 1
val toYUpLeft = y - 1
if (isValidPosition(toXUpLeft, toYUpLeft) && tileHasPieceOfOpponent(toXUpLeft, toYUpLeft)) {
availableMoves.add(Pair(toXUpLeft, toYUpLeft))
}
}
}
when (playingFieldArray[x][y]) {
Piece.Black.Bishop1, Piece.Black.Bishop2, Piece.White.Bishop1, Piece.White.Bishop2, Piece.Black.Queen, Piece.White.Queen -> {
var toXUpLeft = x - 1
var toYUpLeft = y - 1
while (isValidPosition(toXUpLeft, toYUpLeft)
&& !tileHasPieceOfCurrentPlayer(toXUpLeft, toYUpLeft)
) {
availableMoves.add(Pair(toXUpLeft, toYUpLeft))
if (tileHasPieceOfOpponent(toXUpLeft, toYUpLeft)) break
toXUpLeft--
toYUpLeft--
}
var toXUpRight = x - 1
var toYUpRight = y + 1
while (isValidPosition(toXUpRight, toYUpRight)
&& !tileHasPieceOfCurrentPlayer(toXUpRight, toYUpRight)
) {
availableMoves.add(Pair(toXUpRight, toYUpRight))
if (tileHasPieceOfOpponent(toXUpRight, toYUpRight)) break
toXUpRight--
toYUpRight++
}
var toXDownLeft = x + 1
var toYDownLeft = y - 1
while (isValidPosition(toXDownLeft, toYDownLeft)
&& !tileHasPieceOfCurrentPlayer(toXDownLeft, toYDownLeft)
) {
availableMoves.add(Pair(toXDownLeft, toYDownLeft))
if (tileHasPieceOfOpponent(toXDownLeft, toYDownLeft)) break
toXDownLeft++
toYDownLeft--
}
var toXDownRight = x + 1
var toYDownRight = y + 1
while (isValidPosition(toXDownRight, toYDownRight)
&& !tileHasPieceOfCurrentPlayer(toXDownRight, toYDownRight)
) {
availableMoves.add(Pair(toXDownRight, toYDownRight))
if (tileHasPieceOfOpponent(toXDownRight, toYDownRight)) break
toXDownRight++
toYDownRight++
}
}
}
return availableMoves
}
fun movePiece(fromX: Int, fromY: Int, toX: Int, toY: Int) {
if (getAvailableMoves(fromX, fromY).contains(Pair(toX, toY))) {
if (tileHasPieceOfOpponent(toX, toY)) {
removedPiecesList.add(playingField[toX][toY])
}
playingFieldArray[toX][toY] = playingFieldArray[fromX][fromY]
playingFieldArray[fromX][fromY] = Piece.Empty
} else {
throw IllegalArgumentException("Invalid move coordinates")
}
currentPlayer = if (currentPlayer == Player.White) Player.Black else Player.White
}
fun tileHasPieceOfCurrentPlayer(x: Int, y: Int) = when (currentPlayer) {
Player.Black -> {
playingField[x][y] is Piece.Black
}
Player.White -> {
playingField[x][y] is Piece.White
}
}
private fun tileHasPieceOfOpponent(x: Int, y: Int) = when (currentPlayer) {
Player.Black -> {
playingField[x][y] is Piece.White
}
Player.White -> {
playingField[x][y] is Piece.Black
}
}
fun isGameOver() =
removedPieces.contains(Piece.White.King) || removedPieces.contains(Piece.Black.King)
sealed class Piece {
sealed class White : Piece() {
object Pawn1 : White()
object Pawn2 : White()
object Pawn3 : White()
object Pawn4 : White()
object Pawn5 : White()
object Pawn6 : White()
object Pawn7 : White()
object Pawn8 : White()
object Rook1 : White()
object Knight1 : White()
object Bishop1 : White()
object Queen : White()
object King : White()
object Bishop2 : White()
object Knight2 : White()
object Rook2 : White()
}
sealed class Black : Piece() {
object Pawn1 : Black()
object Pawn2 : Black()
object Pawn3 : Black()
object Pawn4 : Black()
object Pawn5 : Black()
object Pawn6 : Black()
object Pawn7 : Black()
object Pawn8 : Black()
object Rook1 : Black()
object Knight1 : Black()
object Bishop1 : Black()
object Queen : Black()
object King : Black()
object Bishop2 : Black()
object Knight2 : Black()
object Rook2 : Black()
}
object Empty : Piece()
}
enum class Player {
Black, White
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T10:35:31.030",
"Id": "512671",
"Score": "3",
"body": "I have rolled back your latest edits. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T10:36:43.163",
"Id": "512672",
"Score": "1",
"body": "@Heslacher sorry, I'll read the rules now!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T10:42:05.943",
"Id": "512673",
"Score": "0",
"body": "new Question: https://codereview.stackexchange.com/questions/259851/chess-in-kotlin"
}
] |
[
{
"body": "<p>There's several parts of your design that can be improved.</p>\n<p>There is currently lots of duplicate code regarding color, allowed moves, and Pawn1, Pawn2, Pawn3 etc.</p>\n<p>Is there really any difference between Pawn1, Pawn2, Pawn3, etc? I don't think so. A <code>Piece</code> could be a composition between a player color and an <code>enum class PieceType</code> that lists all the options (without numbering them).</p>\n<p>Your move logic could use a <code>List<Point></code> where a <code>Point</code> is a <code>data class Point(val x: Int, val y: Int)</code>. For a knight this could then be:</p>\n<pre><code>val knightMoves = listOf(\n Point(2, 1), Point(2, -1),\n Point(-1, 2), Point(1, 2),\n Point(-1, -2), Point(1, -2),\n Point(-2, -1), Point(-2, 1)\n)\n</code></pre>\n<p>Then iterate through this list and check which moves are allowed.</p>\n<pre><code>for (val move in knightMoves) {\n if (isValidPosition(x + move.x, y + move.y)) {\n availableMoves.add(move)\n }\n}\n</code></pre>\n<p>It is possible to make more improvements, but... a few things at a time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:10:03.977",
"Id": "512603",
"Score": "0",
"body": "Wow, I just realized how bad my code actually is. I must've been too engrossed in getting it to work. Thank you, I will apply your suggestions tomorrow!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T21:12:27.610",
"Id": "512613",
"Score": "4",
"body": "@FlorianWalther There's definitely room for improvement :) When you've made improvements, I'd recommend posting a follow-up question here on this site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T09:43:02.993",
"Id": "512663",
"Score": "0",
"body": "I am able to extract the Knight and King moves into a `List<Point>` as you described, but I don't see how I can do this for for example Rook moves, since the increment operator depends on the direction (like `toXUp--`) Any ideas?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T10:42:36.173",
"Id": "512674",
"Score": "0",
"body": "I posted my new question here: https://codereview.stackexchange.com/questions/259851/chess-in-kotlin"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:02:21.070",
"Id": "259820",
"ParentId": "259807",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:18:25.107",
"Id": "259807",
"Score": "1",
"Tags": [
"object-oriented",
"game",
"kotlin",
"chess"
],
"Title": "Chess game in Kotlin"
}
|
259807
|
<p>I'm a beginner to intermediate in programming, and created a Tic-tac-toe game in python. I plan to add an AI player and a GUI using pygame.</p>
<p>Any improvements I could make to the code, especially with the logic, or just formatting in general?</p>
<pre><code>my_board = [
["1", "2", "X"],
["4", "5", "6"],
["7", "8", "9"]
]
class Tictactoe():
def __init__(self, board):
self.board = board
def print_board(self):
print("|-------------|")
print("| Tic Tac Toe |")
print("|-------------|")
print("| |")
print("| " + self.board[0][0] + " " + self.board[0][1] + " " + self.board[0][2] + " |")
print("| " + self.board[1][0] + " " + self.board[1][1] + " " + self.board[1][2] + " |")
print("| " + self.board[2][0] + " " + self.board[2][1] + " " + self.board[2][2] + " |")
print("| |")
print("|-------------|")
print()
def available_moves(self):
moves = []
for row in self.board:
for col in row:
if col != "X" and col != "O":
moves.append(int(col))
return moves
def select_space(self, move, turn):
row = (move-1)//3
col = (move-1)%3
self.board[row][col] = "{}".format(turn)
def has_won(self, player):
for row in self.board:
if row.count(player) == 3:
return True
for i in range(3):
if self.board[0][i] == player and self.board[1][i] == player and self.board[2][i] == player:
return True
if self.board[0][0] == player and self.board[1][1] == player and self.board[2][2] == player:
return True
if self.board[0][2] == player and self.board[1][1] == player and board[2][0] == player:
return True
return False
def game_over(self):
self.available_moves()
if self.has_won("X") or self.has_won("O") or len(self.available_moves()) ==0:
return True
else:
return False
def get_player_move(self, turn):
move = int(input("Player {player} make your turn: ".format(player=turn)))
self.available_moves()
while move not in range (1,10) or move not in self.available_moves():
move = int(input("Invalid move, try again: "))
return move
def game(board):
tictactoe = Tictactoe(my_board)
while not tictactoe.game_over():
tictactoe.print_board()
x_move = tictactoe.get_player_move("X")
tictactoe.select_space(x_move,"X")
tictactoe.print_board()
if tictactoe.game_over():
break
o_move = tictactoe.get_player_move("O")
tictactoe.select_space(o_move,"O")
if tictactoe.has_won("X"):
print("X wins")
elif tictactoe.has_won("O"):
print("O wins")
else:
print("tie")
game(my_board)
</code></pre>
|
[] |
[
{
"body": "<hr />\n<p><strong>Indents</strong></p>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/#indentation\" rel=\"nofollow noreferrer\">PEP 8: <em>Use 4 spaces per indentation level.</em></a></p>\n<hr />\n<p><strong>Main game loop</strong></p>\n<p>The way your game loop is set up now is a bit unelegant. You already implemented all the methods to be able to handle both players, there's only one piece missing:</p>\n<pre><code>from itertools import cycle\n\nplayers = cycle(['X', 'O'])\n</code></pre>\n<p><code>cycle</code> will provide a generator that infinitely repeats the iterable you pass it. This makes the loop quite a bit cleaner:</p>\n<pre><code>while not tictactoe.game_over():\n tictactoe.print_board()\n\n player = next(players)\n move = tictactoe.get_player_move(player)\n tictactoe.select_space(move, player)\n</code></pre>\n<p>I'd also suggest renaming <code>select_space</code> to something like <code>do_move</code>. Makes it a bit clearer what's going on.</p>\n<hr />\n<p><strong>Redundant calls to <code>Tictactoe.available_moves()</code></strong></p>\n<p>In <code>game_over</code> and <code>get_player_move</code> you call <code>self.available_moves()</code> once without using the return value in any way. You can simply delete those lines.</p>\n<hr />\n<p><strong><code>game_over</code></strong></p>\n<p>The pattern</p>\n<pre><code>if self.has_won("X") or self.has_won("O") or len(self.available_moves()) ==0:\n return True\nelse:\n return False\n</code></pre>\n<p>can be simplified to</p>\n<pre><code>return self.has_won("X") or self.has_won("O") or len(self.available_moves()) == 0\n</code></pre>\n<p>What you were doing is basically manually returning the resulting <code>bool</code> value of a condition. We can instead simply return the condition directly.</p>\n<hr />\n<p><strong><code>print_board</code></strong></p>\n<p>Python lets you easily avoid an unelegant pattern</p>\n<pre><code>print("| " + self.board[0][0] + " " + self.board[0][1] + " " + self.board[0][2] + " |")\n</code></pre>\n<p>by using the <code>*</code> operator for unpacking an iterable</p>\n<pre><code>print("| ", *self.board[0], " |")\n</code></pre>\n<p>Since we need to do this for all rows in <code>self.board</code> we should let Python handle it for us as well:</p>\n<pre><code>for row in self.board:\n print("| ", *row, " |")\n</code></pre>\n<hr />\n<p><strong>has_won</strong></p>\n<p>For a cleaner implementation of this method I would suggest implementing helper functions that provide lists of the rows, columns and diagonals of the board. They might also be useful for future feature additions.</p>\n<pre><code>def rows(self):\n return self.board[:] # creates a mutable copy of the rows\n\ndef columns(self):\n return [[row[index] for row in self.board] for index in range(3)]\n\ndef diagonals(self):\n first = [self.board[index][index] for index in range(3)]\n second = [self.board[index][len(self.board[index]) - index - 1] for index in range(3)]\n return [first, second]\n</code></pre>\n<p>These methods are also ready to be used for boards of different sizes. Simply replace the <code>3</code>s by a variable.</p>\n<p><code>has_won</code> is now a lot simpler and more readable:</p>\n<pre><code>def has_won(self, player):\n for line in self.rows() + self.columns() + self.diagonals():\n symbols = set(line)\n if player in symbols and len(symbols) == 1:\n return True\n\n return False\n</code></pre>\n<p>We can take this a step further (as pointed out in the comments) and change <code>has_won</code> to <code>get_winner</code> and return the winning symbol. This will also affect some other parts of your code:</p>\n<p><code>class Tictactoe</code>:</p>\n<pre><code>def get_winner(self):\n for line in self.rows() + self.columns() + self.diagonals():\n symbols = set(line)\n if len(symbols) == 1:\n return symbols.pop()\n\n return None\n\n\ndef game_over(self):\n return self.get_winner() is not None or len(self.available_moves()) == 0\n</code></pre>\n<p>Printing our winner in <code>game</code>:</p>\n<pre><code>def game(...):\n \n # main gameplay here\n \n if (winner := self.get_winner()) is not None:\n print(f"{winner} wins")\n else:\n print("tie")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T22:55:59.063",
"Id": "512619",
"Score": "1",
"body": "Plenty of good advice here. In addition, the OP could consider another simplification of has_won(): unless I've overlooked something, it doesn't need the player argument: if all symbols are the same (and not empty), someone has one; just return who it is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:29:45.220",
"Id": "512722",
"Score": "0",
"body": "Very good suggestion, I added it to my answer!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T19:26:55.467",
"Id": "259817",
"ParentId": "259809",
"Score": "4"
}
},
{
"body": "<p>one performance improvement suggestion</p>\n<p><strong>available_moves</strong></p>\n<p>Instead of iterating through all the moves create a <code>set</code> with all the moves in the beginning and as each player makes a move remove the corresponding move from the set.</p>\n<p>In your code both iterating through all moves to find the valid moves(<code>available_moves</code> function) and then the checking if the move given is valid (<code>move not in self.available_moves()</code>) both of this are <strong>o(n)</strong> operations. But using set I believe both these operation could average to <strong>o(1)</strong>.</p>\n<p>Might not be a huge difference in performance considering tic tac toe only has 9 moves. But might be a good way to tackle the problems in other similar situations.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T05:30:49.127",
"Id": "259841",
"ParentId": "259809",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T15:40:24.627",
"Id": "259809",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"tic-tac-toe",
"formatting"
],
"Title": "Tic-tac-toe in python with OOP"
}
|
259809
|
<p>I've been working on this for a while, and now that I've got a working program I thought I'd see what other people think about it.</p>
<p>Basically if there is anything you think would make it faster or make it simpler, or make it better in general, please share your thoughts. As for actual strength, I have no idea how to test that. And yes, I know I should just use AES, but this is just for practice/fun more than anything.</p>
<p>Anyway, here's the code. (255 lines, sorry)</p>
<pre><code>import base64
import os
import random
# from datetime import datetime
def add_padding(s, i=128):
padding = len(s) % i
for j in range(i - padding):
s += '='
s = ascii_to_bin(s)
# make last byte equal to number of padding bytes
s = s[:len(s) - 8] + decimal_to_binary([i - padding])
return s
def xor_string(k, s):
xored_secret = ''
for i in range(len(s) // len(k)):
if i > 0:
k = round_key(k)
xored_secret += decimal_to_binary([bin_to_decimal(k, len(k))[0] ^ bin_to_decimal(s[i * len(k):len(k) + (i * len(k))], len(k))[0]], len(k))
return xored_secret
def generate_key(k):
if len(k) == 128:
k = ascii_to_bin(k)
return k
elif len(k) < 128:
k = ascii_to_decimal(k)
for i in range(128 - len(k)):
b = decimal_to_binary([k[i]])
b = xor_string(decimal_to_binary([int(sum(k) / len(k))]), b[::-1])
k.append(int(b, 2))
s = ''
for i in k:
s += str(i)
j = str(s[:len(s) // 2])
y = str(s[len(s) // 2:])
s = decimal_to_binary([int(y + j)])
s = s[:1024]
return s
def bin_to_base64(binary):
return base64.b64encode(bytes([int(binary[i * 8:8 + i * 8], 2) for i in range(len(binary) // 8)])).decode()
def ascii_to_bin(string):
return decimal_to_binary(ascii_to_decimal(string))
def bin_to_decimal(binary, length=8):
b = [binary[i * length:length + (i * length)] for i in range(len(binary) // length)]
decimal = [int(i, 2) for i in b]
# returns an list of ints
return decimal
def decimal_to_binary(decimal, length=8):
output = ''
for i in range(len(decimal)):
output += str(bin(decimal[i])[2:].zfill(length))
# returns a string
return output
def ascii_to_decimal(string):
# returns a list of ints
return [ord(i) for i in string]
def bin_to_ascii(binary):
x = bin_to_decimal(binary)
s = ''
for i in x:
s += chr(i)
# returns a string
return s
def base64_to_bin(base):
decoded = ''
for letter in base64.b64decode(base):
# print(letter)
decoded += bin(letter)[2:].zfill(8)
return decoded
def matrix_to_str(m):
s = ''
for i in range(32):
for j in range(32):
s += str(m[i][j])
return s
def obfuscate(binary, k, x, xd):
b = ''
d = k # donkey kong
for i in range(len(binary) // 1024):
if i > 0:
d = round_key(d)
# m = [list(binary[j * 32 + i * 1024:j * 32 + i * 1024 + 32]) for j in range(32)]
if x:
m = [list(binary[j * 32 + i * 1024:j * 32 + i * 1024 + 32]) for j in range(32)]
m = shuffle(m, bin_to_decimal(d, 1024)[0], xd)
b += xor_string(d, matrix_to_str(m))
elif not x:
xor = xor_string(d, binary[i * 1024:i * 1024 + 1024])
m = [list(xor[j * 32:j * 32 + 32]) for j in range(32)]
m = reverse_shuffle(m, bin_to_decimal(d, 1024)[0], xd)
b += matrix_to_str(m)
return xor_string(k, b)
def shuffle(m, d, xd):
for j in range(xd):
# move columns to the right
m = [row[-1:] + row[:-1] for row in m]
# move rows down
m = m[-1:] + m[:-1]
shuffled_m = [[0] * 32 for _ in range(32)]
for idx, sidx in enumerate(test(d)):
shuffled_m[idx // 32][idx % 32] = m[sidx // 32][sidx % 32]
m = shuffled_m
# cut in half and flip halves
m = m[len(m) // 2:] + m[:len(m) // 2]
# test
m = list(map(list, zip(*m)))
return m
def reverse_shuffle(m, d, xd):
for j in range(xd):
# test
m = list(map(list, zip(*m)))
# cut in half and flip halves
m = m[len(m) // 2:] + m[:len(m) // 2]
shuffled_m = [[0] * 32 for _ in range(32)]
for idx, sidx in enumerate(test(d)):
shuffled_m[sidx // 32][sidx % 32] = m[idx // 32][idx % 32]
m = shuffled_m
# move rows up
m = m[1:] + m[:1]
# move columns to the left
m = [row[1:] + row[:1] for row in m]
return m
def test(d):
random.seed(d)
lst = list(range(1024))
random.shuffle(lst)
return lst
def round_key(k):
k = [[k[(j * 32 + n)] for n in range(32)] for j in range(32)]
# get the last column
col = [i[-1] for i in k]
# interweave
col = [x for i in range(len(col) // 2) for x in (col[-i - 1], col[i])]
new_key = ''
for i in range(32):
cols = ''
for row in k:
cols += row[i]
cols = cols[16:] + cols[:16]
new_key += xor_string(''.join(str(ele) for ele in col), cols)
return new_key
def encrypt(p, s, xd):
k = generate_key(p)
s = add_padding(s)
s = xor_string(k, s)
s = obfuscate(s, k, True, xd)
s = bin_to_base64(s)
return s
def decrypt(p, b, xd):
k = generate_key(p)
b = base64_to_bin(b)
b = xor_string(k, b)
b = obfuscate(b, k, False, xd)
pad = b[len(b) - 8:]
b = bin_to_ascii(b)
b = b[:len(b) - bin_to_decimal(pad)[0]]
return b
if __name__ == '__main__':
while True:
os.system('cls')
com = input('1)Encrypt Text \n2)Decrypt Text\n3)Exit\n')
if com == '1':
os.system('cls')
secret = input('Enter the text you wish to encrypt: ')
os.system('cls')
key = input('Enter your key: ')
os.system('cls')
print(f'Encrypted text: {encrypt(key, secret, 1)}') # the 1 is the number of loops, I'm not sure how many I should do :/
input()
elif com == '2':
os.system('cls')
b64 = input('Enter the text you wish to decrypt: ')
os.system('cls')
key = input('Enter your key: ')
os.system('cls')
print(f'Decrypted text: {decrypt(key, b64, 1)}')
input()
elif com == '3':
break
</code></pre>
<p>If you need clarification on anything, just ask. Thanks!</p>
|
[] |
[
{
"body": "<p>Needs docstrings and better parameter names.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T21:07:31.607",
"Id": "512612",
"Score": "0",
"body": "\"not useful\"-voter please explain how it isn't. That code is really hard to understand without those, so I fail to see how this isn't useful advice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T21:21:33.293",
"Id": "512614",
"Score": "3",
"body": "I didn't downvote this, but it does seem pretty curt and barely qualifies as a valid answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T21:27:28.747",
"Id": "512615",
"Score": "0",
"body": "@chicks Where's the rule against curtness and what does it say is the minimum answer length? There really isn't anything more to say, in my opinion. I'm not even going to try reading such obfuscated code. I'd do the same for a review request at work and they'd need to de-obfuscate before sending another."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T23:09:21.107",
"Id": "512622",
"Score": "3",
"body": "There's no such rule that I'm aware of. There might might a rule about showing extra courtesy and effort to new contributors to the site. The community expectations are different on CodeReview.SE than StackOverflow. You might not get downvoted as much for this over there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T00:58:32.877",
"Id": "512627",
"Score": "0",
"body": "@Manuel what is a docstring?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T01:00:42.040",
"Id": "512628",
"Score": "0",
"body": "@Haveaniceday See [google](https://www.google.com/search?q=python+docstring) or [What is a Docstring?](https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T01:01:37.257",
"Id": "512629",
"Score": "0",
"body": "@Manuel so comments basically..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T01:06:17.100",
"Id": "512631",
"Score": "2",
"body": "@Haveaniceday A certain kind, yes. For example, I have no idea what your `shuffle(m, d, xd)` is supposed to do. The parameter names are meaningless, and there's no explanation, either. A docstring would be a good way to say what that function does. If it said what the parameter names mean, then *maybe* some of them could even remain as they are (for example, if `m` is a *message* and the docstring says something like \"Shuffles the message m by blah blah...\")."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T01:08:29.483",
"Id": "512632",
"Score": "0",
"body": "@Manuel +1 :). I've never been very good about commenting, so I'll have to work on that. I'll also go through and get rid of single letter var names."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:28:14.623",
"Id": "512884",
"Score": "2",
"body": "Short reviews like this lack an explanation of how and/or why your suggestion makes the code better, please explain how and/or why you would implement your solution, this helps us all understand how and why it would make the code better in this situation. Please see our Help Section on [How To Give Good Answer](//codereview.stackexchange.com/help/how-to-answer)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:35:43.277",
"Id": "512885",
"Score": "2",
"body": "We do appreciated short answers that are straight to the point, and we do have several Meta Posts about short answers. With that said, none of the good short answers on Code Review are this short, please take some time and check out [some of the examples put together on this Meta Post](https://codereview.meta.stackexchange.com/questions/1008/answering-guidelines-answer-length)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:42:42.420",
"Id": "512886",
"Score": "2",
"body": "@Manuel, I apologize for so many comments. if you were to add some of the information from your comments to your answer, the answer would be much better. Comments are not meant to be long term, they can be wiped out at any time, but the answer posts are much more permanent. you are giving very good information, I just don't want to see it get lost. thank you for taking the time to read through the comments and better understand how Code Review works."
}
],
"meta_data": {
"CommentCount": "12",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:24:37.013",
"Id": "259821",
"ParentId": "259814",
"Score": "-1"
}
},
{
"body": "<p>Welcome to Code Review.</p>\n<h1>good things</h1>\n<ul>\n<li>reasonable function names</li>\n<li>making it importable by putting the CLI into the <code>if __name__ == '__main__':</code> block</li>\n<li>good indentation and use of white space</li>\n</ul>\n<h1>suggestions</h1>\n<ul>\n<li>stuffing the entire function into the <code>return</code> line works better on <code>ascii_to_bin</code> than <code>bin_to_base64</code>.</li>\n<li>single letter variable names are frowned upon because they are easy for folks to get confused. Using <code>key</code> instead of <code>k</code>, and such, would help the code be more readable</li>\n<li>before one of the serious pythonistas comes along you should read up on <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. There are linters to help with this.</li>\n<li>this is limited to running on DOS-derived systems. <code>cls</code> doesn't exist on Macs or Linux. <a href=\"https://stackoverflow.com/a/23075152/2002471\">Here</a> is a portable solution.</li>\n<li>include a sh-bang line (<code>#!</code>) to clarify which python this should run under.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T01:03:47.277",
"Id": "512630",
"Score": "0",
"body": "Ty for the answer! Just one of follow-up question. When you say \"stuffing the entire function into the `return` line works better on `ascii_to_bin` than `bin_to_base64`.\" , was that just because it is so long?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T03:21:17.587",
"Id": "512634",
"Score": "0",
"body": "The length of the line was one factor, but it also seemed much more complicated. Laying that out over a few lines would be kinder to the casual reader."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T04:08:05.883",
"Id": "512639",
"Score": "0",
"body": "Gotcha. Although if I had thought you would mention complicated lines I figured it would have been the one in `xor_string` ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T04:55:09.867",
"Id": "512643",
"Score": "0",
"body": "As you can see readily on this page, code reviews catch what they notice and some things might not crop up until a subsequent review cycle. (Note on this site that you can't modify your current question's code. A new review needs a new question.)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T23:22:07.620",
"Id": "259829",
"ParentId": "259814",
"Score": "5"
}
},
{
"body": "<h1>Add Padding</h1>\n<pre class=\"lang-py prettyprint-override\"><code>def add_padding(s, i=128):\n padding = len(s) % i\n\n for j in range(i - padding):\n s += '='\n\n ...\n</code></pre>\n<p>If <code>s</code> is a 127 characters, <code>padding</code> becomes 127, but only 1 <code>=</code> character is added.</p>\n<p>If <code>s</code> is 128 characters, <code>padding</code> becomes zero, which makes sense. But then 128 <code>=</code> characters get added to the string, which is really unexpected. I understand it is necessary, because you replace the last with the amount of padding, but it violates the principle of least surprise.</p>\n<p>Using...</p>\n<pre><code>s += '=' * (i - padding)\n</code></pre>\n<p>would be more efficient than a loop.</p>\n<p>After adding the padding, and converting it into bits, you remove the last 8 bits of the padding, replacing it with the length of the padding. You could have saved some work by not adding the extra padding character in the first place.</p>\n<hr />\n<p>Here's some reworked code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def add_padding(message, frame_size=128):\n payload_len = len(message) + 1 # Extra character encodes padding length\n padding = -payload_len % frame_size # Amount of padding needed to fill frame\n\n frames = message + '=' * padding + chr(padding + 1)\n return ascii_to_bin(frames)\n</code></pre>\n<hr />\n<h1>ASCII to Decimal</h1>\n<pre><code>def ascii_to_decimal(string):\n # returns a list of ints\n return [ord(i) for i in string]\n</code></pre>\n<p>While this looks nice and simple, much of your code expects 8-bit bytes, not integers. The first <code>ā</code> in the string will get turned into a 257, and a subsequent <code>bin(letter)[2:].zfill(length)</code> will expand that to <code>'100000001'</code>, despite being longer than 8 characters</p>\n<p>Python has a builtin function which converts a string into an array of bytes. <code>str.encode()</code>. By default, it will use the <code>UTF-8</code> encoding and will encode non-ASCII characters into multiple bytes, as required:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> msg = 'cbā'\n>>> msg_bytes = msg.encode()\n>>> print(len(msg), len(msg_bytes), type(msg_bytes))\n3 4 <class 'bytes'>\n</code></pre>\n<p>But note the length of the byte-array is (in this case) greater than the length of the string, which will mess up your padding. The simplest fix is to convert the string into an array of bytes, and then determine how much padding is required, and add that to the byte array.</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> msg_bytes = msg.encode()\n>>> payload_len = len(msg_bytes) + 1\n>>> padding = -payload_len % frame_size\n>>> frames = msg_bytes + b'=' * padding + bytes([padding + 1])\n</code></pre>\n<p>As a bonus, the <code>bytes</code> (read-only) and <code>bytearray</code> (mutable) objects are way more efficient than using lists of integers, so you can gain some speed and/or memory efficiency by switching to them.</p>\n<p>To reverse this in the decoding step:</p>\n<pre class=\"lang-py prettyprint-override\"><code>>>> padding = frames[-1] # amount of padding added\n>>> msg_bytes = frames[:-padding] # unpadded message bytes\n>>> msg = msg_bytes.decode() # decode bytes back to a string\n>>> msg\n'cbā'\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T01:16:53.637",
"Id": "512804",
"Score": "0",
"body": "So I replaced `return [ord(i) for i in string]` with `return bytearray(string.encode())`. Is that what you meant? The change actually seems to be slowing it down :/. `0:00:00.002810` old vs `0:00:00.003025` new (average of 10000 runs)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T02:25:27.117",
"Id": "512809",
"Score": "0",
"body": "So when you say, 'I'm suggesting encoding to a byte array and then padding.', I did this: `frames = (message + '=' * padding + chr(padding + 1)).encode()`. Is that what you meant? Sorry for all the questions, but I really appropriate the help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:20:55.883",
"Id": "512883",
"Score": "0",
"body": "See updated \"ASCII to Decimal\" section in the review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T22:40:31.223",
"Id": "512899",
"Score": "0",
"body": "So I have applied the changes, but there is an issue. After decrypting, it converts from binary to ascii. In that process it converts every 8 bits to an int, and then `chr(num)`'s it. But how can I tell if it sould be more than 8, for the `ā`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T05:09:38.660",
"Id": "512911",
"Score": "0",
"body": "Your not suppose to tell if you need more than one byte per letter; that is the job of `bytes.decode()`. It sounds like you are still trying to use a list of ints, instead of `bytes` (an array of value-restricted ints). We're beyond a code review here. I've suggested an improvement direction, and you've run into problems implementing it. You probably want to post a new question on Stack Overflow asking what you are doing wrong in the conversion. Answers there can be answers to a question, instead of comments on an answer here. (Post a link to the new question here, so we can follow.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T05:20:20.397",
"Id": "512912",
"Score": "0",
"body": "Ah yes, forgot about SO for a second. Ty for all the help!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T05:21:40.487",
"Id": "512914",
"Score": "0",
"body": "When you have a working implementation, feel free to post a new question here for further review."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:39:36.137",
"Id": "513263",
"Score": "0",
"body": "Here's the new question [Encryption/Decryption algorithm #2](https://codereview.stackexchange.com/questions/260077/encryption-decryption-algorithm-2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T23:06:46.643",
"Id": "513539",
"Score": "0",
"body": "New question here [Encryption/Decryption algorithm #3](https://codereview.stackexchange.com/questions/260171/encryption-decryption-algorithm-3)."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T05:39:16.080",
"Id": "259842",
"ParentId": "259814",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259842",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T17:10:53.683",
"Id": "259814",
"Score": "6",
"Tags": [
"python"
],
"Title": "Encryption/Decryption algorithm"
}
|
259814
|
<p>I am trying to write a python script that can search through Fortran code
ignoring comments. I didn't find a simple way of doing this using grep. So I startwed writing my own.</p>
<p>The rules for comments that I am following are:</p>
<ol>
<li>the first character is not a space or a number. It is usually a c, C but I've seen * and other variations</li>
<li>the above condition can be violated if its a fortran90/95 code in that case, its complicated so I am not treating that case for now.</li>
<li>the first non-space character is a "!"</li>
</ol>
<p>I could not find a simple solution that ignores all types of fortran comments in text so I started writing my own in python 2.x. It looks dirty but works in many cases.</p>
<pre class="lang-py prettyprint-override"><code>#!/usr/bin/python
import sys
def fgrep(file_name, cond):
first_valid_chars=tuple(range(0,10 )) + (' ',)
with open(file_name, 'r') as f:
for line in f:
if line[0] in first_valid_chars:
line1 = line.strip()
if line1: # ignore empty lines
if line1[0] != '!':
# fortran is case insensitive so comparing lower to lower
if cond.lower() in line1.lower():
print(line1)
if __name__ == "__main__":
print(sys.argv[1])
file_name = sys.argv[1]
cond = sys.argv[2]
fgrep(file_name, cond)
</code></pre>
<p>It's drty, not clean and too many indents. How do I clean this up? Because I copy-pasted from editor, there could be errors due to indentation.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T18:19:30.680",
"Id": "512590",
"Score": "0",
"body": "@Peilonrayz, probably resulting from copy-pasting from my editor. Can you try now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T18:30:39.623",
"Id": "512591",
"Score": "0",
"body": "Looks runnable now, thank you."
}
] |
[
{
"body": "<h1>Shebang</h1>\n<p><code>#!/usr/bin/python</code> is not portable, <code>#!/usr/bin/env python</code> is preferred.</p>\n<h1>White Space</h1>\n<p>There should be a blank line between your imports and your function declarations.</p>\n<h1>Efficiency</h1>\n<p>You are constantly converting your <code>cond</code> to lowercase. You don't need to repeatedly do this; just do it once, before the loop.</p>\n<h1>Right Leaning Code</h1>\n<p>As you've mention, the code is way-too right leaning.</p>\n<p>You could fix this with <code>continue</code> type statements ...</p>\n<pre class=\"lang-py prettyprint-override\"><code>def fgrep(file_name, cond):\n first_valid_chars=tuple(range(0,10 )) + (' ',)\n\n # Fortran is case insensitive so comparing lower to lower\n cond = cond.lower()\n with open(file_name, 'r') as f:\n for line in f: \n if line[0] not in first_valid_chars:\n continue\n\n line1 = line.strip()\n if not line1: # ignore empty lines\n continue\n\n if line1[0] == '!':\n continue\n\n if cond in line1.lower():\n print(line1)\n</code></pre>\n<h1>RegEx</h1>\n<p>You could use a Regular Expression to identify comment lines.</p>\n<ul>\n<li><code>\\s*!</code> would find an exclamation mark after any number of spaces.</li>\n<li><code>[^\\d\\s]</code> would match anything but a digit or a white-space character.</li>\n</ul>\n<p>Combined these with the <code>|</code> or-operator, and use <code>.match()</code> to search from the start of the string, and you get an easy comment-line predicate:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def fgrep(file_name, cond):\n # A comment line starts with an exclamation mark as the first non-blank character,\n # or any non-blank character other than a digit as the first character. \n comment = re.compile(r'\\s*!|[^\\d\\s]')\n\n # Fortran is case insensitive so comparing lower to lower\n cond = cond.lower()\n\n with open(file_name, 'r') as f:\n for line in f: \n if not comment.match(line) and cond in line.lower():\n print(line)\n</code></pre>\n<h1>Line numbers</h1>\n<p>You might want to print out the line number of the matching line, to make it easier to find the lines in the file. <code>enumerate</code> would help:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def fgrep(file_name, cond):\n # A comment line starts with an exclamation mark as the first non-blank character,\n # or any non-blank character other than a digit as the first character. \n comment = re.compile(r'\\s*!|[^\\d\\s]')\n\n # Fortran is case insensitive so comparing lower to lower\n cond = cond.lower()\n\n with open(file_name, 'r') as f:\n for line_no, line in enumerate(f, 1): \n if not comment.match(line) and cond in line.lower():\n print(line_no, line, sep=": ")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:38:24.293",
"Id": "259822",
"ParentId": "259815",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259822",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T17:55:22.080",
"Id": "259815",
"Score": "1",
"Tags": [
"python",
"fortran"
],
"Title": "Search through fortran source for a string ignoring comments"
}
|
259815
|
<p>I wrote this code that's supposed to implement a 1-dimensional (!) <a href="https://en.wikipedia.org/wiki/Expectation%E2%80%93maximization_algorithm" rel="nofollow noreferrer">EM algorithm</a> with k-means initialization:</p>
<pre><code>begin
import Pkg
Pkg.activate(temp=true)
Pkg.add(["StaticArrays"; "Plots"; "BenchmarkTools"])
end
using Printf
using LinearAlgebra: norm
using Statistics: quantile
using StaticArrays
"Density of standard normal distribution"
@inline ϕ(x) = exp(-x^2 / 2) / sqrt(2π)
"""
Log likelihood to be optimized:
∑ₜlog(∑ᵢpᵢ * ϕ((xₜ - μᵢ) / σᵢ))
"""
@inline log_likelihood(x, p, μ, σ) = sum(log.((p ./ σ)' * ϕ.((x' .- μ) ./ σ)))
# Termination criteria
@inline metric_l1(θ₀::AbstractVector, θ₁::AbstractVector) = maximum(abs.(θ₀ - θ₁))
@inline metric_l2(θ₀::AbstractVector, θ₁::AbstractVector) = norm(θ₀ - θ₁)
"""
All parameters are stored into a single vector θ,
but sometimes individual parameters (p, μ, σ) need to be accessed.
`get_pμσ` implements this access.
"""
@inline function get_pμσ(θ::AbstractVector, k::Integer)
p = @view θ[1:k]
μ = @view θ[k + 1:2k]
σ = @view θ[2k + 1:end]
p, μ, σ
end
@inline function get_pμσ(θ::MVector{_3k}) where _3k
k = Int(_3k / 3)
p = @view θ[1:k]
μ = @view θ[k + 1:2k]
σ = @view θ[2k + 1:end]
p, μ, σ
end
"""
Storage for all data needed for EM algorithm.
`k` - integer that specifies the number of components
in the mixture;
`_3k` - `3 * k`, needed for `StaticArrays`
"""
mutable struct EMData{k, T <: Real, _3k}
# Parameters to be estimated
θ::MVector{_3k, T}
θ_old::MVector{_3k, T}
θ_tmp::MVector{_3k, T}
# Probabilities for each component
probs::MVector{k, T}
probs_tmp::MVector{k, T}
distances::MVector{k, T}
# Vector to store temporary `p ./ σ`
pσ::MVector{k, T}
function EMData(x::AbstractVector{T}, k::UInt) where T <: Real
@assert k > 1
k = Int(k)
# Initialize parameters
θ = MVector([
# pᵢ = 1/k
ones(k) ./ k;
# μᵢ = quantile(i)
quantile(x, range(zero(T), one(T), length=k));
# σᵢ = 1
ones(k)
]...)
θ_old = @MVector zeros(T, 3k)
θ_tmp = MVector{3k, T}(undef)
probs = MVector{k, T}(undef)
probs_tmp = MVector{k, T}(undef)
distances = MVector{k, T}(undef)
new{k, T, 3k}(
θ, θ_old, θ_tmp,
probs, probs_tmp, distances,
MVector{k, T}(undef)
)
end
end
"""
Actual EM algorithm.
Fit the model to data in `x`.
"""
function em!(
data::EMData{k, T}, x::AbstractVector{T};
tol::T=3e-4, eps::T=1e-6, metric=metric_l2
) where {k, T <: Real}
# All of these are "pointers" into `θ`
p, μ, σ = get_pμσ(data.θ)
p_tmp, μ_tmp, σ_tmp = get_pμσ(data.θ_tmp)
i = 0
while i == 0 || metric(data.θ, data.θ_old) > tol
data.probs .= μ_tmp .= σ_tmp .= zero(T)
if i < 4
# Initialization steps using k-means
@inbounds for x_ ∈ x
# Get index of the centroid closest
# to the current data point `x_`
idx = argmin(abs.(μ .- x_))
# Temporary computations for
# new centroids and standard deviations
# for each cluster
μ_tmp[idx] += x_
σ_tmp[idx] += (x_ - μ[idx])^2
# Temporary computations for probabilities
# for a data point to be part of this cluster.
# These aren't really probabilities,
# but number of items in `x` that
# are closest to the centroid number `idx`.
data.probs[idx] += 1
end
else
# EM step
data.pσ .= p ./ σ
for x_ ∈ x
# These are basically the heights of each Gaussian at `x_`
data.distances .= data.pσ .* ϕ.((x_ .- μ) ./ σ)
# Probabilities that `x_` belongs to each component
data.probs_tmp .= data.distances ./ sum(data.distances)
# ``
μ_tmp .+= x_ .* data.probs_tmp
σ_tmp .+= (x_ .- μ).^2 .* data.probs_tmp
data.probs .+= data.probs_tmp
end
end
data.θ_old .= data.θ
# We'll divide by `data.probs` later,
# so make sure there are no zeros
data.probs .+= eps
# Probabilities to choose each mixture component
p .= data.probs ./ sum(data.probs)
# Update centers and standard deviations of mixture components
μ .= μ_tmp ./ data.probs
σ .= sqrt.(σ_tmp ./ data.probs) .+ eps
i += 1
end
i, μ, σ, p
end
x = [
0.000177951775538746, 0.00392297222083862, 0.00573375518171434, -0.00215401267990863, 0.000538068347660303,
-0.00143420605437389, 0.000896137706713716, 0.000896941489857404, 0.00107739281386029, 0.0,
-0.00179501035452376, -0.00429492428288084, -0.00658541135833433, 0.00355429554914226, -0.00160099651736935,
-0.000888336204816467, 0.00195538236688178, 0.00445832214171123, 0.00483741873177002, -0.000718132885440779,
0.00377596420953514, 0.00342867790551233, -0.00306831754125248, 0.00397255849263816, 0.0,
-0.000361794504669915, -0.00144587048503415, -0.000361141210136725, -0.00054146738981984, 0.000180456555574247,
-0.00252343320638076, 0.00270392233240091, 0.00488556115164594, 0.00764752452585767, 0.00476365869676501,
0.00147031822114039, 0.00276268708730977, -0.00129020384684025, 0.00535600135308521, 0.000926354860130661,
0.00371402469637161, -0.00278681090717928, -0.00092721378919225, 0.000370782355008043, 0.000556431434184263,
-0.00055643143418421, 0.000556431434184263, 0.00204290162980033, 0.000929973097806059, 0.00447594928538436,
0.00149644622014601, -0.00149644622014607, -0.0102278901832563, 0.0232089773663753, 0.00474519254248678,
-0.000190240655001527, -0.00190041866394127, 0.00152004589404511, 0.000951203343859139, -0.00057083057396285,
-0.000190204470378469, 0.00782820226743366, 0.0042258994890649, 0.00231258534362122, 0.00347893663596757,
-0.000967585948735971, -0.00386100865745943, 0.00173560934514597, 0.00115874868121845, 0.0,
-0.00597246742094086, 0.0113977859017562, -0.00116504867546977, -0.00329361917425058, 0.000967585948736038,
-0.0130796248184689, -0.0146071078637767, 0.00320664237799695, -0.00395965446177131, -0.0018800531952435,
0.00527308189815804, -0.0013208795202859, 0.00605260028192317, 0.000379506645921242, -0.0039776546430593,
-0.00283152619573845, -0.000753721535588146, 0.00150801159586541, -0.00451722958981981, -0.0221013731937308,
0.000183705337156579, -0.000734618949474405, -0.00293309101204326, -0.00073193049928161, -0.00310474178720573,
-0.0032769008023148, 0.0, 0.00711357308880216, -0.00128052702030923, -0.00182648452603419,
0.0, -0.00145878946365998, 0.000729128723516206, -0.00273149582560972, 0.000181867782623716,
0.000727802069971813, -0.00109150456534317, 0.0146522767868704, -0.000184484826646273, 0.000738143602439221,
-0.00772346612385879, -0.000915499468868335, 0.00587373201209392, 0.00943315974911239, -0.000928763882124529,
0.00839009303177396, -0.00392413845613426, 0.00504815506005073, -0.00262074279539635, -0.00298674853354866,
-0.00372093452569019, 0.00278940208757859, 0.00916665290654104, -0.00580906721169516, -0.00149365225678325,
-0.0129751588631334, -0.00587588910566919, 0.00293362879994538, 0.00829727264081383, -0.00535501233509002,
-0.00183992692200718, 0.00997606647844415, 0.031497181728131, 0.00364718707389437, 0.0,
0.00520583456600374, -0.00212416802859568, 0.00483419678746064, -0.00116234030908892, 0.00855537009118863,
0.00195465269427087, -0.0141818792638312, -0.00269697716932484, 0.0190333964890183, 0.00058840837237535,
-0.020006494229477, 0.00675352301577992, -0.0023206353481625, 0.0030953787531742, 0.000581451707437155,
0.00174638639514873, 0.000388500393386961, 0.00917348094033744, 0.0045200037650227, 0.0017742735063647,
-0.00157728739324861, 0.000591191267588397, 0.00652627650127567, -0.000793336019395874, -0.00474684435621956,
0.00554018037561535, -0.0235304974101942, -0.00232288141613964, -0.00135252653214332, -0.00250699196003446,
-0.00652718769663178, -0.00439141517174207, -0.00247360034793817, 0.000950660780790026, -0.0077688690125669,
0.00151114497967001, 0.00682855460685999, 0.00190512536189465, 0.000763067568502649, -0.00266819293039737,
0.00362284694084784, 0.0124941558021624, -0.00674701354659438, -0.000192104505441552, 0.0172434767494189,
0.00136892560734174, 0.00352872352045298, -0.00117762525876351, 0.00157047539149226, -0.00274671548005741,
-0.0109120334509827, 0.00388350002639761, 0.0, -0.000972289818939222, -0.000388651384604448,
-0.00619796677113697, 0.00115919642037643, -0.00328090615641925, 0.00192864090640569, 0.00425614881223867,
0.000193892390331064, -0.00830361051855981, -0.0105213787415328, 0.00324025824339414, -0.00609061646775083,
0.00323102058144654, 0.000571265368292208, -0.00171281800367483, 0.00266565275894659, 0.013629158084423,
-0.00135200406881384, 0.0025123213523506, -0.00173997143946368, 0.00348297565725149, -0.00271002875886502,
0.00077354480747565, 0.0, 0.00893904125683704, 0.00508807359916059, -0.000392310715114109,
-0.0234529598215287, 0.00499328865399085, 0.0025060254079053, 0.0096975158728236, -0.00563600753364361,
0.000775494416530351, -0.00734302816361565, 0.00212007403298724, 0.000192957067651188, -0.00442861992701387,
]
data = EMData(x, UInt(5))
i, μ, σ, p = em!(data, x)
@show log_likelihood(x, p, μ, σ)
</code></pre>
<p>Output:</p>
<pre><code>log_likelihood(x, p, μ, σ) = 865.892804300474
</code></pre>
<p>Side note: the log-likelihood gets to 864 by iteration 15 and then spends 300+ iterations climbing to 865.89:</p>
<pre><code>(i, ll) = (0, 846.5355881703103)
(i, ll) = (1, 850.7556512372836)
(i, ll) = (2, 852.6190804601607)
(i, ll) = (3, 852.9874081416267)
(i, ll) = (4, 860.0518727031077)
(i, ll) = (5, 862.0286646438534)
(i, ll) = (6, 862.8927967930032)
(i, ll) = (7, 863.3682717865164)
(i, ll) = (8, 863.6668603362682)
(i, ll) = (9, 863.8705036652785)
(i, ll) = (10, 864.0174642505768)
(i, ll) = (11, 864.1280388914373)
(i, ll) = (12, 864.2140020498402)
(i, ll) = (13, 864.2826465763644)
(i, ll) = (14, 864.338720334462)
(i, ll) = (15, 864.3854377968222)
...
(i, ll) = (320, 865.8782037597581)
(i, ll) = (321, 865.8827824031083)
(i, ll) = (322, 865.8863255090024)
(i, ll) = (323, 865.8890568445889)
(i, ll) = (324, 865.8911657112117)
(i, ll) = (325, 865.892804300474)
</code></pre>
<p>I read SQUAREM has better convergence, but it kept putting negative values for the probabilities <code>p</code> and standard deviations <code>σ</code>...</p>
<p>To plot the results (this code is OK):</p>
<pre><code>using Plots
function plot_kde(x::AbstractVector, p::AbstractVector, μ::AbstractVector, σ::AbstractVector; N=200, fname="kde.png")
log_lik = log_likelihood(x, p, μ, σ)
X = range(-.03, .03, length=N)
kde = zeros(size(X))
plt = histogram(
x, normalize=:pdf,
title=@sprintf("Log-likelihood: %.4f", log_lik), label="Histogram",
linewidth=0, alpha=.5
)
for (p, μ, σ) ∈ zip(p, μ, σ)
pdf = (p / σ) .* ϕ.((X .- μ) ./ σ)
kde .+= pdf
plot!(plt, X, pdf, label=@sprintf("p=%.2f μ=%+.3f σ=%.3f", p, μ, σ))
end
plot!(plt, X, kde, label="KDE", linewidth=2)
savefig(plt, fname)
end
plot_kde(x, p, μ, σ)
</code></pre>
<hr />
<p>First things first, I think this code is correct because I followed the papers on EM, derived the formulas and the results look fine (generated by <code>plot_kde</code> above):</p>
<p><a href="https://i.stack.imgur.com/EpYjX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EpYjX.png" alt="enter image description here" /></a></p>
<p>It also increases the log-likelihood on each step, <em>like</em> EM, so it should indeed <em>be</em> the correct EM, but it's rather slow.</p>
<p>Benchmarking this with <code>BenchmarkTools.jl</code>:</p>
<pre><code>let
data = EMData(x, UInt(30))
@benchmark em!(data, x)
end
</code></pre>
<p>...gives these results:</p>
<pre><code>BenchmarkTools.Trial:
memory estimate: 112.64 KiB
allocs estimate: 901
--------------
minimum time: 15.459 ms (0.00% GC)
median time: 16.128 ms (0.00% GC)
mean time: 16.197 ms (0.00% GC)
maximum time: 18.063 ms (0.00% GC)
--------------
samples: 309
evals/sample: 1
</code></pre>
<p>If I use the k-means algorithm instead of EM, the timings are in the order of microseconds, and the resulting log-likelihood isn't that much worse than what EM gives. I need to run this algorithm a million times (and with about 30 mixture components!) on similar vectors of length ~300, so I would like to squeeze as much performance out of this as possible.</p>
<p>I'm pretty new to Julia, and I often discover new ways to speed up Julia code (sometimes drastically, like <a href="https://discourse.julialang.org/t/sum-log-p-c-is-2-to-4-times-slower-than-in-numpy/53960" rel="nofollow noreferrer">here</a>), so I could easily be missing optimizations here. How can this code be improved and sped up?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T12:13:15.513",
"Id": "513131",
"Score": "0",
"body": "I've tried some refactoring for fun: https://gist.github.com/phipsgabler/4d91bcee6d3d56021ee485b8dd00a5fc. But I can't really comment on whether this is working or an improvement, so I won't make it an answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T13:20:40.293",
"Id": "513721",
"Score": "0",
"body": "@phipsgabler, thanks, this code indeed looks cleaner than mine. This also reminded me about the existence of `clamp` - I'm always forgetting about it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T21:33:22.233",
"Id": "514575",
"Score": "0",
"body": "Have you considered using `DifferentialEquations` for this? It should be much faster since it will do much fancier sampling."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T22:13:15.753",
"Id": "514577",
"Score": "0",
"body": "@OscarSmith, how would it help, though? I'm not solving any differential equations here and not sampling anything - I'm trying to fit a Gaussian mixture model to my data. Can DifferentialEquations estimate GMMs?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T23:42:20.423",
"Id": "514586",
"Score": "0",
"body": "Nevermind, I saw the title and didn't look at the code."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T19:57:19.097",
"Id": "259818",
"Score": "1",
"Tags": [
"performance",
"julia"
],
"Title": "How to make my 1D EM algorithm written in Julia faster?"
}
|
259818
|
<p><code>Background</code>: I had created a macro few years ago and when I was reviewing this now, it was hard to understand.
I recently went through all the articles from RubberduckVBA and started learning that VBA can also be Object Oriented language and, I tried implementing this concept in my macro.</p>
<p><strong><code>Purpose of Macro</code></strong>: we have new files every month, we add few columns at the end of the file and provide our comments. Again next month we used to pull comments using concat and vlookup but then I created a quick macro so it directly pulls all the data. It checks all the worksheets, compares with previous months file and pulls extra columns from old file.</p>
<p><code>Example</code>: We have 8 columns in <code>Sheet1</code> + 4 columns for comments.
12 column in <code>Sheet2</code> + 5 columns of comments.
The macro checks last column in current file and base don that dynamically copies last 4 and 5 columns in respective sheet based on the concatenated value of entire row in current/fresh file.</p>
<p><strong>Note</strong>: I am copying entire range as we also have to pull number formatting, formula from the previous file.</p>
<p><code>Request</code>: The macro works fine in both format, I would like to know what I missed or what can be updated in current version of the macro to make it more Object Oriented.</p>
<p>the following is the previous procedural Macro.</p>
<pre><code>Option Explicit
Public Sub CarryForwardOld()
'Declare and set variables
'Add/check Tools> Reference> Microsoft Scripting Runtime
Dim ReadingRange As String
Dim dict As Scripting.Dictionary
Set dict = New Scripting.Dictionary
'Set screenupdating to false to increase the speed of processing
'Application.Calculation = xlCalculationAutomatic
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableCancelKey = xlInterrupt
Dim wbCurrent As Workbook
Set wbCurrent = ActiveWorkbook
Dim getfile As String
getfile = selectedfile(wbCurrent.Name)
If getfile = vbNullString Then Exit Sub
Dim wbOld As Workbook
Set wbOld = Workbooks(getfile)
If Not wbOld Is Nothing Then
If wbOld.Name = wbCurrent.Name Then
MsgBox "Both file names canot be same! System cannot distinguish between old and new file.", vbCritical, "Rename Either of the File"
Exit Sub
End If
End If
wbCurrent.Activate
Dim rOld As Long
Dim rNew As Long
rOld = 0
rNew = 0
Dim index As Long
index = 0
Dim wsOld As Worksheet
Dim wsCurr As Worksheet
Dim LastColumnWrite As Long
Dim WritingRow As Long
Dim LastRowCurrent As Long
Dim LastRowOld As Long
Dim LastColumnCurrent As Long
Dim LastColumnOld As Long
Dim readingrow As Long
For Each wsOld In wbOld.Sheets
On Error Resume Next
Set wsCurr = wbCurrent.Sheets(wsOld.Name)
On Error GoTo 0
If Not wsCurr Is Nothing Then
LastColumnCurrent = GetLasts(wsCurr, "Column") - index
LastRowCurrent = GetLasts(wsCurr, "Row")
LastRowOld = GetLasts(wsOld, "Row")
LastColumnOld = GetLasts(wsOld, "Column")
LastColumnWrite = GetLasts(wsCurr, "Column")
wsOld.Activate
For readingrow = 1 To LastRowOld
With wsOld
On Error Resume Next
Dim AddValue As String
AddValue = Concat(.Range(.Cells(readingrow, 1), .Cells(readingrow, LastColumnCurrent)))
If Not dict.Exists(AddValue) Then
dict.Add key:=AddValue, _
Item:=.Range(.Cells(readingrow, LastColumnCurrent + 1), .Cells(readingrow, LastColumnOld)).Address
End If
On Error GoTo 0
End With
Application.StatusBar = "Reading row " & readingrow & " out of " & LastRowOld
Next readingrow
Application.StatusBar = False
wsCurr.Activate
For WritingRow = 1 To LastRowCurrent
Application.StatusBar = "Writing row in Sheet: " & wsCurr.Name & "=>" & WritingRow & " out of " & LastRowCurrent
ReadingRange = Concat(wsCurr.Range(wsCurr.Cells(WritingRow, 1), wsCurr.Cells(WritingRow, LastColumnCurrent)))
Dim writeRange As Range
If dict.Exists(ReadingRange) = True Then
Set writeRange = wsOld.Range(dict(ReadingRange))
'wsCurr.Range(Cells(WritingRow, LastColumnWrite + 1), Cells(WritingRow, LastColumnOld)) = Split(Dict(ReadingRange), "|")
writeRange.Copy wsCurr.Range(wsCurr.Cells(WritingRow, LastColumnWrite + 1), wsCurr.Cells(WritingRow, LastColumnWrite + 1))
rOld = rOld + 1
Else
Dim outRange As Range
Set outRange = wsCurr.Range(wsCurr.Cells(WritingRow, LastColumnWrite + 1), wsCurr.Cells(WritingRow, LastColumnOld))
Dim cell As Range
outRange.Interior.colorindex = 36
For Each cell In outRange
If cell.Row = 1 Then GoTo nextcell:
If cell.Offset(-1, 0).HasFormula Then
cell.Interior.colorindex = -4142
cell.FillDown
End If
nextcell:
Next cell
'wsCurr.Range(wsCurr.Cells(WritingRow, LastColumnWrite + 1), wsCurr.Cells(WritingRow, LastColumnOld)).Interior.ColorIndex = 36
'wsCurr.Cells(WritingRow, LastColumnWrite + 1) = ReadingRange
rNew = rNew + 1
End If
Next WritingRow
End If
Next wsOld
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
wbOld.Close False
Set wbOld = Nothing
Application.StatusBar = False
MsgBox "There are " & rNew & " new records and " & rOld & " old records!", vbOKOnly, "Success!"
End Sub
Public Function GetLasts(ByVal TargetWorksheet As Worksheet, ByRef RowColum As String) As Long
If Not TargetWorksheet Is Nothing Then
With TargetWorksheet
Select Case True
Case Left$(RowColum, 1) = "R"
On Error Resume Next
GetLasts = .Cells.Find(What:="*", _
after:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
On Error GoTo 0
Case Left$(RowColum, 1) = "C"
On Error Resume Next
GetLasts = .Cells.Find(What:="*", _
after:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
On Error GoTo 0
End Select
End With
End If
End Function
Private Function selectedfile(Optional ByVal CurrentFile As String = vbNullString) As String
On Error GoTo ErrorHandler
Dim dialog As FileDialog
Set dialog = Application.FileDialog(msoFileDialogFilePicker)
With dialog
.AllowMultiSelect = False
.InitialFileName = GetSetting("Office1", "CarryForward", "LastPath")
.Title = "Select Old/Previous file for reference: " & CurrentFile
.Show
If .SelectedItems.Count <> 0 Then
selectedfile = .SelectedItems.Item(1)
SaveSetting "Office1", "CarryForward", "LastPath", selectedfile
Workbooks.Open FileName:=selectedfile
selectedfile = Mid$(selectedfile, InStrRev(selectedfile, "\") + 1)
End If
End With
If selectedfile = vbNullString Then
MsgBox "You cancelled the prcess!", vbOKOnly, "Alert!"
Exit Function
End If
Exit Function
ErrorHandler:
If Err.Number > 0 Then 'TODO: handle specific error
Err.Clear
Resume Next
End If
End Function
Private Function Concat(ByVal ConcatRange As Range) As String
Dim cell As Variant
Dim delim As String
delim = "|"
Dim Result As String
Result = vbNullString
Dim CellArray As Variant
If ConcatRange.Cells.Count > 1 Then
CellArray = Application.WorksheetFunction.Transpose(ConcatRange.Value)
Else
Concat = ConcatRange.Value
Exit Function
End If
For Each cell In CellArray
If IsError(cell) Then
Dim errstring As String
Dim errval As Variant
errval = cell
Select Case errval
Case CVErr(xlErrDiv0)
errstring = "#DIV"
Case CVErr(xlErrNA)
errstring = "#N/A"
Case CVErr(xlErrName)
errstring = "#NAME"
Case CVErr(xlErrNull)
errstring = "#NULL"
Case CVErr(xlErrNum)
errstring = "#NUM"
Case CVErr(xlErrRef)
errstring = "#REF"
Case CVErr(xlErrValue)
errstring = "#VALUE"
Case Else
errstring = vbNullString
End Select
Result = Result & delim & errstring
Else
Result = Result & delim & cell
End If
Next cell
Concat = Right$(Result, Len(Result) - 1)
End Function
</code></pre>
<p>The following is the class module implementing Object Orientation.</p>
<p>Class: <em><code>CarryMe.cls</code></em></p>
<pre><code> Option Explicit
Private Type TCell
Book As Workbook
Sheet As Worksheet
LastRow As Long
LastColumn As Long
Records As Long
End Type
Private Previous As TCell
Private Current As TCell
'Add/check Tools> Reference> Microsoft Scripting Runtime
Private dict As Scripting.Dictionary
Public Sub Execute()
'Set screenupdating to false to increase the speed of processing
With Application
'.Calculation = xlCalculationAutomatic
.Calculation = xlCalculationManual
.ScreenUpdating = False
.EnableCancelKey = xlInterrupt
End With
SelectPreviousFile
If Previous.Book Is Nothing Then Exit Sub
Dim wsheet As Worksheet
For Each wsheet In Current.Book.Sheets
SetParameters wsheet.Name
ReadDataToDictionary
WriteDictToSheet
Next wsheet
Previous.Book.Close False
Set Previous.Book = Nothing
With Application
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
.StatusBar = False
End With
MsgBox "There are " & Current.Records & " new records and " & Previous.Records & " old records!", vbOKOnly, "Success!"
End Sub
Private Sub SetParameters(ByVal SheetName As String)
Set Current.Sheet = Current.Book.Sheets(SheetName)
Set Previous.Sheet = Previous.Book.Sheets(SheetName)
With Current.Sheet
Current.LastRow = .Cells.Find(What:="*", after:=.Range("A1"), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
Current.LastColumn = .Cells.Find(What:="*", after:=.Range("A1"), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column
End With
If Previous.Sheet Is Nothing Then Exit Sub
With Previous.Sheet
Previous.LastRow = .Cells.Find(What:="*", after:=.Range("A1"), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
Previous.LastColumn = .Cells.Find(What:="*", after:=.Range("A1"), Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious, MatchCase:=False).Column
End With
End Sub
Private Sub ReadDataToDictionary()
Set dict = New Scripting.Dictionary
With Previous.Sheet
Dim index As Long
For index = 1 To Previous.LastRow
On Error Resume Next
Dim AddValue As String
AddValue = Concat(.Range(.Cells(index, 1), .Cells(index, Current.LastColumn)))
If Not dict.Exists(AddValue) Then
dict.Add key:=AddValue, _
Item:=.Range(.Cells(index, Current.LastColumn + 1), .Cells(index, Previous.LastColumn)).Address
End If
On Error GoTo 0
Next index
End With
End Sub
Private Sub WriteDictToSheet()
With Current.Sheet
Dim index As Long
For index = 1 To Current.LastRow
Application.StatusBar = "Writing row in Sheet: " & Current.Sheet.Name & "=>" & index & " out of " & Current.LastRow
Dim ReadingRange As String
ReadingRange = Concat(.Range(.Cells(index, 1), .Cells(index, Current.LastColumn)))
If dict.Exists(ReadingRange) Then
Dim writeRange As Range
Set writeRange = Previous.Sheet.Range(dict(ReadingRange))
writeRange.Copy .Range(.Cells(index, Current.LastColumn + 1), .Cells(index, Previous.LastColumn + 1))
Previous.Records = Previous.Records + 1
Else
Dim outRange As Range
Set outRange = .Range(.Cells(index, Current.LastColumn + 1), .Cells(index, Previous.LastColumn))
Dim cell As Range
outRange.Interior.colorindex = 36
For Each cell In outRange
If cell.Row = 1 Then GoTo nextcell:
If cell.Offset(-1, 0).HasFormula Then
cell.Interior.colorindex = -4142
cell.FillDown
End If
nextcell:
Next cell
Current.Records = Current.Records + 1
End If
Next index
End With
End Sub
Private Sub SelectPreviousFile()
On Error GoTo ErrorHandler
Dim dialog As FileDialog
Set dialog = Application.FileDialog(msoFileDialogFilePicker)
With dialog
.AllowMultiSelect = False
.InitialFileName = GetSetting("Office1", "CarryForward", "LastPath")
.Title = "Select Old/Previous file for reference: " & Current.Book.Name
.Show
If .SelectedItems.Count <> 0 Then
Dim selectedfile As String
selectedfile = .SelectedItems.Item(1)
SaveSetting "Office1", "CarryForward", "LastPath", selectedfile
Workbooks.Open FileName:=selectedfile
selectedfile = Mid$(selectedfile, InStrRev(selectedfile, "\") + 1)
End If
End With
Select Case True
Case selectedfile = vbNullString
MsgBox "You cancelled the prcess!", vbOKOnly, "Alert!"
Case selectedfile = Current.Book.Name
MsgBox "Both file names canot be same! System cannot distinguish between old and new file.", vbCritical, "Rename Either of the File"
Case Else
Set Previous.Book = Workbooks(selectedfile)
End Select
Exit Sub
ErrorHandler:
If Err.Number > 0 Then 'TODO: handle specific error
Err.Clear
Resume Next
End If
End Sub
Private Function Concat(ByVal ConcatRange As Range) As String
Dim cell As Variant
Dim delim As String
delim = "|"
Dim Result As String
Result = vbNullString
Dim CellArray As Variant
If ConcatRange.Cells.Count > 1 Then
CellArray = Application.WorksheetFunction.Transpose(ConcatRange.Value)
Else
Concat = ConcatRange.Value
Exit Function
End If
For Each cell In CellArray
If IsError(cell) Then
Dim errstring As String
Dim errval As Variant
errval = cell
Select Case errval
Case CVErr(xlErrDiv0)
errstring = "#DIV"
Case CVErr(xlErrNA)
errstring = "#N/A"
Case CVErr(xlErrName)
errstring = "#NAME"
Case CVErr(xlErrNull)
errstring = "#NULL"
Case CVErr(xlErrNum)
errstring = "#NUM"
Case CVErr(xlErrRef)
errstring = "#REF"
Case CVErr(xlErrValue)
errstring = "#VALUE"
Case Else
errstring = vbNullString
End Select
Result = Result & delim & errstring
Else
Result = Result & delim & cell
End If
Next cell
Concat = Right$(Result, Len(Result) - 1)
End Function
Private Sub Class_Initialize()
Set Current.Book = ActiveWorkbook
Set Previous.Sheet = Nothing
Set Current.Sheet = Nothing
End Sub
</code></pre>
<p>Usage: Following the code that I use to initiate the class and use macro.</p>
<p>Module: <em><code>TempModule.bas</code></em></p>
<pre><code>Public Sub TestingCarryClass()
Dim CarryForward As CarryMe
Set CarryForward = New CarryMe
CarryForward.Execute
End Sub
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:44:50.057",
"Id": "512609",
"Score": "3",
"body": "Good stuff! Thanks for reading all my ramblings!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:52:52.613",
"Id": "512610",
"Score": "0",
"body": "Thank you @MathieuGuindon for all your contributions. I had created hundreds of Macro and UDFs and I am now refactoring and updating all the codes using rubberduck VBA add-in, started learning OOP, SOLID principle and I cannot tell you how much happy I am discovering all these concepts that I never knew in my entire life. It's been more than 7 years and I am planning to refactor more than 30k lines of code. Thank you once again!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T21:06:32.560",
"Id": "512611",
"Score": "0",
"body": "You are on the very site that taught me all these things, I hope you stick around!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T09:08:58.883",
"Id": "512840",
"Score": "0",
"body": "Yes, I never knew about code reviews, while searching for a OOP, I found out about this code review meta and then after exploring questions, the battleship game was the turning point for me, I came to know about your blog and then add-in and other helpful resources and now I am with the flow of exploring the entire new universe of OOP. Thank you and the RubberduckVBA add-in team for all your contributions to community."
}
] |
[
{
"body": "<p>The OOP version of the code generated some thoughts around separation of concerns: user interactions and data processing.</p>\n<p>Single Responsibility Principle(<a href=\"https://en.wikipedia.org/wiki/Single-responsibility_principle\" rel=\"nofollow noreferrer\">SRP</a>):</p>\n<blockquote>\n<p>Every module, class or function in a computer program should have\nresponsibility over a single part of that program's functionality, and\nit should encapsulate that part.</p>\n</blockquote>\n<p>SRP would encourage identifying user interactions and data processing as two responsibilities.</p>\n<p>So, considering to the OOP version of <code>CarryForwardOld</code>, there are two modules:\n<code>TempModule</code> and <code>CarryMe</code>.</p>\n<p><code>TempModule</code> clearly does one <code>thing</code>:</p>\n<p>It is the Entry Point to the operation to be performed. Once the Entry Point is called it delegates all work to <code>Class Module.CarryMe</code> for processing.</p>\n<p><code>CarryMe</code> however, does more that one 'thing':</p>\n<ol>\n<li>Requests user interactions to select the 'Previous' file and to acknowledge success of the process.</li>\n<li>Modifies a 'Current' workbook based on data in a 'Previous' workbook to carry forward the data.</li>\n</ol>\n<p>So, a reasonable improvement to the <code>CarryMe</code> class would be to allow it to be tested free of human interaction. Currently, a user must select the source workbook. Also, at the end of calling <code>Execute</code>, the user receives a pop-up message that requires acknowledgement. Either of these user interactions eliminate the option for using a code-only test client.</p>\n<p><code>CarryMe</code> requires two Workbook objects (Previous and Current) to operate on. However, there is no reason that the<code>CarryMe</code> class needs to take responsibility for <em>getting</em> the workbooks. Further, to accomplish its task, the <code>CarryMe</code> class does not need to be responsible for indicating success with a pop-up message. By extracting the user interaction code from <code>CarryMe</code>, <code>CarryMe.Execute</code> can be unit tested.</p>\n<p>So, rather than exposing a parameterless subroutine (<code>CarryMe.Execute</code>) to accomplish the task, one could expose a function that takes two <code>Workbook</code> parameters and returns <code>True</code> if successful (and <code>False</code> if it fails).</p>\n<p>Using a <code>Boolean</code> returning function is a typical pattern that provides a 'safe' way to attempt an operation that could possibly fail. The pattern/function guarantees that it will return a pass/fail result rather than causing an exception or returning an error code. The functions are typically prefaced with <code>Try</code> and can either attempt an operation or attempt to retrieve a value/object. Either way, the 'TryXXXX' pattern relieves the calling code from having to catch an exception or evaluate error return codes.</p>\n<p>Below, the <code>Execute</code> subroutine has been modified to a <code>Boolean</code> returning function <code>TryExecute</code>:</p>\n<pre><code> Public Function TryExecute(ByVal currentWrkbk As Workbook, ByVal previousWrkbk As Workbook) As Boolean\n \n 'TryExecute wraps the operation with error handling to guarantee Excel \n 'Application settings are reset.\n 'Note: The original Execute() version has a bug in that these settings are not reset if a \n 'Previous' workbook is not selected by the user.\n\n If previousWrkbk Is Nothing Then Exit Function\n \n TryExecute = False 'will be set to True if the code succeeds\n\n On Error GoTo ErrorExit:\n With Application\n .Calculation = xlCalculationManual\n .ScreenUpdating = False\n .EnableCancelKey = xlInterrupt\n End With\n\n Set Current.Book = currentWorkbook\n Set Previous.Book = previousWrkbk\n \n Dim wsheet As Worksheet\n For Each wsheet In Current.Book.Sheets\n \n SetParameters wsheet.Name\n\n ReadDataToDictionary\n\n WriteDictToSheet\n \n Next wsheet\n \n TryExecute = True\n\n ErrorExit:\n With Application\n .ScreenUpdating = True\n .Calculation = xlCalculationAutomatic\n .StatusBar = False\n End With\n \n End Function\n</code></pre>\n<p>For automated testing (no user interaction), a test module could test <code>TryExecute</code> with code like:</p>\n<pre><code> Public Function CarryForwardTryExecuteTest() As Boolean\n Dim previousWorkbook as Workbook\n Dim previousWorkbookPath As String\n previousWorkbookPath = <Filepath to a test 'previous' workbook>\n Set previousWorkbook = Workbooks.Open(previousWorkbookPath)\n\n Dim currentWorkbook as Workbook\n Dim currentWorkbookPath As String\n currentWorkbookPath = <Filepath to a test 'current' workbook>\n Set currentWorkbook = Workbooks.Open(currentWorkbookPath )\n \n Dim CarryForward As CarryMe\n Set CarryForward = New CarryMe\n\n CarryForwardTryExecuteTest= CarryForward.TryExecute(currentWorkbook, previousWorkbook) Then\n End Function\n</code></pre>\n<p>So, where should the extracted user interactions be handled? The module <code>TempModule</code>, which is invoked by a user, is a candidate to handle the user interactions. If it can be assumed that <code>TempModule.TestingCarryClass</code> can only be invoked by a user, then it is reasonable to support user interactions from <code>TempModule</code>. Otherwise, add another module and EntryPoint to be responsible for the user-initiated processes.</p>\n<p>So, if <code>TempModule</code> handles the user interactions, it would look like:</p>\n<pre><code> Option Explicit\n\n Public Sub TestingCarryClass()\n Dim previousWorkbook As Workbook\n Set previousWorkbook = SelectPreviousFile()\n \n If previousWorkbook Is Nothing Then\n Exit Sub\n End If\n \n Dim CarryForward As CarryMe\n Set CarryForward = New CarryMe\n\n 'Note the addition of Properties CurrentRecordCount and PreviousRecordCount\n 'to CarryMe\n If CarryForward.TryExecute(Application.ActiveWorkbook, previousWorkbook) Then\n MsgBox "There are " & CarryForward.CurrentRecordCount & " new records and " & CarryForward.PreviousRecordCount & " old records!", vbOKOnly, "Success!"\n Exit Sub\n End If\n \n MsgBox "Unexpected Error"\n End Sub\n\n 'Note: unchanged\n Private Function SelectPreviousFile() As Workbook\n \n Set SelectPreviousFile = Nothing\n \n On Error GoTo ErrorHandler\n Dim dialog As FileDialog\n Set dialog = Application.FileDialog(msoFileDialogFilePicker)\n\n With dialog\n .AllowMultiSelect = False\n .InitialFileName = GetSetting("Office1", "CarryForward", "LastPath")\n .Title = "Select Old/Previous file for reference: " & Current.Book.Name\n .Show\n If .SelectedItems.Count <> 0 Then\n Dim selectedfile As String\n selectedfile = .SelectedItems.Item(1)\n SaveSetting "Office1", "CarryForward", "LastPath", selectedfile\n Workbooks.Open Filename:=selectedfile\n selectedfile = Mid$(selectedfile, InStrRev(selectedfile, "\\") + 1)\n \n End If\n End With\n\n Select Case True\n\n Case selectedfile = vbNullString\n MsgBox "You cancelled the prcess!", vbOKOnly, "Alert!"\n \n Case selectedfile = ActiveWorkbook.Name 'Current.Book.Name\n MsgBox "Both file names canot be same! System cannot distinguish between old and new file.", vbCritical, "Rename Either of the File"\n \n Case Else\n 'Set Previous.Book = Workbooks(selectedfile)\n Set SelectPreviousFile = Workbooks(selectedfile)\n End Select\n \n Exit Function\n ErrorHandler:\n If Err.Number > 0 Then 'TODO: handle specific error\n Err.Clear\n Resume Next\n End If\n End Function\n</code></pre>\n<p>Extracting user interface responsibilities from the <code>CarryMe</code> class allows it to focus on workbook processing (a single responsibility) with UI responsibilities handled by <code>TempModule</code>. And...<code>CarryMe.TryExecute</code> can now be unit tested.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T09:05:03.793",
"Id": "512839",
"Score": "0",
"body": "Thank you so much for the inputs, I started implementing this using the command pattern from rubberduckvba (https://rubberduckvba.wordpress.com/2020/11/19/from-macros-to-objects-the-command-pattern/) but didn't realize that for testing purpose I have to keep user interaction separated from the other functionality. Quick Question: the class should have only function exposed to client code, right? which accepts 2 workbooks and returns Boolean value. I think I missed the testing part and I have to work on making my codes more test friendly. Thanks again for the thoughts."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-24T22:09:29.140",
"Id": "515356",
"Score": "0",
"body": "As there's no more suggestions, I accepted your answer and will see if someone comes up with more suggestions. :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T03:11:19.510",
"Id": "259889",
"ParentId": "259819",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "259889",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T20:01:35.100",
"Id": "259819",
"Score": "5",
"Tags": [
"object-oriented",
"vba",
"excel",
"comparative-review",
"rubberduck"
],
"Title": "Copy Columns Forward Macro: From Procedural to OOP"
}
|
259819
|
<p>I made this super basic autoclicker using Python (v3.7) and the pynput (v1.7.3) library.</p>
<p>Are there any changes that you could recommend to make the code more efficient, faster, and overall better?</p>
<p>Here's the code:</p>
<pre><code>from pynput.keyboard import Controller
import time
# Autoclicker Functionality
def AutoClick(inputClickKey, inputClickAmount, inputClickDelay):
keyboard = Controller();
clickAmount = 1;
while clickAmount <= inputClickAmount:
clickAmount += 1;
keyboard.press(inputClickKey)
keyboard.release(inputClickKey)
time.sleep(inputClickDelay)
# User Input
KeyInput = input("Key to be autoclicked: ");
ClickAmountInput = int(input("Number of autoclicks (integer): "))
ClickDelayInput = int(input("Delay between each autoclick in seconds (integer): "))
# Code Execution
AutoClick(KeyInput, ClickAmountInput, ClickDelayInput);
</code></pre>
<p>and Here's the GitHub repository:</p>
<p><a href="https://github.com/SannanOfficial/AutoClickPython" rel="nofollow noreferrer">https://github.com/SannanOfficial/AutoClickPython</a></p>
<p>Any sort of critique or suggestion would be appreciated. :)</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T22:57:57.763",
"Id": "512620",
"Score": "3",
"body": "\"Are there any changes that you could recommend to make the code more efficient, faster\" conflicts with `time.sleep`."
}
] |
[
{
"body": "<p>Your code is fairly simple (which is good) and there isn't much to make it "more efficient" or "faster". There's only a couple of suggestions I have to clean it up and you'll end up with a textbook example of a nice and short Python script that does something useful :)</p>\n<h1>Replace the loop</h1>\n<p>You are using a <code>while</code> loop to control your iterations, but you know beforehand how many times you want to run your code <strong>and</strong> you don't care about the iteration you are at, so you can replace that loop by a more idiomatic one:</p>\n<pre class=\"lang-py prettyprint-override\"><code>for _ in range(inputClickAmount):\n # ...\n</code></pre>\n<p>People reading this code understand that you want something to run for <code>inputClickAmount</code> times and that you don't care about the number of your iteration.</p>\n<h1>PEP 8 naming conventions</h1>\n<p><a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a> is the style guide for Python that recommends that you use <code>snake_case</code> for your variables:</p>\n<ul>\n<li><code>input_click_amount</code> instead of <code>inputClickAmount</code>;</li>\n<li><code>auto_click</code> instead of <code>AutoClick</code>;</li>\n<li>etc.</li>\n</ul>\n<p>Of course being consistent within your code is better than following PEP 8 in some places and not following it in other places, so if your code is part of a larger library, for example, you would want to follow the conventions of that library.\nOtherwise, for your personal projects I can recommend that you use this convention, as it will help your code fit in within the community.</p>\n<h1>Basic error handling</h1>\n<p>This is a possible direction of improvement, and depends on how robust you want your code to become.</p>\n<p>At the end of your script you have a couple of <code>int(input())</code> usages, which raise <code>ValueError</code>s if the user (which I think is you?) types something other than a number. To make a more robust application you would probably want to do some input validation/error handling.\nI suggest you follow a "EAFP" coding style – Easier to Ask Forgiveness than Permition – that is, try to do the conversion with <code>int(input())</code> and only if it fails, handle that, for example by saying something to the user:</p>\n<pre class=\"lang-py prettyprint-override\"><code>try:\n click_amount_input = int(input(" ... "))\nexcept ValueError:\n print("The number of clicks should be an integer, defaulting to 1")\n click_amount_input = 1\n</code></pre>\n<p>(You can read more about the EAFP coding style, and its counterpart LBYL (Look Before You Leap) in <a href=\"https://mathspp.com/blog/pydonts/eafp-and-lbyl-coding-styles?utm_source=codereview\" rel=\"nofollow noreferrer\">this article</a>).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T14:45:10.383",
"Id": "512709",
"Score": "1",
"body": "Thank you very much for the suggestions mate. They were useful and I will most certainly implement them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:10:30.937",
"Id": "512713",
"Score": "2",
"body": "+1 This is implicit in the suggested refactoring, but to make it more explicit: while you're refactoring the input, you may want to encapsulate them inside a method like `read_number(question, by_default=1)` so you avoid duplication."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:12:30.303",
"Id": "512714",
"Score": "0",
"body": "@fabiofili2pi I see, that as well is a good suggestion and I'll try to implement it as well."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T13:32:27.340",
"Id": "259858",
"ParentId": "259824",
"Score": "4"
}
},
{
"body": "<p>Some of this is covered by @RGS; still:</p>\n<ul>\n<li>Rather than <code>press</code>/<code>release</code>, just call <code>tap</code></li>\n<li>Do not maintain your own loop counter</li>\n<li>Drop the semicolons</li>\n<li>Follow snake_case naming conventions for variables and methods</li>\n<li>Add a main guard</li>\n<li>The delay should not be constrained to an integer, and should accept floats</li>\n<li>Add type hints</li>\n<li>you could stand to simplify your variable names a little</li>\n<li>The comments do not offer value and should be deleted</li>\n</ul>\n<p>More broadly, the naming is confusing - with no other information, seeing the method name I would assume mouse clicks. This is not an auto-clicker; you could call it an auto-typer, auto-key or somesuch.</p>\n<p>Also, as @Peilonrayz hinted at, you can't particularly improve the performance of something that is already explicitly rate-limited via <code>sleep()</code>. This whole program can be reduced to a single call to <code>Controller().type(...)</code> unless you actually really, <em>really</em> need inter-key delay.</p>\n<p>Suggested, covering most of the above, without bothering to add more input validation:</p>\n<pre><code>from pynput.keyboard import Controller\nfrom time import sleep\n\n\ndef auto_click(key: str, n_clicks: int, delay: float) -> None:\n keyboard = Controller()\n\n for _ in range(n_clicks):\n keyboard.tap(key)\n sleep(delay)\n\n\ndef main() -> None:\n key = input('Key to be auto-clicked: ')\n n_clicks = int(input('Number of auto-clicks: '))\n delay = float(input('Delay between clicks (floating-point seconds): '))\n auto_click(key, n_clicks, delay)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:39:06.097",
"Id": "512727",
"Score": "1",
"body": "Great answer as well, I'll try to implement all the suggestions that I can. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:25:09.863",
"Id": "259864",
"ParentId": "259824",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259858",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-21T22:29:13.400",
"Id": "259824",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"automation"
],
"Title": "Python Autoclicker"
}
|
259824
|
<p>I often see nested loops as a solution to the bubble sort, but my solution involves a recursive function. Is the following solution less efficient than the traditional method?</p>
<pre><code>public static int[] BubbleSort(int[] arrayOfValues)
{
var swapOccurred = false;
for (var i = 0; i < arrayOfValues.Length; i++)
{
if (i == arrayOfValues.Length - 1)
continue;
if (arrayOfValues[i] > arrayOfValues[i + 1])
{
//swap values
var current = arrayOfValues[i];
var next = arrayOfValues[i + 1];
arrayOfValues[i] = next;
arrayOfValues[i + 1] = current;
swapOccurred = true;
}
}
if (swapOccurred)
{
// keep going until no further swaps are required:
BubbleSort(arrayOfValues);
}
return arrayOfValues;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T03:34:33.190",
"Id": "512636",
"Score": "3",
"body": "If it's recursive anything you can almost bet that it's less efficient the the iterative version of anything. It's much more interesting to find out why some particular recursive implementations of something are actually not less efficient then their iterative versions."
}
] |
[
{
"body": "<p>Less efficient? It consumes more stack space, which shouldn’t be a problem for any dataset where a bubble sort would be appropriate.</p>\n<p>With the latest version of the c# compiler, tuple deconstruction will allow you to swap the values with a single line of code (although it will probably be slower).</p>\n<p>On a side note, I’m not clear on why you have a separate continue instead of having a lower conditional check. It’s the same thing.</p>\n<p>Not sure if you know this, but you are examining already sorted elements with your recursive call. An “efficient” bubble sort moves the end position back one cell after each cycle.</p>\n<p><strong>Update</strong>: I did some rough testing your implementation, and get a stack overflow a bit after 8k items. Sorting 8k random numbers without reducing the end point took ~.75 seconds, sorting with reducing the end point took ~.70 seconds. Much better than I expected. Using Moch Yusup modification to use a more traditional structure the time for 8k items was approximately the same, but it took 116.8 seconds for 80k items.</p>\n<p>So, performance wise, within the usable range, recursion was functionally identical, but due to stack overflow the usable range is limited. OTOH, the usable range and "not enough time to go get a cup of coffee" range are fairly close.</p>\n<p>Just for comparison, I tried using the standard List.Sort method, which took .0003681 seconds for 8k items, and .006 seconds for 80k items...</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T03:50:43.133",
"Id": "512637",
"Score": "0",
"body": "Yes, I think a conditional check would be better - I just wanted to prevent the comparison from going outside of the bounds of the array. Thanks, I guess stack space would be a consideration."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T11:08:17.833",
"Id": "512677",
"Score": "0",
"body": "@Alex: if you want to do something different, note that your recursion is basically a GOTO with a parameter and if C# did support tailrecursion that’s what it would look like..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T13:37:41.657",
"Id": "512701",
"Score": "0",
"body": "Thanks for the feedback."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T01:43:04.010",
"Id": "512805",
"Score": "1",
"body": "In languages that do not natively compile recursions into loops (C# versus functional languages like F#) there is always the issue of a StackOverflow with recursions. If you sort 100.000 elements with your algorithm it probably crashes. Would you use a loop you could sort millions of elements without any problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T11:35:56.350",
"Id": "512847",
"Score": "0",
"body": "@Christoph: yeah, but it’s bubble sort. I wouldn’t want to sort much more than 1000 elements under any circumstances. 10k would likely be extremely slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:55:17.957",
"Id": "512893",
"Score": "0",
"body": "I actually tested my recursive method vs the traditional method of nested loops - the recursion method is much faster - in fact many orders of magnitude faster (when performing the operation with 10,000 or 100,000 elements). However, that argument is kind of mute - as bubble sort should only be done with small collections. Interesting to see anyway."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T21:21:31.523",
"Id": "512898",
"Score": "0",
"body": "@jmoreno and @Alex: Either you or I am now totally off the track. For me bubble sort is (taken from Wikipedia) a `\"sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order\"` which is what `Array.Sort()`, `List.Sort()` and everything else in .NET that is based on an `IComparer` or an `IComparable` does. And that is pretty fast and can be used for millions of items (a quick test sorting 10.000.000 random integers took less than 0.8 seconds on my system, even as debug run)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T23:31:43.067",
"Id": "512901",
"Score": "0",
"body": "@Christoph [Array.Sort()](https://docs.microsoft.com/en-us/dotnet/api/system.array.sort?view=netframework-4.8) _This method uses the introspective sort (introsort) algorithm as follows: 1) If the partition size is less than or equal to 16 elements, it uses an insertion sort algorithm. 2) If the number of partitions exceeds 2 * LogN, where N is the range of the input array, it uses a Heapsort algorithm. 3) Otherwise, it uses a Quicksort algorithm._"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T23:32:00.577",
"Id": "512902",
"Score": "0",
"body": "@Christoph: you need to be able to compare, yes, but that is a given. The algorithm matters. The framework uses quicksort, https://stackoverflow.com/questions/5958769/what-sorting-algorithm-does-the-net-framework-implement. What you describe could just as well apply to a bogosort, https://en.wikipedia.org/wiki/Bogosort, which works but in practice is totally unusable after about 5 items."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T05:20:38.483",
"Id": "512913",
"Score": "0",
"body": "@jmoreno I stand corrected on my comment above - I was using an already sorted array containing 1000 elements (there was a bug in my unit test). The traditional method of two nested for loops is actually faster."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T05:22:21.430",
"Id": "512915",
"Score": "0",
"body": "Just want to thank everyone for their input here - it has been a learning experience."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T03:07:12.773",
"Id": "259836",
"ParentId": "259832",
"Score": "3"
}
},
{
"body": "<p>IMHO - I usually use recursive to break down a complex loop code into a simpler and smaller code. So if the function I end up created is still a complex one I'd rather use loop instead. In your case it's simpler and easier to do loop instead of recursion.</p>\n<pre><code>public static int[] BubbleSort(int[] arrayOfValues)\n{\n bool swapOccurred;\n do\n {\n swapOccurred = false;\n for (var i = 0; i < arrayOfValues.Length - 1; i++)\n {\n if (arrayOfValues[i] <= arrayOfValues[i + 1]) \n continue;\n \n (arrayOfValues[i], arrayOfValues[i + 1]) = (arrayOfValues[i + 1], arrayOfValues[i]);\n swapOccurred = true;\n }\n } while (swapOccurred);\n return arrayOfValues;\n}\n</code></pre>\n<p><em>The code above is written in c# 9.</em></p>\n<p>So yes, I think it's less efficient doing it with recursive in this case in my opinion.</p>\n<p>I usually ask these questions before I use recursive code:</p>\n<ul>\n<li>Will it be simpler if I use recursive?</li>\n<li>Does the code loop for small number of times? Because if it does like thousands loop then it may be detected as Stack Overflow.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T00:24:54.897",
"Id": "512909",
"Score": "0",
"body": "Ah I like this! The do-while is much cleaner and has the same intent as my recursive function. Thanks."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T00:10:13.867",
"Id": "259920",
"ParentId": "259832",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259836",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T01:36:51.273",
"Id": "259832",
"Score": "2",
"Tags": [
"c#",
"sorting"
],
"Title": "Recursive function for bubble sort"
}
|
259832
|
<p>I have been trying to learn c++ for the sake of being comfortable with a second language. I found a project that seemed relatively easy, although it may not be implemented perfectly, it was a simple project.</p>
<p>I create a <code>std::map<double, std::string></code>, which will represent the tax rate as a double, and the required income as a string. A user will input their income and the maximum amount of taxes to be paid in dollars will be returned. Here is the code:</p>
<pre><code>#include <stdio.h>
#include <iostream>
#include <cmath>
#include <map>
#include <iomanip>
double TaxesDue(double &income);
double HighestRate(double &income);
std::map<double, std::string> taxRate =
{
{ 0.35, "499999" },
{0.31, "349999"},
{0.25,"249999"},
{0.21,"169999"},
{0.18,"119999"},
{0.14,"79999"},
{0.10,"44999"},
{0.05,"29999"}
};
int main()
{
double income;
std::cout << "Enter your income: " << std::endl;
std::cin >> income;
double taxesDue = TaxesDue(income);
std::cout << taxesDue << std::endl;
}
double TaxesDue(double &income)
{
double totalTaxes = 0.0;
double taxDiff = 0.0; //as taxes are calculates, subtract the income
double highestRate = HighestRate(income);
for (double i = income; i > 29999; )//knowing the lowest tax rate is 0.05
{
taxDiff = (income - std::stod(taxRate[highestRate]));
totalTaxes += (highestRate * taxDiff);
i -= taxDiff;
highestRate = HighestRate(i);
}
return totalTaxes;
}
double HighestRate(double &income)
{
/*
std::map<double, std::string> taxRate =
{
{ 0.35, "499999" },
{0.31,"349999"},
{0.25,"249999"},
{0.21,"169999"},
{0.18,"119999"},
{0.14,"79999"},
{0.10,"44999"},
{0.05,"29999"}
};
*/
if (income > std::stod(taxRate[0.35]))
{
return 0.35;
}
if (income > std::stod(taxRate[0.31]))
{
return 0.31;
}
if (income > std::stod(taxRate[0.25]))
{
return 0.25;
}
if (income > std::stod(taxRate[0.21]))
{
return 0.21;
}
if (income > std::stod(taxRate[0.18]))
{
return 0.18;
}
if (income > std::stod(taxRate[0.14]))
{
return 0.14;
}
if (income > std::stod(taxRate[0.10]))
{
return 0.10;
}
if (income > std::stod(taxRate[0.05]))
{
return 0.05;
}
return 0.0;
}
</code></pre>
<p>My biggest thing is trying to improve the <code>HighestRate(double &income)</code> method. How should I convert the <code>if (income > std::stod(taxRate[x]))</code> to make the code better? Meaning, are there any libraries that I could use to find 'where value > then this std::map value'?</p>
<p>Also I think that I should probably change the <code>std::map<double, std::string></code> to <code>std::map<double, double></code>.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T06:08:58.563",
"Id": "512646",
"Score": "1",
"body": "You say that C++ is your second language - it's probably useful to say what your main programming language is, because a lot of the pitfalls you encounter will depend on your existing practices."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:01:51.667",
"Id": "512683",
"Score": "0",
"body": "Currently your code will not calculate progressive tax rates. Most western countries use progressive taxes. Is this done on purpose?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T19:11:01.090",
"Id": "512771",
"Score": "0",
"body": "My main programming language is c#. c# will have different libraries, eg Linq which will make things a bit easier in regards to my function with multiple namespaces among others."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T19:11:42.240",
"Id": "512772",
"Score": "0",
"body": "If my program does not calculate the taxes correctly, then it is likely I missed a piece of logic or I just do not fully understand taxation. ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T12:05:31.337",
"Id": "512850",
"Score": "0",
"body": "The first thing I noticed is that `HighestRate` hardcodes all the keys in the map. Meaning that if you change or add a rate in the map, you also have to change that function. In that sense, using the map doesn't really provide any benefit over just having the sequence of `if`s without the map. As @indi wrote you may want to swap the map, but regardless, you should define the data in _one_ place and use an iterator to access it in another."
}
] |
[
{
"body": "<p>In <a href=\"https://en.cppreference.com/w/cpp/container\" rel=\"noreferrer\">C++ STL</a>, the <code>set</code> and closely related <code>map</code> containers are <em>sorted</em> and provide an efficient way to look up the set element (or map key) which is not less than a given value. This is accomplished using the <a href=\"https://en.cppreference.com/w/cpp/container/map/lower_bound\" rel=\"noreferrer\"><code>lower_bound</code></a> method, which is available for both <code>set</code> and <code>map</code>. You can use this to your advantage here.</p>\n<p>Instead of having the <code>taxRate</code> map rates to minimum income levels, do the reverse. Have it map minimum income levels to tax rates.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>static const IncomeToRateMap TAX_RATE = {\n {29999, 0}, // income <= 29999, rate is 0\n {44999, 0.05}, // income <= 44999, rate is 0.05\n {79999, 0.1}, // ...\n};\n</code></pre>\n<p>That way you can query the map like this:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>double getTaxRateFromIncome(unsigned long income) {\n // This map cannot be modified after initialization (it is constant)\n // and it is only initialized once (not on each function call)\n using IncomeToRateMap = std::map<unsigned long, double>;\n static const IncomeToRateMap TAX_RATE = {\n {29999, 0}, // income <= 29999, rate is 0\n {44999, 0.05}, // income <= 44999, rate is 0.05\n {79999, 0.1}, // ...\n // ...\n {499999, 0.31}//,\n //{std::numeric_limits<unsigned long>::max(), 0.35}\n };\n // Handle the maximum case separately\n // As an alternative, you could add {std::numeric_limits<unsigned long>::max(), 0.35} to the TAX_RATE map\n // which requires #include <limits>\n if (income > 499999) {\n return 0.35;\n }\n // Otherwise use map::lower_bound to get an iterator to the key which is "not less than" income\n IncomeToRateMap::const_iterator pos = TAX_RATE.lower_bound(income);\n return pos->second;\n}\n</code></pre>\n<h3><a href=\"http://cpp.sh/4ix55\" rel=\"noreferrer\">Live demo</a></h3>\n<h1>String vs. numeral in map</h1>\n<blockquote>\n<p>Also I think that I should probably change the <code>std::map<double, std::string></code> to <code>std::map<double, double></code></p>\n</blockquote>\n<p>Agree that you should make the internal data structure numerals only (no strings) and just convert the user input from string to numeral once. Numbers are faster to deal with than strings.</p>\n<p>Though I would suggest changing the income from <code>double</code> (floating point) to <code>unsigned long</code> (non-negative integer) since (at least in the U.S.) it's rounded to the next dollar and it makes things easier anyway. Note <code>long</code> instead of <code>int</code> because <code>unsigned int</code> caps at ~4 billion and some people may have income that exceeds that. (Whether or not that's fair is another story.)</p>\n<h1>Passing by reference</h1>\n<pre class=\"lang-cpp prettyprint-override\"><code>double HighestRate(double &income)\n</code></pre>\n<p>This is passing in a <code>double</code> by reference, meaning that when we call</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>double myIncome = 133337;\ndouble rate = HighestRate(myIncome);\n</code></pre>\n<p>The variable <code>myIncome</code> outside <code>HighestRate()</code>, and <code>income</code> inside <code>HighestRate()</code> are the same <code>double</code> variable in memory. So if somehow <code>HighestRate()</code> changed <code>income</code>, you would see <code>myIncome</code> change after <code>HighestRate()</code> finishes.</p>\n<p>Sometimes that's what you want to do, but in this case, it looks like that's not the intention.</p>\n<p>For a small data type (like <code>double</code>), you can just drop the <code>&</code> and it will mean that <code>HighestRate()::income</code> is a separate <code>double</code> variable and gets initialized/copied from <code>myIncome</code>. If <code>HighestRate()::income</code> gets modified, <code>myIncome</code> doesn't get touched.</p>\n<p>When the data type is large and you want to avoid a copy (due to memory or runtime performance), you can add <code>const</code> to the reference: <code>HighestRate(const double& income)</code>, which means it is still the same variable in-memory as <code>myIncome</code>, but it is read-only (can't be modified). But again, for <code>double</code>, this is really not necessary and you should probably just go with <code>HighestRate(double)</code>.</p>\n<h3><a href=\"http://cpp.sh/5ogb7\" rel=\"noreferrer\">Live demo on references</a></h3>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T04:47:04.273",
"Id": "512642",
"Score": "2",
"body": "FYI, a `long` is 32 bits on Windows. A `long long` is always 64 bits, however. And it probably makes more sense to use signed integers for this problem since it is possible to have a negative income."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T02:39:09.783",
"Id": "512811",
"Score": "0",
"body": "Thanks, this helped."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T04:05:32.527",
"Id": "259839",
"ParentId": "259833",
"Score": "6"
}
},
{
"body": "<p>This isn’t a bad idea for a learning project, and I’d say it’s implemented quite well.</p>\n<p>Before I dive into the code itself, I’m going to do a high-level design review.</p>\n<h1>Design review</h1>\n<h2>You’re using <code>std::map</code> backwards</h2>\n<p>So you want a list of pairs of values, where one value is the tax rate and the other income lower bound for that tax rate. In your code you made the tax rate the lookup key, and the lower income bound the value.</p>\n<p>The problem with that is that what you want to do is use the income to lookup the tax rate. Since the tax rate is the key in your map, that means you actually have to manually go through the map, checking each entry and inspecting the value.</p>\n<p>If your map were the other way around—with the thing you <em>actually</em> want to lookup, the income, as the key—the lookup code would be trivial:</p>\n<pre><code>// income lower bound is the key, tax rate is the value\nauto const taxRate = std::map<double, double>{\n {499'999, 0.35},\n {349'999, 0.31},\n // and so on\n};\n\ndouble HighestRate(double income)\n{\n // lower_bound() finds the key that is NOT LESS than the argument given\n // (in other words, the key that is greater or equal). So whatever income\n // you give it, it will give you the NEXT greater tax bracket. That means\n // we have to BACKWARDS one tax bracket to get the proper answer.\n //\n // If the data were encoded differently, this could be much simpler, but\n // you have to be careful not to change the logic.\n\n auto p = taxRate.lower_bound(income);\n\n // If we got the first tax bracket, there is no lower tax bracket... so\n // no taxes due.\n if (p == taxRate.begin())\n return 0.0;\n\n // Go backwards one tax bracket.\n --p;\n\n // Now just return the rate.\n return p->second;\n}\n</code></pre>\n<p>Actually, the code is even simpler if you <em>don’t</em> use <code>HighestRate()</code>:</p>\n<pre><code>double TaxesDue(double income)\n{\n double totalTaxes = 0.0;\n\n // Starting tax bracket:\n auto p = taxRate.lower_bound(income);\n\n // Convert the starting tax bracket iterator to a REVERSE iterator so we\n // can go backwards (from highest tax bracket down to lowest).\n for (auto r = std::map<double, double>::reverse_iterator{p}; r != taxRate.rend(); ++r)\n {\n // For each tax bracket:\n\n // 1) subtract the lower bound from the income to get the amount\n // taxable in that bracket\n auto taxable_amount = income - r->first;\n\n // 2) calculate the taxes, and add to the total\n totalTaxes += taxable_amount * r->second;\n\n // 3) the remaining income is everything not yet taxed... which is\n // the same as the lower bound of the bracket\n income = r->first;\n }\n\n return totalTaxes;\n}\n</code></pre>\n<p>Don’t take the two functions above too seriously; I didn’t test them, and I didn’t really think too hard writing them, so there may be mistakes.</p>\n<p>The point I want to make here is about the shape of your map. You should ask what you’re using the map for; what are you using to search? In your case, you are using the income to search the map (to find the tax rate). That means the income should be the key… not the tax rate.</p>\n<h3>An extra map tip</h3>\n<p>Notice in the functions I wrote above that I had to go backwards and use reverse iterators, all of which increased the complexity quite a bit. Well, the cause of that is that <code>std::map</code> will store its elements in increasing order, starting from the lowest to the highest. But when you’re calculating taxes, you want to go the opposite way: you want to start at the highest tax bracket, and work your way down. That’s the way you wrote the data, too: from the largest to smallest tax bracket.</p>\n<p>There is way to flip the order of <code>std::map</code>. <code>std::map</code> has 3 template parameters (well, actually 4, including the allocator). The third template parameter is the comparator function, which defaults to <code>std::less</code>. So to flip the order, all you got to do is use <code>std::greater</code> instead.</p>\n<p>Observe:</p>\n<pre><code>auto const taxRate = std::map<double, double, std::greater<>>{\n {499'999, 0.35},\n {349'999, 0.31},\n // and so on\n};\n\ndouble TaxesDue(double income)\n{\n double totalTaxes = 0.0;\n\n // Easy peasy.\n //\n // (Just note we switched to upper_bound() because the\n // greater-than/less-than logic is reversed.)\n for (auto p = taxRate.upper_bound(income); p != taxRate.end(); ++p)\n {\n auto taxable_amount = income - p->first;\n\n totalTaxes += taxable_amount * p->second;\n\n income = p->first;\n }\n\n return totalTaxes;\n}\n</code></pre>\n<p>One more thing I should mention: I noticed you used the tag “hash map”. You’re not actually using a hash map; you’re using a normal map. In the standard library, the hash map is named <code>std::unordered_map</code>… but you do <em>not</em> want to use that for this case, because it is—as the name says—unordered… and you <em>want</em> ordering to make searching and doing calculations easier.</p>\n<h2>A note about money and floating point values</h2>\n<p>While it’s fine for practice code, you should never, <em>ever</em> use floating point types like <code>double</code> for currency.</p>\n<p>To see why, try running this simple program:</p>\n<pre><code>#include <iostream>\n\nauto main() -> int\n{\n auto my_cash = 100.0;\n\n // Set up cout to print cash values nicely:\n std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);\n std::cout.precision(2);\n\n std::cout << "I have in my account: " << my_cash << "\\n\\n";\n\n my_cash += 1e24;\n std::cout << "The bank screwed up and deposited a septillion dollars!\\n";\n std::cout << "I have in my account: " << my_cash << "\\n\\n";\n\n my_cash -= 1e24;\n std::cout << "The bank took their septillion dollars back.\\n";\n std::cout << "I have in my account: " << my_cash << "\\n\\n";\n\n std::cout << ":(\\n";\n}\n</code></pre>\n<p>Example output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>I have in my account: 100.00\n\nThe bank screwed up and deposited a trillion dollars!\nI have in my account: 999999999999999983222784.00\n\nThe bank took their trillion dollars back.\nI have in my account: 0.00\n\n:(\n</code></pre>\n<p>A better idea is to use an integer type fixed to the smallest money fraction you could want to work with. For example, instead of using a <code>double</code> value of <code>100.0</code> dollars, you might use an <code>int</code> value of <code>10000</code> cents. Or if you need more precision, you might use millionths of a dollar, so $100 would be an <code>int</code> with value <code>100'000'000</code>. If <code>int</code> is too small, you’d use <code>long</code> or <code>long long</code> or <code>std::int_fast64_t</code> instead.</p>\n<p>Then what you’d do is make a class for monetary values, to make working with them painless and transparent. The class would simply wrap your integer type, and then provide a nice interface so you could write code like:</p>\n<pre><code>class money_t\n{\n // ...\n\nprivate:\n std::int_fast64_t _value;\n};\n\nconstexpr auto calculate_taxes(money_t income)\n{\n return income * 0.05; // 0.05 is the tax rate\n}\n\nauto income = 100_dollars;\n\nauto taxes = calculate_taxes(income);\n\nstd::cout << "you pay " << taxes << " in tax.\\n";\nstd::cout << "you have " << (income - tax) << " left over.\\n";\n\n// the output is automatically nicely formatted as:\n// you pay $5.00 in tax.\n// you have $95.00 left over.\n</code></pre>\n<p>I would recommend starting with something as simple as:</p>\n<pre><code>using money_t = std::int_fast64_t; // or "= long long;" or whatever\n</code></pre>\n<p>… then building up to a proper <code>money_t</code> class. That could be your next project! C++ is a strongly-typed language, and I always tell my students that if you get the <em>types</em> right in C++, then everything else because easy. Making a monetary value type isn’t <em>hard</em>, but doing it <em>well</em> will take some work, and teach you a <em>lot</em> about the language along the way.</p>\n<h1>Code review</h1>\n<pre><code>#include <stdio.h>\n</code></pre>\n<p>This is not a C++ header. The proper header here would be <code><cstdio></code>… but honestly, I can’t see why you need it.</p>\n<p>You also don’t use anything from <code><cmath></code> or <code><iomanip></code> so far as I can tell.</p>\n<p>But you <em>do</em> use <code>std::stod()</code>… which is in <code><string></code>… which you <em>don’t</em> include. It “works” probably because <code><string></code> is being included by something else… but you can’t count on that.</p>\n<pre><code>double TaxesDue(double &income);\ndouble HighestRate(double &income);\n</code></pre>\n<p>It is <em>very</em> rare to take function parameters by non-<code>const</code> lvalue reference. There are only a few special cases where that’s normally done.</p>\n<p>When you take an argument by a non-<code>const</code> reference, you are telling the people reading your code that you intend to <em>change</em> that value. So when I see <code>TaxesDue(income)</code>, I assume <code>income</code>’s value is going to change after the function call. The compiler will also assume that, which can prevent optimizations.</p>\n<p>If you’re not going to change the value of the argument, it should be <code>const</code>:</p>\n<pre><code>double TaxesDue(double const& income);\ndouble HighestRate(double const& income);\n</code></pre>\n<p>However, <code>double</code> is a fundamental type, so you don’t really need to take it by reference at all. It doesn’t hurt, though.</p>\n<p>Also, note that the standard practice in C++ is to put the type modifier with the type:</p>\n<ul>\n<li><code>double &income</code>: this is C style.</li>\n<li><code>double& income</code>: this is C++ style.</li>\n</ul>\n<pre><code>std::map<double, std::string> taxRate =\n</code></pre>\n<p>You might want to make this <code>const</code>.</p>\n<pre><code> double income;\n\n std::cout << "Enter your income: " << std::endl;\n std::cin >> income;\n</code></pre>\n<p>Couple things here. You should put the variable declaration as close as possible to the point of initialization. This is better:</p>\n<pre><code> std::cout << "Enter your income: " << std::endl;\n\n double income;\n std::cin >> income;\n</code></pre>\n<p>It’s also wise to avoid uninitialized variables. It’s kinda okay if you do what I did just above, and put the <code>double income;</code> <em>RIGHT</em> above the <code>std::cin</code> that actually initializes it. But the way you wrote it, with the <code>double income;</code> several lines away from where it’s initialized… that’s dangerous.</p>\n<p>One way to avoid initialized variables is to use the more modern practice of “always <code>auto</code>”:</p>\n<pre><code>// double income; // <- bad, uninitialized\nauto income = double{}; // <- better, cannot possibly be uninitialized\n</code></pre>\n<p>Finally, avoid <code>std::endl</code>. I know lots of tutorial code shows to use it, but it’s almost always wrong (or more charitably: unnecessary). Every use of <code>std::endl</code> in your code is wrong; in every case it forces a flush of the output stream unnecessarily.</p>\n<p>If you want a newline, don’t use <code>std::endl</code>. Just use <code>\\n</code>:</p>\n<pre><code>int main()\n{\n std::cout << "Enter your income: \\n";\n\n auto income = double{};\n std::cin >> income;\n\n auto taxesDue = TaxesDue(income);\n std::cout << taxesDue << '\\n';\n}\n</code></pre>\n<p><code>TaxesDue()</code> is cool. It could be simplified and made much more efficient, but the problems aren’t actually in the function, they’re in the way the data is structured, as I mentioned in the design review.</p>\n<p>The only big problem in <code>TaxesDue()</code> is the magic number <code>29999</code>. You shouldn’t hard code that in the function. You should use the tax rate map; just get the income lower bound from the lowest tax bracket… which, with your current design, is just <code>std::stod(taxRate.begin()->second)</code>. (But if you swapped the map key and value, and used <code>double</code>s, it would be <code>taxRate.begin()->first</code>.)</p>\n<p>So that leaves <code>HighestRate()</code>:</p>\n<pre><code>double HighestRate(double &income)\n{\n /*\n std::map<double, std::string> taxRate =\n {\n { 0.35, "499999" },\n {0.31,"349999"},\n {0.25,"249999"},\n {0.21,"169999"},\n {0.18,"119999"},\n {0.14,"79999"},\n {0.10,"44999"},\n {0.05,"29999"}\n };\n */\n\n if (income > std::stod(taxRate[0.35]))\n {\n return 0.35;\n }\n if (income > std::stod(taxRate[0.31]))\n {\n return 0.31;\n }\n\n // ...\n</code></pre>\n<p>There is a <em>lot</em> of unnecessary repetition here. Take the tax rate for example: <code>0.35</code> is repeated three times, once in the tax rate map (which is fine), then <em>twice</em> in <code>HighestRate()</code>.</p>\n<p>Unfortunately, this can’t be simple, because you have the map backwards. If the income were the key, no problem, you just do a normal map lookup with <code>lower_bound()</code> (like I demonstrated in the design review section). But because the income is the value, and the rate is the key, you have to do this the hard way.</p>\n<p>What you have to do is iterate through the map, checking the value. Not only that, you also have to make sure you get the largest value. Something like:</p>\n<pre><code>double HighestRate(double income)\n{\n auto highest_amount = 0.0; // or "= std::numeric_limits<double>::lowest();"\n auto result = 0.0;\n\n for (auto&& [rate, amount_s] : taxRate)\n {\n auto amount = std::stod(amount_s);\n\n if ((income > amount) and (amount < highest_amount))\n result = rate;\n \n }\n\n return result;\n}\n</code></pre>\n<p>Which, as you can see, is pretty complicated. That’s why you really want the income to be the key.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T02:38:10.707",
"Id": "512810",
"Score": "0",
"body": "Thanks this is great. I am glad that I can use `lower_bound()` that will make everything easier. Also with using `long long` instead of double to get more precision, that would be great, and is exactly why I added the `#include <iomanip>` because I was trying to use `setprecision(2)` but was not getting a desirable result. In c# I would use a decimal type instead of double or long. I have a lot to learn but thanks for helping."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T05:21:10.003",
"Id": "259840",
"ParentId": "259833",
"Score": "13"
}
}
] |
{
"AcceptedAnswerId": "259840",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T02:24:23.013",
"Id": "259833",
"Score": "6",
"Tags": [
"c++",
"object-oriented",
"hash-map"
],
"Title": "Income tax rate calculator in c++"
}
|
259833
|
<p>I've started to get far more familiar with C (and coding in general) and the way to use function to my advantage to create more complex programs. As a way of doing something actually useful instead of my "Starting Programming with C: For Dummies" book I decided to make a simple program to help me cheat my way through maths class, a program that calculates the quadratic equation.</p>
<p>However due to the fact that I've never seen a piece of code that is longer than 60 lines outside of a youtube videos and my for Dummies book, I don't exactly know if the way I format functions is readable to other people.</p>
<pre><code>/*El programa calcula la ecuación general de segundo grado,
no tiene mayor proposito más que practicar C y hacer trampa en los exámenes -w-,
trato de usar funciones claras para hacer más legible el código, tómese nota de que me gusta
main en primer lugar main y luego el resto de funciones.*/
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int a,b,c,total,resultado; //total se usa para el resultado de diferentes opercaciones de la ecuación, resultado es el resultado final de la ecuación
void value_input();
int discriminante(int b, int a, int c);
void display();
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
void main(){
value_input();
b=-b; //como todas las operaciones con "b" son su multiplicación *-1 y su cuadrado, decidí solo volver b negativo (o positivo dependiendo del caso)
discriminante(b,a,c);
display();
}
//-----------------------------------------------------------------------------------------------------------------------------------------------------------------------
//value_input solo le pregunta al usuario los valores de a, b y c en la ecuación y los aloca a las variables correspondientes.
void value_input(){
printf("Dame el valor de a: ");
scanf("%d", &a);
printf("Dame el valor de b: ");
scanf("%d", &b);
printf("Dame el valor de c: ");
scanf("%d", &c);
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
//La función calcula la discriminante y devuelve su valor
int discriminante(int b, int a, int c){
int result;
b*=b;
c=4*a*c;
total=b-c;
return total;
}
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
//display calcula el divisor de la ecuación y determina como imprimir la ecuación basado en el discriminante
void display(){
a*=2; //se calcula el divisor
//se calcula valor del discriminante y dependiendo de éste se imprime el resultado
if(total>0){ //es mayor que 0
total=sqrt(total);
printf("El resultado es: (%d±%d)/%d\n",b,total,a);
}
else if(total<0){ //es menor que 0
total=abs(total);
total=sqrt(total);
printf("El resultado es: (%d±%di)/%d\n",b,total,a);
}
else if(total=0){ //es igual a 0
printf("El resultado es: (%d\n",b/a);
}
}
</code></pre>
<p>I think that it is mostly understandable for anyone that wants to review the code in general, but I think that it can become a little convoluted in some places, specially the display() function.</p>
<p>How could I make it clearer?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T13:48:29.717",
"Id": "512704",
"Score": "1",
"body": "@IñakiUlibarri Please [edit] your question to include only your code file's *content*, not the visuals of your editor. In case you have only `nano` at hand, use `M-#` to disable the line numbering temporarily."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:41:18.003",
"Id": "512729",
"Score": "0",
"body": "I see you've edited the question title, but it still only mentions your concerns about the code - here on Code Review, the title should describe what real-work task your program solves. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles. I've edited with what I think the code does."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T19:21:08.600",
"Id": "512773",
"Score": "1",
"body": "@IñakiUlibarri `b*=b; c=4*a*c;` both can overflow `int` math. Is that a concern for you? are you just making this code to handle small integer values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T06:51:13.993",
"Id": "512829",
"Score": "0",
"body": "@chux, it's even worse - see the integer division right at the end!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T16:17:48.810",
"Id": "512871",
"Score": "0",
"body": "@chux-ReinstateMonica Yes, I made this to practice my C and cheat my way through my Highschool maths class, you'll imagine that I rarely input negative values into it, let alone fractions and other whatnots. You'll also see that it's amateurish and generally sucky all around, that is because this is literally my first ever piece of functional, functioning code :-), I came here because I've found my \"For Dummies\" book to be quite unresponsive when I asked for suggestions, so I figured that having good feedback from the start would be good to avoid bad habits, and this place seems good for that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:46:38.570",
"Id": "512889",
"Score": "0",
"body": "Please stop adding the [tag:formatting] tag. None of this code does any formatting, with the arguable exception of the three `printf()` calls at the end, and that's certainly not the focus of the program."
}
] |
[
{
"body": "<p>I would find it easier to understand if the comments were in English, but I'm not the one who will be making changes later, so write your comments for that person (whatever is most useful to future-you).</p>\n<p>What I find actively harmful is the very long lines such as</p>\n<blockquote>\n<pre><code>//----------------------------------------------------------------------------------------------------------------------------------------------------------------------\n</code></pre>\n</blockquote>\n<p>and</p>\n<blockquote>\n<pre><code> b=-b; //como todas las operaciones con "b" son su multiplicación *-1 y su cuadrado, decidí solo volver b negativo (o positivo dependiendo del caso)\n</code></pre>\n</blockquote>\n<p>For the first, I think an empty line would be better; for the second, consider word-wrapping it as a block comment.</p>\n<p>The global variables <code>a</code>, <code>b</code>, <code>c</code>, <code>total</code> and <code>resultado</code> make it harder to reason about each function in isolation. I can't even see where that last one is actually used. Prefer to pass values to and from functions rather than communicating via globals.</p>\n<p>These function declarations would be better as prototypes (i.e. specify that they take no arguments, rather than unspecified ones):</p>\n<pre><code>void value_input(void);\nvoid display(void);\n</code></pre>\n<p>I'd declare all the helpers with <code>static</code> linkage (this becomes more important when you write programs with multiple source files, but it's a good habit to form), and I'd accept the arguments to <code>discriminante()</code> in the less surprising order <code>a</code>, <code>b</code>, <code>c</code>.</p>\n<p><code>void main()</code> is incorrect - the <code>main</code> function must return an <code>int</code>, so we need <code>int main(void)</code>. Your compiler should have warned you about this; make sure you're enabling enough warning options (e.g. <code>gcc -Wall -Wextra</code>).</p>\n<p>When we read input using <code>scanf()</code>, it's important to use the return value that indicates how many conversions were successful. I would write a function to get a single value (and accept non-integer coefficients, since that's what we can expect from real equations - pun intended):</p>\n<pre><code>double read_double(const char *prompt)\n{\n for (;;) {\n printf("%s: ", prompt);\n double x;\n int conversions = scanf("%lf", &x);\n if (conversions == 1) {\n return x;\n }\n if (conversions == EOF) {\n /* not much we can do now */\n fputs("Reading failed\\n", stderr);\n exit(1);\n }\n /* consume the invalid input and start again */\n puts("Input should be a valid number");\n scanf("%*[%\\n]");\n }\n}\n</code></pre>\n<p><code>discriminante()</code> declares <code>total</code> which it never uses, and returns a value that gets ignored. There's clearly something wrong there.</p>\n<p>This line doesn't do what you think it does:</p>\n<blockquote>\n<pre><code> else if(total=0){\n</code></pre>\n</blockquote>\n<p>Thankfully, it's harmless, since if <code>total>0</code> and <code>total<0</code> are both false, we know that <code>total</code> is already zero, and the assignment has no effect.</p>\n<p>When we know a number <code>n</code> is negative, we can make it positive simply with <code>-n</code> rather than calling <code>abs()</code>.</p>\n<hr />\n<h1>Modified code</h1>\n<p>Here's what I ended up with after fixing the above:</p>\n<pre><code>/* El programa calcula la ecuación general de segundo grado, no tiene\n mayor proposito más que practicar C y hacer trampa en los exámenes\n -w-, trato de usar funciones claras para hacer más legible el\n código, tómese nota de que me gusta main en primer lugar main y\n luego el resto de funciones.\n*/\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nstatic double read_double(const char *prompt);\nstatic double discriminante(double a, double b, double c);\nstatic void display(double a, double b, double d);\n\nint main(void)\n{\n const double a = read_double("Dame el valor de a");\n const double b = read_double("Dame el valor de b");\n const double c = read_double("Dame el valor de c");\n\n const double d = discriminante(a, b, c);\n\n display(a, b, d);\n}\n\nstatic double read_double(const char *prompt)\n{\n for (;;) {\n printf("%s: ", prompt);\n double x;\n int conversions = scanf("%lf", &x);\n if (conversions == 1) {\n return x;\n }\n if (conversions == EOF) {\n /* not much we can do now */\n fputs("Reading failed\\n", stderr);\n exit(1);\n }\n /* consume the invalid input and start again */\n puts("Input should be a valid number");\n scanf("%*[%\\n]");\n }\n}\n\n// La función calcula la discriminante y devuelve su valor\nstatic double discriminante(double a, double b, double c)\n{\n return b * b - 4 * a * c;\n}\n\n// display calcula el divisor de la ecuación y determina como imprimir\n// la ecuación basado en el discriminante\nstatic void display(double a, double b, double d)\n{\n printf("El resultado es: ");\n if (d > 0) {\n printf("(%g±%g)/%g\\n", -b, sqrt(d), a);\n } else if (d < 0) {\n printf("(%g±%gi)/%g\\n", -b, sqrt(-d), a);\n } else { /* total == 0 */\n printf("%g/%g\\n", -b, a);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T19:00:25.937",
"Id": "512768",
"Score": "1",
"body": "Yes. I was going to say something about that function being hard to do well, and I inadvertently proved it! Now improved."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T19:57:24.310",
"Id": "512776",
"Score": "0",
"body": "From what I understand, `scanf` exhibits UB when the input isn't representable with the given type, so this still doesn't really work. C99, 7.19.6.2, p10: *[The] input item [...] is converted to a type appropriate to the conversion specifier. [The] result of the conversion is placed in the object pointed to by the first argument following the `format` argument that has not already received a conversion result. If this object\ndoes not have an appropriate type, **or if the result of the conversion cannot be represented in the object, the behavior is undefined**.*"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T06:49:20.483",
"Id": "512828",
"Score": "0",
"body": "@JCC, what would you recommend instead?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T09:29:05.013",
"Id": "512841",
"Score": "1",
"body": "The only way to do this correctly that I'm aware of is to read the entire line, and then parse it using `strto*`, which can indicate an error if one appears. See https://ramblings.implicit.net/c/2014/05/04/c-functions-that-should-be-avoided-part-3-scanf.html."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T09:41:09.527",
"Id": "512842",
"Score": "1",
"body": "Ah, yes, that's good. That said, \"reading an entire line\" is harder than it sounds, in the general case. Thankfully, we can get away with reading, say, up to 40 chars of a line, and if the line is longer and fails conversion, then perform additional reading to discard the rest of the line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T16:03:31.343",
"Id": "512870",
"Score": "0",
"body": "@TobySpeight Ok, so to vastly oversimplify: pass functions to funtions, not function to global variable and then to function; make the code accept a wider range of input with `double` instead of int, which is more limited; make the use of the functions clearer specifying their input, **`main`has to be `int`**; make an output in case the program fails, it will make life easier; make clearer comments, block comments if it has to be elaborate; give space to breath and let the code be far more readable, it doesn't has to be this compact. Right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:49:35.393",
"Id": "512890",
"Score": "0",
"body": "That's a very concise summary! But it seems about right. One other thing you might consider (or not - it's a preference): many people like to define `main()` last, so there's no need to forward-declare the functions it calls."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T09:15:55.843",
"Id": "513570",
"Score": "0",
"body": "@TobySpeight I don't understand this \"preference\". Why would avoiding forward function declarations ever be useful ***provided*** you have a C compiler (it seems not everyone can afford this luxury)? How exactly does this counteract its downsides (potential UB if you (and this never *ever* happens) accidentally call a function before it's declared, inflexibility with such basic things like ordering function definitions, not being consistent because it might be impossible to keep this up (do staunch proponents of this \"preference\" then rewrite their functions or something??))?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T10:35:01.283",
"Id": "513574",
"Score": "0",
"body": "@JCC, I guess that the people who prefer `main()` last dislike having two places to modify when changing a function's signature. If you're not using compiler warnings to prevent calling undeclared functions, then I guess UB is possible - but why would you not use the warnings? Anyway, as I said, it's a _preference_ - something to consider - rather than _advice_."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T10:36:59.390",
"Id": "513575",
"Score": "0",
"body": "In fact, isn't it an *error* (required diagnostic) if a declared function disagrees with an implicit signature?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-01T22:09:38.767",
"Id": "513683",
"Score": "0",
"body": "Yes, it is an error (https://godbolt.org/z/3Gvhr3xx8); the only potentially \"uncaught\" thing (I had to disable implicit warnings) is if you change (or misspell) the function identifier (see the `foo` example). However, if you're not systematic about renaming identifiers you're probably a lost cause anyway. IMHO as a noob, we shouldn't be worrying about ordering function definitions in this day and age, as that is the compiler's job. Compilers warn based on function declaration, not signature (which doesn't exist in C, and is often said not to include the return type)."
}
],
"meta_data": {
"CommentCount": "11",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:24:19.270",
"Id": "259868",
"ParentId": "259835",
"Score": "6"
}
},
{
"body": "<h1>Readability and (light) maintainability</h1>\n<p>Readability in code is highly subjective, so take everything in this section with a grain of salt.</p>\n<h2>Line lengths</h2>\n<p>Most styles used in the wild will explicitly limit the length of the lines to less than 100 characters if possible. Whether it's 72, 80, 96 or another random value isn't important, but >140 is too much.</p>\n<h2>Language</h2>\n<p>Unless you're the only developer working on the software, you should use English identifiers and documentation. But even if you're the only developer working on a piece of code <em>at the moment</em>, you might not be the only dev working on it <em>forever</em>. It's easier to start in an international format first than to change everything later.</p>\n<h2>Giving space to breathe</h2>\n<p>Have a look at the following two code snippets:</p>\n<pre class=\"lang-c prettyprint-override\"><code>#include<stdio.h>\n#include<stdlib.h>\n#include<math.h>\nint a,b,c,total,result; //total is used for the result of different operations of the equation, result is the final result of the equation.\nvoid value_input();\n</code></pre>\n<pre class=\"lang-c prettyprint-override\"><code>#include <stdio.h>\n#include <stdlib.h>\n#include <math.h>\n\nint a, b, c;\nint total; // total is used for the result of different operations of the equation, \nint result; // result is the final result of the equation.\n\nvoid value_input();\n</code></pre>\n<p>Have a look at both variants. Both contain the same code. Which one would you prefer to read in a few weeks after you forgot about this snippet? Which one is easier to overview?</p>\n<p>Space is important. While it doesn't matter to your compiler, it matters to you, the human. Patterns get a lot easier to recognize if they're isolated from each other, and space provides the necessary isolation.</p>\n<p>Also, we were able to cut down the line length by a lot by splitting <code>total</code> and <code>result</code> into their own lines. There's no scrollbar anymore, and we can see the full comments without any hassle.</p>\n<p>Spacing also makes it easier to recognize a bug in the current code:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void display(){\n // <snip>\n else if(total=0){ //es igual a 0\n printf("El resultado es: (%d\\n",b/a);\n }\n}\n</code></pre>\n<p>Do you notice the bug? How about now:</p>\n<pre class=\"lang-c prettyprint-override\"><code>void display(){\n // <snip>\n else if(total = 0){ //es igual a 0\n printf("El resultado es: (%d\\n",b/a);\n }\n}\n</code></pre>\n<p>That's an assignment, not an equality test.</p>\n<p>Note that I would use a single line per declaration, but before that, let's talk about the proper place about those declarations.</p>\n<h1>Global variables and hard maintainability</h1>\n<p>You probably wondered about the "(light)" part in the previous section. While those changes in your formatting and spacing make it easier to read your code, global variables handicap reasoning about code.</p>\n<p>In order to know how <code>a</code>, <code>b</code>, <code>c</code>, <code>total</code> and <code>result</code> change, we need to inspect <em>all</em> functions, because any function from the same file might change it. There might even be a typo somewhere, e.g.</p>\n<pre class=\"lang-c prettyprint-override\"><code>// whoops: v \nint discriminante(int b, int a, int d) {\n int result;\n b *= b;\n c = 4 * a * c; // oh no, global c changed!\n total = b - c;\n return total;\n}\n</code></pre>\n<p>Suddenly, we're changing the global <code>c</code> instead of the local one, because we accidentally called our argument <code>d</code>. Usually, a compiler with proper configuration will throw a warning at our face at that point, but that might not be the default configuration. Also, the unused <code>result</code> variable should yield a warning, but that's another issue.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:34:00.170",
"Id": "259870",
"ParentId": "259835",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259868",
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T02:46:55.117",
"Id": "259835",
"Score": "1",
"Tags": [
"beginner",
"c"
],
"Title": "Find solutions to a quadratic equation"
}
|
259835
|
<p>How does the following look to list the directories on a posix system? This is actually the first piece of C code that I've written where I've actually been able to use for a real-world problem!</p>
<pre><code>#define _GNU_SOURCE
#include <dirent.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>
#define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)
struct linux_dirent {
unsigned long d_ino;
off_t d_off;
unsigned short d_reclen;
char d_name[];
};
void print_files(char* dir, FILE* out)
{
// open the file
int fd = open(dir, O_RDONLY | O_DIRECTORY);
if (fd == -1) handle_error("Error opening file.\n");
// grab a buffer to read the file data
#define BUF_SIZE (1024*1024*1)
char* buffer = malloc(sizeof *buffer * BUF_SIZE);
if (buffer == NULL) handle_error("Error malloc.\n");
// do the getdents syscall writing to buffer
int num_read = syscall(SYS_getdents, fd, buffer, BUF_SIZE);
if (num_read == -1) handle_error("Error getdents syscall.\n");
close(fd);
for (long buffer_position = 0; buffer_position < num_read;) {
struct linux_dirent *d = (struct linux_dirent *) (buffer + buffer_position);
char d_type = *(buffer + buffer_position + d->d_reclen - 1);
// skip on . and .. in the listing
if (d->d_name[0] == '.') {
buffer_position += d->d_reclen;
continue;
}
// path = dir + '/' + name
char path[400];
strcpy(path, dir);
strcat(path, "/");
strcat(path, d->d_name);
// recursive call, as necessary
if (d_type == DT_DIR)
print_files(path, out);
else if (d_type == DT_REG)
fprintf(out, "%s\n", path);
// advance buffer position
buffer_position += d->d_reclen;
}
free(buffer);
}
int main(int argc, char *argv[])
{
char dir[1024];
strcpy(dir, argc > 1 ? argv[1] : ".");
FILE *out = fopen("c-log.txt", "w");
fprintf(out, "-------------[ START ]---------------------\n");
print_files(dir, out);
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<blockquote>\n<pre><code>#define handle_error(msg) do { perror(msg); exit(EXIT_FAILURE); } while (0)\n</code></pre>\n</blockquote>\n<p>There's a long-standing convention to use <code>UPPER_CASE</code> for preprocessor macros. This helps draw attention to them as <em>text replacements</em>, which don't obey the same rules of scope as C identifiers (and which sometimes - though not in this case - expand their arguments multiple times).</p>\n<blockquote>\n<pre><code>void print_files(char* dir, FILE* out)\n</code></pre>\n</blockquote>\n<p>Why a <code>const char* dir</code>? Surely we have no need to overwrite its contents? Also, I'd be inclined to always write to <code>stdout</code> in this program - let the user apply ordinary shell plumbing if a different destination is desired. That's easier than having a special argument in each program.</p>\n<p>In larger programs, it's usually a bad idea to <code>exit()</code> from within functions, particularly if it's possible to either recover, or produce useful information regardless of the error. As a concrete example, if we find a subdirectory we can't read, it's probably more helpful to emit a warning message to <code>stderr</code> but continue listing the directories the user does have permissions for.</p>\n<p>The code using <code>open()</code> and <code>syscall()</code> is much lower level than we'd normally use for this, and tightly bound to Linux rather than POSIX as claimed. I think <code>opendir()</code> and <code>readdir()</code> would be more suited.</p>\n<p>Be careful with resource management and non-local exits in C. We only reach <code>close(fd)</code> in the success case. Although <code>handle_error()</code> currently exits the program, if we change that in future, we'll find ourselves leaking file descriptors. Kudos for closing the descriptor before the recursive call - it's easy to leave it open until the end of the function, and you avoided that trap.</p>\n<blockquote>\n<pre><code>char* buffer = malloc(sizeof *buffer * BUF_SIZE);\n</code></pre>\n</blockquote>\n<p>The multiplication by <code>sizeof *buffer</code> is borderline pointless. I say "borderline" in case there's a chance that we might want to change the type (but still have <code>BUF_SIZE</code> of them).</p>\n<p>We don't seem to handle reading directories larger than <code>BUF_SIZE</code> at all - not even with an error message.</p>\n<blockquote>\n<pre><code> char path[400];\n strcpy(path, dir);\n strcat(path, "/");\n strcat(path, d->d_name);\n</code></pre>\n</blockquote>\n<p>Where's that <code>400</code> come from? Why not use the system's <code>MAX_PATH</code> constant?</p>\n<p><code>strcpy()</code> followed by <code>strcat()</code> is wasteful - that causes another traversal of the string just written, in order to find where to start writing. In this case, we could use <code>printf()</code> like this:</p>\n<pre><code>int path_len = snprintf(path, sizeof path, "%s/%s", dir, d->d_name);\n</code></pre>\n<p>Remember to test <code>path_len</code> to determine whether the path was truncated at this stage.</p>\n<blockquote>\n<pre><code> if (d_type == DT_DIR)\n print_files(path, out);\n else if (d_type == DT_REG)\n fprintf(out, "%s\\n", path);\n</code></pre>\n</blockquote>\n<p>Why don't we print the other kinds of file? I wouldn't expect all my symlinks, sockets, FIFOs and device files to simply disappear from the listing unless I specifically asked for that.</p>\n<blockquote>\n<pre><code> fprintf(out, "-------------[ START ]---------------------\\n");\n</code></pre>\n</blockquote>\n<p>Consider using <code>fputs()</code> when there's no conversions to be done.</p>\n<p>As a general style point, I'd advise more vertical space for conditionals, and use of braces as a consistent rule. E.g.</p>\n<pre><code>if (buffer == NULL) {\n handle_error("Error malloc.\\n");\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:29:33.063",
"Id": "512721",
"Score": "2",
"body": "While sizeof is redundant when the type is `char`, I think it's a reasonable habit to get into always writing `type *var = malloc(sizeof *var * count);`. And little clarity is lost in using `printf()` with no conversions (the compiler will almost certainly optimize it, so no performance is lost either)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:35:21.487",
"Id": "512725",
"Score": "0",
"body": "Yes, to both of those points."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:32:45.543",
"Id": "512761",
"Score": "0",
"body": "\" use UPPER_CASE for preprocessor macros.\" is interesting in that it was followed shortly by `FILE`, a type that may or may not be defined via a macro."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:38:24.890",
"Id": "512762",
"Score": "1",
"body": "\"Consider using fputs() when there's no conversions to be done.\" --> is OK, but borders on premature optimization. Good compilers emit efficient code with `fprintf(out, \"[ START ]\\n\");` or `fputs( \"[ START ]\\n\", out);`. For such minor issues, best to follow groups coding standard and/or clarity."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T06:06:04.063",
"Id": "259843",
"ParentId": "259838",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "259843",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T03:30:51.273",
"Id": "259838",
"Score": "4",
"Tags": [
"beginner",
"c",
"posix"
],
"Title": "Recursively list directories"
}
|
259838
|
<p>I am a total beginner in Python and I am trying with the modules Turtle. I am currently trying to code for 3 sliders (R, G, B) for adjusting the colors of the turtle screen. However, I found parts of my codes filled with redundancies, could anyone please tell me how to trim the code to make it more compact and clear, especially in the draw_red, draw_green, draw_blue parts? Thanks in advance.</p>
<pre><code>import turtle
turtle.setworldcoordinates(0, 0, 4, 255)
turtle.colormode(255)
turtle.tracer(False)
colors = ['red', 'green', 'blue']
painters = []
red_x, green_x, blue_x = 1, 2, 3
turtle.bgcolor(0,0,0)
def spawningPainters():
global painter
for i in range(len(colors)):
painter = turtle.Turtle()
painters.append(painter)
painter.up()
painter.speed(0)
painter.setheading(90)
painter.color(colors[i])
painter.pencolor('black')
painter.shape('turtle')
painter.shapesize(5, 5, 5)
xPos = i + 1
painter.goto(xPos, 0)
def assign_painters():
global redPainter, greenPainter, bluePainter
redPainter = painters[0]
greenPainter = painters[1]
bluePainter = painters[2]
def draw_red(x, y):
redPainter.ondrag(None)
x = red_x
redPainter.goto(x, y)
redPainter.ondrag(draw_red)
update_screen_color()
def draw_green(x, y):
greenPainter.ondrag(None)
x = green_x
greenPainter.goto(x, y)
greenPainter.ondrag(draw_green)
update_screen_color()
def draw_blue(x, y):
bluePainter.ondrag(None)
x = blue_x
bluePainter.goto(x, y)
bluePainter.ondrag(draw_blue)
update_screen_color()
def update_screen_color():
red = max(min(redPainter.ycor(), 255) , 0)
green = max(min(greenPainter.ycor(), 255), 0)
blue = max(min(bluePainter.ycor(), 255), 0)
turtle.bgcolor(int(red), int(green), int(blue))
def back_to_origin():
for painterIndex in range(len(painters)):
painters[painterIndex].goto(painterIndex + 1, 0)
def listening_input():
redPainter.ondrag(draw_red)
greenPainter.ondrag(draw_green)
bluePainter.ondrag(draw_blue)
turtle.onkeypress(back_to_origin, 'c')
def main():
spawningPainters()
assign_painters()
listening_input()
main()
turtle.listen()
turtle.tracer(True)
turtle.mainloop()
</code></pre>
|
[] |
[
{
"body": "<h1>Review</h1>\n<p>I wasn't able to figure out a way to make the code more compact and in my opinion the code is pretty clear. However I do have some other feedback.</p>\n<h2>Use a proper main</h2>\n<p>Instead of:</p>\n<pre class=\"lang-py prettyprint-override\"><code>turtle.setworldcoordinates(0, 0, 4, 255)\nturtle.colormode(255)\nturtle.tracer(False)\nturtle.bgcolor(0,0,0)\n\n...\n\ndef main():\n spawningPainters()\n assign_painters()\n listening_input()\n\nmain()\nturtle.listen()\nturtle.tracer(True)\nturtle.mainloop()\n</code></pre>\n<p>Do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>...\n\nif __name__ == "__main__":\n turtle.setworldcoordinates(0, 0, 4, 255)\n turtle.colormode(255)\n turtle.tracer(False)\n turtle.bgcolor(0,0,0)\n\n spawningPainters()\n assign_painters()\n listening_input()\n\n turtle.listen()\n turtle.tracer(True)\n turtle.mainloop()\n</code></pre>\n<p>For more information you can look at this post: <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">https://stackoverflow.com/questions/419163/what-does-if-name-main-do</a></p>\n<h2>Prevent the turtle from going outside of the window</h2>\n<p>With the current code it is possible to drag the turtle outside of the window. If you then stop dragging you cannot get it back unless you reset the position. To prevent this from happening we can limit the boundaries of <code>y</code> inside of the draw functions.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def draw_blue(x, y):\n bluePainter.ondrag(None)\n x = blue_x\n y = min(y, 255)\n y = max(y, 0)\n bluePainter.goto(x, y)\n bluePainter.ondrag(draw_blue)\n update_screen_color()\n</code></pre>\n<p>By doing this the <code>min</code> and <code>max</code> calls can be removed from the <code>update_screen_color</code> function. However you may want to leave them as a form of defensive programming in case you add more features.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def update_screen_color():\n red = redPainter.ycor()\n green = greenPainter.ycor()\n blue = bluePainter.ycor()\n\n turtle.bgcolor(int(red), int(green), int(blue))\n</code></pre>\n<h2>Update screen color when going back to the origin</h2>\n<p>When the position is put back to the origin the screen color is not redrawn. Unless this is intended it would be good to call the <code>update_screen_color</code> function at the end of the <code>back_to_origin</code> function.</p>\n<h2>Few tips</h2>\n<p>The <code>global painter</code> variable is not used anywhere outside of the <code>spawningPainters</code> function, so it can be removed.</p>\n<p>Move the <code>colors</code> list to the <code>spawningPainters</code> function as it is not used anywhere else.</p>\n<p>You might want to rename <code>spawningPainters</code> to <code>spawn_painters</code>.</p>\n<h1>Extra</h1>\n<h2>Add typing to the <code>painters</code> list</h2>\n<p>When an empty list is declared the intellisense of your IDE may have trouble figuring out what type of elements the list will contain. By adding type annotations you can help the intellisense better understand your code.\nInstead of:</p>\n<pre class=\"lang-py prettyprint-override\"><code>painters = []\n</code></pre>\n<p>Do:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List\n\n...\n\npainters: List[turtle.Turtle] = []\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T11:03:00.970",
"Id": "259853",
"ParentId": "259844",
"Score": "1"
}
},
{
"body": "<p>EDIT: The answer ended up being quite long and I don't want you to forget that you did a really nice job with this program and, <em>especially</em>, in recognising that there probably was a better alternative than tripling the code, one piece per colour.</p>\n<p>This is my take on a less repetitive version of the same code. Notice that my suggestions aren't necessarily <em>the best</em>, and you, and I, and other people that eventually chime in, might be able to design an even better program :)</p>\n<h1>Taking care of the state</h1>\n<p>You had the right idea: you wanted a container with all the turtles so you didn't have to have a variable for each one of them, but executing that is hard because things are interconnected and you need many of your functions to be aware of many things at once.</p>\n<p>On a first iteration I was trying to redesign your code by keeping the three painters in a dictionary that would be then passed around the several functions, but I ended up going using OOP (object-oriented programming) because this is the type of situation where it comes in handy.</p>\n<p>We create objects that are connected and related, and let them store their own relationships and etc.</p>\n<p>Please notice that this is not the <em>only</em> way to go about doing this.</p>\n<h2>Your own turtle</h2>\n<p>First, we need our own turtles that are aware of themselves, so that their <code>.ondrag</code> can know about their current position and etc.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import turtle\n\nclass Painter(turtle.Turtle):\n def __init__(self, turtle_app, i, colour):\n super().__init__()\n self.turtle_app = turtle_app\n self.up()\n self.speed(0)\n self.setheading(90)\n self.color(colour)\n self.pencolor('black')\n self.shape('turtle')\n self.shapesize(5, 5, 5)\n self.goto(i, 0)\n self.ondrag(self.draw)\n\n def draw(self, x, y):\n x = self.xcor()\n self.goto(x, y)\n self.turtle_app.update_screen_colour()\n</code></pre>\n<p>Notice that the <code>__init__</code> method is the thing that initialises the turtle and does almost all of the things you had in your <code>spawningPainters</code> method.\nThe things that are different are that the <code>Painter</code> itself defines its own <code>draw</code> method, and that it stores a reference to this <code>turtle_app</code> which is the "main controller" of your app:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class TurtleApp:\n def __init__(self):\n self.spawn_painters()\n\n def spawn_painters(self):\n self.painters = {}\n for i, colour in enumerate(["red", "green", "blue"], start=1):\n self.painters[colour[0]] = Painter(self, i, colour)\n\n def update_screen_colour(self):\n r = max(min(self.painters["r"].ycor(), 255) , 0)\n g = max(min(self.painters["g"].ycor(), 255), 0)\n b = max(min(self.painters["b"].ycor(), 255), 0)\n\n turtle.bgcolor(int(r), int(g), int(b))\n\n def reset(self):\n for painter in self.painters.values():\n painter.goto(painter.xcor(), 0)\n self.update_screen_colour()\n</code></pre>\n<p>The <code>TurtleApp</code> object stores the painters in a dictionary indexed by the first letter of the colour and provides the helper methods you had to reset positions, update screen colour, etc.</p>\n<p>Using a "proper main" like another answer suggested (and which is a good suggestion!) your code ends with</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == "__main__":\n turtle.setworldcoordinates(0, 0, 4, 255)\n turtle.colormode(255)\n turtle.tracer(False)\n turtle.bgcolor(0,0,0)\n\n ta = TurtleApp()\n turtle.onkeypress(ta.reset, 'c')\n\n turtle.listen()\n turtle.tracer(True)\n turtle.mainloop()\n</code></pre>\n<p>Notice the two lines that I separated, where you create your <code>TurtleApp</code> and then tell <code>turtle</code> to call the <code>TurtleApp.reset</code> if the user presses the <code>"c"</code> key.\nThis has been tested and seems to be working as your original one was.</p>\n<h1>Remove irrelevant variables</h1>\n<p>Try to make your code as self-sufficient as possible.\nYou have dedicated variables to store the <code>x</code> position of each painter, and that is perfectly fine, but notice that as soon as you initialise it, you can always query its <code>x</code> position with <code>painter.xcor()</code>, which you know because you did the same for <code>y</code> with <code>painter.ycor()</code> when updating the background colour.</p>\n<p>Now, if you know the <code>x</code> position of your painter, you can always prevent it from moving to the left or right by doing something like <code>painter.goto(painter.xcor(), y)</code> in the <code>draw</code> function, you don't need to keep the <code>x_red</code>, <code>x_blue</code>, and <code>x_green</code> variables with you :)</p>\n<h1>Enumerate</h1>\n<p><code>enumerate</code> (which I used in the <code>for</code> loop to initialise the painters) is really helpful when you need to iterate over a set of values (in my case, the colours) and also know their index (which you use to set the <code>x</code> position in the beginning).\nIf you don't know <code>enumerate</code>, you can read about it in the docs or in <a href=\"https://mathspp.com/blog/pydonts/enumerate-me?utm_source=codereview\" rel=\"nofollow noreferrer\">this tutorial</a>. Notice that I also used the often-overlooked <code>start</code> optional argument to tell <code>enumerate</code> to start counting from <code>1</code> instead of <code>0</code>.</p>\n<p>I did one other thing:</p>\n<h1>PEP 8 naming conventions</h1>\n<p>Python usually prefers <code>snake_case</code> names, so that is why all my functions have capitalisation that differs from your original ones.</p>\n<h1>Final code proposal</h1>\n<p>Now everything together:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import turtle\n\nclass Painter(turtle.Turtle):\n def __init__(self, turtle_app, i, colour):\n super().__init__()\n self.turtle_app = turtle_app\n self.up()\n self.speed(0)\n self.setheading(90)\n self.color(colour)\n self.pencolor('black')\n self.shape('turtle')\n self.shapesize(5, 5, 5)\n self.goto(i, 0)\n self.ondrag(self.draw)\n\n def draw(self, x, y):\n x = self.xcor()\n self.goto(x, y)\n self.turtle_app.update_screen_colour()\n\nclass TurtleApp:\n def __init__(self):\n self.spawn_painters()\n\n def spawn_painters(self):\n self.painters = {}\n for i, colour in enumerate(["red", "green", "blue"], start=1):\n self.painters[colour[0]] = Painter(self, i, colour)\n\n def update_screen_colour(self):\n r = max(min(self.painters["r"].ycor(), 255) , 0)\n g = max(min(self.painters["g"].ycor(), 255), 0)\n b = max(min(self.painters["b"].ycor(), 255), 0)\n\n turtle.bgcolor(int(r), int(g), int(b))\n\n def reset(self):\n for painter in self.painters.values():\n painter.goto(painter.xcor(), 0)\n self.update_screen_colour()\n \n\nif __name__ == "__main__":\n turtle.setworldcoordinates(0, 0, 4, 255)\n turtle.colormode(255)\n turtle.tracer(False)\n turtle.bgcolor(0,0,0)\n ta = TurtleApp()\n turtle.onkeypress(ta.reset, 'c')\n turtle.listen()\n turtle.tracer(True)\n turtle.mainloop()\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T14:19:20.770",
"Id": "259861",
"ParentId": "259844",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259853",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:31:34.343",
"Id": "259844",
"Score": "4",
"Tags": [
"python",
"turtle-graphics"
],
"Title": "Python: screen colors adjuster using Turtles"
}
|
259844
|
<p>I am writing a benchmarking tool from scratch in Python.
However I can't get the performance of other benchmarking tools like <code>wrk</code> or <code>wrk2</code>. Using wr2 I can make 42k requests/s while my code can only create up to 2200 reqs/s. I have tried multiple ways to parallelize the code execution. I have tried using multiprocessing and parallel computing libraries like <a href="https://tutorial.dask.org/00_overview.html" rel="nofollow noreferrer">Dask</a>. But I can't get better performance. I understand <code>wrk</code> and <code>wrk2</code> are written in C which can be one reason but still 42k vs 2200 seems like a very large difference.</p>
<p>I have tried with different number of workers and <code>number_of_request</code>, but the performance does not change much.</p>
<p>I am trying to understand if I am really hitting the upper limit or I am doing something wrong. The server is running on localhost and written in Java Spring.</p>
<p>This is my code using multiprocessing:</p>
<pre><code>import time
import multiprocessing
from collections import Counter, defaultdict
import requests
# import multiprocessing as mp
num_workers = multiprocessing.cpu_count()
output = multiprocessing.Queue()
def runner(number_of_request):
output=""
for i in range(number_of_request):
try:
output+=str(requests.get("http://127.0.0.1:8000/").text)
except:
pass
# print(output)
return output
if __name__ == '__main__':
number_of_request = 1000
start = time.time()
pool = multiprocessing.Pool(processes=num_workers)
outputs = [pool.apply_async(runner, args = (number_of_request,)) for x in range(num_workers)]
pool.close()
pool.join()
duration = time.time() - start
req_s = (number_of_request*num_workers)/duration
print("duration =", time.time() - start)
print(req_s)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T11:44:37.930",
"Id": "512680",
"Score": "0",
"body": "Bit hard to compare two ways if we see only one of them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T11:52:57.913",
"Id": "512682",
"Score": "4",
"body": "To anyone in the close vote queue, code that is working as expected but not performing well is a good question for code review, this question does not belong in the close vote queue."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:07:47.307",
"Id": "512736",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/revisions/259847/4) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
}
] |
[
{
"body": "<p>Performance notwithstanding, there's some other cleanup that's worth doing:</p>\n<ul>\n<li>Capitalize <code>NUM_WORKERS</code> since it's a global constant</li>\n<li>Do not shadow your global <code>output</code> with a local variable of the same name; and ideally don't have a global <code>output</code> at all</li>\n<li>After your <code>get()</code> and before your call to <code>.text</code>, you need to check whether the request succeeded - either via <code>.ok</code> and a log entry showing the reason; or by <code>.raise_for_status()</code></li>\n<li><em>never</em> <code>try / except / pass</code>. This is the broadest and most dangerous form of silent exception-swallowing. If <code>runner</code> is executing and the user attempts to terminate the application with a Ctrl+C, that will be ignored here, and all other error information has become invisible to you. Consider at least <code>except Exception:</code> and logging the exception using the standard logging framework.</li>\n<li>Consider annotating <code>runner</code> as <code>def runner(number_of_requests: int) -> str</code></li>\n<li>Do not cast the result of <code>.text</code> to a string - it's already a string</li>\n<li>Do not use <code>time.time()</code> here; instead use <code>time.perf_counter()</code> for a sufficiently short duration or <code>time.monotonic()</code> otherwise</li>\n<li>The parens in <code>(number_of_request*num_workers)/duration</code> are redundant</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T15:38:59.437",
"Id": "259907",
"ParentId": "259847",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T07:42:37.180",
"Id": "259847",
"Score": "2",
"Tags": [
"python",
"performance",
"benchmarking",
"multiprocessing"
],
"Title": "benchmarking requests to localhost"
}
|
259847
|
<p>I am trying to find a N number of leading zeros from the output of the sha1 hash function. I would like N to go up to 10 or 9. Currently I can get to 7 in about 7 minutes (even though is not always that fast), but already 8 takes forever. The input to the sha1 must be a combination between an input_str and a random generated string.</p>
<p>Here is my code:</p>
<pre><code>import os
import base64
import hashlib
import time
def gen_keys_06(_urandom=os.urandom, _encode=base64.b64encode):
while True:
yield _encode(_urandom(4)).decode('ascii')
def search_matching_random_str(input_str, zeroes, _sha1=hashlib.sha1):
leading_zeros = "0"*zeroes
for my_random_str in gen_keys_06():
input_str_my_random_str = "".join([input_str, my_random_str])
hashval = _sha1(input_str_my_random_str.encode('utf-8')).hexdigest()
if hashval[:zeroes] == leading_zeros:
return hashval, my_random_str
def get_time(input_data, zeroes):
start = time.perf_counter()
val, random_str = search_matching_random_str(input_data, zeroes)
print(f'hash: {val}')
print(f'random_str: {random_str}')
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} seconds(s)')
if __name__ == '__main__':
first_str = "eTSlASZYlLNgKJuYeIQvGVbiAcLEEOVgAQPzSrtCOIwQxQHyFHcfjgRQJBJDlojx"
get_time(first_str, 4)
</code></pre>
<p>On what should I work to make it faster?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T09:44:01.087",
"Id": "512664",
"Score": "0",
"body": "@Manuel see the EDIT, try to change the value in `get_time` function up to 10. How long does it take?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T09:52:54.400",
"Id": "512665",
"Score": "0",
"body": "Have you tried [profiling](https://docs.python.org/3/library/profile.html)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T09:54:07.580",
"Id": "512666",
"Score": "0",
"body": "Are you trying to mine crypto? Thought the point of mining was to be slow."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T09:58:03.703",
"Id": "512667",
"Score": "0",
"body": "Your random string doesn't look fully random to me. It seems to always end with `==`. Is that a requirement somehow? And does it really need to be a random *string*, not random *bytes*? And does it really need to be *random*?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T10:03:57.890",
"Id": "512668",
"Score": "0",
"body": "No it is not a requirement. Can also be random bytes. The point is to find a random bytes/string that has more entropy (for that I try to include upper, lower, digits and punctuation). The `==` can be cut by slicing, no improvement though"
}
] |
[
{
"body": "<ul>\n<li><code>zeros</code> or <code>zeroes</code>? Better make up your mind and stick with one.</li>\n<li><code>str.join</code> is good when you want to join an iterable. For two strings, just use <code>+</code>.</li>\n<li>Instead of always reencoding and rehashing the input string, you can do it <em>once</em> and then <em>copy</em> the resulting hasher (state) for different extensions.</li>\n<li>Instead of creating random bytes and then elaborately turning them into a string and back to bytes, just use the bytes. Since that's also just a single function call, you can ditch your <code>gen_keys_06</code> and its overhead.</li>\n<li><code>str.startswith</code> is at least simpler, don't know about speed.</li>\n<li>For measuring performance, create a benchmark that runs the function much more than just once, as a single time is rather random. Or change the function so it tries a fixed number of random extensions (let's say a million) instead of stopping at the first successful one.</li>\n<li>You ask us <em>"On what should I work to make it faster?"</em>. That's a question to ask a <a href=\"https://docs.python.org/3/library/profile.html\" rel=\"nofollow noreferrer\">profiler</a>.</li>\n<li>Producing random values takes time. Check the profiler's results (or leave out the randomness when doing the million-extensions thing) to see whether it's significant here. If it is, maybe try a different randomness source (I think I've seen someone say that <code>os.urandom</code> is slow on Linux). Or if you don't actually need randomness, try increasing bytes instead.</li>\n<li>Do you really want zero-<em>nibbles</em>? Or would zero-<em>bytes</em> work as well, i.e., are you maybe really only interested in even numbers of zero-nibbles? Then you could use <code>digest</code> instead of <code>hexdigest</code>, which is probably faster because bytes are probably what the hasher actually works with and because it makes digests half as large and you'd check for fewer zeros.</li>\n</ul>\n<p>A version incorporating some of those points:</p>\n<pre><code>def search_matching_random_str(input_str, zeros, _sha1=hashlib.sha1, _urandom=os.urandom):\n leading_zeros = "0" * zeros\n hasher_copy = _sha1(input_str.encode()).copy\n while True:\n my_random_bytes = _urandom(4)\n hasher = hasher_copy()\n hasher.update(my_random_bytes)\n hashval = hasher.hexdigest()\n if hashval.startswith(leading_zeros):\n return hashval, my_random_bytes\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T13:25:13.333",
"Id": "512698",
"Score": "0",
"body": "Thanks a lot for you comments. I think the last is a very good point. Working with bytes, end so `digest` would make it faster. So I will go that way"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:55:20.210",
"Id": "259857",
"ParentId": "259848",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259857",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T08:53:40.383",
"Id": "259848",
"Score": "1",
"Tags": [
"python-3.x",
"random"
],
"Title": "find leading zeros: performance"
}
|
259848
|
<p>This is an updated version of my first question:
<a href="https://codereview.stackexchange.com/questions/259807/chess-game-in-kotlin?noredirect=1#comment512671_259807">Chess game in Kotlin</a></p>
<p>I wrote the following Chess logic in Kotlin and am looking for feedback to make the code cleaner and follow good software design principles. I tried to adhere to <strong>object-oriented design</strong>.</p>
<p>Some notes and questions I still have:</p>
<p>• I ignored special moves like "Castling" and "en pessant" for simplicity.</p>
<p>• In <code>getAvailableMoves</code> I put each branch into its own <code>if</code>-statement because a Queen gets its moves from <strong>two branches</strong> (the <code>if</code> for <strong>diagonal</strong> moves which also handles the <code>Bishop</code> and the <code>if</code> for <strong>orthogonal</strong> moves together with the <code>Rook</code>). I could put the other branches into <code>else-if</code>s but I found it more readable if it's consistent. What do you think? Does the performance cost matter?</p>
<p>• I didn't really know how to get rid of duplication in some of the <code>getAvailableMoves</code> branches, like the <code>Rook</code> one because the increment operator for each direction is different (<code>toXUp++</code>, <code>toXDown++</code>, <code>toYLeft--</code>, <code>toYRight++</code>..)</p>
<p>• Is it okay to mutate the Pawn's <code>hasStartingPosition</code> value or should I make it a <code>val</code> call <code>copy</code> instead?</p>
<p>• Is it good to make both the <code>Piece</code> and the <code>Player</code> property of a <code>PlayerPiece</code> nullable? My first attempt included a <code>Player.None</code> and <code>Piece.Empty</code> class but then I always have to handle these cases in <code>when</code> expressions.</p>
<p>• To <strong>reset</strong> the game you initialize a new <code>ChessGame</code> object. This design decision was done because of the UI framework I'm using (Jetpack Compose). Would it be better to add a <code>reset</code> method like this instead?</p>
<pre><code>fun resetGame() {
positionsArray = getStartingPositions()
currentPlayer = Player.White
removedPiecesList = mutableListOf()
}
</code></pre>
<p>The code itself:</p>
<pre><code>class ChessGame {
sealed class Piece {
object King : Piece()
object Queen : Piece()
object Bishop : Piece()
object Knight : Piece()
object Rook : Piece()
data class Pawn(var hasStartingPosition: Boolean = true) : Piece()
}
enum class Player {
Black, White
}
data class PlayerPiece(val piece: Piece? = null, val player: Player? = null)
var currentPlayer: Player = Player.White
private var playingFieldArray = getStartingPositions()
val playingField: Array<Array<PlayerPiece>> = playingFieldArray
private fun getStartingPositions() = arrayOf(
arrayOf(
PlayerPiece(Piece.Rook, Player.Black),
PlayerPiece(Piece.Knight, Player.Black),
PlayerPiece(Piece.Bishop, Player.Black),
PlayerPiece(Piece.Queen, Player.Black),
PlayerPiece(Piece.King, Player.Black),
PlayerPiece(Piece.Bishop, Player.Black),
PlayerPiece(Piece.Knight, Player.Black),
PlayerPiece(Piece.Rook, Player.Black),
),
arrayOf(
PlayerPiece(Piece.Pawn(), Player.Black),
PlayerPiece(Piece.Pawn(), Player.Black),
PlayerPiece(Piece.Pawn(), Player.Black),
PlayerPiece(Piece.Pawn(), Player.Black),
PlayerPiece(Piece.Pawn(), Player.Black),
PlayerPiece(Piece.Pawn(), Player.Black),
PlayerPiece(Piece.Pawn(), Player.Black),
PlayerPiece(Piece.Pawn(), Player.Black)
),
Array(8) { PlayerPiece() },
Array(8) { PlayerPiece() },
Array(8) { PlayerPiece() },
Array(8) { PlayerPiece() },
arrayOf(
PlayerPiece(Piece.Pawn(), Player.White),
PlayerPiece(Piece.Pawn(), Player.White),
PlayerPiece(Piece.Pawn(), Player.White),
PlayerPiece(Piece.Pawn(), Player.White),
PlayerPiece(Piece.Pawn(), Player.White),
PlayerPiece(Piece.Pawn(), Player.White),
PlayerPiece(Piece.Pawn(), Player.White),
PlayerPiece(Piece.Pawn(), Player.White)
),
arrayOf(
PlayerPiece(Piece.Rook, Player.White),
PlayerPiece(Piece.Knight, Player.White),
PlayerPiece(Piece.Bishop, Player.White),
PlayerPiece(Piece.Queen, Player.White),
PlayerPiece(Piece.King, Player.White),
PlayerPiece(Piece.Bishop, Player.White),
PlayerPiece(Piece.Knight, Player.White),
PlayerPiece(Piece.Rook, Player.White)
),
)
private var removedPiecesList = mutableListOf<PlayerPiece>()
val removedPieces: List<PlayerPiece> = removedPiecesList
fun getAvailableMoves(x: Int, y: Int): List<Point> {
val field = playingFieldArray[x][y]
if (field.player != currentPlayer || isGameOver()) {
return emptyList()
}
val availableMoves = mutableListOf<Point>()
fun isValidPosition(x: Int, y: Int) = x in 0..7 && y in 0..7 && !tileHasPieceOfCurrentPlayer(x, y)
if (field.piece == Piece.Rook || field.piece == Piece.Queen) {
var toXUp = x - 1
val toYUp = y
while (isValidPosition(toXUp, toYUp)
&& !tileHasPieceOfCurrentPlayer(toXUp, toYUp)
) {
availableMoves.add(Point(toXUp, toYUp))
if (tileHasPieceOfOpponent(toXUp, toYUp)) break
toXUp--
}
var toXDown = x + 1
val toYDown = y
while (isValidPosition(toXDown, toYDown)
&& !tileHasPieceOfCurrentPlayer(toXDown, toYDown)
) {
availableMoves.add(Point(toXDown, toYDown))
if (tileHasPieceOfOpponent(toXDown, toYDown)) break
toXDown++
}
val toXLeft = x
var toYLeft = y - 1
while (isValidPosition(toXLeft, toYLeft)
&& !tileHasPieceOfCurrentPlayer(toXLeft, toYLeft)
) {
availableMoves.add(Point(toXLeft, toYLeft))
if (tileHasPieceOfOpponent(toXLeft, toYLeft)) break
toYLeft--
}
val toXRight = x
var toYRight = y + 1
while (isValidPosition(toXRight, toYRight)
&& !tileHasPieceOfCurrentPlayer(toXRight, toYRight)
) {
availableMoves.add(Point(toXRight, toYRight))
if (tileHasPieceOfOpponent(toXRight, toYRight)) break
toYRight++
}
}
if (field.piece == Piece.Knight) {
listOf(
Point(x - 2, y - 1), Point(x - 2, y + 1), Point(x + 2, y - 1), Point(x + 2, y + 1),
Point(x - 1, y - 2), Point(x - 1, y + 2), Point(x + 1, y - 2), Point(x + 1, y + 2)
).forEach { point ->
if (isValidPosition(point.x, point.y)) {
availableMoves.add(point)
}
}
}
if (field.piece == Piece.King) {
listOf(
Point(x - 1, y), Point(x + 1, y), Point(x, y - 1), Point(x, y + 1), Point(x - 1, y - 1),
Point(x - 1, y + 1), Point(x + 1, y - 1), Point(x + 1, y + 1)
).forEach { point ->
if (isValidPosition(point.x, point.y)) {
availableMoves.add(point)
}
}
}
if (field.piece is Piece.Pawn) {
if (field.player == Player.Black) {
val toXDown = x + 1
val toYDown = y
if (isValidPosition(toXDown, toYDown) && !tileHasPieceOfOpponent(toXDown, toYDown)) {
availableMoves.add(Point(toXDown, toYDown))
}
if (field.piece.hasStartingPosition) {
val toXDown2 = x + 2
val toYDown2 = y
if (isValidPosition(toXDown2, toYDown2) && !tileHasPieceOfOpponent(toXDown2, toYDown2)) {
availableMoves.add(Point(toXDown2, toYDown2))
}
}
listOf(
Point(x + 1, y + 1), Point(x + 1, y - 1)
).forEach { point ->
if (isValidPosition(point.x, point.y)
&& tileHasPieceOfOpponent(point.x, point.y)
) {
availableMoves.add(point)
}
}
} else {
val toXUp = x - 1
val toYUp = y
if (isValidPosition(toXUp, toYUp) && !tileHasPieceOfOpponent(toXUp, toYUp)) {
availableMoves.add(Point(toXUp, toYUp))
}
if (field.piece.hasStartingPosition) {
val toXDown2 = x - 2
val toYDown2 = y
if (isValidPosition(toXDown2, toYDown2) && !tileHasPieceOfOpponent(toXDown2, toYDown2)) {
availableMoves.add(Point(toXDown2, toYDown2))
}
}
listOf(
Point(x - 1, y + 1), Point(x - 1, y - 1)
).forEach { point ->
if (isValidPosition(point.x, point.y)
&& tileHasPieceOfOpponent(point.x, point.y)
) {
availableMoves.add(point)
}
}
}
}
if (field.piece == Piece.Bishop || field.piece == Piece.Queen) {
var toXUpLeft = x - 1
var toYUpLeft = y - 1
while (isValidPosition(toXUpLeft, toYUpLeft)
&& !tileHasPieceOfCurrentPlayer(toXUpLeft, toYUpLeft)
) {
availableMoves.add(Point(toXUpLeft, toYUpLeft))
if (tileHasPieceOfOpponent(toXUpLeft, toYUpLeft)) break
toXUpLeft--
toYUpLeft--
}
var toXUpRight = x - 1
var toYUpRight = y + 1
while (isValidPosition(toXUpRight, toYUpRight)
&& !tileHasPieceOfCurrentPlayer(toXUpRight, toYUpRight)
) {
availableMoves.add(Point(toXUpRight, toYUpRight))
if (tileHasPieceOfOpponent(toXUpRight, toYUpRight)) break
toXUpRight--
toYUpRight++
}
var toXDownLeft = x + 1
var toYDownLeft = y - 1
while (isValidPosition(toXDownLeft, toYDownLeft)
&& !tileHasPieceOfCurrentPlayer(toXDownLeft, toYDownLeft)
) {
availableMoves.add(Point(toXDownLeft, toYDownLeft))
if (tileHasPieceOfOpponent(toXDownLeft, toYDownLeft)) break
toXDownLeft++
toYDownLeft--
}
var toXDownRight = x + 1
var toYDownRight = y + 1
while (isValidPosition(toXDownRight, toYDownRight)
&& !tileHasPieceOfCurrentPlayer(toXDownRight, toYDownRight)
) {
availableMoves.add(Point(toXDownRight, toYDownRight))
if (tileHasPieceOfOpponent(toXDownRight, toYDownRight)) break
toXDownRight++
toYDownRight++
}
}
return availableMoves
}
fun movePiece(fromX: Int, fromY: Int, toX: Int, toY: Int) {
if (getAvailableMoves(fromX, fromY).contains(Point(toX, toY))) {
if (tileHasPieceOfOpponent(toX, toY)) {
removedPiecesList.add(playingField[toX][toY])
}
playingFieldArray[toX][toY] = playingFieldArray[fromX][fromY]
playingFieldArray[fromX][fromY] = PlayerPiece()
(playingFieldArray[toX][toY].piece as? Piece.Pawn)?.hasStartingPosition = false
} else {
throw IllegalArgumentException("Invalid move coordinates")
}
currentPlayer = if (currentPlayer == Player.White) Player.Black else Player.White
}
fun tileHasPieceOfCurrentPlayer(x: Int, y: Int) = when (currentPlayer) {
Player.Black -> {
playingField[x][y].player == Player.Black
}
Player.White -> {
playingField[x][y].player == Player.White
}
}
private fun tileHasPieceOfOpponent(x: Int, y: Int) = when (currentPlayer) {
Player.Black -> {
playingField[x][y].player == Player.White
}
Player.White -> {
playingField[x][y].player == Player.Black
}
}
fun isGameOver() = removedPieces.any { it.piece == Piece.King }
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T11:27:26.040",
"Id": "512933",
"Score": "0",
"body": "Your implementation is very much procedural as can be seen in `getAvailableMoves`. Since you are interested in OOO, you may want to take a look at the \"Anemic domain model\" anti-pattern described here: https://en.wikipedia.org/wiki/Anemic_domain_model"
}
] |
[
{
"body": "<p>I'd start with defining simple, self-contained things, such as a very generic vector:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>data class Vector(val x: Int, val y: Int) {\n companion object {\n val perpendicular = listOf(Vector(-1, 0), Vector(+1, 0), Vector(0, -1), Vector(0, +1))\n val diagonal = listOf(Vector(-1, -1), Vector(+1, +1), Vector(-1, +1), Vector(+1, -1))\n val lShaped = ...\n }\n}\n</code></pre>\n<p>and a point that I can add vectors to</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>data class Point(val x: Int, val y: Int) {\n operator fun plus(vector: Vector) = Point(x + vector.x, y + vector.y)\n\n fun isValid() = x in 0..7 && y in 0..7\n}\n</code></pre>\n<p>If we ignore castling etc, there are basically two kinds of moves, one is adding a vector once, and another is adding it several times. This can be a property of the move, or the piece. Suppose it's a property of the move:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>interface Move {\n fun validPointsForStartingPoint(point: Point): List<Point>\n\n class Step(private val vector: Vector) : Move {\n override fun validPointsForStartingPoint(point: Point) = listOf(point + vector).filter { it.isValid() }\n }\n\n class Linear(private val vector: Vector) : Move {\n override fun validPointsForStartingPoint(point: Point) = sequence {\n var nextPoint = point + vector\n while (nextPoint.isValid()) {\n yield(nextPoint)\n nextPoint += vector\n }\n }.toList()\n }\n\n companion object {\n val linearPerpendicular = Vector.perpendicular.map { Linear(it) }\n val linearDiagonal = Vector.diagonal.map { Linear(it) }\n\n ...\n }\n}\n</code></pre>\n<p>And moves are the properties of pieces:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>sealed class Piece(val availableMoves: List<Move>) {\n object Queen : Piece(Move.linearPerpendicular + Move.linearDiagonal)\n object Bishop : Piece(Move.linearDiagonal)\n object Rook : Piece(Move.linearPerpendicular)\n ...\n}\n</code></pre>\n<p>Then finding available moves becomes easy:</p>\n<pre class=\"lang-kotlin prettyprint-override\"><code>fun Piece.getAvailableMovePointsForPoint(point: Point) = sequence {\n availableMoves.forEach move@{ move ->\n move.validPointsForStartingPoint(point).forEach { point -> \n if (point.occupiedByOwnPiece()) return@move\n yield(move)\n if (point.occupiedByEnemyPiece()) return@move\n }\n }\n}\n</code></pre>\n<p>This is not the best approach but maybe you can get some ideas out of this</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T00:59:03.430",
"Id": "259922",
"ParentId": "259851",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T10:41:07.077",
"Id": "259851",
"Score": "0",
"Tags": [
"object-oriented",
"kotlin",
"chess"
],
"Title": "Chess in Kotlin"
}
|
259851
|
<p>I have the following bit of code in a service worker that checks to see it the url contains any of the values in an array and if so it breaks out of the function. As it is run for every asset on a webpage, it can be run a lot of times so I was wondering if it could be optimised in any way:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const urlsToIgnore = [
'boldchat.com',
'pinimg.com',
'responsetap.com',
'facebook.net',
'dwin1.com',
'bing.com',
'google-analytics.com',
'googletagmanager.com',
'hotjar.com',
'pinterest.com',
];
self.addEventListener('fetch', event => {
// don't load assets from these urls
for (let i = 0; i < urlsToIgnore.length; i++) {
if (event.request.url.indexOf(urlsToIgnore[i]) > -1) {
return;
}
}
// .... rest of code to cache the assets and page
});
</code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:14:45.990",
"Id": "512687",
"Score": "0",
"body": "Do you have access to the HTML at all? Because you add an attribute that would determine if you have to cache the data or not."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:18:42.983",
"Id": "512689",
"Score": "0",
"body": "unfortunately a lot of the requests are injected by google tag manager and our marketing department"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:30:05.690",
"Id": "512690",
"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)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:32:34.640",
"Id": "512691",
"Score": "0",
"body": "@BC my bad, question edited"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:42:12.140",
"Id": "512692",
"Score": "0",
"body": "Probable quicker as a RegExp eg `/boldchat\\.com|pinimg\\.com|andsoon' where names are separated with `|` meaning OR and `\\.` to escape the dot. You can build the RegExp from the array of strings eg `new RegExp(urlsToIgnore,join(\"|\").replace(/\\./g, \"\\\\.\"),\"\")`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:03:23.107",
"Id": "512710",
"Score": "0",
"body": "I'd be tempted personally to use if( urlsToIgnore.includes(event.request.url) ) just for readability and maintenance. Speed wise, not much difference."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T08:28:25.010",
"Id": "512837",
"Score": "0",
"body": "@Blindman67 seems your regex approach is better for performance: https://jsfiddle.net/cwu6Lev9/1/ if you want to add that as an answer, I can accept it. Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T05:49:45.627",
"Id": "513220",
"Score": "0",
"body": "You could use the [`URL`](https://developer.mozilla.org/en-US/docs/Web/API/URL) constructor. `urlsToIgnore.includes(new URL(event.request.url).hostname)` or you could create a [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) for a linear check `urlsToIgnoreSet.has(new URL(event.request.url).hostname)`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T18:08:40.743",
"Id": "513921",
"Score": "0",
"body": "Is there a reason you can't use `includes` vs `indexOf`?"
}
] |
[
{
"body": "<p>If you can use ES6 Features in your code, use a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a> for constant lookup time:</p>\n<pre><code>const urlsToIgnore = new Set([\n 'boldchat.com',\n 'pinimg.com',\n 'responsetap.com',\n 'facebook.net',\n 'dwin1.com',\n 'bing.com',\n 'google-analytics.com',\n 'googletagmanager.com',\n 'hotjar.com',\n 'pinterest.com',\n]);\n\n// later\nif (uslstoIgnore.has(event.request.url) { ... }\n</code></pre>\n<p>Otherwise, just use a simple object as a map:</p>\n<pre><code>const urlsToIgnore = {\n 'boldchat.com': 1,\n 'pinimg.com': 1,\n 'responsetap.com': 1,\n 'facebook.net': 1,\n 'dwin1.com': 1,\n 'bing.com': 1,\n 'google-analytics.com': 1,\n 'googletagmanager.com': 1,\n 'hotjar.com': 1,\n 'pinterest.com': 1,\n};\n\n// later\nif (uslstoIgnore[event.request.url]) { ... }\n</code></pre>\n<p>Both these options offer constant time lookup, as opposed to the linear time of your current solution.</p>\n<p>The actual performance gain depends on the size of the list with ignored items, but since this list can be added to, I'd opt for an O(1) lookup.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T08:25:01.377",
"Id": "512836",
"Score": "0",
"body": "Unfortunately this doesn't seem to work - the urls to ignore is only part of the url (not the full url) - see test 3: https://jsfiddle.net/qdthkcvy/1/"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T20:47:36.903",
"Id": "259876",
"ParentId": "259854",
"Score": "0"
}
},
{
"body": "<p>Sets can be used to achieve constant time lookup, however, it doesn't really makes a difference with a small number of elements.</p>\n<p>The native URL() constructor could be used to parse an URL properly and easily in JavaScript. Check browser compatibility on the bottom of the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/URL/URL\" rel=\"nofollow noreferrer\">URL</a> page on MDN.</p>\n<pre><code>const urlsToIgnore = new Set([\n 'boldchat.com',\n 'pinimg.com',\n 'responsetap.com',\n 'facebook.net',\n 'dwin1.com',\n 'bing.com',\n 'google-analytics.com',\n 'googletagmanager.com',\n 'hotjar.com',\n 'pinterest.com',\n]);\n\nself.addEventListener('fetch', event => {\n // don't load assets from these urls\n const url = new URL(event.request.url);\n if (urlsToIgnore.has(url.host)) {\n return;\n }\n \n // .... rest of code to cache the assets and page\n});\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-19T21:30:51.993",
"Id": "268166",
"ParentId": "259854",
"Score": "2"
}
},
{
"body": "<p>The substring match catches more than you (probably) intend. For example, you have <code>bing.com</code> in your list, which means you'll match anything such as <code>plumbing.com</code>, <code>dubbing.com</code> and so on, not to mention any URL that contains <code>bing.com</code> in its local-part.</p>\n<p>I think we need to be a bit smarter about this: first, it seems we want to restrict to the hostname part of the URL, and then match on whole words ("words" here meaning the DNS hostname components - i.e. split by <code>.</code> only).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-09-21T11:14:11.017",
"Id": "268214",
"ParentId": "259854",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T11:43:53.337",
"Id": "259854",
"Score": "5",
"Tags": [
"javascript",
"performance"
],
"Title": "Check if an array value exists as part of the url"
}
|
259854
|
<p>To improve my Python knowledge I started a small coding project: A telegram chat/quiz bot that is based on official questions about basketball rules. The bot reads them from one or multiple <code>.csv</code> files.</p>
<p>The bot has two modes:</p>
<ul>
<li>Exercise mode: Questions are asked until the user selects to see the results. After each answer of the user, the correct answer and reason is displayed.</li>
<li>Test mode: The user is asked 21 questions. After all answers are given the bot shows the result and displays wrong answers together with the correct answer and reasoning.</li>
</ul>
<p>Questions may have an image associated with them, but the question text is currently included in the image itself.</p>
<p>I tried to seperate game logic and chat interaction as good as possible, but failed somewhat.</p>
<p>I'm glad for any feedback.
Thanks in advance!</p>
<p><strong>Known Limitations</strong></p>
<ul>
<li>Currently no logging, but feedback on that point is still appreciated.</li>
<li>The layout of the <code>.csv</code> files is not easily changable, as they are from an external source.</li>
</ul>
<hr>
<h2>Code</h2>
<p><strong>bot.py</strong></p>
<pre><code>import csv
import datetime
import logging
import os
import random
from logging import debug, info
from pathlib import Path
import telegram
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import (CallbackContext, CallbackQueryHandler,
CommandHandler, ConversationHandler, Filters,
MessageHandler, Updater)
from game import Game
from question import Question
from question_catalogue import QuestionCatalogue
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO)
__location__ = os.path.realpath(
os.path.join(os.getcwd(), os.path.dirname(__file__)))
# read bot api token from file
TOKEN_FILE = os.path.join(__location__, 'token.txt')
TOKEN = Path(TOKEN_FILE).read_text().strip()
TEST_QUESTION_COUNT = 21
MAX_ERRORS = 6
MAX_ERRORS_PERCENTAGE = MAX_ERRORS / TEST_QUESTION_COUNT
def start(update: Update, context: CallbackContext) -> None:
"""Called when starting the bot or when finishing a game. Shows short "How To".
Args:
update (Update): Telegram Update
context (CallbackContext): Telegram Context
"""
global catalogue
context.bot.send_message(
text=" *Willkommen zum Basketball Regelquiz Bot*\n"
+ f"Dieser Bot basiert auf dem aktuellen Regel\- und Kampfrichterfragenkatalog des DBB "
+ f"\({catalogue.catalogue_name(True)}\)\ "
+ f"mit insgesamt {catalogue.question_count()} Fragen\. \n"
+ "Hier erklären wir dir kurz wie\'s geht: \n"
+ "Nutze den _Übungsmodus_ um dir einzelne Fragen anzeigen zu lassen\. "
+ "Nach jeder Frage siehst du direkt die richtige Antwort und Begründung\. \n"
+ f"Beim _Regeltest_ bekommst du {TEST_QUESTION_COUNT} Fragen gestellt, von denen du maximal {MAX_ERRORS} falsch beantworten darfst\.",
chat_id=update.effective_chat.id,
parse_mode='MarkdownV2',
reply_markup=telegram.ReplyKeyboardRemove()
)
keyboard = [
[InlineKeyboardButton(" Übungsmodus", callback_data='exercise')],
[InlineKeyboardButton(" Regeltest", callback_data='test')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
'Bitte wähle den gewünschten Modus aus:', reply_markup=reply_markup)
def ask_question(update: Update, context: CallbackContext):
"""Displays the next question from the game and displays the ReplyKeyboard.
Args:
update (Update): Telegram Update
context (CallbackContext): Telegram Context
"""
try:
context.user_data["game"]
except KeyError:
help_command(update, context)
return
try:
question_data = context.user_data["game"].show_question()
except IndexError:
# no more questions available
context.bot.send_message(chat_id=update.effective_chat.id,
text="Du hast alle verfügbaren Fragen in diesem Durchlauf bereits beantwortet\.",
parse_mode=telegram.ParseMode.MARKDOWN_V2)
show_result(update, context)
return
reply_markup = telegram.ReplyKeyboardMarkup([['Ja'], ['Nein']], True)
context.bot.send_message(chat_id=update.effective_chat.id,
text=question_data[0],
parse_mode=telegram.ParseMode.MARKDOWN_V2,
reply_markup=reply_markup)
if question_data[1] != None:
# question is image question
context.bot.sendPhoto(chat_id=update.effective_chat.id,
photo=open(question_data[1], 'rb'),
parse_mode=telegram.ParseMode.MARKDOWN_V2)
def show_result(update: Update, context: CallbackContext):
"""Shows result of game to user including the evaluation. Presents options to play again
Args:
update (Update): Telegram Update
context (CallbackContext): Telegram Context
"""
try:
context.user_data["game"]
except KeyError:
help_command(update, context)
return
if not context.user_data["game"].finished():
# only show results if game is finished
return
result = context.user_data["game"].result()
result_texts = result[0]
questions = result[1]
first = True
reply_markup = telegram.ReplyKeyboardMarkup([['/start']], True)
for text in result_texts:
context.bot.send_message(chat_id=update.effective_chat.id,
text=text,
parse_mode=telegram.ParseMode.MARKDOWN_V2,
reply_markup=reply_markup)
if first:
reply_markup = None
# show wrong answers and their reason
for question in questions:
if question.image_question():
# question is image question, show question number before image
context.bot.send_message(chat_id=update.effective_chat.id,
text=question.question_header(),
parse_mode=telegram.ParseMode.MARKDOWN_V2)
# reason as caption below image
context.bot.sendPhoto(chat_id=update.effective_chat.id,
photo=open(question.path, 'rb'),
caption=question.reason_string(),
parse_mode=telegram.ParseMode.MARKDOWN_V2)
else:
# one message containing all
context.bot.send_message(chat_id=update.effective_chat.id,
text=question.full_question_string(),
parse_mode=telegram.ParseMode.MARKDOWN_V2)
context.bot.send_message(chat_id=update.effective_chat.id,
text=" Benutze /start um ein neues Quiz zu starten\.",
parse_mode=telegram.ParseMode.MARKDOWN_V2,
reply_markup=reply_markup)
def button(update: Update, context: CallbackContext) -> None:
"""Handles inline keyboard presses.
Args:
update (Update): Telegram Update
context (CallbackContext): Telegram Context
"""
query = update.callback_query
# CallbackQueries need to be answered, even if no notification to the user is needed
# Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery
query.answer()
global catalogue
if query.data == "exercise":
mode = query.data
query.edit_message_text(text=f" Übungsmodus ausgewählt")
context.user_data["game"] = Game(query.data, catalogue)
ask_question(update, context)
elif query.data == "test":
mode = query.data
query.edit_message_text(text=f" Testmodus ausgewählt")
context.user_data["game"] = Game(
query.data, catalogue, TEST_QUESTION_COUNT, MAX_ERRORS_PERCENTAGE)
ask_question(update, context)
elif query.data == "next":
query.edit_message_text(text=f"⏭️ Nächste Frage:")
ask_question(update, context)
elif query.data == "result":
query.edit_message_text(text=f" Übungsmodus beendet")
show_result(update, context)
def exercise_options_handler(update: Update, context: CallbackContext) -> None:
"""Removes inline keyboard and proceeds with next question.
Args:
update (Update): Telegram Update
context (CallbackContext): Telegram Context
"""
if context.match.group(0).lower() == "nächste frage":
ask_question(update, context)
else:
show_result(update, context)
def answer_handler(update: Update, context: CallbackContext) -> None:
"""Handles user answers based on chat message. Shows inline keyboards for next options or shows result.
Args:
update (Update): Telegram Update
context (CallbackContext): Telegram Context
"""
try:
context.user_data["game"]
except KeyError:
help_command(update, context)
return
if context.match.group(0).lower() == "ja":
context.user_data["game"].add_answer(True)
else:
context.user_data["game"].add_answer(False)
if context.user_data["game"].mode == "exercise":
# show answer validation
for text in context.user_data["game"].check_answer():
context.bot.send_message(chat_id=update.effective_chat.id,
text=text,
parse_mode=telegram.ParseMode.MARKDOWN_V2,
reply_markup=telegram.ReplyKeyboardMarkup(
[['Nächste Frage'], ['Auswertung']], True
))
if context.user_data["game"].mode == "exercise":
keyboard = [
[InlineKeyboardButton("⏭️ Nächste Frage",
callback_data='next')],
[InlineKeyboardButton(" Auswertung", callback_data='result')],
]
reply_markup = InlineKeyboardMarkup(keyboard)
update.message.reply_text(
'Wie möchtest du fortfahren:', reply_markup=reply_markup)
else:
if not context.user_data["game"].finished():
ask_question(update, context)
else:
show_result(update, context)
def help_command(update: Update, context: CallbackContext) -> None:
"""Displays help message if a command is unknown
Args:
update (Update): Telegram Update
context (CallbackContext): Telegram Context
"""
update.message.reply_text("Benutze /start um den Bot zu starten.")
def main():
"""Creates question catalogue and starts bot
"""
global catalogue
catalogue = QuestionCatalogue(2020, 2)
catalogue.add_questions_from_file(
os.path.join(__location__, '../resources/rules.csv'))
catalogue.add_questions_from_file(
os.path.join(__location__, '../resources/kampf.csv'))
catalogue.add_questions_from_file(
os.path.join(__location__, '../resources/image-questions.csv'), True)
updater = Updater(
token=TOKEN, use_context=True)
dispatcher = updater.dispatcher
updater.dispatcher.add_handler(CommandHandler('start', start))
updater.dispatcher.add_handler(CallbackQueryHandler(button))
updater.dispatcher.add_handler(MessageHandler(
Filters.regex("^(?:ja|Ja|nein|Nein)$"), answer_handler))
updater.dispatcher.add_handler(MessageHandler(
Filters.regex("^(?:Nächste Frage|Auswertung)$"), exercise_options_handler))
updater.dispatcher.add_handler(CommandHandler('help', help_command))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
</code></pre>
<hr>
<p><strong>game.py</strong></p>
<pre><code>import datetime
import telegram
from question import Question
from question_catalogue import QuestionCatalogue
from quiz import Quiz
# settings for default test
TEST_QUESTION_COUNT = 21
MAX_ERRORS = 6
MAX_ERRORS_PERCENTAGE = MAX_ERRORS / TEST_QUESTION_COUNT
class Game:
def __init__(self, mode: str, question_catalogue: QuestionCatalogue, questions_count: int = TEST_QUESTION_COUNT, max_error_percentage: float = MAX_ERRORS_PERCENTAGE):
"""Creates a new game with the given question catalogue and starts the timer for this game.
Args:
mode (str): Either "test" or "exercise"
question_catalogue (QuestionCatalogue): The questions to be used in this game
questions_count (int, optional): The number of questions to ask. Ignored if mode is "exercise". Defaults to TEST_QUESTION_COUNT.
max_error_percentage (float, optional): Maximum percentage of wrongly answered questions to pass. Defaults to MAX_ERRORS_PERCENTAGE.
Raises:
ValueError: If the mode is not either "test" or "exercise".
"""
self.mode = mode
self.question_catalogue = question_catalogue
if self.mode == "test":
self.quiz = Quiz(self.question_catalogue, questions_count)
elif self.mode == "exercise":
self.quiz = Quiz(self.question_catalogue)
else:
raise ValueError
self.timer = datetime.datetime.now().replace(microsecond=0)
self.max_error_percentage = max_error_percentage
def finished(self) -> bool:
"""Check whether this game is finished.
Returns:
bool: True if finished, False otherwise.
"""
return self.quiz.finished()
def time_elapsed(self) -> datetime.timedelta:
"""Calculates time passed from start/creation of the game until now.
Returns:
timedelta: Time passed since start of the game
"""
return datetime.datetime.now().replace(microsecond=0) - self.timer
def show_question(self) -> str:
"""Returns the next question formatted as markdown string containing question number and the question text.
Returns:
str: The formatted question string
"""
question = self.quiz.get_next_question()
text = (f"❓ *Frage {self.quiz.get_current_question_number()}/{self.quiz.question_count()} "
f"\({question.full_number(True)}\)*:\n "
f"{telegram.utils.helpers.escape_markdown(question.question_text, 2)}")
return (text, question.path)
def add_answer(self, answer: bool) -> None:
"""Adds the users answer for the current question.
Args:
answer (bool): The users answer
"""
self.quiz.add_answer(answer)
def check_answer(self) -> [str]:
"""Stores users answer, returns feedback and the correct reasoning. Only used in exercise mode.
Returns:
[str]: Array of markdown formatted strings
"""
if self.mode == "exercise":
message = []
message.append(self.quiz.check_answer())
message.append(self.quiz.get_current_question().reason_string())
return message
def result(self) -> [str]:
"""Returns feedback and evaluation of the current game. Does nothing when in test mode and the game is not finished yet.
Contains all wrongly answered questions and the correct reasoning in test mode.
Returns:
[str]: Array of markdown formatted strings containing error percentages, evaluation and time elapsed.
"""
if self.mode == "test" and (not self.quiz.finished()):
return
result = []
questions = []
result.append((f" *Auswertung* \n"
f"_Fehler_: {self.quiz.get_wrong_answer_count()} von {self.quiz.question_count()}"
f"\({self.quiz.get_wrong_percentage_string(True)}\) \n"
f"_Ergebnis_: {self.quiz.result(self.max_error_percentage)} \n"
f"_Benötigte Zeit_: {self.time_elapsed()}⏲️"))
if self.mode == "test":
result.append("Folgende Fragen wurden _falsch_ beantwortet:")
if self.quiz.get_wrong_answers():
# add wrong questions and their reason
questions = [question['question']
for question in self.quiz.get_wrong_answers()]
else:
# no wrong answer, congratulations!
result.append("_ keine _")
return (result, questions)
</code></pre>
<hr>
<p><strong>quiz.py</strong></p>
<pre><code>import random
import telegram
from question import Question
from question_catalogue import QuestionCatalogue
class Quiz:
def __init__(self, question_catalogue: QuestionCatalogue, question_count: int = 0):
"""Creates a new quiz based on the given question catalogue
Args:
question_catalogue (QuestionCatalogue): Questions to randomly choose from.
question_count (int, optional): Populate the quiz with question_count questions. Must be greater or equal to 0.
If 0 is given, "exercise mode" is used.
This mode always appends new questions to the quiz when the next question is asked. Defaults to 0.
Raises:
ValueError: If the question_count is negative.
"""
self.question_catalogue = question_catalogue
if question_count < 0:
raise ValueError
# do not select more questions than available
self.questions = [{"question": question, "answer": None} for question in random.sample(
self.question_catalogue.questions, min(question_count, question_catalogue.question_count()))]
self.current_question_index = -1
def question_count(self) -> int:
"""Current number of questions int this quiz.
Returns:
int: Number of questions
"""
return len(self.questions)
def get_current_question(self) -> Question:
"""Returns the active question. This is usually the first unanswered question.
Returns:
Question: The current active question
"""
return self.questions[self.current_question_index]['question']
def check_answer(self, question: Question = None) -> str:
"""Checks and stores the answer for the current active question or a specified question.
Args:
question (Question, optional): Question to check the answer for. If None is given, the current question is assumed. Defaults to None.
Returns:
str: String containing feedback if the question was answered correctly.
"""
index = self.current_question_index
if question != None:
index = self.questions.index(
{"question": question, "answer": None})
if self.questions[index]['answer'] == self.questions[index]['question'].answer:
return "✅ Richtig\! "
else:
return "❌ Leider falsch "
def get_current_question_number(self) -> int:
"""Returns the number of the question in this quiz. 1-based indexed.
Returns:
int: The 1-based index of the current active question
"""
return self.current_question_index + 1
def finished(self) -> bool:
"""Returns whether this quiz is finished (there are no unanswered questions) or not.
Returns:
bool: True if quiz is finished. False otherwise.
"""
# finished if there are no unanswered questions
return len(list(filter(lambda el: (el['answer'] == None), self.questions))) == 0
def add_unique_question(self) -> None:
"""Appends a unique question from the catalogue to the quiz.
Raises:
IndexError: If the quiz already contains all questions from the catalogue
"""
current_questions = set(x['question'] for x in self.questions)
# calculate difference of the two lists to avoid adding duplicates
available_questions = list(
set(self.question_catalogue.questions) - current_questions)
if available_questions:
self.questions.append(
{"question": random.choice(available_questions), "answer": None})
def get_next_question(self) -> Question:
"""Returns the next question of the quiz.
Sets the active question accordingly.
If the quiz is already finished (usually in exercise mode) a new question is appended and then returned.
Returns:
Question: The new current active question.
Raises:
IndexError: If the quiz already contains all questions from the catalogue
"""
if self.finished():
self.add_unique_question()
if self.current_question_index == -1 or self.questions[self.current_question_index]['answer'] != None:
# only go to next question when user answered the current one
self.current_question_index += 1
return self.questions[self.current_question_index]['question']
def add_answer(self, answer: bool, question: Question = None) -> None:
"""Stores an answer for the given question.
Args:
answer (bool): The user submitted answer to the question
question (Question, optional): The question the answer was submitted for. If None is given, the current active question is assumed. Defaults to None.
"""
index = self.current_question_index
if question != None:
index = self.questions.index(
{"question": question, "answer": None})
if self.questions[index]['answer'] == None:
self.questions[index]['answer'] = answer
def get_wrong_answers(self) -> list:
"""Returns all wrongly answered questions as a list.
Returns:
list: All questions where the users answer does not match the correct answer
"""
return list(filter(lambda el: (el['answer'] != el['question'].answer), self.questions))
def get_wrong_answer_count(self) -> int:
"""Returns the number of wrongly answered questions
Returns:
int: Number of questions where the users answer does not match the correct answer
"""
return len(self.get_wrong_answers())
def get_wrong_percentage(self) -> float:
"""Computes the percentage of wrong answers based on total question count in this quiz
Returns:
float: The percentage of wrongly answered questions
"""
return self.get_wrong_answer_count() / self.question_count()
def get_wrong_percentage_string(self, escape_markdown: bool = False) -> str:
"""Formates the percentage as string with two decimals precision, e.g. "66.67%".
Args:
escape_markdown (bool, optional): Escape the returned string for use in markdown. Defaults to False.
Returns:
str: Formatted percentage string
"""
percentage = f"{round(self.get_wrong_percentage() * 100, 2)}%"
if escape_markdown:
return telegram.utils.helpers.escape_markdown(percentage, 2)
else:
return percentage
def result(self, max_error_percentage: float) -> str:
"""Returns the result (passed or failed) of the quiz as string depending on the allowed error percentage.
Args:
max_error_percentage (float): The maximum percentage of wrongly answered questions allowed to pass this quiz.
Returns:
str: Result of the as string
"""
if self.get_wrong_percentage() <= max_error_percentage:
return "bestanden ✅"
else:
return "NICHT BESTANDEN ❌"
</code></pre>
<hr>
<p><strong>question_catalogue.py</strong></p>
<pre><code>import csv
import os
import telegram
from question import Question
class QuestionCatalogue:
def __init__(self, year: int, version: int, questions: [Question] = []):
"""Creates a new question catalogue, containing zero ore more questions
Args:
year (int): The year of publication for this catalogue
version (int): The version within the publication year
questions ([Question], optional): Questions to initialize the catalogue with. Defaults to [].
"""
self.questions = questions
self.version = version
self.year = year
def catalogue_name(self, escape_markdown: bool = False) -> str:
"""The name of the catalogue, composed of year and version, e.g. "2020_V2"
Args:
escape_markdown (bool, optional): Escape the resulting name for markdown use. Defaults to False.
Returns:
str: The name of the catalogue
"""
name = self.year
if self.version != 1:
name = f"{self.year}_V{self.version}"
if escape_markdown:
return telegram.utils.helpers.escape_markdown(name, 2)
else:
return name
def question_count(self) -> int:
"""Returns number of questions in this catalogue
Returns:
int: Number of questions
"""
return len(self.questions)
def add_questions_from_file(self, filename: str, image_mode: bool = False):
"""Import questions from a csv-formatted file.
Lines must be formatted according to the following format: "Nr.;Frage;J;N;Antwort;Art.;"
If image_mode is used the format is as follows: "Nr.;Frage;J;N;Antwort;Art.;Path;"
Args:
filename (str): The csv file to read from. Uses ";" as delimiter.
image_mode (bool, optional): The input file contains image questions, additional path column to read. Defaults to False.
"""
with open(filename, newline='') as csvfile:
reader = csv.DictReader(csvfile, delimiter=';')
for row in reader:
if row['J'].lower() == 'x':
answer = True
else:
answer = False
if not('K-' in row['Nr.'] or 'R-' in row['Nr.']):
break
# extract question type and number
parts = row['Nr.'].split('-')
question_type = parts[0]
number = parts[1]
path = None
if image_mode:
# construct full path to image
path = os.path.join(os.path.dirname(filename), row['Path'])
# create question
self.questions.append(Question(question_type, number,
row['Frage'], row['Antwort'], row['Art.'], answer, path))
</code></pre>
<hr>
<p><strong>question.py</strong></p>
<pre><code>import telegram
class Question:
def __init__(self, question_type: str, number: int, question_text: str, reason_text: str, article: str, answer: bool, path: str = None):
"""Creates a new question object
Args:
question_type (str): Type of the question, mostly "R" for rule questions or "K" for questrions for table officials.
number (int): The number of the question
question_text (str): The question itself
reason_text (str): The reasoning for the correct answer
article (str): The article or interpretation on which the question is based
answer (bool): The correct answer
path (str, optional): The path to an image, if the question has one. Defaults to None.
"""
self.question_type = question_type
self.number = number
self.question_text = question_text
self.reason_text = reason_text
self.article = article
self.answer = answer
self.path = path
def image_question(self) -> bool:
"""Determines whether this question has an image and is therefore an image question or not.
Returns:
bool: True, if the question is an image question. False otherwise.
"""
return self.path != None
def full_number(self, escape_markdown: bool = False) -> str:
"""Returns the complete question number, composed of the question type and the question number
Args:
escape_markdown (bool, optional): Escape the returned string for use in markdown. Defaults to False.
Returns:
str: Complete question number, e.g. "R-42" or "K-9"
"""
text = self.question_type + "-" + self.number
if escape_markdown:
return telegram.utils.helpers.escape_markdown(text, 2)
else:
return text
def question_header(self) -> str:
"""Returns markdown formatted header for questions containing the full question number only
Returns:
str: Header string , markdown escaped
"""
return f"*❓ Frage {telegram.utils.helpers.escape_markdown(self.full_number(), 2)}*: \n"
def full_question_string(self) -> str:
"""Returns markdown escaped string containing question number, question text and reason
Returns:
str: The resulting question, markdown escaped
"""
return (f"{self.question_header()}"
f"{telegram.utils.helpers.escape_markdown(self.question_text, 2)}\n"
f"{self.reason_string()}")
def reason_string(self) -> str:
"""Returns markdown escaped reasoning string
Returns:
str: Reason string, markdown escaped
"""
return (f"ℹ️ *Begründung*: \n"
f"{telegram.utils.helpers.escape_markdown(self.reason_text, 2)}\n")
</code></pre>
<hr>
<p><strong>Sample <code>.csv</code> file</strong> for <strong>non-image</strong> questions</p>
<pre><code>Nr.;Frage;J;N;Antwort;Art.;
R-42;This is a sample question and not an actual question. Correct?;;x;No (Art. 4). Sample questions are illegal according to article 4.;4;
</code></pre>
<hr>
<p><strong>Sample <code>.csv</code> file</strong> for <strong>image questions</strong>, mostly no question text</p>
<pre><code>Nr.;Frage;J;N;Antwort;Art.;Path;
K-9;;x;;Yes (KRHB);KRHB;./images/K-9.png;
</code></pre>
|
[] |
[
{
"body": "<p><strong><code>__location__</code></strong></p>\n<p>Here's a recommendation I have also started implementing recently: Using a <code>definitions.py</code> (naming up to preference of course) file at project level that exports all the references to directories and files I might need. I feel it significantly improved my codebases. Here's an example from one of my projects:</p>\n<pre><code>from pathlib import Path\nimport sys\n\nrunning_from_executable = getattr(sys, "frozen", False)\n\nif running_from_executable:\n ROOT_DIR = Path(sys.executable).parent\n DATA_DIR = Path(sys._MEIPASS).joinpath("data")\n\nelse:\n ROOT_DIR = Path(__file__).parent\n DATA_DIR = ROOT_DIR.joinpath("data")\n\nCONFIG_DIR = ROOT_DIR.joinpath("config")\n\nLOG_FILE = CONFIG_DIR.joinpath("debug.log")\nCONFIG_FILE = CONFIG_DIR.joinpath("config.json")\n\nICONS_DIR = DATA_DIR.joinpath("icons")\nFONTS_DIR = DATA_DIR.joinpath("fonts")\n</code></pre>\n<p>Checking if the script is run from an executable might not be relevant for you. As you can see <code>ROOT_DIR</code> would be the equivalent for your global variable <code>__location__</code>. You could also provide the paths to <code>TOKEN_FILE</code>, the <em>resources</em> directory and the various <em>question</em>.csv files from that module in your project. In the current state of your code some paths are hardcoded in <code>main()</code>, others are assigned at module level in <code>main.py</code>, which makes them harder to find and change.</p>\n<p>I would also recommend either sticking to <code>os.path</code> or <code>pathlib.Path</code> when handling file system paths instead of mixing them. I personally prefer <code>pathlib.Path</code>.</p>\n<p>Here's what it could look like for your project. This represents my understanding of your project structure, if you decide to use it please make sure to double check the paths.</p>\n<pre><code>from pathlib import Path\n\nSCRIPT_DIR = Path(__file__).parent\nPROJECT_DIR = SCRIPT_DIR.parent\n\nRESOURCES_DIR = PROJECT_DIR.joinpath("resources")\n\nTOKEN_FILE = PROJECT_DIR.joinpath("token.txt")\n\nRULES_CSV = RESOURCES_DIR.joinpath("rules.csv")\nKAMPF_CSV = RESOURCES_DIR.joinpath("kampf.csv")\nIMAGE_QUESTIONS_CSV = RESOURCES_DIR.joinpath("image-questions.csv")\n\nQUESTIONS_CSV_FILES = RULES_CSV, KAMPF_CSV, IMAGE_QUESTIONS_CSV\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:52:32.757",
"Id": "259865",
"ParentId": "259856",
"Score": "2"
}
},
{
"body": "<p>Overall it seems pretty reasonable; some specific points:</p>\n<p>Do not use the root logger. For a non-trivial application such as this, make your own logger instance for each module. You can configure the format of the root logger from the entry point, but don't do that at the global level - be courteous to people importing your code that may want to log differently.</p>\n<p>Avoid making a global <code>catalogue</code>. Pass it around by method parameters.</p>\n<p>From what I see here you've done a great job in separating implementation language (English) from locale (German). Given that there is only one hard-coded locale, consider calling into <a href=\"https://docs.python.org/3.9/library/locale.html\" rel=\"noreferrer\">https://docs.python.org/3.9/library/locale.html</a> to either assert that the locale is indeed German, or to simply set it as such. Which you should use depends on details of deployment.</p>\n<p>The only place where there's been some locale leakage is here:</p>\n<pre><code> os.path.join(__location__, '../resources/rules.csv'))\n os.path.join(__location__, '../resources/kampf.csv'))\n</code></pre>\n<p>Those filenames should standardize on language.</p>\n<p>Rather than <code>!= None</code> use <code>is not None</code>, since <code>None</code> is a singleton in Python.</p>\n<p>Avoid logic-by-exception; this:</p>\n<pre><code> try:\n context.user_data["game"]\n except KeyError:\n help_command(update, context)\n</code></pre>\n<p>should simply be</p>\n<pre><code>if 'game' not in context.user_data:\n help_command(update, context)\n</code></pre>\n<p>Use tuple unpacking to convert this:</p>\n<pre><code>result_texts = result[0]\nquestions = result[1]\n</code></pre>\n<p>to</p>\n<pre><code>result_texts, questions = result\n</code></pre>\n<p>Your loop flag <code>first</code> can go away; this:</p>\n<pre><code>first = True\nfor text in result_texts:\n context.bot.send_message(..., reply_markup=reply_markup)\n if first:\n reply_markup = None\n</code></pre>\n<p>is more simply expressed as</p>\n<pre><code>for text in result_texts:\n context.bot.send_message(..., reply_markup=reply_markup)\n reply_markup = None\n</code></pre>\n<p>This:</p>\n<pre><code> message = []\n message.append(self.quiz.check_answer())\n message.append(self.quiz.get_current_question().reason_string())\n</code></pre>\n<p>should use list literal syntax:</p>\n<pre><code>message = [\n self.quiz.check_answer(),\n self.quiz.get_current_question().reason_string(),\n]\n</code></pre>\n<p>and its docstring lies when it calls that an array. It's not an array; it's a list.</p>\n<p>More broadly, you have a data representation problem. Whereas you have reasonable <code>Quiz</code> and <code>QuestionCatalogue</code> classes, <code>Quiz.questions</code> is a list of dictionaries. This is an instance of early serialization and should be refactored to a list of class instances.</p>\n<p>Methods like <code>get_current_question_number</code> are well-represented as <code>@property</code> functions.</p>\n<pre><code>len(list(filter(lambda el: (el['answer'] == None), self.questions))) == 0\n</code></pre>\n<p>can be simplified to</p>\n<pre><code>all(el.answer is not None for el in self.questions)\n</code></pre>\n<p>assuming that the above dict-to-class refactoring is done.</p>\n<p><code>get_next_question</code>, along with your initially-negative-one-counter, betray an aspect of your <code>Quiz</code> class that would be better-represented as a normal Python iterator. In other words, you can make the class an iterable over its questions, and dispense with <code>current_question_index</code>, <code>question_count</code>, <code>get_current_question</code>, and <code>get_next_question</code>; replacing them with the standard iterator methods. Read <a href=\"https://docs.python.org/3/library/stdtypes.html#iterator-types\" rel=\"noreferrer\">https://docs.python.org/3/library/stdtypes.html#iterator-types</a> and <a href=\"https://docs.python.org/3/reference/datamodel.html\" rel=\"noreferrer\">https://docs.python.org/3/reference/datamodel.html</a> for information on <code>__next__</code> and <code>__len__</code> .</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:29:31.500",
"Id": "259869",
"ParentId": "259856",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "259869",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T12:00:18.337",
"Id": "259856",
"Score": "7",
"Tags": [
"python",
"python-3.x",
"telegram"
],
"Title": "Python Telegram Quiz Bot"
}
|
259856
|
<p>I am making a simple file explorer with tkinter Python.<br />
This is the <a href="https://github.com/Adityasingh76/Explorer" rel="nofollow noreferrer">file repository on github</a>.<br />
I know that this is pretty much long code and it took that much time to write but i have somehow added the comments.<br />
And I want someone to test my code.<br />
Also the additional mechanisms are not here and this is only for show purpose.
Secondly can you suggest that how can I show all the drives instead of <code>F:</code> drive (as I was using it for testing purpose.
Thank you in advance for any help.</p>
<pre><code>import tkinter as tk
from os import listdir
from os.path import isdir
from tkinter import messagebox
from PIL import ImageTk, Image
# globals
h = []
value = 0
m = 0
b, a, f, q, type, r= "", "", "", "", "", ""
g = 1
l = 1
photo = ""
new_name = 0
row = ""
image = ""
text = ""
# modifying button for files and folders
class modified_button(tk.Button):
def __init__(self, root, type=None, *args, **kw):
global h, value, m, b
tk.Button.__init__(self, root, *args, **kw)
self.type = type
self.root = root # root of the given button widget
if value == 0:
for i in range(len(x.lst)):
h.append(tk.Button(bg="#ffffff")) # creating a list of buttons when the first button is created
h.insert(value, self) # updating the list with newly created buttons
value += 1 # increasing the value so that list is not created again
self.x = ""
self.bind("<Enter>", lambda event, a="enter": self.changebg(a,
event)) # changing the color of the button when it is under cursor
self.bind("<Leave>", lambda event, a="leave": self.changebg(a,
event)) # changing the color of the button when the cursor leaves it
if type == "folder" or type == "file": # if the button is of a file or a folder
self.bind("<Button 1>",
lambda event, a="click": self.changebg(a, event)) # binding the click and rightclick
self.bind("<Button-3>", lambda event, a="right-click": self.changebg(a, event))
def changebg(self, a, event):
global g, l, q,type
if self["bg"] != "#80bfff" and a == "leave" and l != 0: # if the bg of the color is not dark blue change the bg to white
self.config(bg="#ffffff")
if self["bg"] != "#80bfff" and a == "enter" and g != 0 and l != 0: # same as above
self.config(bg="#cce6ff")
if self["bg"] != "#80bfff" and a == "click" and l != 0: # if the user has clicked then changing the bg
for ech in h:
if type == "renaming":
self.rename()
if ech["bg"] == "#80bfff": # checking if any other button has dark blue bg
ech.config(bg="#ffffff") # if it has then change it to light blue
self.config(bg="#80bfff") # lastly changing the bg to dark blue
if self.type != "other":
if self["bg"] == "#80bfff" and a == "right-click" and l != 0:
# checking if the button is clicked before or not
# creating menu for rightclick
self.m = tk.Menu(self.root, tearoff=0)
self.m.add_command(label="Cut ", command=lambda a=self, b="cut": self.copy_paste(b, a))
self.m.add_command(label="Copy ", command=lambda a=self, b="copy": self.copy_paste(b, a))
if self.type == "folder": # if the button is of a folder then only add the option to paste in it
self.m.add_command(label="Paste ", command=lambda a=self, b="paste": self.copy_paste(b, a))
else:
pass
self.m.add_separator()
self.m.add_command(label="Delete")
self.m.add_command(label="Rename", command=lambda a=self, b="rename": self.copy_paste(b, a))
try:
self.m.tk_popup(event.x_root, event.y_root)
finally:
self.m.grab_release()
def copy_paste(self, command, file):
global b, a, g, l, q,type,r,photo,row,image,text,new_name
if self.type != "other":
if command == "cut": # if the user has selected to cut the file
self.u = "{0}/{1}".format(x.z, file["text"])
a = "cut"
b = self.u
if command == "copy": # if the user has selected to copy the file
self.u = "{0}/{1}".format(x.z, file["text"])
a = "copy"
b = self.u
if command == "paste": # if the user has selected to paste the file
try:
file[0].isalpha()
if file == x.z:
self.x = file
else:
self.x = "{0}/{1}".format(x.z, file) # creating the path to paste
except:
self.x = "{0}/{1}".format(x.z, file["text"])
if a == "copy":
# sh.copy(b,self.x)
pass
if a == "cut":
# sh.move(b,self.x)
pass
if command == "rename": # renaming file
row = self.grid_info()["row"]
image = self["image"]
text = self["text"]
type = "renaming"
self.grid_forget()
r = tk.Frame(master=self.root, width=1750, height=10, bg="#ffffff")
photo = tk.Label(master=r, image=x.p1)
photo.grid(row=0, column=0)
new_name = tk.Entry(master=r, width=30)
new_name.grid(row=0, column=1)
r.grid(column=0, row=row, sticky="w")
new_name.bind("<Return>", lambda event: self.rename())
if command == "delete":
# remove(b)
pass
def rename(self):
# exact renaming method is not here
global r,new_name,text,row,type
print(r,2,new_name,3,text,4,row)
r.grid_forget()
button = modified_button(self.root, type=type, image=image, bg="#ffffff", text=new_name.get(), width=750,
height=13,
compound="left",
anchor="w",
borderwidth=0)
button.bind("<Double 1>", lambda event, a=text: x.create_dirlst(a))
if button["text"] == "":
button["text"] = text
button.grid(column=0, row=row)
type = ""
class explorer(tk.Frame):
def __init__(self, root, *args, **kwargs):
global f
tk.Frame.__init__(self, *args, **kwargs)
# creating the basics and handlers
self.window = root
self.lst = []
self.starting_path = "F:"
self.z = " "
self.last_search = ""
self.val = [0, 0, 0, 1, 0, 1, 0, 0, 1, 0]
self.p1 = ImageTk.PhotoImage(file="Folder.png")
self.p2 = ImageTk.PhotoImage(file="file.png")
self.p3 = ImageTk.PhotoImage(Image.open("Untitled-1.png").resize((20, 20), Image.ANTIALIAS))
self.p4 = ImageTk.PhotoImage(Image.open("Untitled-2.png").resize((20, 20), Image.ANTIALIAS))
self.no_of_files = 0
self.no_of_folders = 0
self.last_opened_folder = ""
def create_basics(self, a):
if self.val[0] == 0: # if this is first time then pass
pass
else: # if this not the first time then delete all the old widgets
self.left.pack_forget()
self.up.pack_forget()
self.parent_frame.pack_forget()
self.down.pack_forget()
# after deleting the old widgets creating new one
self.left = tk.Frame(self.window, bg="#ffffff", width=10)
self.left.pack(side="left", fill="y")
self.up = tk.Frame(master=self.window, height=10, width=10)
self.navigation_buttons = tk.Frame(self.up)
self.back_button = modified_button(self.navigation_buttons, type="other", image=self.p3, borderwidth=0,
bg="#ffffff")
self.forward_button = modified_button(self.navigation_buttons, type="other", image=self.p4, borderwidth=0,
bg="#ffffff")
self.back_button.grid(row=0, column=0)
self.back_button.bind("<Button-1>", lambda event, command="back": self.navigation(event, command))
self.forward_button.grid(row=0, column=1)
self.forward_button.bind("<Button-1>", lambda event, command="next": self.navigation(event, command))
self.navigation_buttons.pack(side="left", fill="y")
self.search = tk.Entry(master=self.up)
if self.last_search == "":
self.search.insert(tk.END, "Search")
else:
self.search.insert(tk.END, self.last_search)
self.search.bind("<Button-1>", lambda event, a="click": explorer.modify_search(self, a, event))
self.search.bind("<Leave>", lambda event, a="leave": explorer.modify_search(self, a, event))
self.search.bind("<Return>", lambda event, a="enter": explorer.modify_search(self, a, event))
self.search.bind("<BackSpace>", lambda event, a="Backspace": explorer.modify_search(self, a, event))
self.search.pack(side="right", fill="y")
self.path = tk.Frame(self.up, bg="#ffffff")
self.path.pack(fill="both", expand=1)
self.up.pack(fill="x")
self.parent_frame = tk.Frame(self.window)
self.canvas = tk.Canvas(self.parent_frame, bg="#ffffff")
self.canvas.pack(side="left", fill="both", expand=1)
self.scrollbar = tk.Scrollbar(self.parent_frame, orient="vertical", command=self.canvas.yview)
self.scrollbar.pack(side="right", fill="y")
self.canvas.configure(yscrollcommand=self.scrollbar.set)
self.canvas.bind("<Configure>", lambda event: self.canvas.configure(scrollregion=self.canvas.bbox("all")))
self.frame = tk.Frame(self.canvas)
self.canvas.create_window((0, 0), window=self.frame)
self.parent_frame.pack(fill="both", expand=1)
self.down = tk.Frame(self.window, width=100, borderwidth=1, bg="#444444")
self.down.pack(anchor="w")
self.canvas.bind("<Button-3>", lambda event: self.mod_canvas(event))
if a == "R":
self.val[5] = 0
explorer.create_folder(self)
def modify_search(self, a, event): # modifying the search widget
if self.search.get() == "" and a == "leave" and self.val[3] != 0 and self.val[
6] == 0: # if the method is called for first time or after changing the directory
self.search.insert(tk.END, "Search")
if a == "click" and self.search.get() == "Search" and self.val[
3] != 0: # if the user has clicked the widget to type
self.search.delete(0, tk.END)
self.val[6] = 1
if a == "enter" and self.search.get() != "" and self.search.get() != "Search": # if the user has pressed enter to search
m = self.lst # first saving the list
self.lst = [] # emptying the list
for x in m:
if self.search.get().lower() == x[0:len(
self.search.get())].lower(): # sortin all the matches of the search
self.lst.append(x) # updating self.lst
self.val[4] += 1 # updating self.val[4] to identify is any file matches or not
print(self.val[4])
if self.val[4] == 0: # if no file matches raise error
messagebox.showwarning('Error', "Can't find the specified file.")
else: # if the files are found creating the new sest of buttons with modified self.lst
self.last_search = self.search.get()
self.no_of_files = 0
self.no_of_folders = 0
self.create_basics("")
self.create_folder()
self.val[4] = 0
if a == "Backspace":
if self.search.get() == "Search":
self.search.delete(0, tk.END)
self.val[3] = 0
else:
pass
def navigation(self, event, command):
global f
if command == "back": # if the user has pressed back
try:
self.last_opened_folder = f # updating the last_opened_folder for later use
f = self.z[:len(f) - f[::-1].index("/") - 1] # obtaining the upper directory
except:
pass
# doing basic things as before to create new
self.lst = list(f for f in listdir(f) if f[0].isalpha())
self.starting_path = f
self.no_of_files = 0
self.no_of_folders = 0
self.create_basics("")
self.create_folder()
if command == "next":
try: # if the user has clicked next button
self.lst = list(f for f in listdir(self.last_opened_folder) if
f[0].isalpha()) # using the last_opened_folder from before
except:
pass
f = self.last_opened_folder
self.starting_path = self.last_opened_folder
self.no_of_files = 0
self.no_of_folders = 0
self.create_basics("")
self.create_folder()
def show_no_of_files(self):
# creating widgets to show no. of files and folders
self.files = tk.Label(master=self.down,
text=f"No. of files: {self.no_of_files}, No. of folders: {self.no_of_folders}",
borderwidth=1)
self.files.pack(fill="x", expand=1)
def create_dirlst(self, a):
global f
self.lst = []
# here self.z is the clicked icon or the file/folder user wants to open
if self.val[0] == 0: # if this method is called first time then initialise self.z
self.z = self.starting_path
self.val[2] += 1
if self.val[0] != 0 and self.val[
2] == 1: # if this method is not called for the first time then modifying self.z
self.z = "{0}/{1}".format(self.starting_path, a)
if isdir(self.z) == False and self.val[0] != 0: # if self.z is not a folder then raise error
#exact opening file method is not here
messagebox.showwarning('Open Error', "Can't open this file.")
self.val[1] += 1
if self.val[0] != 0 and isdir(self.z): # if the clicked icon is folder
self.starting_path = "{0}/{1}".format(self.starting_path, a)
self.lst = list(f for f in listdir(self.starting_path) if f[0].isalpha())
self.no_of_files = 0
self.no_of_folders = 0
self.create_basics("")
self.create_folder()
self.val[5] = 1
if self.val[1] != 0: # setting val[1] to zero so that the show_no_of_files method can be called later
self.val[1] = 0
f = self.z
if self.val[0] == 0: # creating the list if the method is called for first time
self.lst = list(f for f in listdir(self.starting_path) if f[0].isalpha() and f[0] != "$")
def create_folder(self):
for ech in self.lst: # iterating through the list of dir and files
if isdir("{0}/{1}".format(self.starting_path, ech)): # if ech is a folder
button = modified_button(self.frame, type="folder", image=self.p1, bg="#ffffff", text=ech, width=750,
height=13,
compound="left",
anchor="w",
borderwidth=0)
button.bind("<Double 1>", lambda event, a=ech: self.create_dirlst(a))
button.grid(column=0, row=self.lst.index(ech))
if self.val[5] != 0:
self.no_of_folders += 1 # incrementing self.no_of_folders
else:
button = modified_button(self.frame, type="file", image=self.p2, bg="#ffffff", text=ech, width=750,
height=13,
compound="left",
anchor="w",
borderwidth=0)
button.bind("<Double 1>", lambda event, a=ech: self.create_dirlst(a))
button.grid(column=0, row=self.lst.index(ech))
if self.val[5] != 0:
self.no_of_files += 1
self.val[0] += 1
if self.val[8] != 0:
q = self.starting_path.split("/")
for g in q:
self.path_buttons = modified_button(self.path, type="other", text=g, bg="#ffffff", borderwidth=0)
self.path_buttons.grid(row=0, column=q.index(g), padx=4)
self.path_buttons.bind("<Button-1>", lambda event, r=g: self.updating_path(r))
if self.val[1] == 0:
self.show_no_of_files()
def updating_path(self, k):
if self.starting_path == k:
pass
else:
self.starting_path = self.starting_path[:self.starting_path.index(k) + len(k)]
self.lst = list(f for f in listdir(self.starting_path) if f[0].isalpha())
self.create_basics("")
self.create_folder()
def mod_canvas(self,
event): # modifying the canvas at the right side to paste in the current directory and also for refreshing
self.menu = tk.Menu(self.canvas, tearoff=0)
self.menu.add_command(label="Refresh ", command=lambda a="R": explorer.create_basics(self, a))
self.menu.add_command(label="Paste ",
command=lambda a="paste", b=self.z: modified_button.copy_paste(self, a, b))
try:
self.menu.tk_popup(event.x_root, event.y_root)
finally:
self.menu.grab_release()
if __name__ == "__main__": # creating basic window
window = tk.Tk()
window.geometry("900x600")
window.title("Door Explorer 1.0")
window.iconbitmap("icon1.ico")
x = explorer(window)
x.create_basics("")
x.create_dirlst(x.starting_path)
x.create_folder()
window.mainloop()
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:06:07.420",
"Id": "512711",
"Score": "5",
"body": "Welcome to Code Review. Unfortunately your question is off-topic as of now, as the code to be reviewed must be [present in the question.](//codereview.meta.stackexchange.com/q/1308) Please add the code you want reviewed in your question. Thanks!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:33:14.810",
"Id": "512723",
"Score": "0",
"body": "I want the full code to be reviewed as all the classes and methods in it are interlinked. And when I add all the code to the question it shows your question contains mostly code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:35:03.183",
"Id": "512724",
"Score": "0",
"body": "And if it is not possible then you can just test the code by compiling the file and checking if it performs all the necessary functions of a simple file explorer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:45:31.360",
"Id": "512731",
"Score": "1",
"body": "_I want the full code to be reviewed_ - Great; then copy-and-paste it. A link is not enough; links die."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T15:45:47.880",
"Id": "512732",
"Score": "1",
"body": "Welcome to the Code Review Community. We can use repositories as references, but we can't review code in repositories, only the code embedded in the question post. Please add the code from the repository."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:22:52.603",
"Id": "512757",
"Score": "0",
"body": "The code you pasted is both incomplete - it's missing all of its imports - and malformatted - the indentation is incorrect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T03:08:33.273",
"Id": "512814",
"Score": "0",
"body": "Sorry for bad indentation but i think now its correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T03:10:13.650",
"Id": "512815",
"Score": "0",
"body": "I am new to stackoverflow as well as code review that's why i don't know way of formatting text."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T08:16:06.373",
"Id": "512833",
"Score": "0",
"body": "Just a note to possible reviewers: Can confirm code works on my machine."
}
] |
[
{
"body": "<p><em>Note: I don't have experience with <code>tkinter</code>, so this will be a review for general code style. I welcome anyone who has experience with <code>tkinter</code> to add their review as well!</em></p>\n<hr>\n<h1>Class Naming</h1>\n<p>Class names should be in <code>PascalCase</code>, not <code>snake_case</code>.</p>\n<pre><code>modified_button -> ModifiedButton\nexplorer -> Explorer\n</code></pre>\n<h1>Constants</h1>\n<p>Littered through your code are strings of hex values and specific strings representing events. You should define these at the top of your file, and just reference them throughout your code. One mistype, e.g <code>"#80bfff" to "#08bfff"</code>, will cause you to search through your code to where you might have mistyped that.</p>\n<pre><code>DARK_BLUE = "#80bfff"\nWHITE = "#ffffff"\n...\n</code></pre>\n<h1>Comments</h1>\n<p>To me, your comments make this code 10x harder to read.</p>\n<pre><code>if self.type == "folder": # if the button is of a folder\n</code></pre>\n<p>Do you really need this comment? Comments should tell the user how a specific part of the code works, your intentions with that part, and to explain an algorithmic piece of code that could be confusing.</p>\n<h1>Reserved Names</h1>\n<p><code>type</code> is a reserved name (function) in python, so you should rename it to something like <code>file_type</code>, or along those lines.</p>\n<p>While we're talking about variables names, what are these?</p>\n<pre><code># globals\nh = []\nvalue = 0\nm = 0\nb, a, f, q, type, r= "", "", "", "", "", ""\ng = 1\nl = 1\n</code></pre>\n<p>While you say they're globals, I don't have the faintest clue about what they represent. And looking through your code, I'm still confused. Variables should be representative of the data they store.</p>\n<h1>Cleaner Logic</h1>\n<p>Instead of</p>\n<pre><code>if self.val[0] == 0: # if this is first time then pass\n pass\nelse: # if this not the first time then delete all the old widgets\n self.left.pack_forget()\n self.up.pack_forget()\n self.parent_frame.pack_forget()\n self.down.pack_forget()\n</code></pre>\n<p>How about checking if the value isn't 0?</p>\n<pre><code>if self.val[0] != 0:\n self.left.pack_forget()\n self.up.pack_forget()\n self.parent_frame.pack_forget()\n self.down.pack_forget()\n</code></pre>\n<p>The same concept can be applied to multiple other places in your code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T12:28:26.417",
"Id": "512855",
"Score": "0",
"body": "Thanks for your answer.I will try to avoid these cases in my next project which is possibly not of tkinter."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T08:32:02.967",
"Id": "259894",
"ParentId": "259862",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T14:23:45.167",
"Id": "259862",
"Score": "0",
"Tags": [
"python",
"tkinter"
],
"Title": "Making a File explorer with Python tkinter"
}
|
259862
|
<p>I am developing a system for runtime macro executions in an automatic test environment. Macros are defined in an xml and are for configuring multiple devices/DUTs for a specific use case.
The xml parsing of these macros is outside of the scope of this question.</p>
<p>For building the macros in code I created the code shown below.
In this example, there is no 'Macro' class, but rather a collection of 'Statement's. This can be regarded as the same thing.</p>
<p>A macro consists out of statements and some statements are only to be executed under certain conditions (e.g. IfStatement).</p>
<p>For execution of the statements a context object is passed between the statements and the conditions. This context can then be used/modified by the statements and checked by the conditions.</p>
<p>For this I use 2 interfaces: IStatement and ICondition:</p>
<ul>
<li><p>Each Statement implements IStatement - having an Execute(object context) method - and tries to cast the context (of type object) to one or more interfaces which the statement needs. Some statements do not actually need the context (e.g. DelayStatement)</p>
</li>
<li><p>The same goes for the Conditions, they implement ICondition - having an IsTrue(object context) method - and cast the context to expected interfaces. Some conditions do not need the context (e.g. True, False), but implement the interface explicitly.</p>
</li>
</ul>
<p>There is a Core project, that defines the basics of the macros, but this can be extended for more specific projects. The context object can vary per project and can even have a different type (e.g. Context, SpecificContext). More statements/conditions can be added per project.</p>
<p>I have a couple of questions about this:</p>
<ul>
<li>Is the way of passing context a good way for a use case like this? Should the statement/condition 'know' about the context it is going to receive/expect? Or should that be the responsibility of the caller?</li>
<li>If so, what is a better approach for this?</li>
<li>Should I define multiple interfaces for Statements that require context, and statements that do not? Same goes for conditions.</li>
<li>If this context-passing is a design pattern, what is the name of it?</li>
<li>Within a statement/condition: should I check for multiple interfaces/classes? (e.g. in the DeviceConnectedCondition: should I check if the context is a Device and then check if the context is a IDeviceContainer, or should I just check for IDeviceContainer?)</li>
</ul>
<p>Some notes:</p>
<ul>
<li>I can create an interface IContext, that has at least the Arguments, Messages, and Result to reduce some castings.</li>
<li>There are more statements/conditions than shown below, this is just a sandbox.</li>
<li>I started out using the Visitor pattern and no common Execute(object)/IsTrue(object) method, but stumbled upon problems in the stage of the Specific projects where I did not know how to properly extend the Core.Visitor. In this case, only the Visitor knew about the specific Context class/object and knew which methods to invoke on the Statements/Conditions (e.g: it knew that a True condition does not need context, but for the SendI2CToDevice, it only provided the Device by invoking a specific method)</li>
</ul>
<p>Many thanks!</p>
<pre><code>using ContextPassing.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ContextPassing.Client
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Please write a random text and press enter.");
string randomText = Console.ReadLine();
Console.Clear();
Console.WriteLine("Do you want to send the the text to the DUT/Device ? (y for yes)");
string printInput = Console.ReadKey().KeyChar.ToString();
Console.Clear();
Console.WriteLine("If previous answer was yes, do you want to add a delay before sending it to the DUT/Device ? (y for yes)");
string addDelay = Console.ReadKey().KeyChar.ToString();
Console.Clear();
var statements = new List<IStatement>();
statements.Add(new SetFieldStatement { FieldName = "RandomText", Value = randomText });
statements.Add(new SetFieldStatement { FieldName = "SendInput", Value = printInput });
statements.Add(new SetFieldStatement { FieldName = "AddDelay", Value = addDelay });
var printInputIfStatement = new IfStatement() { Condition = new FieldCondition { FieldName = "SendInput", Value = "y" } };
var elseif = new ElseIf { Condition = new FieldCondition { FieldName = "SendInput", Value = "k" } };
elseif.Statements.Add(new LogStatement { Message = "This is an easter egg." });
printInputIfStatement.ElseIfs.Add(elseif);
printInputIfStatement.Else.Add(new LogStatement { Message = "Input was not sent." });
var addDelayIfStatement = new IfStatement() { Condition = new FieldCondition { FieldName = "AddDelay", Value = "y" } };
addDelayIfStatement.Statements.Add(new DelayStatement() { Time = TimeSpan.FromSeconds(1) });
printInputIfStatement.Statements.Add(addDelayIfStatement);
printInputIfStatement.Statements.Add(new LogFieldStatement() { FieldName = "RandomText" });
printInputIfStatement.Statements.Add(new ContextPassing.Specific.SendI2cBytesToDevice() { Bytes = Encoding.ASCII.GetBytes(randomText) });
statements.Add(printInputIfStatement);
var context = new ContextPassing.Specific.SpecificContext();
context.Device = new ContextPassing.Specific.Device();
new StatementExecutor().Execute(statements, context);
Console.WriteLine("*** Execution complete - Message overview: ***");
foreach (string msg in (context as IMessageContainer).Messages)
{
Console.WriteLine(msg);
}
Console.WriteLine("***");
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
}
namespace ContextPassing.Core
{
public interface IArgumentContainer
{
IEnumerable<object> Arguments { get; }
}
public interface IFieldContainer
{
IDictionary<string, object> Fields { get; }
}
public interface IMessageContainer
{
ICollection<string> Messages { get; }
}
public class Context : IArgumentContainer, IMessageContainer, IFieldContainer
{
public Collection<object> Arguments { get; } = new Collection<object>();
public Collection<string> Messages { get; } = new Collection<string>();
public Dictionary<string, object> Fields { get; } = new Dictionary<string, object>();
object Result { get; set; }
IEnumerable<object> IArgumentContainer.Arguments => Arguments;
ICollection<string> IMessageContainer.Messages => Messages;
IDictionary<string, object> IFieldContainer.Fields => Fields;
}
public class StatementExecutor
{
public void Execute(IEnumerable<IStatement> statements, object context)
{
foreach (IStatement statement in statements)
{
statement.Execute(context);
}
}
}
public interface IStatement
{
void Execute(object context);
}
public interface ICondition
{
bool IsTrue(object context);
}
public class True : ICondition
{
public bool IsTrue() => true;
public bool IsTrue(object context) => IsTrue();
}
public class False : ICondition
{
public bool IsTrue() => false;
public bool IsTrue(object context) => throw new NotImplementedException();
}
public class Not : ICondition
{
ICondition Condition { get; set; }
public bool IsTrue(object context) => !Condition.IsTrue(context);
}
public class Or : ICondition
{
Collection<ICondition> Conditions { get; } = new Collection<ICondition>();
public bool IsTrue(object context) => Conditions.Any(x => x.IsTrue(context));
}
public class FieldCondition : ICondition
{
public string FieldName { get; set; }
public object Value { get; set; }
public bool IsTrue(object context)
{
var fieldContainer = context as IFieldContainer;
if (fieldContainer is null)
throw new InvalidOperationException("Context needs to be an IFieldContainer.");
return fieldContainer.Fields[FieldName].Equals(Value);
}
}
public class IfStatement : IStatement
{
public Collection<IStatement> Statements { get; } = new Collection<IStatement>();
public Collection<ElseIf> ElseIfs { get; } = new Collection<ElseIf>();
public Collection<IStatement> Else { get; set; } = new Collection<IStatement>();
public ICondition Condition { get; set; }
public void Execute(object context)
{
if (Condition.IsTrue(context))
{
foreach (IStatement statement in Statements)
statement.Execute(context);
return;
}
foreach (ElseIf elseIf in ElseIfs)
{
if (elseIf.Condition.IsTrue(context))
{
foreach (IStatement statement in elseIf.Statements)
statement.Execute(context);
return;
}
}
if (Else != null)
{
foreach (IStatement statement in Else)
statement.Execute(context);
}
}
}
public class ElseIf
{
public ICondition Condition { get; set; }
public Collection<IStatement> Statements { get; } = new Collection<IStatement>();
}
public class SetFieldStatement : IStatement
{
public string FieldName { get; set; }
public object Value { get; set; }
public void Execute(object context)
{
var fieldsContainer = context as IFieldContainer;
if (fieldsContainer is null)
throw new InvalidOperationException("Context needs to be an IFieldContainer.");
fieldsContainer.Fields[FieldName] = Value;
}
}
public class LogStatement : IStatement
{
public string Message { get; set; }
public void Execute(object context)
{
var msgsContainer = context as IMessageContainer;
if (msgsContainer is null)
throw new ArgumentException("Context needs to be an IMessageContainer.");
msgsContainer.Messages.Add(Message);
}
}
public class LogFieldStatement : IStatement
{
public string FieldName { get; set; }
public void Execute(object context)
{
var fieldContainer = context as IFieldContainer;
var msgsContainer = context as IMessageContainer;
if (fieldContainer is null)
throw new InvalidOperationException("Context needs to be an IFieldContainer.");
if (msgsContainer is null)
throw new ArgumentException("Context needs to be an IMessageContainer.");
msgsContainer.Messages.Add($"Field {FieldName} its value is: {fieldContainer.Fields[FieldName]}");
}
}
public class DelayStatement : IStatement
{
public TimeSpan Time { get; set; } = TimeSpan.FromSeconds(1);
public void Execute()
{
Thread.Sleep(Time);
}
// This statement does not need any context.
void IStatement.Execute(object context) => Execute();
}
}
namespace ContextPassing.Specific
{
public class Device
{
public void SendI2cBytes(byte[] bytes) => Console.WriteLine($"Sending bytes bleep bloep blaap: {BitConverter.ToString(bytes)}");
public bool IsConnected => true;
}
public interface IDeviceContainer
{
Device Device { get; }
}
public class SpecificContext : ContextPassing.Core.Context, IDeviceContainer
{
public Device Device { get; set; } = new Device();
}
public class IsConnected : ICondition
{
public bool IsTrue(object context)
{
var dc = context as IDeviceContainer;
if (dc is null)
throw new ArgumentException("Context should be a device container.");
return dc.Device.IsConnected;
}
}
public class SendI2cBytesToDevice : IStatement
{
public byte[] Bytes;
public void Execute(object context)
{
var dc = context as IDeviceContainer;
if (dc is null)
throw new ArgumentException("Context should be a device container.");
dc.Device.SendI2cBytes(Bytes);
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[] |
[
{
"body": "<p>Passing the context that way is acceptable but the problem with the context that you have is that it can grow larger the more you add custom statements. This is an anti pattern, because it can be a GOD Object. And if you create new custom statements in the future you may need to touch the context again, which tainted the SOLID principle.</p>\n<p>The better approach for this is if you have specific dependency, like device in this case, I'd suggest to inject it either into constructor or as a Field in the context.</p>\n<p>The following is my version of the code</p>\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Collections.ObjectModel;\nusing System.Linq;\nusing System.Text;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing ContextPassing.Core;\nusing ContextPassing.Specific;\nusing SetField = ContextPassing.Core.SetFieldStatement;\nusing Delay = ContextPassing.Core.DelayStatement;\nusing SendToDevice = ContextPassing.Specific.SendToDeviceStatement;\nusing LogField = ContextPassing.Core.LogFieldStatement;\nusing Log = ContextPassing.Core.LogStatement;\nusing If = ContextPassing.Core.IfStatement;\nusing static System.Console;\n\nnamespace ContextPassing.Client\n{\n class Program\n {\n static void Main(string[] args)\n {\n WriteLine("Please write a random text and press enter.");\n string randomText = ReadLine();\n Clear();\n\n WriteLine("Do you want to send the the text to the DUT/Device ? (y for yes)");\n string printInput = ReadKey().KeyChar.ToString();\n Clear();\n\n WriteLine("If previous answer was yes, do you want to add a delay before sending it to the DUT/Device ? (y for yes)");\n string addDelay = ReadKey().KeyChar.ToString();\n Clear();\n\n var device = new Device\n {\n IsConnected = true\n };\n // declarative initialisation\n IStatement rootStatement = new Statements(\n new SetField("RandomText", randomText),\n new SetField("SendInput", printInput),\n new SetField("AddDelay", addDelay),\n new If(new FieldCondition("SendInput", "y"),\n new Statements(\n new If(new FieldCondition("AddDelay", "y"),\n new Delay {Time = TimeSpan.FromSeconds(1)}),\n new LogField("RandomText"),\n new If(new CheckDeviceCondition(device), \n new SendToDevice("RandomText", device),\n new Log("Error: Device is not connected!"))),\n new If(new FieldCondition("SendInput", "k"),\n new Log("This is an easter egg."),\n new Log("Input was not sent."))));\n\n // normal initialisation\n // IStatement rootStatement = new Statements(\n // new SetField("RandomText", randomText),\n // new SetField("SendInput", printInput),\n // new SetField("AddDelay", addDelay));\n //\n // var printInputIfStatement = new If(new FieldCondition("SendInput", "y"));\n // var addDelayIfStatement = new If(new FieldCondition("AddDelay", "y"));\n //\n // addDelayIfStatement.IfTrue(new Delay {Time = TimeSpan.FromSeconds(1)});\n //\n // var sendToDeviceIfStatement = new If(new CheckDeviceCondition(device));\n //\n // sendToDeviceIfStatement.IfTrue(new SendToDevice("RandomText", device));\n // sendToDeviceIfStatement.IfFalse(new Log("Error: Device is not connected!"));\n //\n // printInputIfStatement.IfTrue(\n // new Statements(\n // addDelayIfStatement,\n // new LogField("RandomText"),\n // sendToDeviceIfStatement));\n //\n // var elseif = new IfStatement(new FieldCondition("SendInput", "k"));\n //\n // elseif.IfTrue(new Log("This is an easter egg."));\n // elseif.IfFalse(new Log("Input was not sent.")); // else\n // printInputIfStatement.IfFalse(elseif);\n //\n // rootStatement.Enqueue(printInputIfStatement);\n\n var context = new Context();\n rootStatement.Execute(context);\n WriteLine("*** Execution complete - Message overview: ***");\n\n var msgContainer = MessageContainer.GetContainer(context);\n foreach (string msg in msgContainer.Messages)\n {\n WriteLine(msg);\n }\n\n WriteLine("***");\n\n WriteLine("Press any key to exit.");\n ReadKey();\n }\n }\n}\n\nnamespace ContextPassing.Core\n{\n public interface IFieldContainer\n {\n IDictionary<string, object> Fields { get; }\n }\n\n public interface IMessageContainer\n {\n ICollection<string> Messages { get; }\n }\n\n public class Context : IFieldContainer\n {\n public IDictionary<string, object> Fields { get; } = new Dictionary<string, object>();\n }\n\n public class MessageContainer : IMessageContainer\n {\n private static readonly string MESSAGE_KEY = typeof(IMessageContainer).FullName;\n public ICollection<string> Messages { get; } = new Collection<string>();\n public static IMessageContainer GetContainer(object context)\n {\n if (context is not IFieldContainer fieldsContainer)\n throw new InvalidOperationException("Context needs to be an IFieldContainer.");\n if (fieldsContainer.Fields.TryGetValue(MESSAGE_KEY, out var value) && value is IMessageContainer messageContainer)\n return messageContainer;\n messageContainer = new MessageContainer();\n fieldsContainer.Fields.Add(MESSAGE_KEY, messageContainer);\n return messageContainer;\n }\n }\n\n public interface IStatement\n {\n void Enqueue(IStatement nextStatement);\n IStatement Dequeue();\n void Execute(object context);\n }\n\n public interface ICondition\n {\n bool IsTrue(object context);\n }\n\n public class True : ICondition\n {\n public bool IsTrue(object context) => true;\n }\n\n public class False : ICondition\n {\n public bool IsTrue(object context) => false;\n }\n\n public class Not : ICondition\n {\n private readonly ICondition _condition;\n public Not(ICondition condition) => _condition = condition;\n public bool IsTrue(object context) => !_condition.IsTrue(context);\n }\n\n public abstract class AggregateConditionBase : ICondition\n {\n protected readonly IReadOnlyCollection<ICondition> _conditions;\n protected AggregateConditionBase(params ICondition[] conditions)\n {\n _conditions = conditions ?? Array.Empty<ICondition>();\n }\n \n public abstract bool IsTrue(object context);\n }\n\n public class Or : AggregateConditionBase\n {\n public override bool IsTrue(object context) => _conditions.Any(c => c.IsTrue(context));\n }\n\n public class And : AggregateConditionBase\n {\n public override bool IsTrue(object context) => _conditions.All(c => c.IsTrue(context));\n }\n\n public class FieldCondition : ICondition\n {\n private readonly string _field;\n private readonly string _value;\n public FieldCondition(string field, string value)\n {\n _field = field;\n _value = value;\n }\n public bool IsTrue(object context)\n {\n if (context is not IFieldContainer fieldContainer)\n throw new InvalidOperationException("Context needs to be an IFieldContainer.");\n return fieldContainer.Fields[_field].Equals(_value);\n }\n }\n\n public abstract class StatementBase : IStatement\n {\n private readonly Queue<IStatement> _nextStatements = new();\n protected StatementBase(params IStatement[] nextStatements)\n {\n if (nextStatements == null) return;\n foreach (var nextStatement in nextStatements)\n {\n Enqueue(nextStatement);\n }\n }\n public void Enqueue(IStatement nextStatement) => _nextStatements.Enqueue(nextStatement);\n public IStatement Dequeue() => _nextStatements.Dequeue();\n protected abstract void Execute(object context);\n void IStatement.Execute(object context)\n {\n Execute(context);\n foreach (var nextStatement in _nextStatements)\n {\n nextStatement.Execute(context);\n }\n }\n }\n\n // this is just a wrapper of statements\n public class Statements : StatementBase\n {\n public Statements(params IStatement[] nextStatements)\n : base(nextStatements)\n { }\n protected override void Execute(object context)\n { /* do nothing */ }\n }\n\n public class IfStatement : StatementBase\n {\n private readonly ICondition _condition;\n private IStatement _ifTrue;\n private IStatement _ifFalse;\n public IfStatement(ICondition condition, IStatement ifTrue = null, IStatement ifFalse = null, params IStatement[] nextStatements)\n : base(nextStatements)\n {\n _condition = condition;\n _ifTrue = ifTrue;\n _ifFalse = ifFalse;\n }\n public void IfTrue(IStatement ifTrue)\n {\n _ifTrue = ifTrue;\n }\n public void IfFalse(IStatement ifFalse)\n {\n _ifFalse = ifFalse;\n }\n protected override void Execute(object context)\n {\n if (_condition.IsTrue(context))\n {\n _ifTrue?.Execute(context);\n return;\n }\n \n _ifFalse?.Execute(context);\n }\n }\n \n public class SetFieldStatement : StatementBase\n {\n private readonly string _field;\n private readonly string _value;\n public SetFieldStatement(string field, string value, params IStatement[] nextStatements)\n : base(nextStatements)\n {\n _field = field;\n _value = value;\n }\n protected override void Execute(object context)\n {\n if (context is not IFieldContainer fieldsContainer)\n throw new InvalidOperationException("Context needs to be an IFieldContainer.");\n fieldsContainer.Fields[_field] = _value;\n }\n }\n\n public class LogStatement : StatementBase\n {\n private readonly string _message;\n public LogStatement(string message, params IStatement[] nextStatements) \n : base(nextStatements) => _message = message;\n protected override void Execute(object context)\n {\n var msgContainer = MessageContainer.GetContainer(context);\n msgContainer.Messages.Add(_message);\n }\n }\n\n public class LogFieldStatement : StatementBase\n {\n private readonly string _field;\n public LogFieldStatement(string field, params IStatement[] nextStatements) \n : base(nextStatements) => _field = field;\n protected override void Execute(object context)\n {\n if (context is not IFieldContainer fieldContainer)\n throw new InvalidOperationException("Context needs to be an IFieldContainer.");\n var msgContainer = MessageContainer.GetContainer(context);\n msgContainer.Messages.Add($"Field {_field} its value is: {fieldContainer.Fields[_field]}");\n }\n }\n\n public class DelayStatement : StatementBase\n {\n public DelayStatement(params IStatement[] nextStatements) \n : base(nextStatements)\n { }\n public TimeSpan Time { get; init; } = TimeSpan.FromSeconds(1);\n protected override void Execute(object context) => Thread.Sleep(Time);\n }\n}\n\nnamespace ContextPassing.Specific\n{\n public interface IDevice\n {\n public void Send(object data);\n public bool IsConnected();\n }\n \n public class Device : IDevice\n {\n public bool IsConnected { get; set; }\n public void SendI2cBytes(byte[] bytes) => WriteLine($"Sending bytes bleep bloep blaap: {BitConverter.ToString(bytes)}");\n void IDevice.Send(object data) => SendI2cBytes(Encoding.ASCII.GetBytes(data.ToString() ?? string.Empty));\n bool IDevice.IsConnected() => IsConnected;\n }\n\n public class CheckDeviceCondition : ICondition\n {\n private readonly IDevice _device;\n public CheckDeviceCondition(IDevice device) => _device = device;\n public bool IsTrue(object context) => _device.IsConnected();\n }\n\n public class SendToDeviceStatement : StatementBase\n {\n private readonly string _field;\n private readonly IDevice _device;\n public SendToDeviceStatement(string field, IDevice device, params IStatement[] nextStatements)\n : base(nextStatements)\n {\n _field = field;\n _device = device;\n }\n protected override void Execute(object context)\n {\n if (context is not IFieldContainer fieldContainer)\n throw new ArgumentException("Context should be a device container.");\n _device.Send(fieldContainer.Fields[_field]);\n }\n }\n}\n</code></pre>\n<p>Notes:</p>\n<ul>\n<li>I use a behavioral Pattern called <em>Chain of Responsibility</em></li>\n<li>Introduced <em>Enqueue</em> and <em>Dequeue</em> methods in <em>IStatement</em> to add/remove next statements. I also add nextStatements as part of constructor so we can do declarative initialisation.</li>\n<li>Context contains only <em>Fields</em>. If you think there wont be any use case that we need to introduce new interfaces into the context, I would suggest to just use IFieldContainer as context type (not object)</li>\n<li>Introduced <em>IDevice</em> in case there'll be multiple kind of devices. This is injected into <em>CheckDeviceConnectionCondition</em> and <em>SendToDeviceStatement</em>. You can also use context to store the field (like IMessageContainer)</li>\n<li><em>IMessageContainer</em> now is injected into Fields. I add a static Method in MessageContainer to grab the message container instance from context.</li>\n</ul>\n<p>If you need to introduce new custom statements you don't need to update the context or any existing class or funcationlities.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T08:34:41.147",
"Id": "513113",
"Score": "0",
"body": "Thank you for your clear and crisp explanation of the shortcomings and improvements on my current implementation. Very helpful feedback! I'm glad that I was on the right track, but you are right on the context becoming a GOD object and having to adjust it when new statements are added. I was a bit confused by the two Execute methods, since the StatementBase.Execute implementation executes only the current instance, while the IStatement.Execute executes the current statements and the next in the queue. _Is it best to rename one of them not to confuse future readers of my code?_"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T08:43:40.497",
"Id": "513116",
"Score": "0",
"body": "Merely out of curiosity: I was also wondering if MessageContainer.Get(...) does not violate the _single-responsibility-principle_? Since the MessageContainer extracts/injects itself from/into the context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T13:33:14.700",
"Id": "513136",
"Score": "1",
"body": "`StatementBase`, the first `Execute` method is an abstract protected method, which is the real implementation/execution of the statement. And the other `Execute` method is the _explicit implementation of interface_ `IStatement`. This is final, and it determines the flow of execution. They have same name, but different intention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T13:34:55.010",
"Id": "513137",
"Score": "1",
"body": "The reason I didn't merge that into one is to prevent subclass to call `base.Execute()` which in this case the position is very important, wrong position would cause problem. But in this case, the subclass don't have to worry about that and just focus on the implementation code. You can change the abstract method to different name but I prefer the same name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T13:35:04.027",
"Id": "513139",
"Score": "1",
"body": "As far as the `MessageContainer.GetContainer(object context)`, it's a _static method_ so it doesn't violate the single-responsibility-principle of that class. It's merely an extension/helper to get the message container from and into the context, which you can extract to any static class if needs to. I put it in the same class to make it cleaner, because the `MessageContainer` is a small class, and putting it there make it easier to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T14:56:57.140",
"Id": "513144",
"Score": "0",
"body": "Thank you for the clarification!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:47:27.787",
"Id": "259942",
"ParentId": "259866",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259942",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:05:52.177",
"Id": "259866",
"Score": "2",
"Tags": [
"c#",
"xml",
"macros"
],
"Title": "Is this a good design for runtime Macro execution?"
}
|
259866
|
<p>After I have been doing some improvements from my <a href="https://codereview.stackexchange.com/questions/259561/check-if-new-dict-values-has-been-added/259622">Previous code review</a>. I have taken the knowledge to upgrade and be a better coder but now im here again asking for Code review where I think it could be better.</p>
<p>The purpose of this code is a monitoring that checks for a special site every random 30 to 120 seconds. If there has been a changes then it goes through some if statements as you can see and it will then print to my discord if there has been a changed made.</p>
<p>This is what I have created:</p>
<p><strong>monitoring.py</strong></p>
<pre><code>#!/usr/bin/python3
# -*- coding: utf-8 -*-
import concurrent.futures
import random
import time
from datetime import datetime, timedelta
from typing import Any, Dict, List
import pendulum
from loguru import logger
from scrape_values import Product
store: str = "shelta"
link: str = "https://shelta.se/sneakers/nike-air-zoom-type-whiteblack-cj2033-103"
# -------------------------------------------------------------------------
# Utils
# -------------------------------------------------------------------------
_size_filter: Dict[str, datetime] = {}
def monitor_stock():
"""
Function that checks if there has happen a restock or countdown change on the website
"""
payload = Product.from_page(url=link).payload
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
while True:
# Request for new product information
new_payload = Product.from_page(url=link).payload
# Release sleep
release_date_sleeper(new_payload)
# Check countdown timer comparision
if countdown_timer_comparision(payload, new_payload):
# Send notification to discord
executor.submit(send_notification, new_payload, "Timer change!")
# Replace list
payload["displayCountDownTimer"] = new_payload["displayCountDownTimer"]
# Check sizes comparision
if sizes_comparision(payload, new_payload):
# Send notification to discord
executor.submit(send_notification, new_payload, "Restock!")
# Replace list
payload["sizes"] = new_payload["sizes"]
else:
# No changes happen
logger.info("No changes made")
payload["sizes"] = new_payload["sizes"]
time.sleep(random.randint(30, 120))
def release_date_sleeper(payload) -> None:
"""
Check if there is a release date on the website. We should sleep if there is to save resources
:param payload:
"""
if payload.get('releaseDate'):
delta_seconds = (payload["releaseDate"].subtract(seconds=10)) - pendulum.now()
if not delta_seconds.seconds:
logger.info(f'Release date enabled | Will sleep to -> {(payload["releaseDate"].subtract(seconds=10)).to_datetime_string()}')
time.sleep(delta_seconds.seconds)
def countdown_timer_comparision(payload, new_payload) -> bool:
"""
Compare the first requests with the latest request and see if the countdown timer has been changed on the website
:param payload: First request made
:param new_payload: Latest request made
:return: bool
"""
if new_payload.get("displayCountDownTimer") and payload["displayCountDownTimer"] != new_payload[
"displayCountDownTimer"]:
logger.info(f'Detected new timer change -> Name: {new_payload["name"]} | Display Time: {new_payload["displayCountDownTimer"]}')
return True
def sizes_comparision(payload, new_payload) -> bool:
"""
Compare the first requests with the latest request and see if the sizes has been changed on the website
:param payload: First request made
:param new_payload: Latest request made
:return: bool
"""
if payload["sizes"] != new_payload["sizes"]:
if spam_filter(new_payload["delay"], new_payload["sizes"]):
logger.info(f'Detected restock -> Name: {new_payload["name"]} | Sizes: {new_payload["sizes"]}')
return True
def send_notification(payload, status) -> Any:
"""
Send to discord
:param payload: Payload of the product
:param status: Type of status that being sent to discord
"""
payload["status"] = status
payload["keyword"] = True
# FIXME: call create_embed(payload) for post to discord
# See more here https://codereview.stackexchange.com/questions/260043/creating-embed-for-discord-reading-from-dictionary
def spam_filter(delay: int, requests: List[str]) -> List[str]:
"""
Filter requests to only those that haven't been made previously within our defined cooldown period.
:param delay: Delta seconds
:param requests:
:return:
"""
# Get filtered set of requests.
filtered = [
r for r in list(set(requests))
if (
r not in _size_filter
or datetime.now() - _size_filter[r] >= timedelta(seconds=delay)
)
]
# Refresh timestamps for requests we're actually making.
for r in filtered:
_size_filter[r] = datetime.now()
return filtered
if __name__ == "__main__":
monitor_stock()
</code></pre>
<p><strong>scrape_values.py</strong></p>
<pre><code>import json
import re
from dataclasses import dataclass
from typing import List, Optional
import requests
from bs4 import BeautifulSoup
@dataclass
class Product:
name: Optional[str] = None
price: Optional[str] = None
image: Optional[str] = None
sizes: List[str] = None
@staticmethod
def get_sizes(doc: BeautifulSoup) -> List[str]:
pat = re.compile(
r'^<script>var JetshopData='
r'(\{.*\})'
r';</script>$',
)
for script in doc.find_all('script'):
match = pat.match(str(script))
if match is not None:
break
else:
return []
data = json.loads(match[1])
return [
variation
for get_value in data['ProductInfo']['Attributes']['Variations']
if get_value.get('IsBuyable')
for variation in get_value['Variation']
]
@classmethod
def from_page(cls, url: str) -> Optional['Product']:
with requests.get(url) as response:
if not response.ok:
return None
doc = BeautifulSoup(response.text, 'html.parser')
name = doc.select_one('h1.product-page-header')
price = doc.select_one('span.price')
image = doc.select_one('meta[property="og:image"]')
return cls(
name=name and name.text.strip(),
price=price and price.text.strip(),
image=image and image['content'],
sizes=cls.get_sizes(doc),
)
@property
def payload(self) -> dict:
return {
"name": self.name or "Not found",
"price": self.price or "Not found",
"image": self.image or "Not found",
"sizes": self.sizes,
}
</code></pre>
<p>My concern is that I might have done it incorrectly where I have split it into multiple functions that maybe is not necessary to do? Im not sure and I do hope I will get some cool feedbacks! Looking forward</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:19:29.453",
"Id": "512754",
"Score": "0",
"body": "This code will not run. You have imbalanced parens."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T17:22:29.687",
"Id": "512756",
"Score": "0",
"body": "@Reinderien Sorry, was a typo miss in sleep :) Fixed now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T16:44:00.163",
"Id": "513502",
"Score": "0",
"body": "Why is the `monitor_stock` running at random intervals?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T16:46:45.803",
"Id": "513503",
"Score": "0",
"body": "@Mast Im not sure why I used random. Thought it would be cooler :) That could be changed to 120 sec or even more :) the idea is to check again and compare with previous requests if there has been a change. If there has been then it checks for the if statements inside the `monitor_stock`"
}
] |
[
{
"body": "<p>I believe you are still facing some issues with <code>Real Classes</code> comment from the previous post. Why do I say this? Your <code>Product</code> class is not even necessary. It has only functions that can be without a class.</p>\n<ol>\n<li><p>Using <a href=\"https://docs.python.org/3/library/collections.html#collections.namedtuple\" rel=\"nofollow noreferrer\">Named Tuple</a> instead of data class.</p>\n<pre><code># Basic example\n>>> Point = namedtuple('Point', ['x', 'y'])\n>>> p = Point(11, y=22) # instantiate with positional or keyword arguments\n>>> p[0] + p[1] # indexable like the plain tuple (11, 22)\n33\n>>> x, y = p # unpack like a regular tuple\n>>> x, y\n(11, 22)\n>>> p.x + p.y # fields also accessible by name\n33\n>>> p # readable __repr__ with a name=value style\nPoint(x=11, y=22)\n</code></pre>\n<p>Return named tuple from <code>payload</code> and <code>from_page</code></p>\n</li>\n<li><p>Creating variable delays.</p>\n<p>Instead of:</p>\n<pre><code>def monitor_stock():\n ...\n time.sleep(random.randint(30, 120))\n</code></pre>\n<p>Use something like:</p>\n<pre><code># Global Scope\ndelays = [30, 60, 90, 120]\ncurr_delay = 0\n\ndef get_delay():\n res = curr_delay\n curr_delay += 1\n if curr_delay >= len(delays):\n curr_delay = 0\n return res\n\ndef monitor_stock():\n ...\n time.sleep(delays[get_delay()])\n</code></pre>\n</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T17:39:21.190",
"Id": "513748",
"Score": "0",
"body": "Hi! Im kinda curious regarding the named tuples, what is the reason why I dont need the class if I might ask? Is it more like im doing too much sort of? - Regarding the variable delays, that is pretty neat! Very cool!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T03:54:48.037",
"Id": "513778",
"Score": "0",
"body": "@ProtractorNewbie, you are not doing anything with the class. If you want to have data class, use named tuples. You are not using 'O' (object) in OOPs, i.e. there are no objects or any need in your case."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-06T12:54:58.513",
"Id": "514064",
"Score": "0",
"body": "Named tuples are great! That said, it's my opinion that [`typing.NamedTuple`](https://docs.python.org/3/library/typing.html#typing.NamedTuple) is better than [`collections.namedtuple`](https://docs.python.org/3/library/collections.html#collections.namedtuple), and in practice `dataclasses.dataclass` is even better for nearly all applications. [Dataclasses](https://docs.python.org/3/library/dataclasses.html) take a little more reading to understand what all the pieces do, but they're worth learning and `@dataclass(frozen=True)` is basically a drop-in replacement for `NamedTuple`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T16:27:25.363",
"Id": "260265",
"ParentId": "259867",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260265",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T16:09:43.233",
"Id": "259867",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"web-scraping"
],
"Title": "Take information from a webpage and compare to previous request"
}
|
259867
|
<p>Currently working on a pre-solve collision library. My goal is to have it be potentially usable in potential video game projects of mine, so time constraint is small as this should be used in a game loop: this algorithm currently takes too long. I am aware of broadphasing, but I believe there is gains to be made here too. I'm not interested in a substepping approach for the time being.</p>
<p>A general explanation of the algorithm: Loop through each side of the polygon, check if relative velocity points against the line's outward-facing normal. If so, line segment-line segment test from each point of the opposite polygon along velocity against the side of the polygon. Return the shortest collision distance if any.</p>
<p>This is an algorithm I made up after finding no helpful resources online (not that they aren't there), so I suspect that there may be large optimisations to be made that I'm not familiar enough with computational geometry to be aware of. Or any other significant optimisations, for that matter.</p>
<pre><code>use cgmath::{ElementWise, InnerSpace, Vector2}; // latest version of the cgmath crate on crates.io
fn poly_poly_sweep(b1: &Body, p1: &Poly, b2: &Body, p2: &Poly, t: f64) -> Option<(f64, Vector2<f64>)> {
let dpos = b2.pos - b1.pos;
let rv1 = (b1.vel - b2.vel).mul_element_wise(t);
// snip (ignore, ~5ns perf penalty, no side effects)
let mut immenence = f64::MAX; // time to collision
let mut imminent_norm = cgmath::vec2(0.0, 0.0); // norm of collision from 2
let rv2 = -rv1;
for p1vi in 0..p1.norms.len() {
let n = p1.norms[p1vi];
// check if normal faces a similar direction to rv2
if n.dot(rv2) >= 0.0 { continue; }
let v = p1.verts[p1vi];
let dpos_v = v - dpos;
let v_dot = n.dot(v - dpos) as f64; // seperating axis dot
let mut clsst_dot = f64::MAX; // closest vert dot
let mut clsst_index = usize::MAX; // closest vert index
let mut multi_clsst_len = 0;
// SAT, store closest vert
for p2vi in 0..p2.norms.len() {
let proj = n.dot(p2.verts[p2vi]) as f64;
if proj < clsst_dot { // closer vert found
// will store the most anticlockwise if proj is equal
clsst_dot = proj;
clsst_index = p2vi;
multi_clsst_len = 0;
} else if proj == clsst_dot { // not rounding-error safe?
multi_clsst_len += 1;
}
}
if clsst_dot < v_dot { continue; } // invalid seperating axis
// inlined line-segment intersection tests
let diff_verts = p1.verts[p1vi+1] - v;
let dot = rv2.perp_dot(diff_verts);
let dd = dot * dot;
for p2vi in clsst_index..(clsst_index + multi_clsst_len + 1) {
let vc = p2.verts[p2vi] - dpos_v;
let desc = rv2.perp_dot(vc) * dot;
if desc >= 0.0 && desc <= dd {
let t = diff_verts.perp_dot(vc) * dot;
if t >= 0.0 && t <= dd && t < immenence * dd {
immenence = t / dd;
imminent_norm = n;
}
}
}
}
for p2vi in 0..p2.norms.len() {
let n = p2.norms[p2vi];
if n.dot(rv1) >= 0.0 { continue; }
let v = p2.verts[p2vi];
let dpos_v = v - dpos;
let v_dot = n.dot(dpos_v) as f64;
let mut clsst_dot = f64::MAX;
let mut clsst_index = usize::MAX;
let mut multi_clsst_len = 0;
for p1vi in 0..p1.norms.len() {
let proj = n.dot(p1.verts[p1vi]) as f64;
if proj < clsst_dot {
clsst_dot = proj;
clsst_index = p1vi;
multi_clsst_len = 0;
} else if proj == clsst_dot {
multi_clsst_len += 1;
}
}
if clsst_dot < v_dot { continue; }
let diff_verts = p2.verts[p2vi+1] - v;
let dot = rv1.perp_dot(diff_verts);
let dd = dot * dot;
for p1vi in clsst_index..(clsst_index + multi_clsst_len + 1) {
let vc = p1.verts[p1vi] - dpos_v;
let desc = rv1.perp_dot(vc) * dot;
if desc >= 0.0 && desc <= dd {
let t = diff_verts.perp_dot(vc) * dot;
if t >= 0.0 && t <= dd && t < immenence * dd {
immenence = t / dd;
imminent_norm = -n;
}
}
}
}
if immenence < 1.0 {
Some((immenence, imminent_norm))
} else {
None
}
}
</code></pre>
<p>This algorithm, as tested by <code>criterion-rs</code> takes 96-100ns between a 6 and 4 sided polygon on my machine (R3200G), I'd be more than happy with 50ns, and am hoping for under 60-70ns. I am willing to change data structures to a certain extent if it will give significant returns, but am looking to minimize artificial restrictions on the code.</p>
<p>This is a personal project, API maintenance is not an issue, nor am I looking for code-style advice, but feel free to give such if you wish.</p>
<p>Extra code that may be relevant:</p>
<pre><code>#[derive(Debug, Clone)]
pub struct Body {
/// Posistion
pub pos: Vector2<f64>,
/// Compositing shapes
pub shapes: Vec<Shape>,
/// Bounding box
pub aabb: Aabb,
/// Velocity
pub vel: Vector2<f64>,
/// Whether the object is *relatively* fast moving.
pub bullet: bool,
}
#[derive(Debug, Clone, Copy)]
pub struct Aabb {
pub min: Vector2<f64>,
pub max: Vector2<f64>,
}
/// A 2D convex polygon, vertices arranged clockwise - tailed with a duplicate of the first, with unit-length normals - without duplication.
#[derive(Debug, Clone)]
pub struct Poly {
pub aabb: Aabb,
/// First vertex's duplicate tails. `verts.len() - 1 == norms.len()`
pub verts: Vec<Vector2<f64>>,
/// Length equals actual vertex count. `verts.len() - 1 == norms.len()`
pub norms: Vec<Vector2<f64>>,
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T19:38:23.350",
"Id": "512774",
"Score": "2",
"body": "Welcome to Code Review. There's some content missing. You seem to be using a 2d library that contains `Vec2` and `Aabb`, neither are part of the Rust standard library. Also, `Poly::new` is not in your currently posted code. Please add at least your `Cargo.toml` dependency section as well as your `use` statements. Also keep in mind that you shouldn't strip parts of the code otherwise it may be hard for reviewers to reason about your code and review *any* part of it. Thanks."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T20:13:33.863",
"Id": "512782",
"Score": "1",
"body": "@Zeta I have included some omitted code, and clarified some other bits. The implementation of Poly::new is not relevant, the documentation for Poly describes the resulting arrangement of data. (I'm trying not to bloat this post with too much code, especially if it's not necessary to review). The library I'm using is cgmath, I have included that in a use statement. Thank you for your suggestions, I hope these amendments are good enough."
}
] |
[
{
"body": "<p>I have found a significant optimisation, in taking out all of the extra code I had added to the basic concept of the algorithm.</p>\n<p>I'm not entirely satisfied with this gain, as it still takes ~80ns for the 6 side-4 side test described. I have also identified a bug in the original code and modified it accordingly, though it's performance was relatively unchanged in the 6-4 test case.</p>\n<p>The new code:</p>\n<pre><code>fn poly_poly_sweep_(b1: &Body, p1: &Poly, b2: &Body, p2: &Poly, t: f64) -> Option<(f64, Vector2<f64>)> {\n let dpos = b2.pos - b1.pos;\n let rv1 = (b1.vel - b2.vel).mul_element_wise(t);\n \n // snip\n \n let mut immenence = f64::MAX; // time to collision\n let mut imminent_norm = cgmath::vec2(0.0, 0.0); // norm of collision from 2\n let rv2 = -rv1;\n for p1vi in 0..p1.norms.len() {\n let n = p1.norms[p1vi];\n if n.dot(rv2) >= 0.0 { continue; }\n let v = -p1.verts[p1vi];\n\n let diff_verts = p1.verts[p1vi+1] + v;\n let dot = rv2.perp_dot(diff_verts);\n let dd = dot * dot;\n for p2vi in 0..p2.norms.len() {\n let p2v = p2.verts[p2vi] + dpos + v;\n let desc = rv2.perp_dot(p2v) * dot;\n if desc >= 0.0 && desc <= dd { \n let t = diff_verts.perp_dot(p2v) * dot;\n if t >= 0.0 && t <= dd && t < immenence * dd {\n immenence = t / dd;\n imminent_norm = n;\n }\n }\n }\n }\n for p2vi in 0..p2.norms.len() {\n let n = p2.norms[p2vi];\n if n.dot(rv1) >= 0.0 { continue; }\n let v = -p2.verts[p2vi];\n\n let diff_verts = p2.verts[p2vi+1] + v;\n let dot = rv1.perp_dot(diff_verts);\n let dd = dot * dot;\n for p1vi in 0..p1.norms.len() {\n let vc = p1.verts[p1vi] + dpos + v;\n let desc = rv1.perp_dot(vc) * dot;\n if desc >= 0.0 && desc <= dd { \n let t = diff_verts.perp_dot(vc) * dot;\n if t >= 0.0 && t <= dd && t < immenence * dd {\n immenence = t / dd;\n imminent_norm = -n;\n }\n }\n }\n }\n if immenence < 1.0 {\n Some((immenence, imminent_norm))\n } else {\n None\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:16:39.773",
"Id": "260072",
"ParentId": "259873",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T19:15:54.810",
"Id": "259873",
"Score": "4",
"Tags": [
"performance",
"rust",
"computational-geometry"
],
"Title": "Convex polygon-polygon swept collision test"
}
|
259873
|
<p>The purpose of this code is to use it to calculate some number theoretic function efficiently for the numbers from 1 to 1000000, but I am not sure if it will be really useful. The main purpose was to program a piece of C++ code because I have almost no experience in this language. So it would be nice if you could give me some feedback not to the algorithm but to its C++ implementation. There are also some things that are unclear to me: should the duplication of the block with the case statement be avoided? Should the usage of the global variables be avoided? Is the usage of an array appropriate or should I use some container datatype?</p>
<pre><code>/*
if a positive integer number n has a prime divisor p>=sqrt(n), then n=p*q and p and q are uniquely defined and (p,q)=1 and q<=sqrt(n).
More general: if n is a positive integer number then there is a prime p such that n=(p^e)*q1*q2, such that (p,q1)=(p,q2)=(q1,q2)=1 and q1<=sqrt(n), q2<=sqrt(n). p,e,q1,q2 are not uniquely define.
this program calculates and stores such factors q1,q2,p^e, for every n between sqrt(limit) and limit and prints some sample output
*/
#include <iostream>
#include <cmath>
#include <cassert>
const int limit=1000000;
int sqrtlimit;
int primefactor[limit]={0};
int smallfactor1[limit]={0};
int primepowerfactor[limit]={0};
int smallfactor2[limit]={0};
void init_sieve(void){
/*
initializes the array primefactor
primefactor[n]==n if n is a prime or n==1 or n==0, otherwise
primefactor[n] is largest prime factor of n that
is smaller than sqrtkimit
*/
sqrtlimit=int(std::pow(limit,.5))+1;
for (int n=0;n<limit;n++){
primefactor[n]=n;
}
for (int n=2;n<=sqrtlimit;n++){
if (primefactor[n]==n){
for (int i=n;i<limit;i+=n){
primefactor[i]=n;
}
}
}
}
void split_factors(void){
/*
uses the initialized array primefactor
sets the arrays smallfactor1, smalfactor2, primepowerfactor
splits a number in three, pairwise relativly prime factors
where the first and the third are smaller than sqrtlimit and the second is a prime power
*/
enum State {
continue_first_factor,
in_second_factor,
continue_third_factor
};
for (int n=sqrtlimit; n<limit; n++){
int current_prod=1;
int quotient=n;
int last_prime=0;
int prime_exponent=0;
int first_factor=1;
int second_factor=1;
int third_factor=1;
int prime_power=1;
int p;
State state=continue_first_factor;
while(primefactor[quotient]>1){
p=primefactor[quotient];
quotient/=p;
/*
if last prime power was found,
put it to first factor
and restart calculating the next prime power
*/
if (p!=last_prime){
switch (state) {
case continue_first_factor:
first_factor*=prime_power;
break;
case in_second_factor:
second_factor=prime_power;
current_prod=1;
state=continue_third_factor;
break;
case continue_third_factor:
third_factor*=prime_power;
break;
default:
assert(0);
break;
}
last_prime=p;
prime_power=p;
}
else {
prime_power*=p;
}
if (state==continue_first_factor){
current_prod*=p;
if (current_prod>sqrtlimit){
state=in_second_factor;
}
}
/* process the last prime power */
if (quotient==1){
switch (state) {
case continue_first_factor:
first_factor*=prime_power;
break;
case in_second_factor:
second_factor=prime_power;
current_prod=1;
state=continue_third_factor;
break;
case continue_third_factor:
third_factor*=prime_power;
break;
default:
assert(0);
break;
}
}
}
smallfactor1[n]=first_factor;
primepowerfactor[n]=second_factor;
smallfactor2[n]=third_factor;
}
}
int main() {
init_sieve();
split_factors();
// some sample output
std::cout<<"limit "<<limit<<std::endl;
std::cout<<"sqrtlimit "<<sqrtlimit<<std::endl;
std::cout<<std::endl;
std::cout<<"print some prime factorization"<<std::endl;
for (int n=limit-20;n<limit; n++){
int m=n;
std::cout << m << " = " ;
bool first=true;
while (m>1){
if (first){
first=false;
}
else {
std::cout << " * ";
}
std::cout <<primefactor[m];
m=m/primefactor[m];
}
std::cout <<std::endl;
}
std::cout<<std::endl<<"smallfactor * primepower * smallfactor"<<std::endl;
std::cout<<"\tthe second factor is a prime power"<<std::endl;
std::cout<<"\t'!' at the end prime power exponent > 1"<<std::endl;
for (int n=limit-20;n<limit; n++){
std::cout<<n<<" = "<<smallfactor1[n]<<" * "<<primepowerfactor[n]<<" * "<<smallfactor2[n];
if (primefactor[primepowerfactor[n]]!=primepowerfactor[n]){
std::cout<<" !";
}
std::cout<<std::endl;
}
}
</code></pre>
|
[] |
[
{
"body": "<h1>Questions</h1>\n<p>You’ve asked for a review of the C++ specifically, not the algorithm, so that’s what I’ll do. But first, I’ll answer your questions.</p>\n<p><strong>Should the duplication of the block with the case statement be avoided?</strong></p>\n<p>Yes.</p>\n<p>Unless it’s <em>really</em> trivial—we’re talking like two lines, <em>maybe</em> three, max, and even then only if those lines are not complex or “clever”—you should never be shy about breaking repeated chunks of code out into separate functions.</p>\n<p>In fact, forget “repeated”; anytime you have a subsection of an algorithm that seems somewhat self-contained, you should consider splitting it out. But that’s obviously especially true for repeated blocks.</p>\n<p>There are a <em>lot</em> of good reasons for this:</p>\n<ul>\n<li><strong>Simplification</strong>: It makes any code that repeated block appears in shorter and simpler, and that’s usually a win for understanding and maintenance.</li>\n<li><strong>Reusability</strong>: If you’ve used it twice, there’s a good chance you could use it thrice, and you’d save time in the long run.</li>\n<li><strong>Modularization</strong>: When you break a chunk of code out into a separate function, you can treat function as a separate unit. You can test it separately. You can optimize it separately. You can work with it to improve it—and, by extension, anything that uses it—without worrying about breaking any code that uses it (assuming you’re properly testing it, of course… which you should).</li>\n</ul>\n<p>And with any modern compiler, there is likely to be little to no cost to breaking code out into a separate function… <em>especially</em> if you make that function body visible everywhere (which will happen by default if you make it a <code>constexpr</code> function, which you should really try to do).</p>\n<p><strong>Should the usage of the global variables be avoided?</strong></p>\n<p>Yes.</p>\n<p>Now, there <em>are</em> situations where global variables (or something similar, like a function that returns a reference to a static variable) are okay. But those are last resort situations: you should do everything in your power to avoid global variables, and <em>only</em> use them as a last resort, when <em>every</em> other option is worse.</p>\n<p>By making your variables global, you have introduced four major problems:</p>\n<ol>\n<li><strong>You’ve made your algorithm less efficient.</strong> Because of their nature, global variables <em>must</em> be allocated in memory somewhere. (Usually! <em>Technically</em> there is room for compilers to cheat and avoid actually allocating them. In practice, that’s <em>extremely</em> unlikely.) That means that the compiler no longer has the option of eliding them if it figures out a trick where it doesn’t need them. Not only that, they are very likely allocated somewhere in memory that is <em>not</em> close to where you happen to be working, meaning that it’s not going to be hot in cache.</li>\n<li><strong>You’ve made your algorithm functionally impossible to use in concurrent code.</strong> This is the future, and <em>everything</em> is concurrent these days. You probably can’t get a general purpose consumer CPU with less than 4 cores these days, even on a cheap machine. (Hell, my <em>router</em> has 4 cores!) And that’s not even considering GPGPU stuff, which trades in hundreds or <em>thousands</em> of cores.</li>\n<li><strong>You’ve made your algorithm harder to test.</strong> Global variables are difficult to mock, and damn near impossible to isolate, making testing a royal pain. You should really take writing testable code seriously; in fact, you should make it a top priority. Any code I see without tests, I consider garbage code, and I won’t allow it anywhere <em>near</em> any serious projects I’m working on.</li>\n<li><strong>You’ve made your algorithm buggy.</strong> Even if you’re a genius programmer who only ever writes perfect code and never, ever introduces bugs… this code is unreliable. That’s because even if <em>your</em> code is perfect, someone else could fugger with those global variables and completely screw up the results of your algorithm. And you’d probably never know why: this would one of those horror-story bugs you hear about—the kind where the code works perfectly except on Bob’s computer and only then on Tuesdays and only if the Leafs happen to be playing that night.</li>\n</ol>\n<p>We don’t say “avoid global variables” because we’re jerks who like to make up rules and force them on programmers so we can feel superior. Global variables are really, <em>really</em> bad. They are inefficient, they are untestable, and they are dangerous. Yes, there <em>sometimes</em> situations where they’re okay (like <code>std::cout</code>; that’s a global variable (well, technically, in a namespace, but close enough)). But you should only use them when you really, <em>really</em> must.</p>\n<p><strong>Is the usage of an array appropriate or should I use some container datatype?</strong></p>\n<p>This answer is less clear cut than the others, but I’d say that you should use <code>std::vector</code> instead.</p>\n<p>First, if you <em>must</em> use arrays, I’d recommend using <code>std::array</code> rather than C arrays. <code>std::array</code> has safety features that make it less dangerous than a C array, as well as some really sweet usability enhancements.</p>\n<p>However, the key issue with your usage is that those are some really freaking huge arrays. Take <code>primefactor</code> for example. It has <em>a million elements</em>. And each element is an <code>int</code>, which is probably going to be 4 bytes. So <code>primefactor</code> alone takes up 4 MB (roughly 3.8 MiB). Well, on Windows, last I checked (and, admittedly, I don’t check Windows stuff that frequently), the default stack size, at least for threads, is only 1 MiB. <code>primefactor</code> blows right past that… and you have <em>four</em> arrays that big. There is a decent likelihood that even if this program compiles, it will crash or behave erratically on some platforms, due to stack overflow.</p>\n<p>For datasets that big, you should use dynamic allocation. That way, if there just isn’t enough memory, at least you will get predictable behaviour, rather than a crash. (Theoretically. In practice, the platform may over-commit and then start killing processes, and your program may end up crashing anyway. But at least you tried.)</p>\n<p>So I’d say no to arrays for these huge datasets, and suggest using <code>std::vector</code> instead. In practice, not a single line of your code will have to change (yanno, other than those 4 array declarations). <em>However</em>… once you start using modern C++ tools like <code>std::array</code> or <code>std::vector</code>, you <em>could</em> make several improvements. I’ll get to that in the code review.</p>\n<h1>Code review</h1>\n<pre><code>#include <cassert>\nconst int limit=1000000;\n</code></pre>\n<p>You should put some space between the headers and the actual code. Whitespace costs nothing, but makes a <em>huge</em> difference for readability.</p>\n<pre><code>const int limit=1000000;\n</code></pre>\n<p><code>const</code> is the wrong word here; you want <code>constexpr</code>. <code>const</code> means “this value will not change”; <code>constexpr</code> means “this value is a constant”. Note that those are <em>not</em> the same thing. <code>const</code> variables can be set any time, even at runtime. The <code>const</code> just means that <em>after</em> it is set, it won’t change. But it’s still a variable, not a constant.</p>\n<p><code>constexpr</code> (when applied to variables) means a value is a true constant.</p>\n<p>Also, I’d recommend putting some space around the <code>=</code>. Again, whitespace costs nothing, but makes things so much easier to read.</p>\n<p>You might also consider using digit separators to make large numbers more readable:</p>\n<pre><code>constexpr auto limit = 1'000'000;\n</code></pre>\n<p>(The <code>auto</code> is optional, but honestly, when I write modern C++, <em>everything</em> is <code>auto</code> these days. Specific types usually don’t matter, interfaces do.)</p>\n<pre><code>const int limit=1000000;\nint sqrtlimit;\n\nint primefactor[limit]={0};\n\nint smallfactor1[limit]={0};\nint primepowerfactor[limit]={0};\nint smallfactor2[limit]={0};\n</code></pre>\n<p>Since these are all global variables, they are all zero-initialized. Which means, you technically don’t need to write the <code>={0}</code>… but it doesn’t hurt.</p>\n<p>However, the fact that these are all zero-initialized is not really a good thing… because that’s just wasted cycles, since the first thing you do when the program actually gets going is to really initialize them with their real values.</p>\n<p>This wasted initialization won’t be a problem if you don’t use global variables… which is what I’m about to suggest.</p>\n<pre><code>void init_sieve(void){\n</code></pre>\n<p>Okay, first, we don’t write <code>void</code> in empty parameter lists. That’s an <em>ancient</em> practice from C. It doesn’t apply to C++, and just clutters things up unnecessarily.</p>\n<p>More importantly, though, when you have an “init” function… that’s a code smell. In C++, initialization and cleanup is usually handled automatically… in constructors and destructors. Those make initialization impossible to forget, and they make cleanup happen in every circumstance. And they’re usually no brainers; you don’t even really need to think about them, because they just work automatically.</p>\n<p>Here’s what a class for your algorithm might look like, roughly:</p>\n<pre><code>class your_algo\n{\n enum class factor_split_state\n {\n continue_first_factor,\n in_second_factor,\n continue_third_factor\n };\n\n static constexpr int _default_limit = 1'000'000;\n // better make sure a million can fit in an int!\n //\n // something like:\n // static_assert(static_cast<long>(std::numeric_limits<int>::max()) >= 1'000'000L);\n //\n // or you could replace all the "int"s with "value_type",\n // and set "value_type" to "int" or "long", depending\n // on what fits:\n // using value_type = std::conditional_t<\n // (static_cast<long>(std::numeric_limits<int>::max()) >= 1'000'000L),\n // int,\n // long>;\n //\n // static constexpr auto _default_limit = value_type(1'000'000L);\n //\n // value_type limit = _default_limit;\n // value_type sqrtlimit;\n // std::vector<value_type> primefactor;\n // // ... and so on...\n\npublic:\n your_algo() :\n your_algo(_default_limit)\n {}\n\n explicit your_algo(int lim) :\n limit{lim},\n sqrtlimit{int(std::pow(lim, 0.5)) + 1},\n primefactor(lim),\n smallfactor1(lim),\n primepowerfactor(lim),\n smallfactor2(lim)\n {\n // i've just duplicated your algorithm exactly, because you didn't\n // want that critiqued\n\n init_sieve();\n split_factors();\n }\n\n // i've just left all the variables public, because i don't understand\n // what you actually *need* to be public\n //\n // this is *not* good practice; you should decide what interface you\n // actually need\n int limit = _default_limit;\n int sqrtlimit;\n std::vector<int> primefactor;\n std::vector<int> smallfactor1;\n std::vector<int> primepowerfactor;\n std::vector<int> smallfactor2;\n\nprivate:\n constexpr auto init_sieve() -> void\n {\n // for (int n=0;n<limit;n++){\n // primefactor[n]=n;\n // }\n std::iota(primefactor.begin(), primefactor.end(), 0);\n\n for (auto n = 2; n <= sqrtlimit; ++n)\n {\n if (primefactor[n] == n)\n {\n for (auto i = n; i < limit; i += n)\n primefactor[i] = n;\n }\n }\n }\n\n constexpr auto split_factors() -> void\n {\n // might want to make sure that:\n // limit == primefactor.size()\n // limit == smallfactor1.size()\n // limit == primepowerfactor.size()\n // limit == smallfactor2.size()\n\n for (auto n = sqrtlimit; n < limit; ++n)\n {\n auto current_prod = 1;\n auto quotient = n;\n auto last_prime = 0;\n auto prime_exponent = 0;\n auto first_factor = 1;\n auto second_factor = 1;\n auto third_factor = 1;\n auto prime_power = 1;\n auto state = factor_split_state::continue_first_factor;\n\n while (primefactor[quotient] > 1)\n {\n auto p = primefactor[quotient];\n quotient /= p;\n\n if (p != last_prime)\n {\n std::tie(state, first_factor, second_factor, third_factor) =\n _factor_calculator_thingy(state, prime_power, first_factor, second_factor, third_factor);\n\n if (state == factor_split_state::in_second_factor)\n current_prod = 1;\n\n last_prime = p;\n prime_power = p;\n }\n else {\n prime_power *= p;\n }\n\n if (state == factor_split_state::continue_first_factor)\n {\n current_prod *= p;\n if (current_prod > sqrtlimit)\n state = factor_split_state::in_second_factor;\n }\n\n /* process the last prime power */\n if (quotient == 1)\n {\n std::tie(state, first_factor, second_factor, third_factor) =\n _factor_calculator_thingy(state, prime_power, first_factor, second_factor, third_factor);\n\n if (state == factor_split_state::in_second_factor)\n current_prod = 1;\n }\n }\n\n smallfactor1[n] = first_factor;\n primepowerfactor[n] = second_factor;\n smallfactor2[n] = third_factor;\n }\n }\n\n // obviously this needs a better name\n static constexpr auto _factor_calculator_thingy(\n factor_split_state state,\n int prime_power,\n int first_factor,\n int second_factor,\n int third_factor\n ) noexcept\n -> std::tuple<factor_split_state, int, int, int>\n {\n switch (state)\n {\n case continue_first_factor:\n return {state, first_factor * prime_power, second_factor, third_factor};\n case in_second_factor:\n return {factor_split_state::continue_third_factor, first_factor, second_factor * prime_power, third_factor};\n case continue_third_factor:\n return {state, first_factor, second_factor, third_factor * prime_power};\n }\n }\n};\n</code></pre>\n<p>Now your <code>main()</code> might look like:</p>\n<pre><code>auto main() -> int\n{\n auto algo = your_algo{};\n\n std::cout << "limit " << algo.limit << '\\n';\n std::cout << "sqrtlimit " << algo.sqrtlimit << '\\n';\n std::cout << '\\n';\n\n std::cout << "print some prime factorization\\n";\n for (auto n = algo.limit - 20; n < algo.limit; ++n)\n {\n auto m = n;\n std::cout << m << " = " ;\n\n auto first = true;\n while (m > 1)\n {\n if (not std::exchange(first, false))\n std::cout << " * ";\n\n std::cout << algo.primefactor[m];\n m = m / algo.primefactor[m];\n }\n\n std::cout << '\\n';\n }\n\n std::cout << "\\nsmallfactor * primepower * smallfactor\\n"\n "\\tthe second factor is a prime power\\n"\n "\\t'!' at the end prime power exponent > 1\\n";\n\n for (auto n = algo.limit - 20; n < algo.limit; ++n)\n {\n std::cout << n << " = " << algo.smallfactor1[n] << " * "\n << algo.primepowerfactor[n] << " * " << algo.smallfactor2[n];\n\n if (algo.primefactor[algo.primepowerfactor[n]] != algo.primepowerfactor[n])\n std::cout << " !";\n\n std::cout << '\\n';\n }\n}\n</code></pre>\n<p>Okay, back to the review.</p>\n<pre><code>sqrtlimit=int(std::pow(limit,.5))+1;\n</code></pre>\n<p>I don’t see the logic of using <code>std::pow(limit, 0.5)</code> rather than <code>std::sqrt(limit)</code>. I presume you have a reason?</p>\n<pre><code>enum State {\n continue_first_factor,\n in_second_factor,\n continue_third_factor\n };\n</code></pre>\n<p>You should use the modern <code>enum class</code> rather than the old-school <code>enum</code>. It’s a bit more verbose, but <em>much</em> safer.</p>\n<pre><code> int current_prod=1;\n int quotient=n;\n int last_prime=0;\n int prime_exponent=0;\n int first_factor=1;\n int second_factor=1;\n int third_factor=1;\n int prime_power=1;\n</code></pre>\n<p>When I see a long list of variables like this, it really suggests to me that you could use some more types. For example, a type for the factors:</p>\n<pre><code>struct factors_t\n{\n int first = 1;\n int second = 1;\n int third = 1;\n};\n</code></pre>\n<p>Then the list above reduces a bit to:</p>\n<pre><code> auto current_prod = 1;\n auto quotient = n;\n auto last_prime = 0;\n auto prime_exponent = 0;\n auto factors = factors_t{};\n auto prime_power = 1;\n</code></pre>\n<p>That’s an improvement. It also simplifies the helper function:</p>\n<pre><code> static constexpr auto _factor_calculator_thingy(factor_split_state state, int prime_power, factors_t factors) noexcept\n -> std::tuple<factor_split_state, factors_t>\n {\n switch (state)\n {\n case continue_first_factor:\n return {state, {factors.first * prime_power, factors.second, factors.third}};\n case in_second_factor:\n return {factor_split_state::continue_third_factor, {factors.first * prime_power, factors.second, factors.third}};\n case continue_third_factor:\n return {state, {factors.first, factors.second, factors.third * prime_power}};\n }\n }\n</code></pre>\n<p>You can probably bundle some of the other variables into types as well.</p>\n<pre><code> int p;\n</code></pre>\n<p>Now this <em>definitely</em> doesn’t belong.</p>\n<p>This would immediately trigger a “nope” from me in a code review, because it is an uninitialized variable. That’s bad.</p>\n<p>But “fixing” it by adding an initializer is the wrong move, because the truth is this variable shouldn’t be here at all. It only needs to exist within the loop, so it should be created when it is needed:</p>\n<pre><code> int third_factor=1;\n int prime_power=1;\n\n State state=continue_first_factor;\n while(primefactor[quotient]>1){\n auto p = primefactor[quotient]; // <-- this is where it needs to be created\n quotient/=p;\n</code></pre>\n<p>All the other variables need to maintain their values across loop iterations, so they have to be instantiated outside of the loop.</p>\n<pre><code>switch (state) {\n case continue_first_factor:\n first_factor*=prime_power;\n break;\n case in_second_factor:\n second_factor=prime_power;\n current_prod=1;\n state=continue_third_factor;\n break;\n case continue_third_factor:\n third_factor*=prime_power;\n break;\n default:\n assert(0);\n break;\n}\n</code></pre>\n<p>Adding a default case here is perhaps being overly defensive. All modern compilers that I’m familiar with will automatically detect that the switch is exhaustive, because you’ve accounted for every value of the <code>State</code> <code>enum</code>.</p>\n<p>So all that’s left is <code>main()</code>. The biggest crime that’s going on in <code>main()</code> is using <code>std::endl</code>. Don’t do that. Yes, I know that tutorials all over the place use it; well, I’m saying they all suck for doing so. Using <code>std::endl</code> is almost always wrong. (Or at the <em>very least</em>, pointlessly wasteful.) In fact, every single usage of <code>std::endl</code> in your code is wrong.</p>\n<p>If you want a newline, just use <code>\\n</code>.</p>\n<pre><code> bool first=true;\n while (m>1){\n if (first){\n first=false;\n }\n else {\n std::cout << " * ";\n }\n // ... [snip] ...\n }\n</code></pre>\n<p>There’s a little trick for the pattern you’re using above. The key is <a href=\"https://en.cppreference.com/w/cpp/utility/exchange\" rel=\"nofollow noreferrer\"><code>std::exchange()</code></a>. <code>std::exchange()</code> takes a variable as its first argument, and a value as its second: <code>std::exchange(variable, value)</code>. What it does is:</p>\n<ol>\n<li>set the value of <code>variable</code> to <code>value</code>; and</li>\n<li>return the <em>old</em> value of <code>variable</code>.</li>\n</ol>\n<p>And it does all that maximally efficiently.</p>\n<p>So what you do is this:</p>\n<pre><code> auto first = true;\n while (m > 1)\n {\n if (not std::exchange(first, false))\n std::cout << " * ";\n\n // ... [snip] ...\n }\n</code></pre>\n<p>On the first time through, the <code>exchange()</code> call sets <code>first</code> to <code>false</code>, and returns <code>true</code> (which is the old value of <code>first</code>). Since <code>not true</code> is <code>false</code>, the <code>cout</code> statement never fires.</p>\n<p>On the second time through, and every time after, the <code>exchange()</code> sets <code>first</code> to <code>false</code> (pointlessly, because <code>first</code> is already <code>false</code>, but it doesn’t matter on any modern hardware), and returns <code>false</code> (which was the old value of <code>first</code>). <code>not false</code> is <code>true</code>, so the <code>cout</code> statement prints.</p>\n<p>This is just one of those patterns you get to know; like for printing a bunch of values in a vector nicely:</p>\n<pre><code>auto const vec = std::vector{1, 2, 3, 4};\n\nstd::ranges::for_each(vec, [first=true](auto&& v) mutable\n {\n if (not std::exchange(first, false))\n std::cout << ", ";\n std::cout << v;\n });\n\n// prints:\n// 1, 2, 3, 4\n</code></pre>\n<p>Now let’s clean up the big printing block:</p>\n<pre><code> std::cout<<std::endl<<"smallfactor * primepower * smallfactor"<<std::endl;\n std::cout<<"\\tthe second factor is a prime power"<<std::endl;\n std::cout<<"\\t'!' at the end prime power exponent > 1"<<std::endl;\n</code></pre>\n<p>First we remove all the <code>std::endl</code>s (and space out the tokens, for readability):</p>\n<pre><code> std::cout << '\\n' << "smallfactor * primepower * smallfactor" << '\\n';\n std::cout << "\\tthe second factor is a prime power" << '\\n';\n std::cout << "\\t'!' at the end prime power exponent > 1" << '\\n';\n</code></pre>\n<p>Next, we merge all the <code>'\\n'</code>s into the strings:</p>\n<pre><code> std::cout << "\\nsmallfactor * primepower * smallfactor\\n";\n std::cout << "\\tthe second factor is a prime power\\n";\n std::cout << "\\t'!' at the end prime power exponent > 1\\n";\n</code></pre>\n<p>Next, instead of 3 <code>cout</code> statements, we merge them into one:</p>\n<pre><code> std::cout << "\\nsmallfactor * primepower * smallfactor\\n"\n << "\\tthe second factor is a prime power\\n"\n << "\\t'!' at the end prime power exponent > 1\\n";\n</code></pre>\n<p>Next, we take advantage of the fact that C++ will automatically merge adjacent string literals, and turn those 3 <code>operator<<()</code> calls into 1:</p>\n<pre><code> std::cout << "\\nsmallfactor * primepower * smallfactor\\n"\n "\\tthe second factor is a prime power\\n"\n "\\t'!' at the end prime power exponent > 1\\n";\n</code></pre>\n<p>We could leave it at this, which will already be considerably faster than the original code, but there is another option you could consider: raw strings:</p>\n<pre><code> std::cout << R"(\nsmallfactor * primepower * smallfactor\n the second factor is a prime power\n '!' at the end prime power exponent > 1\n)";\n</code></pre>\n<p>That’s about all I can think to recommend without a complete overhaul of the algorithm, and code structure. A starting point for that would be to use a class like I demonstrated above. After that, perhaps the next step would be to look at breaking out parts of the process into independent functions or types—in particular, it probably shouldn’t be necessary to work with 4 arrays. Then, maybe in the long run, look at opportunities for parallelization.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T09:09:15.427",
"Id": "512928",
"Score": "0",
"body": "Thanks for the effort you made. I am impressed. Every line of this post is useful to me. I will revise my program and try to reconsider and incorporate the suggestions you have made."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T00:15:34.037",
"Id": "259921",
"ParentId": "259874",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259921",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T20:01:11.983",
"Id": "259874",
"Score": "2",
"Tags": [
"c++",
"beginner"
],
"Title": "splitting numbers in three factors"
}
|
259874
|
<p>I have this code:</p>
<pre><code>Sorted=False
while not Sorted:
Sorted=True
for x,y in enumerate(List[:-1]):
if List[x]>List[x+1]:
List[x],List[x+1]=List[x+1],List[x]
Sorted=False
</code></pre>
<p>However the use of</p>
<pre><code>Sorted=True/False
</code></pre>
<p>being repeated is quite ugly and it would be much nicer to write the code is something similar to:</p>
<pre><code>while True:
for x,y in enumerate(List[:-1]):
if List[x]>List[x+1]:
List[x],List[x+1]=List[x+1],List[x]
break
else:break
</code></pre>
<p>The only problem is that breaking from the loop this early causes the loop to be repeated many more times taking up more time overall. Are there any ways around this to make the code more pythonic or do I just need to leave it as ugly as it is?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T21:18:24.480",
"Id": "512786",
"Score": "3",
"body": "Hi and welcome to CodeReview. Unfortunately, `List` is missing. While its name indicates that it's a usual Python list, several other collections in Python also provide an iterator interface as well as (range-based) indexing. Also, keep in mind that while reviewers *might* answer additional questions, it's not mandatory. Asking for other ways is inherently off-topic, so you might want to remove your question or rephrase it into a concern. Last but not least, you probably want to tag your question with [tag:reinventing-the-wheel] and [tag:comparative-review]. I hope you get nice reviews :)."
}
] |
[
{
"body": "<p>One approach is to move most of the logic into a helper function that does the\nswapping and returns the N of swaps. The outer part of the algorithm then\nreduces to almost nothing.</p>\n<p>While you're at it: (1) use conventional names for Python variables (lowercase\nfor variables, capitalized for classes, uppercase for constants); (2) let your\noperators breathe for readability, (3) take full advantage of <code>enumerate()</code>,\nwhich gives both index and value (<code>x1</code>), (4) use convenience variables to make\ncode more readable (<code>x2</code> rather that repeated uses of <code>xs[i + 1]</code>); (5)\nlook for ways to pick simple variable names that help the reader understand the\nalgorithm (<code>i</code> for an index; <code>xs</code> for a list of values; <code>x1</code> and <code>x2</code> for\nindividual values that are being swapped) rather than purely abstract variable\nnames that convey nothing substantive to the reader (<code>List</code>, <code>x</code> for an\nindex, and <code>y</code> for a value); and (6) put your sort in a proper function.</p>\n<pre><code>def bubble_sort(xs):\n while bubble(xs):\n pass\n\ndef bubble(xs):\n n_swaps = 0\n for i, x1 in enumerate(xs[:-1]):\n x2 = xs[i + 1]\n if x1 > x2:\n xs[i] , xs[i + 1] = x2, x1\n n_swaps += 1\n return n_swaps\n\nvals = [9, 3, 4, 2, 6, 8, 10, 1]\nbubble_sort(vals)\nprint(vals)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T01:12:16.047",
"Id": "512803",
"Score": "0",
"body": "Nice review. But how `xs` would help the reader to understand that it's a list of values?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T02:05:38.110",
"Id": "512808",
"Score": "1",
"body": "Also, counting the swaps is unnecessary, a flag would be enough."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T02:43:30.567",
"Id": "512812",
"Score": "0",
"body": "@Marc Yes, adjust as needed. The truth evaluation is the same and bubble() could be used for something else in our bUbBle-SoRt library. More seriously, `xs` is a conventional name for exactly this purpose: one `x`, many `xs` (especially in contexts where the values are generic in some sense). It's ubiquitous in functional programming, for example, and works great in Python -- if applied with good sense."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T21:54:06.623",
"Id": "259879",
"ParentId": "259877",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T20:48:19.787",
"Id": "259877",
"Score": "1",
"Tags": [
"python",
"python-3.x"
],
"Title": "How would I make this bubble sort more pythonic?"
}
|
259877
|
<p>Been looking into some simple algorithms, I came up with the following piece of code in C to implement the Euclidean algorithm iteratively (I like to be clear here, I don't want the recursive implementation for now).</p>
<p>I've seen various other implementations and in fact most books prefer a different pseudo code.</p>
<p>I'm wondering if the following implementation is any better or worse?</p>
<pre class="lang-c prettyprint-override"><code>#include <stdlib.h>
void swap_numbers(void *a, void *b)
{
int temp = *(int *)a;
*(int *)a = *(int *)b;
*(int *)b = temp;
}
unsigned euklid_iterative(unsigned a, unsigned b)
{
while ((a = a % b))
swap_numbers(&a, &b);
return b;
}
</code></pre>
|
[] |
[
{
"body": "<h3>Unnecessary function calls</h3>\n<p>My quick thought is that you are making an unnecessary function call.</p>\n<pre><code>unsigned temp;\nwhile ((temp = a % b)) {\n a = b;\n b = temp;\n}\n</code></pre>\n<p>The thing with the doubled parentheses is a hack to keep some compilers from warning you that you may be doing an unintentional assignment. It should make no functional difference.</p>\n<p>This does fewer assignments. Three compared to four in your version. And it makes no function calls. Typically a function call is more involved than an assignment. Because it has to first save the current state, then jump somewhere else and do work, and finally restore the original state. The save and restore steps themselves often involve assignments. And those may be relatively expensive assignments from register to cache or memory. Whereas that loop can be done with three registers (or even two if the compiler optimizes out <code>temp</code> by doubling the code).</p>\n<pre><code>while ((a = a % b)) {\n if (!(b = b % a)) {\n return a;\n }\n}\n</code></pre>\n<p>No <code>temp</code> in that version, but duplicate logic. I wouldn't normally recommend writing that code. But it would be a perfectly legitimate compiler optimization if there is a shortage of available registers.</p>\n<p>Note: if you only call this function a few times, this won't make a difference. Use whatever you find more readable. But if you are calling GCD in your main loop, it is possible that efficiency will matter. If efficiency does matter, my revised version (the first one) will (absent compiler optimizations) probably be faster than your version. While premature optimizations are to be avoided, there is little harm in picking the more efficient version if you have two working versions. And GCD is exactly the kind of problem that may be subject to profiling that would lead to that kind of optimization. So many sources may offer the best optimized algorithm rather than an alternative.</p>\n<p>I find it a best practice to never use the statement form of control structures and always use the block form. I also prefer the brackets on the same line as the control structure. The latter is very much opinion, but the former is based on actual experience with bugs caused by editing.</p>\n<h3>Be careful of types</h3>\n<p>I also find it a bit risky that your variables are <code>unsigned</code> in the original function but <code>int</code> in the <code>swap_numbers</code> function. This presumably works because the <code>unsigned</code> and <code>int</code> types use the same storage width. But that's an implementation detail. Is that implementation detail guaranteed always? I don't know off-hand. Perhaps you already did that work and do know. But you don't say that you know and there's no comment explaining when you can and cannot use <code>swap_numbers</code>.</p>\n<p>For example, what would happen if used with an <code>unsigned long</code>? On some systems, that might work because <code>int</code> and <code>long</code> are the same width. On other systems, you may only swap part of the numbers. Possibly only some of the time (because if the bytes that you are swapping happen to be the ones with data, it might not matter).</p>\n<p>You might fix this by switching from pointers to handles (pointers to pointers).</p>\n<pre><code>void swap_numbers(void **a, void **b)\n{\n void *temp = *a;\n *a = *b;\n *b = temp;\n}\n\nunsigned euklid_iterative(unsigned *a, unsigned *b)\n{\n while ((*a = *a % *b))\n {\n swap_numbers(&a, &b);\n }\n\n return *b;\n}\n</code></pre>\n<p>But it might be easier just to write a <code>swap_unsigned</code> function. Or write out the swap entirely as I did originally.</p>\n<p>All code in this post is untested. Not even for compilable syntax much less correct logic. Use at your own risk.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T07:15:00.103",
"Id": "512830",
"Score": "2",
"body": "I'm pretty sure that for any signed integer type `T`, then `sizeof (unsigned T) == sizeof (T)`. [6.2.5.6](http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1570.pdf#%5B%7B%22num%22%3A116%2C%22gen%22%3A0%7D%2C%7B%22name%22%3A%22XYZ%22%7D%2C-27%2C816%2Cnull%5D) says \"_For each of the signed integer types, there is a corresponding (but different) unsigned integer type (designated with the keyword `unsigned` that **uses the same amount of storage** (including sign information) and has the same alignment requirements_\" (my emphasis). I'd still avoid that type-punning, though."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T08:07:58.900",
"Id": "512832",
"Score": "5",
"body": "With optimization options enabled, the gcc compiler produces the very same code for `while ((a = a % b)) { unsigned tmp = a;` etc. and `while ((tmp = a %b)) { ...`. So, don't worry to much about the number of assignments in the *source* code with execution speed in mind. Focus on simplicity and readability (which may be a reason to prefer the latter version)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T12:11:37.713",
"Id": "512852",
"Score": "0",
"body": "Which one do you mean by \"the latter\"? @MichelBillaud"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T23:46:29.820",
"Id": "512908",
"Score": "0",
"body": "On x86, it's impossible to perform the inner loop with less than 4 registers: DIV takes divisor from EDX:EAX and writes quotient and remainder into EAX and EDX, and arguments are in EDI and ESI on function entry, so that's 4 in total. And doubling the code only makes it execute twice as much DIVs, so it's a guaranteed pessimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T05:36:51.400",
"Id": "512918",
"Score": "0",
"body": "@Joker_vD I'm not following how that code would change the number of DIVs. Yes, there are two per iteration of the loop. But it tests after each one it does; i.e. it tests twice per loop and will jump out immediately. So that version would do the same number of DIVs as the other version (because it only does half as many loop iterations). Which seems irrelevant to the point that I was making, since I explicitly said not to use that code and instead let the compiler do it -- if the compiler found it a useful optimization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T15:55:31.307",
"Id": "512955",
"Score": "0",
"body": "@j3141592653589793238 the preference is left to the reader. Maybe or maybe not. Speaking about personal taste, I'd write `while(whatever != 0)` instead of `while((whatever))`, but that's another thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T20:44:48.400",
"Id": "512994",
"Score": "0",
"body": "\" Is that implementation detail guaranteed always?\" --> No. when `int` is the rare non 2's complement, traps may occur. I do not see a possible problem with `2's complement. Yet it is certainly clearer to swap using the same type: `unsigned`."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T01:41:28.993",
"Id": "259885",
"ParentId": "259878",
"Score": "6"
}
},
{
"body": "<blockquote>\n<pre><code>#include <stdlib.h>\n</code></pre>\n</blockquote>\n<p>This is not required - we use nothing declared by that header.</p>\n<blockquote>\n<pre><code>void swap_numbers(void *a, void *b)\n{\n int temp = *(int *)a;\n</code></pre>\n</blockquote>\n<p>Avoid <code>void</code>! We don't need to erase and reinstate type information like that:</p>\n<pre><code>static void swap_unsigned(unsigned *a, unsigned *b)\n{\n unsigned temp = *a;\n *a = *b;\n *b = temp;\n}\n</code></pre>\n<p>If we'll need this for several types, we could use a preprocessor macro to help us create the functions:</p>\n<pre><code>#define MAKE_SWAP_FUNCTION(type, name) \\\n static void swap_name(type *a, type *b) \\\n { \\\n type temp = *a; \\\n *a = *b; \\\n *b = temp; \\\n }\n\nMAKE_SWAP_FUNCTION(unsigned int, unsigned)\nMAKE_SWAP_FUNCTION(long double, long_double)\n/* etc. */\n\n#undef MAKE_SWAP_FUNCTION\n</code></pre>\n<p>Or just replace the function with a macro:</p>\n<pre><code>#define SWAP_VALUES(type, a, b) \\\n { \\\n type temp = a; \\\n a = b; \\\n b = temp; \\\n }\n</code></pre>\n<p>Or, as suggested in the other answer, simply code the swap directly in the main function.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T08:18:21.443",
"Id": "512834",
"Score": "0",
"body": "Sorry, @mdfst13, I really don't understand what you're trying to say there. What \"multi-line syntax\" is weird?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T11:46:12.563",
"Id": "512848",
"Score": "0",
"body": "Oh, just the continuation lines? I'm not sure what needs to be explained, given it's not a [tag:beginner] question."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T12:09:37.997",
"Id": "512851",
"Score": "1",
"body": "I'm alright with that as is! I don't think the continuation lines are specific to this question. But thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T07:08:16.643",
"Id": "259893",
"ParentId": "259878",
"Score": "5"
}
},
{
"body": "<blockquote>\n<p>if the following implementation is any better or worse?</p>\n</blockquote>\n<p><strong>Consider <code>0</code></strong></p>\n<p><code>GCD(a,b)</code> is usually considered communicative: <code>GCD(a,b) == GCD(b,a)</code>.</p>\n<p><code>while ((a = a % b))</code> is OK when <code>a==0</code>, yet undefined when <code>b==0</code>.</p>\n<hr />\n<p><strong>No swap</strong></p>\n<p>Rather than spend time swapping, just add a little more code.</p>\n<pre><code>unsigned gcd_no_swap(unsigned a, unsigned b) {\n while (a) {\n b %= a;\n if (b == 0) return a;\n a %= b;\n }\n return b;\n}\n</code></pre>\n<p><strong>When <code>/, %</code> is expensive</strong></p>\n<p>A solution without <code>/, %</code> may run faster when such repetitive operations are expensive.</p>\n<pre><code>unsigned gcd_no_div(unsigned a, unsigned b) {\n int shift;\n\n // GCD(0,b) == b; GCD(a,0) == a, GCD(0,0) == 0\n if (a == 0) {\n return b;\n } else if (b == 0) {\n return a;\n }\n\n // find common power 2\n for (shift = 0; ((a | b) & 1) == 0; shift++) {\n a >>= 1;\n b >>= 1;\n }\n\n // Adjust so a is odd.\n while ((a & 1) == 0) {\n a >>= 1;\n }\n\n do {\n // Adjust so b is odd.\n while ((b & 1) == 0) {\n b >>= 1;\n }\n\n // a and b are both odd here.\n \n // Swap if necessary so a <= b,\n if (a > b) {\n unsigned t = b;\n b = a;\n a = t;\n } // Swap a and b.\n\n b -= a; // Here b >= a.\n } while (b != 0);\n\n return a << shift; // Restore power-of-2 factor\n}\n</code></pre>\n<hr />\n<p><strong>Courtesy test harness</strong></p>\n<pre><code>unsigned gcd_utest(unsigned m, unsigned n) {\n unsigned g1 = gcd_no_div(m, n);\n unsigned g2 = gcd_no_swap(m, n);\n if (g1 != g2) {\n printf("Differ %u %u --> %u %u\\n", m, n, g1, g2);\n exit(-1);\n }\n //printf("%u %u --> %u %u\\n", m, n, g1, g2);\n return g1;\n}\n\nunsigned gcd_utests() {\n unsigned a[] = {0, 1, 2, UINT_MAX - 2, UINT_MAX - 1, UINT_MAX};\n unsigned n = sizeof a / sizeof *a;\n for (unsigned i = 0; i < n; i++) {\n for (unsigned j = 0; j < n; j++) {\n gcd_utest(a[i], a[j]);\n }\n }\n for (unsigned i = 0; i < 1000; i++) {\n gcd_utest(rand(), rand());\n }\n return 0;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T21:13:25.633",
"Id": "259961",
"ParentId": "259878",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259885",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T21:00:30.467",
"Id": "259878",
"Score": "6",
"Tags": [
"algorithm",
"c",
"iteration"
],
"Title": "Euclidean algorithm to determine GCD (greatest common divisor) in C -- alternative method"
}
|
259878
|
<p>I implemented a key:value format file parser in C, or something that comes close to it as there is no such thing as dynamically creating structs in C.</p>
<p>Assumptions: we are creating a C program that needs some config options (e.g. the number <code>K</code> of threads in a concurrent server that handles requests using a pool of <code>K</code> worker threads), and we want to have them read from a text file. The file contains a pair key:value on each line. In our program, we know in advance the name of the parameters and their type.</p>
<p>fileparser.h</p>
<pre><code>#ifndef FILE_PARSER_H
#define FILE_PARSER_H
typedef struct _parser Parser;
Parser* parseFile(char* filename, char* delim);
void getValueFor(Parser* p, char* key, char* dest, char* defaultVal);
int testError(Parser* p);
void destroyParser(Parser* p);
#endif
</code></pre>
<p>fileparser.c</p>
<pre><code>#include "fileparser.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "../scerrhand.h"
#define MAX_FILENAME_LEN 100
#define MAX_DELIM_LEN 1
#define MAX_KEY_LEN 50
#define MAX_VAL_LEN 200
struct _pair {
char key[MAX_KEY_LEN + 1];
char val[MAX_VAL_LEN + 1];
struct _pair* nextPtr;
};
typedef struct _parser {
char filename[MAX_FILENAME_LEN + 1];
char delim[MAX_DELIM_LEN + 1];
struct _pair* hPtr;
int err;
} Parser;
static int cmpKeys(char* k1, char* k2) {
return strcmp(k1, k2);
}
static void _push(struct _pair** hPtr, struct _pair* newPair) {
newPair->nextPtr = *hPtr;
*hPtr = newPair;
}
static int _parse(Parser* p, FILE* fp) {
char buf[BUFSIZ + 1];
struct _pair* kvPair;
size_t i = 0;
while (i++, fgets(buf, BUFSIZ, fp)) {
char* savePtr, * token;
kvPair = calloc(sizeof(struct _pair), 1);
if (!kvPair) {
return -1; // out of memory
}
// get key
token = strtok_r(buf, p->delim, &savePtr);
strncpy(kvPair->key, token, strlen(token));
// remove any trailing spaces after the key name
kvPair->key[strcspn(kvPair->key, " ")] = '\0';
// get value
token = strtok_r(NULL, p->delim, &savePtr);
if (!token) { // delim missing: invalid syntax
return i;
}
strncpy(kvPair->val, token, strlen(token));
// remove trailing newline
kvPair->val[strcspn(kvPair->val, "\n")] = '\0';
_push(&p->hPtr, kvPair);
}
return 0;
}
Parser* parseFile(char* filename, char* delim) {
FILE* fp;
Parser* p = calloc(sizeof(Parser), 1);
if (!p) {
return NULL;
}
strncpy(p->filename, filename, MAX_FILENAME_LEN);
strncpy(p->delim, delim, MAX_DELIM_LEN);
SYSCALL_OR_DIE_NULL(fp = fopen(filename, "r"));
// parse file and capture error code
p->err = _parse(p, fp);
fclose(fp);
return p;
}
int testError(Parser* p) {
return p->err;
}
void getValueFor(Parser* p, char* key, char* dest, char* defaultVal) {
struct _pair*
currPtr = p->hPtr,
* prevPtr = NULL,
** target = NULL; // address of the node to remove after consuming its value
while (currPtr && cmpKeys(key, currPtr->key)) {
prevPtr = currPtr;
currPtr = currPtr->nextPtr;
}
// copy value if key is found; otherwise copy default value
strncpy(dest, currPtr ? currPtr->val : defaultVal, MAX_VAL_LEN);
// pop node out of list
if (currPtr) {
target = prevPtr ? &prevPtr->nextPtr : &p->hPtr;
*target = currPtr->nextPtr;
free(currPtr);
}
}
void destroyParser(Parser* p) {
struct _pair* tmp;
while (p->hPtr) {
tmp = p->hPtr;
p->hPtr = p->hPtr->nextPtr;
free(tmp);
}
free(p);
p = NULL;
}
</code></pre>
<p>scerrhand.h</p>
<pre><code>#ifndef SC_ERR_HAND_H
#define SC_ERR_HAND_H
#include <stdlib.h>
// makes a system call and exits if return value is not zero
#define SYSCALL_OR_DIE_NZ(s) if(s) { puts("System call failed with nonzero status"); exit(EXIT_FAILURE); }
// makes a system call and exits if return value is -1
#define SYSCALL_OR_DIE_NEG_ONE(s) if((s) == -1) { puts("System call failed with status -1"); exit(EXIT_FAILURE); }
// makes a system call and exits if return value is NULL
#define SYSCALL_OR_DIE_NULL(s) if((s) == NULL) { puts("System call returned NULL"); exit(EXIT_FAILURE); }
#endif
</code></pre>
<p>I'd like some feedback on design, implementation, and whatnot.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T02:53:09.740",
"Id": "512813",
"Score": "2",
"body": "`SYSCALL_OR_DIE` seems like a good bumper sticker"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T13:45:19.127",
"Id": "512856",
"Score": "0",
"body": "@Reinderien LOL, did I correctly decipher your comment."
}
] |
[
{
"body": "<h1>General Observations</h1>\n<p>It would be much easier to review this code if there was either a unit test or example code to see how this code should be used.</p>\n<p>It also isn't clear why the code deletes the <code>key value pair</code> within the function <code>getValueFor()</code>. The function name does not indicate that it is deleting the pair as well as getting the value for the key.</p>\n<h1>Error Reporting</h1>\n<p>There are a few of issues with the <code>SYSCALL_OR_DIE_*</code> macros. The first is that you are hiding the calls to <code>exit()</code>, which can be bad for maintenance.</p>\n<p>The second is that the error messages are not very meaningful to the person running the program, for instance I would prefer to see something like <code>Can't open file ... for input</code> rather than <code>System call returned NULL</code>. One I know how to fix as a user, the other I have no clue what it means. If this code were in production and the user was getting these error messages the user would need support to know how to correct what was causing the problem.</p>\n<p>The third issue is that the error messages are going to <code>stdout</code> rather than <code>stderr</code> where error messages of this nature should go. If the output of the program is being redirected to a file than the user won't know the program failed until the file is examined.</p>\n<h1>Maintaining Memory Allocation</h1>\n<p>A fairly common usage of <code>calloc()</code> is to use what the pointer points to in the <code>sizeof()</code> call because this reduces the amount of editing needed if a change is necessary, for example in the following code from <code>static int _parse(Parser* p, FILE* fp)</code> 2 lines would need to be changed if the type of struct was changed:</p>\n<pre><code> struct _pair* kvPair; // change needed here\n size_t i = 0;\n while (i++, fgets(buf, BUFSIZ, fp)) {\n char* savePtr, * token;\n kvPair = calloc(sizeof(struct _pair), 1); // change needed here\n if (!kvPair) {\n return -1; // out of memory\n }\n</code></pre>\n<p>The following code is easier to maintain:</p>\n<pre><code> struct _pair* kvPair; // Only this line changes\n size_t i = 0;\n while (i++, fgets(buf, BUFSIZ, fp)) {\n char* savePtr, * token;\n kvPair = calloc(sizeof(*kvPair), 1); // No need to change this code\n if (!kvPair) {\n return -1; // out of memory\n }\n</code></pre>\n<h1>Unnecessary Wrapping of Function Calls</h1>\n<p>It isn't clear why the following function has been added or used since it doesn't change the value returned and doesn't really improve readability:</p>\n<pre><code>static int cmpKeys(char* k1, char* k2) {\n return strcmp(k1, k2);\n}\n</code></pre>\n<p>If the function was returning a boolean value rather than an int it might make sense but just returning the value of <code>strcmp()</code> doesn't add any value.</p>\n<p>A good compiler may just inline this function, otherwise the code is adding the cost of an additional function call.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T20:38:24.477",
"Id": "512895",
"Score": "0",
"body": "Thank you. I'll include a unit test soon. @popping the elements from the list upon reading the value: I agree that the function name doesn't make it clear. My rationale was that knowing that the list gets smaller as you consume the values would make the use of a list vs say a hash table more acceptable from a time complexity standpoint. In retrospect, that's pretty silly. @errors: do you think that having the macro accept a string and print that with `perror` would work better?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T20:39:25.687",
"Id": "512896",
"Score": "0",
"body": "@wrapping the compare function: I did that in case I want to support compare functions supplied externally, so I wouldn't have to go back into the value that calls it and edit it there. I agree it's pretty useless as it is now"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T13:36:49.647",
"Id": "259902",
"ParentId": "259881",
"Score": "5"
}
},
{
"body": "<h1>Naming</h1>\n<p>C reserves identifiers beginning with <code>_</code> followed by any letter for the implementation, so they should not be defined by user programs.</p>\n<p>I can't quite remember whether leading <code>_</code> is permitted in <code>struct</code> tags (that's a different namespace to object and function names), because it's simpler to just avoid using leading <code>_</code> anywhere, and never have to know the exact details of what's allowed.</p>\n<h1>Exiting</h1>\n<p>I'm not a fan of exiting the whole program from within a utility function (particularly if we're creating a library - that can really hamstring the caller). We should include <code><stdio.h></code> from <code>scerrhand.h</code> so that the header is self-reliant.</p>\n<p>Error messages should go to <code>stderr</code>, not <code>stdout</code>. Given that we're using macros here, we have an opportunity to be more informative about exactly what failed (perhaps only in debug builds), using <code>#s</code> in the substitutions. For example:</p>\n<pre><code>#define SYSCALL_OR_DIE_NZ(s) \\\n if (s) { \\\n fprintf(stderr, "%s failed with nonzero status", #s); \\\n exit(EXIT_FAILURE); \\\n }\n</code></pre>\n<p>We really want to wrap those in the <code>do { … } while (0)</code> idiom, so that they can be used safely in compound statements (e.g. <code>if (c) SYSCALL_OR_DIE(something); else SYSCALL_OR_DIE(something_else);</code>).</p>\n<h1>Testing</h1>\n<p>It's a real shame you haven't shown us the unit-tests for this class. I think there are a few cases that are missing from the tests, as we'll see shortly.</p>\n<h1>Pointless function</h1>\n<p>This function seems to have no value:</p>\n<blockquote>\n<pre><code>static int cmpKeys(char* k1, char* k2) {\n return strcmp(k1, k2);\n}\n</code></pre>\n</blockquote>\n<p>We should change the caller to invoke <code>strcmp()</code> directly.</p>\n<h1>Parse function</h1>\n<p>This loop control:</p>\n<blockquote>\n<pre><code>size_t i = 0;\nwhile (i++, fgets(buf, BUFSIZ, fp)) {\n</code></pre>\n</blockquote>\n<p>has an initialisation, a test and a step, so it reads more naturally as a <code>for</code> loop:</p>\n<pre><code>for (size_t i = 1; fgets(buf, BUFSIZ, fp); ++i) {\n</code></pre>\n<p>I'm not sure why we're using <code>size_t</code> for <code>i</code> but return it as <code>int</code> - it would be better if those two types were made to agree.</p>\n<p>As the code stands, we silently split any input lines that are longer than BUFSIZ. I think that should be made more robust, with tests to cover.</p>\n<p>Also, why did we create <code>buf</code> with <code>BUFSIZE+1</code> elements, and never use the last one? (<code>fgets()</code> will write up to <code>BUFSIZE</code> characters, including the terminating null).</p>\n<blockquote>\n<pre><code> kvPair = calloc(sizeof(struct _pair), 1);\n</code></pre>\n</blockquote>\n<p>I don't see why this variable needs the entire function as its scope. We can declare and initialise together, for safer code:</p>\n<pre><code> struct _pair *kvPair = calloc(sizeof *kvPair, 1);\n</code></pre>\n<p>Do we really need the memory to be zeroed? I think not, as we immediately write valid data there. So use plain <code>malloc()</code> instead.</p>\n<p>We have completely missed the point of <code>strncpy()</code> here:</p>\n<blockquote>\n<pre><code> strncpy(kvPair->key, token, strlen(token));\n</code></pre>\n</blockquote>\n<p>This is just a less efficient way to write <code>strcpy(kvPair->key, token)</code>, except that doesn't write the null terminator. The point of the <code>length</code> argument is to tell the function <em>how much it may safely write</em>, but we're claiming that <code>kvPair->key</code> has enough space for the token regardless of its length. In this case, we want</p>\n<pre><code> strncpy(kvPair->key, token, sizeof kvPair->key);\n kvPair->key[sizeof kvPair->key - 1] = '\\0';\n</code></pre>\n<p>We could do with improved tests of over-length keys, and consider whether we could do better than truncating them.</p>\n<p><code>strcspn()</code> is overkill when there's only a single character we're looking for - use <code>strchr()</code> instead.</p>\n<p>Using <code>strtok_r()</code> to get the value will truncate any value that happens to contain the separator string (again, add tests for this, as well as for values longer than <code>MAX_VAL_LEN</code>).</p>\n<p>The early return when value is empty omits <code>free(kvPair)</code>, which is a memory leak. Execute the unit tests under Valgrind from time to time.</p>\n<h1>Value getter</h1>\n<p>It surprised me that getting a value is a <em>destructive</em> operation. I also don't see why the <code>key</code> and <code>defaultVal</code> arguments need to be modifiable - I expected <code>const char*</code> for those.</p>\n<p>Given the suggested use cases, it would be helpful to have versions that obtain numeric values directly (e.g. as <code>int</code>, <code>unsigned</code> and/or <code>double</code>), rather than forcing the user to deal with strings.</p>\n<h1>File interface</h1>\n<p>The problems in <code>parseFile()</code> are mostly similar to those in <code>_parse()</code>.</p>\n<h1>Destructor</h1>\n<p>The scope of <code>tmp</code> can be reduced to within the loop.</p>\n<p>The assignment to <code>p</code> at the end is a <em>dead write</em>, as the variable goes out of scope immediately after.</p>\n<p>There's really no need to keep reassigning <code>p->hPtr</code> within the loop - we can just use a local:</p>\n<pre><code>void destroyParser(Parser *parser)\n{\n if (!parser) {\n return;\n }\n\n struct _pair *p = parser->hPtr;\n while (p) {\n struct _pair *tmp = p;\n p = p->nextPtr;\n free(tmp);\n }\n\n free(parser);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T20:41:17.687",
"Id": "512897",
"Score": "0",
"body": "Thank you! I didn't know about the underscore thing. As per the wrapping the system calls in my macro(s) inside of a `do...while(0)` loop, would wrapping them inside of a set of curly brackets have the same effect?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T06:25:09.977",
"Id": "512922",
"Score": "0",
"body": "The `do { … } while (0)` idiom is more comfortable for the user of the macro than just braces, because it [can be followed by semicolon](https://stackoverflow.com/q/1067226/4850040) in contexts where an empty statement wouldn't be allowed.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T11:11:33.617",
"Id": "512932",
"Score": "0",
"body": "Definitely helpful. A few comments: as far as dealing with strings that are larger than `BUFSIZ`, how would you deal with that? Do you think I could do a check on the string's length with `strlen` and throw some kind of error/reallocate a bigger buffer? For the use of `calloc`: I'd initially used `malloc`, but I was getting some `Conditional jump depends on uninitialized memory` from valgrind which apparently only went away when I started using `calloc` instead."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:05:55.067",
"Id": "512961",
"Score": "0",
"body": "A first step would be to at least report the problem to the caller. You'd need to use the return value from `fgets()` and see if it read a newline - if not, the line was too long for the buffer, and we should read and discard to the next newline, and return a suitable error code. From there, I'd work up towards having code that can adapt and store longer keys and values."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:07:04.847",
"Id": "512962",
"Score": "1",
"body": "The problem reported by Valgrind (glad to know you're using the tools well), is because you told `strncpy` to only write the first `strlen()` characters of the strings - specifically not copying the final null character. Once you correct that, you'll be Valgrind-clean without `calloc()`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T14:11:33.710",
"Id": "259903",
"ParentId": "259881",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259903",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-22T22:23:16.263",
"Id": "259881",
"Score": "5",
"Tags": [
"c",
"parsing",
"file"
],
"Title": "C key: value file parser"
}
|
259881
|
<p>I am running a PowerShell script that shows disk usage for drives into HTML reports. While this works quite well it has a problem on some file servers with a massive amount of files. It can sometimes take up to 1 day in a worst case scenario which obviously isn't ideal. I'm wondering if there if there any way to optimize this script so it performs much quicker?</p>
<p>From testing the bulk of the slowness seems to stem from the
<strong># iterate all subdirectories</strong> and <strong># iterate all files</strong> sections, although there may be others that I'm missing.</p>
<p>Any tips/suggestions/help would be greatly appreciated.</p>
<pre><code>#requires -version 2
function TreeSizeHtml {
<#
.SYNOPSIS
A Powershell clone of the classic TreeSize administrators tool. Works on local volumes or network shares.
Outputs the report to one or more interactive HTML files, and optionally zips them into a single zip file.
Requires Powershell 2. For Windows 2003 servers, install http://support.microsoft.com/kb/968930
Author: James Weakley (jameswillisweakley@gmail.com)
.DESCRIPTION
Recursively iterates a folder structure and reports on the space consumed below each individual folder.
Outputs to a single HTML file which, with the help of a couple of third party javascript libraries,
displays in a web browser as an expandable tree, sorted by largest first.
.PARAMETER paths
One or more comma separated locations to report on.
A report on each of these locations will be output to a single HTML file per location, defined by htmlOutputFilenames
Pass in the value "ALL" to report on all fixed disks.
.PARAMETER reportOutputFolder
The folder location to output the HTML report(s) and zip file. This folder must exist already.
.PARAMETER htmlOutputFilenames
One or more comma separated filenames to output the HTML reports to. There must be one of these to correspond with each path specified.
If "ALL" is specified for paths, then this parameter is ignored and the reports use the filenames "C_Drive.html","D_Drive.html", and so on
.PARAMETER zipOutputFilename
Name of zip file to place all generated HTML reports in. If this value is empty, HTML files are not zipped up.
.PARAMETER topFilesCountPerFolder
Setting this parameter filters the number of files shown at each level.
For example, setting it to 10 will mean that at each folder level, only the largest 10 files will be displayed in the report.
The count and sum total size of all other files will be shown as one item.
The default value is 20.
Setting the value to -1 disables filtering and always displays all files. Note that this may generate HTML files large enough to crash your web browser!
.PARAMETER folderSizeFilterDepthThreshold
Enables a folder size filter which, in conjunction with folderSizeFilterMinSize, excludes from the report sections of the tree that are smaller than a particular size.
This value determines how many subfolders deep to travel before applying the filter.
The default value is 8
Note that this filter does not affect the accuracy of the report. The total size of the filtered out branches are still displayed in the report, you just can't drill down any further.
Setting the value to -1 disables filtering and always displays all files. Note that this may generate HTML files large enough to crash your web browser!
.PARAMETER folderSizeFilterMinSize
Used in conjunction with folderSizeFilterDepthThreshold to excludes from the report sections of the tree that are smaller than a particular size.
This value is in bytes.
The default value is 104857600 (100MB)
.PARAMETER displayUnits
A string which must be one of "B","KB","MB","GB","TB". This is the units to display in the report.
The default value is MB
.EXAMPLE
TreeSizeHtml -paths "C:\" -reportOutputFolder "C:\temp" -htmlOutputFilenames "c_drive.html"
This will output a report on C:\ to C:\temp\c_drive.html using the default filter settings.
.EXAMPLE
TreeSizeHtml -paths "C:\,D:\" -reportOutputFolder "C:\temp" -htmlOutputFilenames "c_drive.html,d_drive.html" -zipOutputFilename "report.zip"
This will output two size reports:
- A report on C:\ to C:\temp\c_drive.html
- A report on D:\ to C:\temp\d_drive.html
Both reports will be placed in a zip file at "C:\temp\report.zip"
.EXAMPLE
TreeSizeHtml -paths "\\nas\ServerBackups" -reportOutputFolder "C:\temp" -htmlOutputFilenames "nas_server_backups.html" -topFilesCountPerFolder -1 -folderSizeFilterDepthThreshold -1
This will output a report on \\nas\ServerBackups to c:\temp\nas_server_backups.html
The report will include all files and folders, no matter how many or how small
.EXAMPLE
TreeSizeHtml -paths "E:\" -reportOutputFolder "C:\temp" -htmlOutputFilenames "e_drive_summary.html" -folderSizeFilterDepthThreshold 0 -folderSizeFilterMinSize 1073741824
This will output a report on E:\ to c:\temp\e_drive_summary.html
As soon as a branch accounts for less than 1GB of space, it is excluded from the report.
.NOTES
You need to run this function as a user with permission to traverse the tree, otherwise you'll have sections of the tree labeled 'Permission Denied'
#>
param (
[Parameter(Mandatory=$true)][String] $paths,
[Parameter(Mandatory=$true)][String] $reportOutputFolder,
[Parameter(Mandatory=$false)][String] $htmlOutputFilenames = $null,
[Parameter(Mandatory=$false)][String] $zipOutputFilename = $null,
[Parameter(Mandatory=$false)][int] $topFilesCountPerFolder = 10,
[Parameter(Mandatory=$false)][int] $folderSizeFilterDepthThreshold = 2,
[Parameter(Mandatory=$false)][long] $folderSizeFilterMinSize = 104857600,
[Parameter(Mandatory=$false)][String] $displayUnits = "MB"
)
$ErrorActionPreference = "Stop"
$pathsArray = @();
$htmlFilenamesArray = @();
# check output folder exists
if (!($reportOutputFolder.EndsWith("\")))
{
$reportOutputFolder = $reportOutputFolder + "\"
}
$reportOutputFolderInfo = New-Object System.IO.DirectoryInfo $reportOutputFolder
if (!$reportOutputFolderInfo.Exists)
{
Throw "Report output folder $reportOutputFolder does not exist"
}
# passing in "ALL" means that all fixed disks are to be included in the report
if ($paths -eq "ALL")
{
gwmi win32_logicaldisk -filter "drivetype = 3" | % {
$pathsArray += $_.DeviceID+"\"
$htmlFilenamesArray += $_.DeviceID.replace(":","_Drive.html");
}
}
else
{
if ($htmlOutputFilenames -eq $null -or $htmlOutputFilenames -eq '')
{
throw "paths was not 'ALL', but htmlOutputFilenames was not defined. If paths are defined, then the same number of htmlOutputFileNames must be specified."
}
# split up the paths and htmlOutputFilenames parameters by comma
$pathsArray = $paths.split(",");
$htmlFilenamesArray = $htmlOutputFilenames.split(",");
if (!($pathsArray.Length -eq $htmlFilenamesArray.Length))
{
Throw "$($pathsArray.Length) paths were specified but $($htmlFilenamesArray.Length) htmlOutputFilenames. The number of HTML output filenames must be the same as the number of paths specified"
}
}
for ($i=0;$i -lt $htmlFilenamesArray.Length; $i++)
{
$htmlFilenamesArray[$i] = ($reportOutputFolderInfo.FullName)+$htmlFilenamesArray[$i]
}
if (!($zipOutputFilename -eq $null -or $zipOutputFilename -eq ''))
{
$zipOutputFilename = ($reportOutputFolderInfo.FullName)+$zipOutputFilename
}
write-host "Report Parameters"
write-host "-----------------"
write-host "Locations to include:"
for ($i=0;$i -lt $pathsArray.Length;$i++)
{
write-host "- $($pathsArray[$i]) to $($htmlFilenamesArray[$i])"
}
if ($zipOutputFilename -eq $null -or $zipOutputFilename -eq '')
{
write-host "Skipping zip file creation"
}
else
{
write-host "Report HTML files to be zipped to $zipOutputFilename"
}
write-host
write-host "Filters:"
if ($topFilesCountPerFolder -eq -1)
{
write-host "- Display all files"
}
else
{
write-host "- Displaying largest $topFilesCountPerFolder files per folder"
}
if ($folderSizeFilterDepthThreshold -eq -1)
{
write-host "- Displaying entire folder structure"
}
else
{
write-host "- After a depth of $folderSizeFilterDepthThreshold folders, branches with a total size less than $folderSizeFilterMinSize bytes are excluded"
}
write-host
for ($i=0;$i -lt $pathsArray.Length; $i++){
$_ = $pathsArray[$i];
# get the Directory info for the root directory
$dirInfo = New-Object System.IO.DirectoryInfo $_
# test that it exists, throw error if it doesn't
if (!$dirInfo.Exists)
{
Throw "Path $dirInfo does not exist"
}
write-host "Building object tree for path $_"
# traverse the folder structure and build an in-memory tree of objects
$treeStructureObj = @{}
buildDirectoryTree_Recursive $treeStructureObj $_
$treeStructureObj.Name = $dirInfo.FullName; #.replace("\","\\");
write-host "Building HTML output"
# initialise a StringBuffer. The HTML will be written to here
$sb = New-Object -TypeName "System.Text.StringBuilder";
# output the HTML and javascript for the report page to the StringBuffer
# below here are mostly comments for the javascript code, which
# runs in the browser of the user viewing this report
sbAppend "<!DOCTYPE html>"
sbAppend "<html>"
sbAppend "<head>"
# jquery javascript src (from web)
sbAppend "<link rel=`"stylesheet`" href=`"http://jquery.bassistance.de/treeview/jquery.treeview.css`" />"
sbAppend "<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js' type='text/javascript'></script>"
# jstree javascript src (from web)
sbAppend "<script src='http://jquery.bassistance.de/treeview/jquery.treeview.js' type='text/javascript'></script>"
sbAppend "<script type='text/javascript'>"
# check that jquery and jstree loaded in the browser, display error messages if they aren't
sbAppend "function checkjQuery()"
sbAppend "{"
sbAppend " if (typeof jQuery=='undefined' || typeof `$('#tree').treeview=='undefined')"
sbAppend " {"
sbAppend " var errorMsg = 'Error: Internet access is required to view this report, as the jQuery and JsTree javascript libraries are loaded from web sources.<br/><br/>';"
sbAppend " if (typeof jQuery=='undefined')"
sbAppend " {"
sbAppend " errorMsg+='Unable to load jQuery from http://static.jstree.com/v.1.0pre/jquery.js<br/>';"
sbAppend " }"
sbAppend " if (typeof `$('#tree').treeview=='undefined')"
sbAppend " {"
sbAppend " errorMsg+='Unable to load treeview from http://jquery.bassistance.de/treeview/jquery.treeview.js<br/>';"
sbAppend " }"
sbAppend " "
sbAppend " document.getElementById('error').innerHTML=errorMsg;"
sbAppend " }"
sbAppend " else"
sbAppend " {"
# initialise treeview
sbAppend " `$(function () {"
sbAppend " `$('#tree').treeview({"
sbAppend " collapsed: true,"
sbAppend " animated: 'medium',"
sbAppend " persist: `"location`""
sbAppend " });"
sbAppend " })"
sbAppend " }"
sbAppend "}"
sbAppend "window.onload = checkjQuery; "
sbAppend "</script>"
sbAppend "</head>"
sbAppend "<body>"
sbAppend "<div id='header'>"
sbAppend "<h1>Disk utilisation report</h1>"
sbAppend "<h3>Root Directory: ($($dirInfo.FullName))</h3>"
$machine = hostname
sbAppend "<h3>Generated on machine: $machine</h3>"
sbAppend "<h3>Report Filters</h3>"
sbAppend "<ul>"
if ($topFilesCountPerFolder -eq -1)
{
sbAppend "<li>Displaying all files</li>"
}
else
{
sbAppend "<li>Displaying largest $topFilesCountPerFolder files per folder</li>"
}
if ($folderSizeFilterDepthThreshold -eq -1)
{
sbAppend "<li>Displaying entire folder structure</li>"
}
else
{
sbAppend "<li>After a depth of $folderSizeFilterDepthThreshold folders, branches with a total size less than $folderSizeFilterMinSize bytes are excluded</li>"
}
sbAppend "</ul>"
sbAppend "</div>"
sbAppend "<div id='error'/>"
sbAppend "<div id='report''>"
sbAppend "<ul id='tree' class='filetree'>"
$size = bytesFormatter $treeStructureObj.SizeBytes $displayUnits
$name = $treeStructureObj.Name.replace("'","\'")
# output the name and total size of the root folder
sbAppend " <li><span class='folder'>$name ($size)</span>"
sbAppend " <ul>"
# recursively build the javascript object in the format that jsTree uses
outputNode_Recursive $treeStructureObj $sb $topFilesCountPerFolder $folderSizeFilterDepthThreshold $folderSizeFilterMinSize 1;
sbAppend " </ul>"
sbAppend " </li>"
sbAppend "</ul>"
sbAppend "</div>"
# include a loading message and spinny icon while jsTree initialises
#sbAppend "<div id='tree'>Loading...<img src='http://static.jstree.com/v.1.0pre/themes/default/throbber.gif'/></div>"
sbAppend "</body>"
sbAppend "</html>"
# finally, output the contents of the StringBuffer to the filesystem
$outputFileName = $htmlFilenamesArray[$i]
write-host "Writing HTML to file $outputFileName"
Out-file -InputObject $sb.ToString() $outputFileName -encoding "UTF8"
}
if ($zipOutputFilename -eq $null -or $zipOutputFilename -eq '')
{
write-host "Skipping zip file creation"
}
else
{
# create zip file
set-content $zipOutputFilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipOutputFilename).IsReadOnly = $false
for ($i=0;$i -lt $htmlFilenamesArray.Length; $i++){
write-host "Copying $($htmlFilenamesArray[$i]) to zip file $zipOutputFilename"
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipOutputFilename)
$zipPackage.CopyHere($htmlFilenamesArray[$i])
# the zip is asynchronous, so we have to wait and keep checking (ugly)
# use a DirectoryInfo object to retrieve just the file name within the path,
# this is what we check for every second
$fileInfo = New-Object System.IO.DirectoryInfo $htmlFilenamesArray[$i]
$size = $zipPackage.Items().Item($fileInfo.Name).Size
while($zipPackage.Items().Item($fileInfo.Name) -Eq $null)
{
start-sleep -seconds 1
write-host "." -nonewline
}
}
$inheritance = get-acl $zipOutputFilename
$inheritance.SetAccessRuleProtection($false,$false)
set-acl $zipOutputFilename -AclObject $inheritance
}
}
#.SYNOPSIS
#
# Used internally by the TreeSizeHtml function.
#
# Used to perform Depth-First (http://en.wikipedia.org/wiki/Depth-first_search) search of the entire folder structure.
# This allows the cumulative total of space used to be added up during backtracking.
#
#.PARAMETER currentNode
#
# The current node object, a temporary custom object which represents the current folder in the tree.
#
#.PARAMETER currentPath
#
# The path to the current folder in the tree
function buildDirectoryTree_Recursive {
param (
[Parameter(Mandatory=$true)][Object] $currentParentDirInfo,
[Parameter(Mandatory=$true)][String] $currentDirInfo
)
$substDriveLetter = $null
# if the current directory length is too long, try to work around the feeble Windows size limit by using the subst command
if ($currentDirInfo.Length -gt 248)
{
Write-Host "$currentDirInfo has a length of $($currentDirInfo.Length), greater than the maximum 248, invoking workaround"
$substDriveLetter = ls function:[d-z]: -n | ?{ !(test-path $_) } | select -First 1
$parentFolder = ($currentDirInfo.Substring(0,$currentDirInfo.LastIndexOf("\")))
$relative = $substDriveLetter+($currentDirInfo.Substring($currentDirInfo.LastIndexOf("\")))
write-host "Mapping $substDriveLetter to $parentFolder for access via $relative"
subst $substDriveLetter $parentFolder
$dirInfo = New-Object System.IO.DirectoryInfo $relative
}
else
{
$dirInfo = New-Object System.IO.DirectoryInfo $currentDirInfo
}
# add its details to the currentParentDirInfo object
$currentParentDirInfo.Files = @()
$currentParentDirInfo.Folders = @()
$currentParentDirInfo.SizeBytes = 0;
$currentParentDirInfo.Name = $dirInfo.Name;
$currentParentDirInfo.Type = "Folder";
# iterate all subdirectories
try
{
$dirs = $dirInfo.GetDirectories() | where {!$_.Attributes.ToString().Contains("ReparsePoint")}; #don't include reparse points
$files = $dirInfo.GetFiles();
# remove any drive mappings created via subst above
if (!($substDriveLetter -eq $null))
{
write-host "removing substitute drive $substDriveLetter"
subst $substDriveLetter /D
$substDriveLetter = $null
}
$dirs | % {
# create a new object for the subfolder to pass in
$subFolder = @{}
if ($_.Name.length -lt 1)
{
return;
}
# call this function in the subfolder. It will return after the entire branch from here down is traversed
buildDirectoryTree_Recursive $subFolder ($currentDirInfo + "\" + $_.Name);
# add the subfolder object to the list of folders at this level
$currentParentDirInfo.Folders += $subFolder;
# the total size consumed from the subfolder down is now available.
# Add it to the running total for the current folder
$currentParentDirInfo.SizeBytes= $currentParentDirInfo.SizeBytes + $subFolder.SizeBytes;
}
# iterate all files
$files | % {
# create a custom object for each file, containing the name and size
$htmlFileObj = @{};
$htmlFileObj.Type = "File";
$htmlFileObj.Name = $_.Name;
$htmlFileObj.SizeBytes = $_.Length
# add the file object to the list of files at this level
$currentParentDirInfo.Files += $htmlFileObj;
# add the file's size to the running total for the current folder
$currentParentDirInfo.SizeBytes= $currentParentDirInfo.SizeBytes + $_.Length
}
}
catch [Exception]
{
if ($_.Exception.Message.StartsWith('Access to the path'))
{
$currentParentDirInfo.Name = $currentParentDirInfo.Name + " (Access Denied to this location)"
}
else
{
Write-Host $_.Exception.ToString()
}
}
}
function bytesFormatter{
<#
.SYNOPSIS
Used internally by the TreeSizeHtml function.
Takes a number in bytes, and a string which must be one of B,KB,MB,GB,TB and returns a nicely formatted converted string.
.EXAMPLE
bytesFormatter -bytes 102534233454 -notation "MB"
returns "97,784 MB"
#>
param (
[Parameter(Mandatory=$true)][decimal][AllowNull()] $bytes,
[Parameter(Mandatory=$true)][String] $notation
)
if ($bytes -eq $null)
{
return "unknown size";
}
$notation = $notation.ToUpper();
if ($notation -eq 'B')
{
return ($bytes.ToString())+" B";
}
if ($notation -eq 'KB')
{
return (roundOffAndAddCommas($bytes/1024)).ToString() + " KB"
}
if ($notation -eq 'MB')
{
return (roundOffAndAddCommas($bytes/1048576)).ToString() + " MB"
}
if ($notation -eq 'GB')
{
return (roundOffAndAddCommas($bytes/1073741824)).ToString() + " GB"
}
if ($notation -eq 'TB')
{
return (roundOffAndAddCommas($bytes/1099511627776)).ToString() + " TB"
}
Throw "Unrecognised notation: $notation. Must be one of B,KB,MB,GB,TB"
}
function roundOffAndAddCommas{
<#
.SYNOPSIS
Used internally by the TreeSizeHtml function.
Takes a number and returns it as a string with commas as thousand separators, rounded to 2dp
#>
param(
[Parameter(Mandatory=$true)][decimal] $number)
$value = "{0:N2}" -f $number;
return $value.ToString();
}
function sbAppend{
<#
.SYNOPSIS
Used internally by the TreeSizeHtml function.
Shorthand function to append a string to the sb variable
#>
param(
[Parameter(Mandatory=$true)][string] $stringToAppend)
$sb.Append($stringToAppend) | out-null;
}
function outputNode_Recursive{
<#
.SYNOPSIS
Used internally by the TreeSizeHtml function.
Used to output the folder tree to a StringBuffer in the format of an HTML unordered list which the TreeView library can display.
.PARAMETER node
The current node object, a temporary custom object which represents the current folder in the tree.
#>
param (
[Parameter(Mandatory=$true)][Object] $node,
[Parameter(Mandatory=$true)][System.Text.StringBuilder] $sb,
[Parameter(Mandatory=$true)][int] $topFilesCountPerFolder,
[Parameter(Mandatory=$true)][int] $folderSizeFilterDepthThreshold,
[Parameter(Mandatory=$true)][long] $folderSizeFilterMinSize,
[Parameter(Mandatory=$true)][int] $CurrentDepth
)
# If there is more than one subfolder from this level, sort by size, largest first
if ($node.Folders.Length -gt 1)
{
$folders = $node.Folders | Sort -Descending {$_.SizeBytes}
}
else
{
$folders = $node.Folders
}
# iterate each subfolder
for ($i = 0; $i -lt $node.Folders.Length; $i++)
{
$_ = $folders[$i];
# append to the string buffer a HTML List Item which represents the properties of this folder
$size = bytesFormatter $_.SizeBytes $displayUnits
$name = $_.Name.replace("'","\'")
sbAppend "<li><span class='folder'>$name ($size)</span>"
sbAppend "<ul>"
if ($name -eq "winsxs")
{
sbAppend "<li><span class='folder'>Contents of folder hidden as <a href='http://support.microsoft.com/kb/2592038'>winsxs</a> commonly contains tens of thousands of files</span></li>"
}
elseif ($folderSizeFilterDepthThreshold -le $CurrentDepth -and $_.SizeBytes -lt $folderSizeFilterMinSize)
{
sbAppend "<li><span class='folder'>Contents of folder hidden via size filter</span></li>"
}
else
{
# call this function in the subfolder. It will return after the entire branch from here down is output to the string buffer
outputNode_Recursive $_ $sb $topFilesCountPerFolder $folderSizeFilterDepthThreshold $folderSizeFilterMinSize ($CurrentDepth+1);
}
sbAppend "</ul>"
sbAppend "</li>"
}
# If there is more than one file on level, sort by size, largest first
if ($node.Files.Length -gt 1)
{
$files = $node.Files | Sort -Descending {$_.SizeBytes}
}
else
{
$files = $node.Files
}
# iterate each file
for ($i = 0; $i -lt $node.Files.Length; $i++)
{
if ($i -lt $topFilesCountPerFolder)
{
$_ = $files[$i];
# append to the string buffer a HTML List Item which represents the properties of this file
$size = bytesFormatter $_.SizeBytes $displayUnits
$name = $_.Name.replace("'","\'")
sbAppend "<li><span class='file'>$name ($size)</span></li>"
}
else
{
$remainingFilesSize = 0;
while ($i -lt $node.Files.Length)
{
$remainingFilesSize += $files[$i].SizeBytes
$i++;
}
$size = bytesFormatter $_.SizeBytes $displayUnits
$name = "..."+($node.Files.Length-$topFilesCountPerFolder)+" more files"
sbAppend "<li><span class='file'>$name ($size)</span></li>"
}
}
}
TreeSizeHtml -paths "ALL" -reportOutputFolder "C:\Logs\Disk Usage Reports" -zipOutputFilename "Disk-Usage-Reports-$(Get-Date -Format 'yyyy-MM-ddTHHmm').Zip"
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T17:31:31.787",
"Id": "512872",
"Score": "0",
"body": "**1.** [Avoid `Out-Null` cmdlet](https://powershell-guru.com/powershell-best-practice-12-avoid-out-null/); **2.** Why do you repeat expensive operations in `function bytesFormatter`? Don't pass `$notation`, check it _before_ all loops; moreover, compute there `$divisor = 1*('1' + ($notation -replace '^B', ''));` and then compute `$notation = ' ' + $notation.ToUpper();` Then, the function body reduces to `if ($bytes -eq $null) { \"unknown size\";} else { (roundOffAndAddCommas($bytes/$divisor)).ToString() + $notation }`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T17:53:35.783",
"Id": "512875",
"Score": "0",
"body": "(continued). Then the `roundOffAndAddCommas` function becomes unnecessary at all (as called from the only code line). **3.** Not sure whether passing so much parameters to the `outputNode_Recursive` e.g. `$sb` or always constant `$topFilesCountPerFolder`, `$folderSizeFilterDepthThreshold` and `$folderSizeFilterMinSize`. I'd omit those at all. **4.** More to read and follow at https://powershell-guru.com/ and [Slow Code: Top 5 …](https://docs.microsoft.com/en-gb/archive/blogs/ashleymcglone/slow-code-top-5-ways-to-make-your-powershell-scripts-run-faster#problem-1-expensive-operations-repeated)"
}
] |
[
{
"body": "<p>Your primary performance problem is due to this pattern:</p>\n<pre><code>$Set = 1..10000\n$Array = @()\nforeach ($i in $Set) { $Array += $i }\n</code></pre>\n<p>This is an awful pattern whether you're concatenating arrays or strings, because both of those are immutable in .Net. That means when you <code>+=</code> an element to an array (or string), the system creates a brand new array one larger and copies over every element then deletes the old array. It's a tremendous amount of memory I/O. A good rule of thumb is: <strong>The <code>+=</code> operator is usually wrong</strong>.</p>\n<p>There are two better patterns:</p>\n<h3>Assign the loop itself as the value</h3>\n<p>This is the preferred pattern. It requires no initialization, and it generally forces you to think and work in a way that favors how Powershell works. However, this isn't always the easiest to make work in complex loops.</p>\n<pre><code>$Set = 1..10000\n$Array = foreach ($i in $Set) { $i }\n</code></pre>\n<h3>Use a mutable collection</h3>\n<p>This is easier to refactor. The easiest collection to use is the <code>ArrayList</code>. You can get further gains using a typed <code>System.Collections.Generic.List</code> for arbitrary object or a <code>StringBuilder</code> for strings (which you have done) but an <code>ArrayList</code> will work.</p>\n<pre><code>$Set = 1..10000\n$Array = New-Object -TypeName System.Collections.ArrayList\nforeach ($i in $Set) { $Array.Add($i) }\n</code></pre>\n<p>Compare the performance:</p>\n<pre><code>$Set = 1..10000\n\nMeasure-Command {\n$Array = @()\nforeach ($i in $Set) { $Array += $i }\n} | Select-Object -ExpandProperty TotalMilliseconds\n\nMeasure-Command {\n$Array = foreach ($i in $Set) { $i }\n} | Select-Object -ExpandProperty TotalMilliseconds\n\nMeasure-Command {\n$Array = New-Object -TypeName System.Collections.ArrayList\nforeach ($i in $Set) { $Array.Add($i) }\n} | Select-Object -ExpandProperty TotalMilliseconds\n</code></pre>\n<p>The first command completes in ~2400 ms on my old and busted laptop. The second completes in 17 ms (140 times faster) and the last one completes in 23 ms (100 times faster). That's with only 10,000 integers, which are a very small object in memory.</p>\n<hr />\n<p>As a general criticism, I would strongly, <em>strongly</em> recommend that you move beyond targetting Powershell 2. The last operating system that supported that version of Powershell is Windows Server 2008 R2, and that has been out of extended support for over a year at this point. Nobody should be using Powershell 2 anywhere anymore. The fact that this script uses <code>Get-WmiObject</code> in order to support Powershell v2 instead of <code>Get-CimInstance</code> means that by targeting Powershell v2 you're excluding Powershell v6+.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T15:20:42.900",
"Id": "260074",
"ParentId": "259887",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T02:12:36.633",
"Id": "259887",
"Score": "3",
"Tags": [
"performance",
"powershell"
],
"Title": "Disk usage reporting script performing poorly with lots of files"
}
|
259887
|
<p>I have a set of Italian words in a <code>txt</code> file hosted on GitHub.
I use it as stopwords vocabulary for further NLP tasks.</p>
<p>When I dump from GitHub it returns me, obviously, also <code>\n</code></p>
<p>Better or more efficient way to replace the special character compared with my working code?</p>
<pre><code>import urllib.request
stopwords_link = "https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt"
file_name = urllib.request.urlopen(stopwords_link)
list_nowords = [x.decode("utf-8") for x in file_name]
splitted = [x.split('\n')[0] for x in list_nowords]
</code></pre>
<p>As usual I am a self-taught and this is the best place where I can learn, discover new ways and aspects on how to code efficiently with Python</p>
|
[] |
[
{
"body": "<p>Code is very readable, and that's a good start.</p>\n<p><code>file_name</code> is in fact the file_content; <code>splitted</code> (split) should be just <code>stop_words</code>; <code>stopwords_list</code> is a constant, so by PEP 8, should be uppercase <code>STOPWORDS_LIST</code>.</p>\n<p>The problem I see here is that you are decoding each word, when in fact you should decode the whole file, just once.</p>\n<p>This is just personal preference, but I tend to always use the <code>requests</code> library, because, in my experience, is always a step ahead of what I need. <code>requests</code> tries to understand the encoding, based on the response, so there should be no need to decode.</p>\n<p>A bit of data validation is also needed. The file could have been moved, the network or Github could be down, so it always better to be prepared for the worse. In this case, if the network is down (Connection Timeout) or the file is not there (404) there isn't a big difference: your application should handle the exception and the execution should not proceed.\nWhile a connection timeout would normally raise an exception, a 404 (or any other HTTP error) would still be considered a valid HTTP response, that's why <code>requests</code> has a handy method when you just want 2** responses: <code>raise_for_status</code>.</p>\n<p>Then, to remove the <code>\\n</code> there is actually the method <code>splitlines()</code> which is exactly what you need.</p>\n<pre><code>import requests\n\nSTOPWORDS_LIST= "https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt"\n\ntry:\n response = requests.get(STOPWORDS_LIST)\n response.raise_for_status() \n file_content = response.text\n words = file_content.splitlines()\nexcept Exception as e:\n print(f"There was an error: {str(e)}")\n\n\n\n</code></pre>\n<p>This piece of code should put inside a function, so it is clearer what it does and restrict its scope. I'm also adding a type to the function, that can be useful to avoid errors at compile time. Maybe some day you will have stopwords in other languages, so I'm just writing a main as example.</p>\n<pre><code>from typing import List\n\nimport requests\n\n\ndef download_stop_words(url: str) -> List[str]:\n try:\n response = requests.get(url)\n response.raise_for_status()\n return response.text.splitlines()\n except Exception as e:\n print(f"There was an error: {str(e)}")\n\nif __name__ == '__main__': # this avoids the program being executed when the module is imported \n STOP_WORDS = {\n "it": "https://raw.githubusercontent.com/stopwords-iso/stopwords-it/master/stopwords-it.txt"\n }\n for lang, url in STOP_WORDS.items():\n stop_words = download_stop_words(url)\n print(f"In '{lang}' there are {len(stop_words)} stop words")\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T07:58:01.747",
"Id": "512925",
"Score": "0",
"body": "no, it wasn't part of a biggere piece of code :D It was just a basic Colab Notebook for practice with Natural Language Processing. What should be \"main scope check\" (I don't have testing knowledge and I started a course about it)? Thank you for your time and energy :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T12:26:53.403",
"Id": "513016",
"Score": "0",
"body": "Hi @AndreaCiufo I've updated the answer, putting the code in a function and with a main as example."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T09:37:05.307",
"Id": "259896",
"ParentId": "259895",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "259896",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T09:04:30.750",
"Id": "259895",
"Score": "4",
"Tags": [
"python",
"performance"
],
"Title": "Remove \\n newline from a list of string dumped from github used for a Italian stopwords vocabulary"
}
|
259895
|
<p>I'm making a top-down dungeon minigame where you are a knight and can attack zombies by swinging a sword.
So far I haven't implemented collision, player <code>rect()</code>, enemy <code>rect()</code>, a game over screen, or the player sword animation, but all the code I have so far is working well, even though the main loop is crowded.
I was wondering how I could either condense the code or streamline it?</p>
<pre><code>import pygame, random, os
from pygame.locals import *
pygame.init()
scr_width = 1020
scr_height = 510
screen = pygame.display.set_mode((scr_width, scr_height))
pygame.display.set_caption('Dungeon Minigame')
clock = pygame.time.Clock()
images = {}
path = 'Desktop/Files/Dungeon Minigame/'
filenames = [f for f in os.listdir(path) if f.endswith('.png')]
for name in filenames:
imagename = os.path.splitext(name)[0]
images[imagename] = pygame.image.load(os.path.join(path, name))
font = pygame.font.SysFont('Times_New_Roman', 27)
white = [240, 240, 240]
def main_menu():
onclick = False
while True:
mx, my = pygame.mouse.get_pos()
screen.blit(images['background'], (0, 0))
button = screen.blit(images['button'], (480, 300))
if button.collidepoint((mx, my)):
if onclick:
game()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == MOUSEBUTTONDOWN:
onclick = True
pygame.display.update()
clock.tick(60)
def game():
lives = 3
score = 0
def player(x, y):
screen.blit(images['r_knight'], (playerX, playerY))
class Enemy:
def __init__(self):
self.x = random.randint(8, 800)
self.y = random.randint(8, 440)
self.moveX = 0
self.moveY = 0
def move(self, speed = 1):
if self.x > playerX:
self.x -= speed
elif self.x < playerX:
self.x += speed
if self.y < playerY:
self.y += speed
elif self.y > playerY:
self.y -= speed
def draw(self):
screen.blit(images['r_zombie'], (self.x, self.y))
def enemy(x, y):
screen.blit(images['r_zombie'], (x, y))
enemy_list = []
for i in range(4):
new_enemy = Enemy()
enemy_list.append(new_enemy)
playerX = 510
playerY = 220
while True:
screen.blit(images['background'], (0, 0))
score_text = font.render('Score: ' + str(score), True, white)
lives_text = font.render('Lives: ', True, white)
screen.blit(score_text, (20, 20))
screen.blit(lives_text, (840, 20))
screen.blit(images['r_knight'], (playerX, playerY))
if lives == 3:
screen.blit(images['triple_heart'], (920, 0))
if lives == 2:
screen.blit(images['double_heart'], (920, 0))
if lives == 1:
screen.blit(images['single_heart'], (920, 0))
if lives <= 0:
screen.blit(images['triple_empty_heart'], (920, 0))
if lives < 0:
lives = 0
onpress = pygame.key.get_pressed()
if onpress[pygame.K_a]:
playerX -= 3
screen.blit(images['l_knight'], (playerX, playerY))
if onpress[pygame.K_w]:
playerY -= 3
screen.blit(images['l_knight'], (playerX, playerY))
if onpress[pygame.K_d]:
playerX += 3
screen.blit(images['r_knight'], (playerX, playerY))
if onpress[pygame.K_s]:
playerY += 3
screen.blit(images['r_knight'], (playerX, playerY))
if onpress[pygame.K_w] and onpress[pygame.K_a]:
screen.blit(images['l_knight'], (playerX, playerY))
if onpress[pygame.K_s] and onpress[pygame.K_a]:
screen.blit(images['l_knight'], (playerX, playerY))
if onpress[pygame.K_w] and onpress[pygame.K_d]:
screen.blit(images['r_knight'], (playerX, playerY))
if onpress[pygame.K_s] and onpress[pygame.K_d]:
screen.blit(images['r_knight'], (playerX, playerY))
if playerX <= -8:
playerX = -8
elif playerX >= 965:
playerX = 965
if playerY <= 5:
playerY = 5
elif playerY >= 440:
playerY = 440
for enemy in enemy_list:
enemy.move()
enemy.draw()
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
clock.tick(60)
pygame.display.update()
main_menu()
</code></pre>
<p><a href="https://i.stack.imgur.com/yJ8eW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/yJ8eW.png" alt="Output" /></a></p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T14:37:45.540",
"Id": "512860",
"Score": "2",
"body": "Welcome to Code Review. I have rolled back your last edit. Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*."
}
] |
[
{
"body": "<h1>Streamlining blitting of the player</h1>\n<p>You did a good job in realising you can streamline some of your code, because you have some patterns that are repeated over and over again. That is always a good indication that something shorter can be done.</p>\n<p>Taking a look at the series of <code>if</code>s you have to blit the correct images, here is a possible suggestion to make it more condensed, like you say.</p>\n<h2>Compute player position changes</h2>\n<pre class=\"lang-py prettyprint-override\"><code># ...\nonpress = pygame.key.get_pressed()\n\ndx = 0\nif onpress[pygame.K_a]:\n dx -= 3\nif onpress[pygame.K_d]:\n dx += 3\nplayerX += dx\n\ndy = 0\nif onpress[pygame.K_w]:\n dy -= 3\nif onpress[pygame.K_s]:\n dy += 3\nplayerY += dy\n</code></pre>\n<h2>Blit knight afterwards</h2>\n<p>Notice that your code has 8 <code>if</code> that are not exclusive, so if at a certain point in time the player is pressing down on <code>AWSD</code> at the same time, your game will make a total of eight blits on top of each other, which is unnecessary.</p>\n<p>If you compute the position changes like I showed above, or in any other way you prefer, then you can use <code>dx</code> and <code>dy</code> to decide which player image to blit.\nFor example, you can just look at <code>dx</code> that tells you if the player moved left or right, and blit accordingly:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if dx > 0:\n screen.blit(images['r_knight'], (playerX, playerY))\nelif dx < 0:\n screen.blit(images['l_knight'], (playerX, playerY))\n</code></pre>\n<p><strong>Attention</strong>: The code I shared is <em>not</em> strictly equivalent to yours and I took the liberty of interpreting your <em>intentions</em>, please let me know if my interpretation is wrong.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T14:26:37.913",
"Id": "512858",
"Score": "0",
"body": "Is there a way I can implement the Player controls into a class? maybe using `self.x` and `self.y` instead of dx and dy? @RGS"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T14:35:08.513",
"Id": "512859",
"Score": "0",
"body": "@Zelda you mean only the controls, or the whole player entity?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T14:45:51.240",
"Id": "512861",
"Score": "0",
"body": "The whole player entity, but include the controls as later I need to add an animation to said player class. The images are already loaded in the `for name in filenames():` function. The class would define the player's current position, then after a wsad input, change those values and have an update function to blit it to the screen."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T12:15:12.513",
"Id": "512935",
"Score": "0",
"body": "@Zelda You can definitely do so, if you need some inspiration I have two minigames on [this repo](https://github.com/RojerGS/minigames) where I have used WASD for player movement inside a player class, the `agarIO` and the `dumbfire` ones. The [pigeon one](https://github.com/RojerGS/minigames/blob/master/pigeon-simulator/pigeon.py#L81) also defines a class for the player entity. Give it your best shot and then post your new code here so we can review it :)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T13:17:15.207",
"Id": "259901",
"ParentId": "259900",
"Score": "2"
}
},
{
"body": "<h1>Loading images with <code>pathlib</code></h1>\n<p>Currently, you are loading your images like so:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\n\nimages = {}\npath = 'Desktop/Files/Dungeon Minigame/'\nfilenames = [f for f in os.listdir(path) if f.endswith('.png')]\nfor name in filenames:\n imagename = os.path.splitext(name)[0]\n images[imagename] = pygame.image.load(os.path.join(path, name))\n</code></pre>\n<p>If you turn to <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a>, which I understand to be the more modern alternative to <code>os.path</code>, you see you can rewrite your image loading as such:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pathlib\n\nimages = {}\npath = pathlib.Path('Desktop/Files/Dungeon Minigame/')\nfor img_path in path.glob("*.png"):\n images[img_path.name] = pygame.image.load(img_path)\n</code></pre>\n<p>or perhaps even a bit shorter if you don't need the original path anywhere else:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import pathlib\n\nimages = {}\nfor img_path in pathlib.Path('Desktop/Files/Dungeon Minigame/').glob("*.png"):\n images[img_path.name] = pygame.image.load(img_path)\n</code></pre>\n<p>Notice that shorter isn't always better, I am just trying to avoid creating too many variables that are used just once.</p>\n<p>However, if you end up having to load many resources from that same folder, you probably want to declare it as a variable in all CAPS LOCK (which is the universal way to signal a constant, global variable) and then use it in the loop to load images and elsewhere.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T12:25:02.690",
"Id": "259935",
"ParentId": "259900",
"Score": "1"
}
},
{
"body": "<h1>Clipping player position</h1>\n<p>There are a couple of places where you do an operation that is fairly common, which is to ensure a value <code>v</code> is between a lower bound <code>l</code> and an upper bound <code>u</code>, and forcing <code>v</code> to be there if it isn't. This is commonly referred to as clipping, and you do it in a couple of places (more prominently, when dealing with the player position) so you can actually create a short function to do so for you, which makes the rest of the code more to-the-point.</p>\n<p>What we want to do is shorten this code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if playerX <= -8:\n playerX = -8\nelif playerX >= 965:\n playerX = 965\n\nif playerY <= 5:\n playerY = 5\nelif playerY >= 440:\n playerY = 440\n</code></pre>\n<p>For example, if you <a href=\"https://pypi.org/project/clip-values/\" rel=\"nofollow noreferrer\">install <code>clip_values</code></a>, you can do</p>\n<pre class=\"lang-py prettyprint-override\"><code>from clip_values import clip\nplayerX = clip(playerX).between_(-8).and_(965)\nplayerY = clip(playerY).between_(5).and_(440)\n</code></pre>\n<p>If you don't want to install anything, you can also do something like</p>\n<pre class=\"lang-py prettyprint-override\"><code>def clip(value, lower, upper):\n return min(upper, max(value, lower))\n</code></pre>\n<p>which is then used as follows:</p>\n<pre class=\"lang-py prettyprint-override\"><code>playerX = clip(playerX, -8, 965)\nplayerY = clip(playerY, 5, 440)\n</code></pre>\n<h1>Clipping the lives</h1>\n<p>Now that you have this <code>clip</code> function, you can actually take a look at this:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if lives == 3:\n screen.blit(images['triple_heart'], (920, 0))\n\n if lives == 2:\n screen.blit(images['double_heart'], (920, 0))\n\n if lives == 1:\n screen.blit(images['single_heart'], (920, 0))\n\n if lives <= 0:\n screen.blit(images['triple_empty_heart'], (920, 0))\n if lives < 0:\n lives = 0\n</code></pre>\n<p>The way this code is written makes it look like the user always has between 0 and 3 lives, and then you want to blit the appropriate image of the lives the user has.\nIf you start by clipping the number of lives to be in <code>[0, 1, 2, 3]</code>, you can then determine <em>programmatically</em> the image to blit:</p>\n<pre class=\"lang-py prettyprint-override\"><code>heart_images = ["triple_empty_heart", "single_heart", "double_heart", "triple_heart"]\nlives = clip(lives).between_(0).and_(3)\nscreen.blit(images[heart_images[lives]], (920, 0))\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:22:58.377",
"Id": "512964",
"Score": "0",
"body": "Ok, sorry I fixed all the code that I have so far and I'm working on the sword animation :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T19:31:14.173",
"Id": "512983",
"Score": "0",
"body": "@Zelda alright, good luck. I just edited to add another clipping alternative that is maybe easier to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T19:36:35.543",
"Id": "512985",
"Score": "1",
"body": "I understood the earlier code"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T12:31:55.567",
"Id": "259937",
"ParentId": "259900",
"Score": "1"
}
},
{
"body": "<h1>Use GLOBALS for constant settings, positions, etc.</h1>\n<p>In Python we do not have syntax to declare a variable that is no longer allowed to change, but amongst the community it is very well understood that CAPS LOCK variables are to be seen as constants, i.e., variables that will never change.</p>\n<p>So, your variables that you create and should not be changed could actually be defined in upper case, e.g. <code>SCR_WIDTH</code> and <code>SCR_HEIGHT</code>.</p>\n<p>Furthermore, throughout your code you have "magic numbers" here and there, which are numbers you have determined but that from reading the code it is not clear how they arose. For example, you always make sure the player position in the X axis remains between <code>-8</code> and <code>965</code>, but why those values..?\nNot only that, but those "magic" numbers tend to appear in more than one place, so if you change one, you have to look for all the occurrences of that number to change it again.\nWhat is more, what happens if two or more magic numbers happen to be the same?! Code becomes really confusing.</p>\n<p>Therefore, it is advisable that you take all such magic numbers and/or constants, and give them names. For example, I like to have my constants for the game in the beginning of the script. Looking at your code, these are just some examples of things I would move to the beginning:</p>\n<pre class=\"lang-py prettyprint-override\"><code>SCR_WIDTH, SCR_HEIGHT = 1024, 512\nWHITE = [240, 240, 240]\nPLAYER_LIVES_POSITION = (920, 0)\nPLAYER_X_BETWEEN = (-8, 965)\nPLAYER_Y_BETWEEN = (5, 440)\nENEMY_X_BETWEEN = (8, 800)\nENEMY_Y_BETWEEN = (8, 440)\nFPS = 60\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T12:40:50.020",
"Id": "259939",
"ParentId": "259900",
"Score": "2"
}
},
{
"body": "<h1>Create a Player class</h1>\n<p>The player has a fair amount in common with your zombies:</p>\n<ol>\n<li>There is logic to <code>move()</code> the Player.</li>\n<li>Players and monsters both have a blittable image.</li>\n<li>Players and monsters both have a "facing" direction.</li>\n<li>Players and monsters both have a speed of movement.</li>\n</ol>\n<p>There's enough there to form a base class:</p>\n<pre><code>class Mobile:\n def __init__(self, **kwargs):\n self.x = kwargs['x']\n self.y = kwargs['y']\n self.speed = kwargs['speed']\n self.facing = kwargs['facing']\n self.images = ...\n\n def move(self): ...\n\n def draw(self):\n screen.blit(self.images[self.facing], (self.x, self.y))\n</code></pre>\n<p>The <code>.move()</code> for Monsters and Players is obvious different -- monsters will just pursue the player, as you have coded. The Player's <code>move()</code> can contain the logic you have to check the pressed keys and to clamp the position, although I think that you are adjusting the position, then drawing the image, <em>then</em> clamping the position, which seems like a bug.</p>\n<h1>Break your code into functions and methods</h1>\n<p>Make it explicit what is being done. Pass whatever arguments you need to pass.</p>\n<p>I would rewrite your main loop like this:</p>\n<pre><code>mobiles = [Player(), *[Monster() for _ in range(4)]]\nstill_playing = True\n\nwhile still_playing:\n\n draw_background()\n\n for mob in mobiles:\n mob.move()\n mob.draw()\n\n still_playing = was_quit_pressed()\n\n pygame.display.update()\n clock.tick(60)\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T00:25:29.103",
"Id": "259966",
"ParentId": "259900",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259939",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T12:56:19.653",
"Id": "259900",
"Score": "8",
"Tags": [
"python",
"classes",
"pygame"
],
"Title": "Top-Down Dungeon RPG"
}
|
259900
|
<p>I am teaching myself c++ by doing a series of exercises.
I liked the idea of working out how hash tables could be done using just the language
and no std calls. I discovered that you cant do
"class member function partial template specialisation" and so worked on options for
how this would be achieved.
The code below is a stripped down version of the useful parts of a hash table.
Leaving just enough to show the structure of what is needed.</p>
<p>Is there a better way to construct the class - IE a better idiom to solve partial specialisation?</p>
<p>I have tried full class specialisation and struct partial template specialisation
but this seems the best so far.</p>
<p>I would be interested in comments about other ways to call the members and fuctions.
I have thought of:</p>
<ol>
<li>A 'using' line for all the members/function in the fuctions.</li>
<li>One 'using' line to create a typedef that can be used as the prefix.</li>
<li>Putting the full cast at each use.</li>
</ol>
<pre><code>#include "stdio.h"
template <typename K, typename H>
class hash_table_common {
public:
H& hash_type() // Standard CRTP helper function
{
return static_cast<H&>(*this);
}
int& operator[](K key)
{
return hash_type().get_value(key);
}
size_t hash(int key)
{
return key % 10;
}
int m_storage[10]{ 0 };
};
template <typename K>
class hash_table : public hash_table_common<K, hash_table<K>> {
public:
class hash_table_common<K, hash_table<K>>& hash_type()
{
return static_cast<hash_table_common<K, hash_table<K>>&>(*this);
}
int& get_value(K key)
{
int hashable = 3; // value_to_int(); Real code will go here, for this demo it works for one value!
int index1 = hash_type().hash(hashable);
return hash_type().m_storage[index1];
}
};
template <>
class hash_table<const char*> : public hash_table_common<const char*, hash_table<const char*>> {
public:
class hash_table_common<const char*, hash_table<const char*>>& hash_type()
{
return static_cast<hash_table_common<const char*, hash_table<const char*>>&>(*this);
}
int& get_value(const char* key)
{
int hash_as_int = (int)key[0];
int index = hash_type().hash(hash_as_int);
return hash_type().m_storage[index];
}
};
#endif
int main() {
class hash_table<const char*> a;
class hash_table<float> b;
a["word"] = 3;
b[4.5f] = 14;
printf("%d %d", a["word"], b[4.5f]);
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:43:58.740",
"Id": "512887",
"Score": "2",
"body": "Here, we review *complete, finished* code. We don't want to see a \"stripped down\" version (unlike [so], for example). You'll get better reviews if you show the full code in context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:46:30.387",
"Id": "512888",
"Score": "0",
"body": "@TobySpeight Thanks so much. Sorry about this I was advised on stackoverflow that I should have posted it here. Sorry. Do I just delete this now?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T19:51:56.510",
"Id": "512892",
"Score": "1",
"body": "If you want a full code review (to improve _any_ aspect of the code), then I suggest you [edit] to replace with the complete code (don't worry if it's big - you're unlikely to exceed the size limit here). If you're not open to general review, you could choose to delete."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T10:56:41.047",
"Id": "512931",
"Score": "0",
"body": "@TobySpeight Thanks, I might do that as it would be good to get comments, but the full thing is not all done yet. I know most of what I want to do, but I have not coding it all yet. I will do so when I am done. Thanks again for the guidance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T11:44:43.263",
"Id": "512934",
"Score": "0",
"body": "What problem is this solving? Why not do the same thing that [`std::unordered_map`](https://en.cppreference.com/w/cpp/container/unordered_map) does, have defaulted template parameters for things like the hash function?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T12:41:08.280",
"Id": "512936",
"Score": "1",
"body": "Deleting a question doesn't remove it from the database and you can un-delete it when the question is finished. If you change the title to indicate what the code does and finish coding it will be a very good question for the code review site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T14:01:16.820",
"Id": "512949",
"Score": "0",
"body": "@G.Sliepen Yes that is what is it mimicking - it is certainly not going to do it better! This is a study to learn C++ and hopeful be able to have the idiom available when other algorithms need it. This is the minimum example I can make that shows a need for partial specialisation of functions in a templated class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T14:04:23.150",
"Id": "512950",
"Score": "0",
"body": "Thanks @pacmaninbw Thanks. I will do that when I finish up all the code. I have been thinking that the code that implements std functions is not very easy to understand as a newbie and thus not a great learning tool. Showing code for one of the key apis, like vector and map in a series of stages increase the complexity and explaining the coding reasons would be awesome."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T16:39:39.987",
"Id": "259908",
"Score": "0",
"Tags": [
"c++",
"hash-map",
"template",
"classes"
],
"Title": "Is this a good way to construct the class for a C++ template partial specialisation of a member function?"
}
|
259908
|
<p>I have an event handler function which every time is triggered should clear a <code>setTimeout()</code> and set a new timeout.</p>
<p>Now the callback for the timeout has to take few arguments, for example the event object received by the handler.</p>
<p>And that's it. I did it, but I believe that my solution is not optimal, nor the cleanest:</p>
<pre class="lang-js prettyprint-override"><code>
let timer;
const handler = (event, type) => {
clearTimeout(timer);
if(type === 'CHANGE') timer = setTimeout(callback, 500, { argumentsForTheCallBack });
}
</code></pre>
<p>As you can see I have my <code>timer</code> as a global variable, even though I need it only in the event handler.</p>
<p>Is there a way to make the handler self-contained?</p>
<p>I am interested in ECMAScript solutions as well as solution using React.js syntax (in my original code the callback is a dispatcher for a <code>useReducer</code> hook)</p>
|
[] |
[
{
"body": "<p>Since you mention <code>useReducer</code> React hook I will assume you are using a functional component and thus can use other React hooks.</p>\n<p>I suggest:</p>\n<ol>\n<li>Use a React ref to hold a reference to the timer (versus global variable).</li>\n<li>Use an <code>useEffect</code> hook to clear any running timeouts in the case the component unmounts before the timeout expires. Provide an empty dependency array so the effect callback is called only once. Here it is just to return the cleanup function to clear any running timeouts.</li>\n</ol>\n<p>Code:</p>\n<pre><code>import { useEffect, useRef } from 'react';\n\n...\n\n// in component\nconst timerRef = useRef(null);\n\nuseEffect(() => {\n return () => clearTimeout(timerRef.current);\n}, []);\n\nconst handler = (event, type) => {\n clearTimeout(timerRef.current);\n\n if (type === 'CHANGE') {\n timerRef.current = setTimeout(callback, 500, { argumentsForTheCallBack });\n }\n}\n</code></pre>\n<h1>Why provide cleanup function from <code>useEffect</code>?</h1>\n<p>If you attempt to update state of an unmounted component you'll get a React warning stating:</p>\n<blockquote>\n<p>Warning: Can’t perform a React state update on an unmounted component.\nThis is a no-op, but it indicates a memory leak in your application.\nTo fix, cancel all subscriptions and asynchronous tasks in a useEffect\ncleanup function.</p>\n</blockquote>\n<p>It's <em>just</em> a warning though, so if you are ok with the warning in non-production builds and you know you don't actually have a memory leak (open sockets, connections, subscriptions, etc...) then you can likely safely ignore them.</p>\n<p>In general you should strive to write code that doesn't generate warnings though, and this is a warning that is easily preventable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:41:37.167",
"Id": "512948",
"Score": "1",
"body": "Thanks for the answer. I am fairly new to React and as far as I know this `useEffect` with an empty array as dependency should run only one time, when the app starts running. What am I missing?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:43:00.753",
"Id": "512966",
"Score": "1",
"body": "@SheikYerbouti Yes, that is exactly the intention. I updated answer to provide this additional information for clarity and purpose."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:53:29.590",
"Id": "512970",
"Score": "0",
"body": "So the only purpose of this `useEffect` is *to clear any running timeouts in the case the component unmounts before the timeout expires*? In my case the timeout triggers a new state for `useReduce` (the state keeps track of whether username and password entered so far are valid) . Should I really care if the component unmounts (whatever it means) before the timeout expires?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T18:02:45.670",
"Id": "512971",
"Score": "1",
"body": "@SheikYerbouti Added response to your follow-on question in an update in my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T18:11:43.967",
"Id": "512973",
"Score": "1",
"body": "Thank you very much for the explanation. Now I got that I should clear any asynchronous task, but wasn't the `useEffect` executed only once at the beginning? Is it automatically called again when the component unmounts? And if yes, is this true only for `useEffect`s with an empty array as dependency?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T18:17:32.927",
"Id": "512974",
"Score": "1",
"body": "@SheikYerbouti In this case, yes, the `useEffect` hook is called at the end of the initial render, and the effect cleanup will be called when the component unmounts. Generally, the cleanup function is called at the end of the render cycle before the component is rerendered (to clean up any effects from the previous render) or when the component is unmounting. The effect with empty dependency and returned cleanup function is roughly equivalent to the `componentDidMount` and `componentWillUnmount` lifecycle methods. See https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T18:21:22.830",
"Id": "512975",
"Score": "0",
"body": "Thank you again! You are a great teacher!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T18:22:19.033",
"Id": "512976",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/123389/discussion-between-drew-reese-and-sheik-yerbouti)."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T05:52:36.193",
"Id": "259926",
"ParentId": "259910",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259926",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T17:39:08.217",
"Id": "259910",
"Score": "3",
"Tags": [
"javascript",
"react.js"
],
"Title": "Setting and clearing setTimeout() inside of an event handler"
}
|
259910
|
<p>My objective with this code was to create a class and call it from other .py files. The code itself is working, but I would like to know what could be improved or be better implemented.</p>
<p>I wrote another program just to call this class and its methods and it worked. I'm using functions that will only work on Windows because this is an exercise, not production code. My code has only one class (<code>StudingClassFirstTime</code>) and 13 methods. It is using the external library <a href="https://pynacl.readthedocs.io/en/latest/" rel="nofollow noreferrer">PyNaCl</a>.</p>
<pre><code>import getpass # Allow user input a password without echo it on terminal
import os # To be able to use os.system('cls')
from nacl import pwhash, secret, utils, exceptions # Encrypt functions to be used
class StudingClassFirstTime:
# Constructor mode: Here I will define the KDF (argon2id) parameters that will be used by default
def __init__(self, kdf=pwhash.argon2id.kdf,
ops=pwhash.argon2id.OPSLIMIT_SENSITIVE,
mem=pwhash.argon2id.MEMLIMIT_SENSITIVE,
size=secret.SecretBox.KEY_SIZE):
self.kdf = pwhash.argon2id.kdf
self.ops = pwhash.argon2id.OPSLIMIT_SENSITIVE
self.mem = pwhash.argon2id.MEMLIMIT_SENSITIVE
self.size = secret.SecretBox.KEY_SIZE
# Load an encryption key stored on file
# This file should have only one encryption key inside it
# If you have one file.key, you can encrypt as many files as you want, but, all of them will use the very same key
# If you encrypt the same file twice with the same key, the output will not be equal thanks to NONCE
def load_key(self, key_file):
with open(key_file, 'rb') as my_key:
key_of_file = my_key.read()
return key_of_file
# Generate an encryption key and return it's value(key)
def generate_key(self):
self.salt = utils.random(pwhash.argon2id.SALTBYTES) # 16 bytes == 128 bits
password = self.password() # Ask a user to input a password
key = self.kdf(self.size, password, self.salt, opslimit=self.ops, memlimit=self.mem)
return key # Key have 32 bytes == 256 bits
# Generate a raw 256 bits (32 bytes) as a key
# Do not need any user password, or KDF function
def generate_key_file(self):
password = utils.random(32) # 32 bytes == 256 bits
file_key = secret.SecretBox(password).encode()
return file_key
# Generate a encryption key and write it to a file
def write_key_file(self, key_file):
key = self.generate_key_file()
with open(key_file, 'ab') as my_key:
if os.path.getsize(key_file) > 0: # Check if the file have more than 0 bytes
my_key.write(b'\n' + key_file) # If positive, first add a new line, then, write the key
else: # If negative, just write the key, without add new line
my_key.write(key_file)
# Encrypt a message, generating an encryption key based on password.
# The key will not be write to file.
def encrypt(self, message):
encrypt_key = self.generate_key()
encrypt_box = secret.SecretBox(encrypt_key)
encrypted = encrypt_box.encrypt(message)
assert len(encrypted) == len(message) + encrypt_box.NONCE_SIZE + encrypt_box.MACBYTES # NONCE_SIZE == 24 bytes // MACBYTES == 16 bytes
return self.salt + encrypted
# Encrypt a message with a key stored on file
# To use it, first you should use generate_key_file() or already have a key contains your key.
def encrypt_with_key(self, key_file, message):
encrypt_key = self.load_key(key_file) # Load the encryption key stored on file
encrypt_box = secret.SecretBox(encrypt_key)
encrypted = encrypt_box.encrypt(message)
assert len(encrypted) == len(message) + encrypt_box.NONCE_SIZE + encrypt_box.MACBYTES
return encrypted
# Decrypt a message, using a user supplied password
def decrypt(self, message):
try:
password = getpass.getpass(prompt="\nType password to DECRYPT: ", stream=None).encode() # Ask a user for the password to decrypt the message
salt = message[:16] # The first 16 bytes of message [0 included : 16 not included] is the salt value
decrypt_key = self.kdf(secret.SecretBox.KEY_SIZE, password, salt, opslimit=self.ops, memlimit=self.mem) # Derivate the enc. key from password
decrypt_box = secret.SecretBox(decrypt_key)
decrypted = decrypt_box.decrypt(message[16:])
assert len(decrypted) == len(message[16:]) - decrypt_box.NONCE_SIZE - decrypt_box.MACBYTES
return decrypted
except exceptions.CryptoError:
return 'error'
# Decrypt a message with a key stored on file
# To use it, first you should use encrypt_with_key() method.
def decrypt_with_key(self, key_file, message):
try:
decrypt_key = self.load_key(key_file)
decrypt_box = secret.SecretBox(decrypt_key)
decrypted = decrypt_box.decrypt(message)
assert len(decrypted) == len(message) - decrypt_box.NONCE_SIZE - decrypt_box.MACBYTES
return decrypted
except exceptions.CryptoError:
return 'error'
# Ask a user to type a password and verify it and return the password
def password(self):
while True:
password1 = getpass.getpass(prompt="\nType your password: ", stream=None).encode() # getpass do not echo the password on terminal
password2 = getpass.getpass(prompt="Type your password again: ", stream=None).encode()
if password1 != password2:
input("\nPassword does not match! Press any key to try again.")
os.system('cls')
continue
else:
return password1
# Similar as write_key_file(), but, will not write the key on file.
# This will be done by the function that call it.
# The objective here is allow the caller (function) to store multiple keys in one single file, instead of, one file.key per encrypted file
def key_db(self):
key = self.generate_key_file()
return key
# Similar to encrypt_with_key(), but the key will be supplied.
def encrypt_db(self, encrypt_key_db, message):
encrypt_box = secret.SecretBox(encrypt_key_db)
encrypted = encrypt_box.encrypt(message)
assert len(encrypted) == len(message) + encrypt_box.NONCE_SIZE + encrypt_box.MACBYTES
return salt + encrypted
# The inverse of encrypt_db()
def decrypt_db(self, key_db, message):
try:
decrypt_box = secret.SecretBox(bytes.fromhex(key_db))
decrypted = decrypt_box.decrypt(message)
assert len(decrypted) == len(message) - decrypt_box.NONCE_SIZE - decrypt_box.MACBYTES
return decrypted
except exceptions.CryptoError:
return 'error'
'''
The first 56 bytes of encrypted text are:
[0:16] = SALT (16) # Will be present only if the user supply a password
[16:40] = NONCE (24) # Always present
[40:56] = MACBYTES (16) # Always present
[56:] = Encrypted Text
'''
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T23:35:00.657",
"Id": "512904",
"Score": "2",
"body": "You mention calling it from other code, and it appears to be encryption, but could you briefly say what is a use case when one would call this code? What does it do?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T14:00:42.990",
"Id": "513028",
"Score": "0",
"body": "This will be used to encrypt data and will be called from other .py files. Thank you for your interest in helping."
}
] |
[
{
"body": "<p>First lets discuss the class and method naming:</p>\n<p><code>StudingClassFirstTime</code> First of all, the word <code>Studing</code> is not in my vocabulary. But please just name classes after what they are supposed to do, and don't include the word <code>class</code>; we know it is a class.</p>\n<ul>\n<li><code>load_key</code>: this loads a 32 byte key from file, which is fine, however it doesn't include <code>file</code> in the identifier as in later methods;</li>\n<li><code>generate_key</code>: this derives a key from a password; this is not the same thing as generating a key, which in cryptography generally means taking bytes from a random number generator;</li>\n<li><code>generate_key_file</code>: here a file is suggested, however no file is being produced;</li>\n<li><code>write_key_file</code>: here a key file (or, as talked about before, the contents) is generated and encrypted first, which is not in the method description;</li>\n<li><code>encrypt</code>: OK, fine, here you perform the encryption which always uses a key, however the key parameter is missing - you just assume that the reader expects that the key is generated;</li>\n<li><code>encrypt_with_key</code>: one would suggest that this is a pleonasm - a key is required to encrypt anything;</li>\n<li><code>password</code>: password is not a verb - so it should be named <code>ask_user_for_password</code> for instance.</li>\n<li><code>key_db</code>: similar problem as above, no verb - the extensive commenting required shows that this is not a well thought out name;</li>\n<li><code>encrypt_db</code>: this begs the question: what DB, did we define a DB somewhere?</li>\n<li><code>decrypt_db</code>: OK, but the comment here isn't necessary, everybody should know that decrypt is the inverse of encrypt.</li>\n</ul>\n<p>For <code>write_key_file</code> it is not symmetric with <code>load_key</code> which is generally what would be expected.</p>\n<p>For <code>encrypt_db</code>, the DB is not present in the method call, instead there is a parameter <code>message</code>, which we have to guess is the DB. Moreover, <code>encrypt_key_db</code> to me suggests that there is a database of keys, not that this represents the key to encrypt the DB.</p>\n<p>The only difference between the the <code>encrypt_db</code> and the <code>encrypt_with_key</code> seems to be that the key is in a file or not. That is not reflected by the API.</p>\n<hr />\n<p>Now lets talk about the way the program/class is structured. It seems to be doing a lot of things at the same time. For one, it mixes file IO, user input, clearing of the terminal as well as the "business logic" of performing encryption / decryption and generation of the keys from passwords.</p>\n<p>Generally we try and separate these three as much as possible. What you certainly now want is to make your business logic UI dependent. This is exactly what the class does when calling <code>getpass.getpass</code> from the business logic. This could be called "reversal of control". Generally there is a controller class that performs the business logic, which is in turn controlled by the UI class. At most the controller class allows the UI class to insert callback functionality (e.g. for updating a progress bar). The UI class or main method would instead configure the password through a method or constructor call. That makes the code reusable for e.g. GUI applications instead of console applications.</p>\n<hr />\n<p>Finding Argon to perform the password hashing is of course fine, and a good choice.</p>\n<hr />\n<p>For me as a user it is unclear what this class is for. Yes, it encrypts things, but what does that tell me? Why would it be used to encrypt, encrypt with a key or encrypt a DB? Generally you should focus on just one 'use case', e.g. encrypting a DB.</p>\n<p>Generally, programmers tend to present one interface to the user when it comes to performing writing one or multiple items. Having a separate function for this that does things slightly differently just confuses matters. One way to avoid this is to have a class that is specific for a (password protected) key, which you can then use to encrypt separate items that make up the DB using separate method calls.</p>\n<p>Unfortunately the use case / requirements for this class are sufficiently unclear for me to propose a better API for it.</p>\n<hr />\n<p>With regards to cryptography:</p>\n<ul>\n<li>always indicate the protocol in the description of the class; if you haven't got a separate protocol description then you'll have to provide it here;</li>\n<li>a key and a password are separate entities: <code>password = getpass.getpass</code> is fine, but <code>password = utils.random(32)</code> is not (32 random bytes are not human readable, and hence not a password).</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T13:57:42.110",
"Id": "513026",
"Score": "0",
"body": "This answer was exactly what I was looking for. Thank you very much for your time, attention and effort in answering it. \nBy the way: English is not my first language, so, sorry for any grammatical mistake."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:42:40.093",
"Id": "259941",
"ParentId": "259915",
"Score": "2"
}
},
{
"body": "<h1>Short comments as docstrings</h1>\n<p>Docstrings are triple-quoted strings that come immediately after you define a class or function, and they are special in the sense that Python can tell those strings are to be seen as comments that <em>document</em> the code.</p>\n<p>For most of your methods you have a short comment immediately before the function, which is great. My suggestion is that you move it to "inside" the function.</p>\n<p>For example, instead of</p>\n<pre class=\"lang-py prettyprint-override\"><code> # Generate an encryption key and return it's value(key)\n def generate_key(self):\n self.salt = utils.random(pwhash.argon2id.SALTBYTES) # 16 bytes == 128 bits\n password = self.password() # Ask a user to input a password\n key = self.kdf(self.size, password, self.salt, opslimit=self.ops, memlimit=self.mem)\n return key # Key have 32 bytes == 256 bits\n</code></pre>\n<p>do</p>\n<pre class=\"lang-py prettyprint-override\"><code> def generate_key(self):\n """Generate an encryption key and return it's value(key)."""\n self.salt = utils.random(pwhash.argon2id.SALTBYTES) # 16 bytes == 128 bits\n password = self.password() # Ask a user to input a password\n key = self.kdf(self.size, password, self.salt, opslimit=self.ops, memlimit=self.mem)\n return key # Key have 32 bytes == 256 bits\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T13:29:34.377",
"Id": "513022",
"Score": "1",
"body": "I did not known that. From now on, I will do that. Thank you for your time, help and attention."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T13:59:13.950",
"Id": "259943",
"ParentId": "259915",
"Score": "1"
}
},
{
"body": "<h1>Write as little code as possible inside a <code>try</code></h1>\n<p>I see you are writing some of your code in a EAFP (easier to ask for forgiveness than permission) style, as opposed to a LBYL style (look before you leap).\nThis means that you are using <code>try: ... except: ...</code> blocks, which is perfectly fine and often encouraged in Python (<a href=\"https://mathspp.com/blog/pydonts/eafp-and-lbyl-coding-styles?utm_source=codereview\" rel=\"nofollow noreferrer\">article on EAFP vs LBYL in Python</a>).</p>\n<p>However, when you write EAFP code, it is advisable to write the least amount of code possible inside the <code>try</code> statement. The idea is that we don't want our <code>except</code> to catch an error other than the one we are trying to prevent.\nSo, while I am not familiar with the libraries you are using, you can probably take something like</p>\n<pre class=\"lang-py prettyprint-override\"><code> # The inverse of encrypt_db()\n def decrypt_db(self, key_db, message):\n try:\n decrypt_box = secret.SecretBox(bytes.fromhex(key_db))\n decrypted = decrypt_box.decrypt(message)\n assert len(decrypted) == len(message) - decrypt_box.NONCE_SIZE - decrypt_box.MACBYTES\n return decrypted\n\n except exceptions.CryptoError:\n return 'error'\n</code></pre>\n<p>and rewrite it as</p>\n<pre class=\"lang-py prettyprint-override\"><code> # The inverse of encrypt_db()\n def decrypt_db(self, key_db, message):\n try:\n decrypt_box = secret.SecretBox(bytes.fromhex(key_db))\n decrypted = decrypt_box.decrypt(message)\n except exceptions.CryptoError:\n return 'error'\n\n assert len(decrypted) == len(message) - decrypt_box.NONCE_SIZE - decrypt_box.MACBYTES\n return decrypted\n</code></pre>\n<p>Now, depending on what line might actually raise a <code>CryptoError</code>, you would further change that part of the code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T13:28:37.583",
"Id": "513021",
"Score": "1",
"body": "I will read the article as soon as possible. Thank you for your time, help and attention."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T00:33:13.157",
"Id": "513073",
"Score": "1",
"body": "Hi there! You may not know, but the post length limit on this site is *double* that of other Stack Exchange sites. I'll invite you to read [this post](https://codereview.meta.stackexchange.com/a/8434/23788) on our meta site about posting multiple answers on a given question. Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T06:24:40.150",
"Id": "513085",
"Score": "1",
"body": "@MathieuGuindon hey, thanks for sharing. A couple of days ago I had a short discussion regarding posting multiple answers and I was under the impression having several independent answers was ok, because that makes it easier for other people to give feedback on the several types of suggestions, and to me this makes sense. However, if moderators are going to be frowning upon my answers every time I do that, then I am not interested in answering like that. This leads to a follow-up: what if I answer with some suggestions and later want to add more, independent suggestions?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T06:25:15.723",
"Id": "513086",
"Score": "0",
"body": "Should I edit my answer and notify the OP in some way? Or how would I go about it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T12:34:36.790",
"Id": "513133",
"Score": "0",
"body": "Nothing to worry about, no mod is tracking down your activity =) but community members are noticing a pattern of multiple-posting and just wanted to be sure you saw what we had on meta about it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T12:47:18.503",
"Id": "513134",
"Score": "0",
"body": "@MathieuGuindon thanks. Like I said, if this is a pattern people don't like, I won't do it :) thanks for the heads-up!"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T14:05:13.677",
"Id": "259944",
"ParentId": "259915",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T21:15:02.587",
"Id": "259915",
"Score": "3",
"Tags": [
"python",
"beginner",
"object-oriented",
"cryptography",
"classes"
],
"Title": "Creating a class and calling it from other .py files"
}
|
259915
|
<p><strong><a href="https://leetcode.com/problems/3sum/" rel="nofollow noreferrer">Question</a>:</strong></p>
<blockquote>
<p>Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.</p>
</blockquote>
<p>Notice that the solution set must not contain duplicate triplets.</p>
<p>Here's my pythonic approach to leetcode 3Sum, it passes and actually beats 93% in time! However, the code is unweildy and the approach seems much overly complicated. I am looking to clean up the two sum function, and overall approach, but I'm not sure how.</p>
<pre class="lang-py prettyprint-override"><code> def threeSum(self, nums: List[int]) -> List[List[int]]:
def twoSum(i,target):
ans = []
for j in range(i+1,len(nums)):
#avoid dupes
if j > i+1 and nums[j] == nums[j-1]:
continue
if nums[j] > target//2:
break
# when target is even, two dupes may add to make it
if nums[j] == target/2 and j+1 < len(nums):
if nums[j+1] == target // 2:
ans.append([nums[i],nums[j],nums[j+1]])
break
#traditional two sum variation
elif -(-target + nums[j]) in values and -(-target + nums[j]) != nums[j]:
ans.append([nums[i],nums[j],-(-target + nums[j])])
return ans
values = set(nums)
nums.sort()
answer = []
for i,num in enumerate(nums):
if i > 0 and nums[i-1] == nums[i]:
continue
values.remove(num)
answer.extend(twoSum(i,-num))
return answer
</code></pre>
<p>Even if you aren't able to follow my code, I would really appreciate general pythonic tips. Thanks!</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T23:28:46.750",
"Id": "512900",
"Score": "4",
"body": "Providing the problem statement and/or sample in- and output will help contributors point you towards a better or more straightforward solution. As it is now, it's hard to understand what's (supposed to be) going on."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T23:38:59.253",
"Id": "512999",
"Score": "0",
"body": "It doesn't address Python-specific questions, but the Wikipedia [pseudocode](https://en.wikipedia.org/wiki/3SUM#Quadratic_algorithm) for 3sum is intuitive and has a nice visualization to accompany it. Seems like a simpler algorithmic approach than the one you've taken, so it might be worth a look."
}
] |
[
{
"body": "<p>You can just create every possible triplets with nested loops and keep a record of those that satisfy the requirements.</p>\n<p>I don't know Python, so I learned a bit of it to write this code, take it as an example and translate it to proper Python. I think that the main issue of the code is the usage of while loops. I am used to the C's <code>for</code> loops where you have direct access to the indexes of the elements, and here I used <code>while</code> loops as equivalent even thought I saw there are <a href=\"https://stackoverflow.com/questions/522563/accessing-the-index-in-for-loops\">better ways in Python</a>.</p>\n<p>It's a pretty straightforward approach:</p>\n<pre class=\"lang-py prettyprint-override\"><code>n = [-1,0,1,2,-1,-4]\nl = len(n)\ntriplets = []\n\ni = 0\nwhile i < l - 2:\n j = i + 1\n while j < l - 1:\n k = j + 1\n while k < l:\n if n[i] + n[j] + n[k] == 0:\n candidate = [n[i], n[j], n[k]]\n unique = True\n for tri in triplets:\n if set(candidate) == set(tri):\n unique = False\n break\n if unique:\n triplets.append(candidate)\n k += 1\n j += 1\n i += 1\n\nprint(triplets)\n</code></pre>\n<p>You could improve the algorithm by skipping a lap of the first loop if <code>n[i]</code> is a dupe of a previous <code>n[i]</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-30T10:47:33.480",
"Id": "534294",
"Score": "1",
"body": "Please argue what is better about the code presented as an answer (and *why* it is better). [What insight about the code presented for review](https://codereview.stackexchange.com/help/how-to-answer) does it provide?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-11-30T16:16:19.437",
"Id": "534322",
"Score": "0",
"body": "Your solution is worse than the OP's code. The OP's code runs in \\$O(n^2)\\$ time, yours runs in \\$O(n^3)\\$."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:01:03.513",
"Id": "259949",
"ParentId": "259916",
"Score": "-2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T22:09:48.497",
"Id": "259916",
"Score": "2",
"Tags": [
"python",
"algorithm",
"python-3.x",
"hash-map"
],
"Title": "3Sum - leetcode"
}
|
259916
|
<p>This is my current code to check list of urls for response code within same domain.</p>
<p>I would like to know if there's a way where i can improve my code performance more better.</p>
<pre class="lang-py prettyprint-override"><code>import argparse
import logging
import os
import smtplib
import time
import httpx
import trio
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import tabulate
logger = logging.getLogger('MyLog')
logger.setLevel(logging.INFO)
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)-5.5s - %(message)s', "%Y-%m-%d %H:%M:%S")
file_handler = logging.FileHandler(
'MyLog.log', 'a', encoding='utf-8')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
year, month = time.strftime('%Y:%m').split(":")
def validfile(parser, fn):
if not os.path.isfile(fn):
parser.error(f"File {fn} Doesn't Exist")
else:
return fn
result = []
async def checker(channel):
async with channel:
async for client, ticker in channel:
while True:
try:
r = await client.head(f"https://www.hiddenurl.com/{year}/{month}/{ticker}")
break
except httpx.RequestError as e:
logger.error('Url: {:75}, Reason: {}'.format(
r.url, type(e).__name__))
continue
status = "Url: {:75}, Status: {}".format(r.url, r.status_code)
logger.info(status)
if r.status_code == 200:
print(status)
result.append(r.url)
async def mailer():
myemail = "my@my.com"
HTML = tabulate(result, tablefmt='html')
msg = MIMEMultipart("alternative", None, [MIMEText(HTML, 'html')])
msg['Subject'] = f'We Got {len(result)} Result!'
msg['From'] = myemail
msg['To'] = "hidden@hidden.com"
try:
with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
smtp.login(myemail, 'mypass')
smtp.send_message(msg)
logger.info('Email Sent! ---> {}'.format(result))
print(f"Yay! Email Sent With {len(result)} Records!")
except (smtplib.SMTPException, smtplib.socket.error) as e:
status = 'Unable To Send Email Due To --> {}'.format(type(e).__name__)
logger.error(status)
print(status)
async def main(links):
headers = {
'User-Agent': 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)'
}
async with httpx.AsyncClient(timeout=None) as client, trio.open_nursery() as nurse, await trio.open_file(links) as f:
client.headers.update(headers)
sender, receiver = trio.open_memory_channel(0)
async with receiver:
for _ in range(50):
nurse.start_soon(checker, receiver.clone())
async with sender:
async for ticker in f:
ticker = ticker.lower().rstrip()
if ticker and not ticker.startswith('#'):
await sender.send([client, ticker])
if result:
await mailer()
else:
logger.info('No Active Ticker Detected!')
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description='Checking Tickers Response Code')
parser.add_argument('tickers', help='File Include Tickers',
type=lambda x: validfile(parser, x))
trio.run(main, parser.parse_args().tickers)
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-23T22:49:52.640",
"Id": "259917",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "check list of urls response code"
}
|
259917
|
<p>I am trying to calculate some values using numpy. Here is my code,</p>
<pre><code>x= np.zeros([nums])
for i in range (nums):
x[i] = np.mean((Zs[i :] - Zs[:len(Zs)-i]) ** 2)
</code></pre>
<p>The code runs perfectly and give desired result. But it takes very long time for a large number <code>nums</code> value. Because the <code>Zs</code> and <code>nums</code>value having same length.
Is it possible to use some other method or multiprocessing to increase the speed of calculation?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T13:27:42.777",
"Id": "513601",
"Score": "2",
"body": "How are you sure that this is where the code is slow? Have you profiled the entire program? For us to help you optimize the code we need to understand more about what the code does."
}
] |
[
{
"body": "<h1>Minor style edits</h1>\n<p>Like you said, the code seems to be perfectly fine and I don't see a very obvious way to make it faster or more efficient, as the consecutive computations you are making in your <code>for</code> loop don't seem to be easy to relate to one another.</p>\n<p>Of course this is just my input after thinking for some time, other people may have clever suggestions I can't come up with.</p>\n<p>However, I would make <em>minor</em> edits to your code, for the sake of homogenisation:</p>\n<pre class=\"lang-py prettyprint-override\"><code>x = np.zeros(Zs.shape)\nfor i in range(len(Zs)): \n x[i] = np.mean((Zs[i:] - Zs[:-i])**2)\n</code></pre>\n<p>For the snippet of code we have, it is not clear the relationship between <code>nums</code> and <code>Zs</code> and so it makes more sense to have the loop in terms of <code>Zs</code>.</p>\n<p>Also, notice that the right term of the subtraction I replaced <code>Zs[:len(Zs)-i]</code> with <code>Zs[:-i]</code>, which is a nice feature of Python that is worth getting used to, you can learn about <a href=\"https://mathspp.com/blog/pydonts/sequence-indexing#negative-indices?utm_source=codereview\" rel=\"nofollow noreferrer\">using negative indices in Python</a>.</p>\n<p>Other minor things were just fixing spacing. If you want, take a look at the <a href=\"https://www.python.org/dev/peps/pep-0008/#whitespace-in-expressions-and-statements\" rel=\"nofollow noreferrer\">PEP 8</a> style guide for Python :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T08:59:49.397",
"Id": "512927",
"Score": "0",
"body": "thank you for your comment. Zs and nums having the same length so using that range in for loop are perfectly fine."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T08:49:28.127",
"Id": "259930",
"ParentId": "259927",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T08:04:01.983",
"Id": "259927",
"Score": "-1",
"Tags": [
"python",
"numpy"
],
"Title": "Speed up calculation time of for loop in numpy"
}
|
259927
|
<p>I'm currently learning Go and I have decided to implement a Circular Doubly Linked List (Deque) structure for the training. Go is not my first language. I program mainly in Python, therefore I would like to learn if code follows Go structure and idioms and if you have any advice of improving.</p>
<p><strong>About the code:</strong></p>
<p>This is circular doubly linked list data structure, so the idea is to have O(1) add/remove/peek access to the elements at the beginning/end of the list and no access to elements between the two. I implemented methods for adding and removing elements and also to represent list as string and compare two lists. <code>deque.test</code> also contains test cases for each of the methods.</p>
<p>I use linked list here, but I acknowledge that same thing can be achieved with slices (maybe more efficiently), but my secondary goal was to get used to pointers and references - as those doesn't appear in Python.</p>
<p><strong>Question about the code:</strong></p>
<p>I'm hoping for general feedback but I also have questions about specific section:</p>
<ul>
<li>When deque is empty and I'm trying to pop element, method would call panic to stop execution of the program, instead of returning an error. Is this a good practice in Go? Should I return value and error from pop instead (it seems a bit awkward to me to require handling possible empty list error every time an element is popped).</li>
</ul>
<p><strong>Project Structure</strong></p>
<pre><code>collections/
- cmd/
- - main.go
- deque/
- - deque.go
- - deque_test.go
- - node.go
- - test_cases.go
- some_other_collection/
- - ...
</code></pre>
<p><strong>deque.go</strong></p>
<pre><code>// Package deque implements deque type and common methods to interact with
// deque.
package deque
import (
"strconv"
"strings"
)
// Deque is implemented as circular doubly linked list with sentinel node.
// This allows for O(1) non-amortized add/remove operations for both ends
// of the structure. This makes it a perfect implementation of queue data
// structure.
type Deque struct {
sentinel *IntNode
length int
}
// Constructor for new empty deque.
func New() Deque {
sentinel := &IntNode{0, nil, nil}
sentinel.prev = sentinel
sentinel.next = sentinel
return Deque{sentinel, 0}
}
// Constructor for new empty deque populated with elements from slice.
func FromSlice(slice []int) Deque {
deq := New()
for _, val := range slice {
deq.Append(val)
}
return deq
}
// Append adds element to the end of the deque.
func (d *Deque) Append(elem int) {
newNode := IntNode{value: elem, next: d.sentinel, prev: d.sentinel.prev}
d.sentinel.prev.next = &newNode
d.sentinel.prev = &newNode
d.length += 1
}
// AppendLeft adds element to the front of the deque.
func (d *Deque) AppendLeft(elem int) {
newNode := IntNode{value: elem, next: d.sentinel.next, prev: d.sentinel}
d.sentinel.next.prev = &newNode
d.sentinel.next = &newNode
d.length += 1
}
// Pop removes and returns last element in deque.
func (d *Deque) Pop() int {
if d.Empty() {
panic("popping from empty list")
}
value := d.sentinel.prev.value
d.sentinel.prev.prev.next = d.sentinel
d.sentinel.prev = d.sentinel.prev.prev
d.length -= 1
return value
}
// Pop removes and returns first element in deque.
func (d *Deque) PopLeft() int {
if d.Empty() {
panic("popping from empty list")
}
value := d.sentinel.next.value
d.sentinel.next.next.prev = d.sentinel
d.sentinel.next = d.sentinel.next.next
d.length -= 1
return value
}
// Last return value of the first element in deque.
func (d *Deque) First() int {
return d.sentinel.next.value
}
// Last return value of the last element in deque.
func (d *Deque) Last() int {
return d.sentinel.prev.value
}
// Length returns number of elements in deque.
func (d *Deque) Length() int {
return d.length
}
// Empty checks if there are any elements in deque.
func (d *Deque) Empty() bool {
return d.length == 0
}
// String outputs string representation of deque.
func (d *Deque) String() string {
var b strings.Builder
curr := d.sentinel.next
b.WriteString("Deque{")
for i := 0; i < d.Length(); i++ {
b.WriteString(strconv.Itoa(curr.value))
b.WriteString(",")
curr = curr.next
}
b.WriteString("}")
return b.String()
}
// Equals checks if both deques contain same elements in the same order.
func (d *Deque) Equals(other *Deque) bool {
if d.Length() != other.Length() {
return false
}
curr := d.sentinel.next
otherCurr := other.sentinel.next
for i := 0; i < d.Length(); i++ {
if curr.value != otherCurr.value {
return false
}
curr = curr.next
otherCurr = otherCurr.next
}
return true
}
</code></pre>
<p><strong>node.go</strong></p>
<pre><code>package deque
type IntNode struct {
value int
next *IntNode
prev *IntNode
}
</code></pre>
<p><strong>deque_test.go</strong></p>
<pre><code>package deque
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestEquals(t *testing.T) {
for _, tc := range TestCasesEquals {
if tc.this.Equals(&tc.other) != tc.expected {
t.Errorf(tc.msg)
}
}
}
func TestAppend(t *testing.T) {
for _, tc := range TestCasesAppend {
actual := tc.actual()
if !actual.Equals(&tc.expected) {
t.Errorf(tc.msg)
}
}
}
func TestAppendLeft(t *testing.T) {
for _, tc := range TestCasesAppendLeft {
actual := tc.actual()
if !actual.Equals(&tc.expected) {
t.Errorf(tc.msg, actual, tc.expected)
}
}
}
func TestPop(t *testing.T) {
// Main test cases
for _, tc := range TestCasesPop {
deque, popped := tc.actual()
if !deque.Equals(&tc.expectedDeque) || popped != tc.expectedPopped {
t.Errorf(tc.msg)
}
}
// Popping from empty list
poppingEmpty := func() {
d := FromSlice([]int{})
d.Pop()
}
assert.Panics(t, poppingEmpty, "popping from empty deque")
}
func TestPopLeft(t *testing.T) {
// Main test cases
for _, tc := range TestCasesPopLeft {
deque, popped := tc.actual()
if !deque.Equals(&tc.expectedDeque) || popped != tc.expectedPopped {
t.Errorf(tc.msg)
}
}
// Popping from empty list
poppingEmpty := func() {
d := FromSlice([]int{})
d.Pop()
}
assert.Panics(t, poppingEmpty, "popping from empty deque")
}
func TestString(t *testing.T) {
d := New()
if d.String() != "Deque{}" {
t.Errorf("empty deque; got: %v", d.String())
}
d = FromSlice([]int{1, 2, 7, 4})
if d.String() != "Deque{1,2,7,4,}" {
t.Errorf("4 element deque; got: %v", d.String())
}
}
</code></pre>
<p><strong>test_cases.go</strong></p>
<pre><code>package deque
type TestCaseEquals struct {
this Deque
other Deque
expected bool
msg string
}
var TestCasesEquals = []TestCaseEquals{
{
this: New(),
other: New(),
expected: true,
msg: "two empty deques",
},
{
this: FromSlice([]int{1, 2, 3}),
other: FromSlice([]int{1, 2, 3}),
expected: true,
msg: "two identical, 3-element deques",
},
{
this: FromSlice([]int{1, 2, 3}),
other: FromSlice([]int{1, 2, 4}),
expected: false,
msg: "same length, last element mismatching",
},
{
this: FromSlice([]int{1, 2, 3}),
other: FromSlice([]int{1, 2}),
expected: false,
msg: "different length, elements matching",
},
}
type TestCaseAppend struct {
actual func() Deque
expected Deque
msg string
}
var TestCasesAppend = []TestCaseAppend{
{
actual: func() Deque {
return New()
},
expected: New(),
msg: "2 empty deques",
},
{
actual: func() Deque {
d := New()
d.Append(1)
return d
},
expected: FromSlice([]int{1}),
msg: "adding one element to deque",
},
{
actual: func() Deque {
d := New()
d.Append(1)
d.Append(3)
d.Append(5)
d.Append(19)
return d
},
expected: FromSlice([]int{1, 3, 5, 19}),
msg: "adding multiple elements to deque",
},
}
var TestCasesAppendLeft = []TestCaseAppend{
{
actual: func() Deque {
d := New()
d.AppendLeft(1)
return d
},
expected: FromSlice([]int{1}),
msg: "adding one element to deque. Got: %v, Expected: %v",
},
{
actual: func() Deque {
d := New()
d.AppendLeft(1)
d.AppendLeft(3)
d.AppendLeft(5)
d.AppendLeft(19)
return d
},
expected: FromSlice([]int{19, 5, 3, 1}),
msg: "adding multiple elements to deque. Got: %v, Expected: %v",
},
}
type TestCasePop struct {
actual func() (Deque, int)
expectedDeque Deque
expectedPopped int
msg string
}
var TestCasesPop = []TestCasePop{
{
actual: func() (Deque, int) {
d := FromSlice([]int{1})
val := d.Pop()
return d, val
},
expectedDeque: New(),
expectedPopped: 1,
msg: "popping from deque with 1 element",
},
{
actual: func() (Deque, int) {
d := FromSlice([]int{1, 2, 3})
val := d.Pop()
return d, val
},
expectedDeque: FromSlice([]int{1, 2}),
expectedPopped: 3,
msg: "popping from deque with 3 elements",
},
{
actual: func() (Deque, int) {
d := FromSlice([]int{1, 2, 3})
d.Pop()
val := d.Pop()
return d, val
},
expectedDeque: FromSlice([]int{1}),
expectedPopped: 2,
msg: "popping twice from deque with 3 elements",
},
}
var TestCasesPopLeft = []TestCasePop{
{
actual: func() (Deque, int) {
d := FromSlice([]int{1})
val := d.PopLeft()
return d, val
},
expectedDeque: New(),
expectedPopped: 1,
msg: "popping from deque with 1 element",
},
{
actual: func() (Deque, int) {
d := FromSlice([]int{1, 2, 3})
val := d.PopLeft()
return d, val
},
expectedDeque: FromSlice([]int{2, 3}),
expectedPopped: 1,
msg: "popping from deque with 3 elements",
},
{
actual: func() (Deque, int) {
d := FromSlice([]int{1, 2, 3})
d.PopLeft()
val := d.PopLeft()
return d, val
},
expectedDeque: FromSlice([]int{3}),
expectedPopped: 2,
msg: "popping twice from deque with 3 elements",
},
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T21:52:12.903",
"Id": "513193",
"Score": "0",
"body": "Pop can return two variables an int and a bool to inform caller if queue is empty or not with bool instead of panicking or returning an error. Also you should not shadow types with variables."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T08:22:34.633",
"Id": "259928",
"Score": "1",
"Tags": [
"linked-list",
"go"
],
"Title": "Integer Double Ended Queue GO"
}
|
259928
|
<p>I have a single producer and single consumer, and the producer never stops, but the consumer might not keep up. There's no need to consume every item, as long as we always access the most-recently produced item, and never process an item twice. In other words, we should drop items if the consumer isn't keeping up, but wait for the producer if it is.</p>
<pre><code>#ifndef TRIPLE_BUFFER_HPP
#define TRIPLE_BUFFER_HPP
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
template<typename T>
class triple_buffer
{
// the actual buffer
T buffer[3] = {};
// the roles the buffers currently have
// read and write buffers are private to each side
// the available buffer is passed between them
T* readbuffer = &buffer[0];
T* writebuffer = &buffer[1];
std::atomic<T*> available = &buffer[2];
// the last fully-written buffer waiting ready for reader
std::atomic<T*> next_read_buf = nullptr;
// When the reader catches up, it needs to wait for writer (slow path only)
std::mutex read_queue_mutex = {};
std::condition_variable read_queue = {};
public:
// Writer interface
// Writer has ownership of this buffer (this function never blocks).
T *get_write_buffer()
{
return writebuffer;
}
// Writer releases ownership of its buffer.
void set_write_complete()
{
// give back the write buffer
auto *written = writebuffer;
writebuffer = available.exchange(writebuffer);
// mark it as written
next_read_buf.store(written, std::memory_order_release);
// notify any waiting reader
read_queue.notify_one();
}
// Reader interface
// Reader gets ownership of the buffer, until the next call of
// get_read_buffer().
T *get_read_buffer(std::chrono::milliseconds timeout = std::chrono::milliseconds::max())
{
auto const timeout_time = std::chrono::steady_clock::now() + timeout;
// get the written buffer, waiting if necessary
auto *b = next_read_buf.exchange(nullptr);
while (b != readbuffer) {
// it could be the available buffer
readbuffer = available.exchange(readbuffer);
if (b == readbuffer) {
// yes, that's it
return readbuffer;
}
// else we need to wait for writer
b = nullptr;
std::unique_lock lock{read_queue_mutex};
auto test = [this,&b]{ b = next_read_buf.exchange(nullptr); return b; };
if (!read_queue.wait_until(lock, timeout_time, test)) {
return nullptr;
}
}
return readbuffer;
}
// The unit test helper is enabled only if <gtest.h> is included before this header.
// It's not available (or necessary) in production code.
#ifdef TEST
// N.B. not thread-safe - only call this when reader and writer are idle
void test_invariant(const char *file, int line) const
{
const std::set<const T*> buffers{&buffer[0], &buffer[1], &buffer[2]};
const std::set<const T*> roles{readbuffer, available, writebuffer};
auto const fail = buffers != roles
|| next_read_buf && !buffers.count(next_read_buf)
|| next_read_buf == writebuffer;
if (fail) {
auto name = [this](const T *slot){
if (slot == &buffer[0]) { return "buffer[0]"; }
if (slot == &buffer[1]) { return "buffer[1]"; }
if (slot == &buffer[2]) { return "buffer[2]"; }
if (slot == nullptr) { return "(null)"; }
return "(invalid)";
};
ADD_FAILURE_AT(file, line) <<
"Buffer/role mismatch:\n"
"Buffers = " << &buffer[0] << ", " << &buffer[1] << ", " << &buffer[2] << "\n"
"Read = " << readbuffer << " = " << name(readbuffer) << "\n"
"Available = " << available << " = "<< name(available) << "\n"
"Write = " << writebuffer << " = " << name(writebuffer) << "\n"
"Next Read = " << next_read_buf << " = " << name(next_read_buf) << "\n";
}
}
#endif
};
#endif // TRIPLE_BUFFER_HPP
</code></pre>
<p>I created this with help from a set of unit tests:</p>
<pre><code>#include <gtest/gtest.h>
#include <triple-buffer.hpp>
#include <set>
#define EXPECT_INVARIANT(obj) (obj.test_invariant(__FILE__, __LINE__))
TEST(triple_buffer, no_write_read_returns_null)
{
triple_buffer<int> buffer;
EXPECT_INVARIANT(buffer);
EXPECT_EQ(buffer.get_read_buffer({}), nullptr);
EXPECT_INVARIANT(buffer);
}
TEST(triple_buffer, write_once_read_once)
{
triple_buffer<int> buffer;
auto *write0 = buffer.get_write_buffer();
EXPECT_INVARIANT(buffer);
EXPECT_NE(write0, nullptr);
EXPECT_EQ(buffer.get_read_buffer({}), nullptr);
EXPECT_INVARIANT(buffer);
buffer.set_write_complete();
EXPECT_INVARIANT(buffer);
// having written, we can read
EXPECT_EQ(buffer.get_read_buffer({}), write0);
EXPECT_INVARIANT(buffer);
// another read should block/fail
EXPECT_EQ(buffer.get_read_buffer({}), nullptr);
EXPECT_INVARIANT(buffer);
}
TEST(triple_buffer, write_twice_read)
{
triple_buffer<int> buffer;
auto *write0 = buffer.get_write_buffer();
EXPECT_NE(write0, nullptr);
buffer.set_write_complete();
auto *write1 = buffer.get_write_buffer();
EXPECT_NE(write1, nullptr);
EXPECT_NE(write1, write0);
buffer.set_write_complete();
// read should get newest
EXPECT_EQ(buffer.get_read_buffer({}), write1);
// another read should block/fail
EXPECT_EQ(buffer.get_read_buffer({}), nullptr);
}
TEST(triple_buffer, write_read_write2)
{
triple_buffer<int> buffer;
auto *write0 = buffer.get_write_buffer();
EXPECT_NE(write0, nullptr);
buffer.set_write_complete();
// read should get newest
auto *read0 = buffer.get_read_buffer({});
EXPECT_EQ(read0, write0);
auto *write1 = buffer.get_write_buffer();
EXPECT_NE(write1, nullptr);
EXPECT_NE(write1, write0);
buffer.set_write_complete();
auto *write2 = buffer.get_write_buffer();
EXPECT_NE(write2, nullptr);
EXPECT_NE(write2, write1);
EXPECT_NE(write2, read0); // don't touch reader's buffer
buffer.set_write_complete();
// read should get newest
auto *read1 = buffer.get_read_buffer({});
EXPECT_EQ(read1, write2);
}
TEST(triple_buffer, write_read_write3)
{
triple_buffer<int> buffer;
auto *write0 = buffer.get_write_buffer();
EXPECT_NE(write0, nullptr);
buffer.set_write_complete();
// read should get newest
auto *read0 = buffer.get_read_buffer({});
EXPECT_EQ(read0, write0);
auto *write1 = buffer.get_write_buffer();
EXPECT_NE(write1, nullptr);
EXPECT_NE(write1, write0);
buffer.set_write_complete();
auto *write2 = buffer.get_write_buffer();
EXPECT_NE(write2, nullptr);
EXPECT_NE(write2, write1);
EXPECT_NE(write2, read0); // don't touch reader's buffer
buffer.set_write_complete();
auto *write3 = buffer.get_write_buffer();
EXPECT_EQ(write3, write1); // we should be overwriting the old unread value
EXPECT_NE(write3, read0); // still don't touch reader's buffer
buffer.set_write_complete();
// read should get newest
auto *read1 = buffer.get_read_buffer({});
EXPECT_EQ(read1, write3);
}
TEST(triple_buffer, read_during_write)
{
triple_buffer<int> buffer;
auto *write0 = buffer.get_write_buffer();
EXPECT_NE(write0, nullptr);
buffer.set_write_complete();
auto *write1 = buffer.get_write_buffer();
// read should get complete buffer
auto *read0 = buffer.get_read_buffer({});
EXPECT_EQ(read0, write0);
buffer.set_write_complete();
auto *write2 = buffer.get_write_buffer();
EXPECT_NE(write2, nullptr);
EXPECT_NE(write2, write1);
EXPECT_NE(write2, read0); // don't touch reader's buffer
auto *read1 = buffer.get_read_buffer({});
EXPECT_EQ(read1, write1);
buffer.set_write_complete();
}
</code></pre>
<p>Obviously, the unit tests are limited, being single threaded. In particular, they don't cover the <code>wait_until()</code> call or provoke any races. I feel I should probably create some <em>module</em> tests that can be slower than unit tests (I consider 1ms runtime the absolute upper limit for a unit-test), but don't have any experience using slower tests like that.</p>
<p>Anyway, my main concerns with the code (both the class and its tests) are:</p>
<ol>
<li><strong>Correctness</strong>. I believe it's correct in all cases, but concurrent code is notoriously hard to fully reason about, and I'd appreciate any insight into what I've missed.</li>
<li><strong>Readability</strong>. Can this be understood and modified by someone else (future-me, in particular)?</li>
<li>Given I know there's only one reader, do I really need <code>read_queue_mutex</code> to be a member, or can I get away with instantiating a new one in each <code>get_read_buffer()</code> call? If so, should I?</li>
</ol>
|
[] |
[
{
"body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>Correctness. I believe it's correct in all cases, but concurrent code is notoriously hard to fully reason about, and I'd appreciate any insight into what I've missed.</p>\n</blockquote>\n<p>It don't see any correctness issues.</p>\n<blockquote>\n<p>Readbility. Can this be understood and modified by someone else (future-me, in particular)?</p>\n</blockquote>\n<p>Lock-free code is always hard to follow. I think the <code>get_write_buffer()</code> and <code>set_write_complete()</code> functions are relatively easy to understand. The hardest to follow is <code>get_read_buffer()</code>. I would explain the invariants in the code:</p>\n<ul>\n<li><code>readbuffer</code> is always owned by the consumer</li>\n<li><code>writebuffer</code> is always owned by the producer</li>\n<li><code>available</code> is never owned by either</li>\n<li>you can atomically exchange <code>read/writebuffer</code> with <code>available</code> without breaking the above invariants</li>\n</ul>\n<p>And then also explain the trick: <code>next_read_buf</code> is set by the producer after it is finished with the buffer, and it also swaps <code>writebuffer</code> and <code>available</code>, after which <code>next_read_buf == available</code>. The consumer can atomically take over <code>available</code> in this case.</p>\n<p>The wait is necessary in two cases: <code>next_read_buf</code> is <code>nullptr</code> (producer didn't produce anything yet since last consume), or if it just exchanged <code>available</code> and <code>writebuffer</code>, but had not written to <code>next_read_buf</code> yet.</p>\n<blockquote>\n<p>Given I know there's only one reader, do I really need read_queue_mutex to be a member, or can I get away with instantiating a new one in each get_read_buffer() call? If so, should I?</p>\n</blockquote>\n<p>You can instantiate a new one in each call. Either you pay the small price of instantiating a new <code>std::mutex</code> every call, or you pay the price of keeping a <code>std::mutex</code> around all the time. I don't think it matters much for performance. I would keep it like it is, so that the mutex and condition variable are kept close together in the source code.</p>\n<p>This problem is solved in C++20 with <a href=\"https://en.cppreference.com/w/cpp/atomic/atomic_wait\" rel=\"noreferrer\"><code>std::atomic_wait()</code></a>.</p>\n<h1>Consider using RAII to convey buffer ownership</h1>\n<p>A producer has to do two steps: get a pointer to a buffer to write to, and then release that buffer when it is done. That sounds like a job for <a href=\"https://en.cppreference.com/w/cpp/language/raii\" rel=\"noreferrer\">RAII</a>. Similar to <a href=\"https://en.cppreference.com/w/cpp/thread/lock_guard\" rel=\"noreferrer\"><code>std::lock_guard</code></a>, consider adding a way to get a handle for the write buffer that will automatically do <code>set_write_complete()</code> when its lifetime ends. You could even do the same for the read buffer for symmetry's sake.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:14:49.547",
"Id": "512963",
"Score": "0",
"body": "Just the kind of review I was hoping for - thank you. I didn't know `std::atomic_wait()` - looks useful, but it's a shame there isn't a version with a timeout (I need to poll occasionally to check whether the program wants to terminate). I remember thinking about an RAII interface early on, but never followed up on that - thanks for reminding me to consider that again."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:35:36.977",
"Id": "512965",
"Score": "2",
"body": "Hm, good point about the timeout. But if it is for checking if the program needs to terminate, don't! The usual way to avoid polling is to enqueue a new item which in some way signals that the consumer should immediately quit. Or in this case, you could for example have a dummy `T` that you point `next_read_buf` to (for example, use `&buffer[3]`), and you can check for that in the slow path in `get_read_buffer()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:48:31.340",
"Id": "512967",
"Score": "0",
"body": "Good suggestions for the termination handler. I think I'm still in a position to change that and incorporate your advice. My items have quite a few members already (and I plan to add some to track what proportion of items get dropped, and how long the rest spend waiting to be read) so adding a flag shouldn't be a problem."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T11:09:50.350",
"Id": "259934",
"ParentId": "259929",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T08:42:32.323",
"Id": "259929",
"Score": "7",
"Tags": [
"c++",
"lock-free"
],
"Title": "Lock-free triple buffer"
}
|
259929
|
<p>I am working on the subject of the French championship 2019, composed of 20 teams, and each team plays 38 times, if team A plays with team B, whatever the result, each team plays another time with another team determined by the draw.</p>
<p>If team A plays with team B, that means there are three possibilities 1/3 team A wins.</p>
<p>1/3 draw.</p>
<p>1/3 team A loses.</p>
<p>I have to look for the indifferent forecast of (probability of 1/3 team A wins, 1/3 draw and 1/3 team A loses) and that using R.</p>
<p>This is what I did me using R:</p>
<pre><code>Binochampionnat = function(n = 38, p=1/3){
mu <- n * p ; sigm <- sqrt(n * p * (1-p))
probabino <- dbinom(0:n,n,p)
ak <- (0:(n+1) - mu) / sigm
etendue <- (ak[2]-ak[1])/2
bk <- ak - etendue
probagauss <- rep(NA, n+1)
for(i in 1:(n+1)) probagauss[i] <- pnorm(bk[i+1]) - pnorm(bk[i])
cat("binomiale distribution","\n") ; print(probabino)
cat("Gauss Distribution","\n") ; print(probagauss)
x <- t(as.matrix(data.frame(BINO=probabino,GAUSS=probagauss)))
barplot(x,beside=T,legend=T, names.arg = 0:n,
xlab = "Discrete variable values", ylab = "Probabilities")
title(paste("Approximation of the binomial law n =",n," ; p =",p))}
Binochampionnat(n = 38, p=1/3)
</code></pre>
<p>and I got a beautiful graph and results, that I could not stick here</p>
<p>What do you think? Is that correct?</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T15:32:00.687",
"Id": "259946",
"Score": "1",
"Tags": [
"r"
],
"Title": "using R probability"
}
|
259946
|
<p>This is my first month learning HTML and CSS, I have built a working download page for one of my Java projects and I wanted to see if there is anything to improve on my website.</p>
<p>The website works as I expect, but I'm unsure if I'm doing anything wrong.</p>
<p>Here is my code snippet, any feedback is appreciated!</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
margin: 0;
padding: 0;
}
body {
font-family: "Montserrat", sans-serif;
}
.container {
animation: transitionIn 1s;
height: 100vh;
width: 100%;
background-image: url(../resources/images/background.jpeg);
background-position: center;
background-size: cover; /* auto, cover*/
padding-left: 5%;
padding-right: 5%;
box-sizing: border-box;
position: relative;
background-repeat: no-repeat;
background-attachment: fixed;
}
.logo {
width: 120px;
cursor: pointer;
}
/* loading animation */
@keyframes transitionIn {
from {
opacity: 0;
transform: rotateX(-10deg);
}
to {
opacity: 1;
transform: rotateX(0);
}
}
.center {
margin: auto;
width: 50%;
text-align: center;
padding: 50px;
line-height: 60px;
}
.center p {
line-height: 50px;
font-size: 20px;
}
.shadow {
-moz-box-shadow: 3px 3px 5px 6px #ccc;
-webkit-box-shadow: 3px 3px 5px 6px #ccc;
box-shadow: 3px 3px 5px 3px rgba(0, 0, 0, 0.4);
}
.img-row img {
max-width: 60vh;
height: auto;
}
.img-row {
display: flex;
padding: 5%;
justify-content: center;
}
.img-column {
flex: 33.33%;
padding: 5px;
}
/* top banner */
.banner {
background-color: #ffc87c;
}
.banner__content {
padding: 16px;
max-width: 1000px;
margin: 0 auto;
display: flex;
align-items: center;
justify-content: center;
}
.banner__text {
line-height: 1.4;
font-size: 2vh;
}
.banner__close {
background: none;
border: none;
cursor: pointer;
width: 30px;
height: 30px;
}
@media only screen and (max-device-width: 480px) {
.container, .banner {
float: none;
width: auto;
}
.center {
font-size: 10px;
width: auto;
padding: 0%;
}
#head_text {
font-size: 2em;
}
#head_warning {
font-size: 20px;
line-height: 2em;
}
.center h2 {
font-size: 1em;
line-height: normal;
}
.center p {
line-height: 20px; font-size: 1em;
}
.img-column img {
max-width: 40vh;
}
.img-row {
flex-direction: column;
}
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Project Name</title>
<link rel="preconnect" href="https://fonts.gstatic.com" />
<link
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300&display=swap"
rel="stylesheet"
/>
<link rel="stylesheet" href="./styles/style.css" />
<link
rel="shortcut icon"
type="image/png"
href="resources/images/project_logo.png"
/>
</head>
<body>
<div class="container">
<div class="banner">
<div class="shadow">
<div class="banner__content">
<div class="banner__text">
<strong>Newest Release:</strong> v1.0.1 on 4/21/21
</div>
<button class="banner__close" type="button">&times;</button>
</div>
</div>
</div>
<div class="center">
<h1 id="head_text">Try Out Project</h1>
<h2>
Install Java
<a href="https://java.com/en/download/" target="_blank">Here </a>
<h1 id="head_warning">
If you have Java installed, download the Project zip file
<a
href="resources/files/Project.zip"
download
style="line-height: 100px"
>Download Project</a
>
</h1>
</h2>
<p>
Please extract the contents of the zip file, and run the .JAR file.
<br />
For more information on running a JAR file, please refer
<a
href="https://www.computerhope.com/issues/ch001343.htm"
target="_blank"
>here.</a
>
</p>
<!-- images -->
<div class="img-row">
<div class="img-column">
<img
class="shadow"
src="resources/images/project_home.jpg"
alt="project demo"
/>
</div>
<div class="img-column">
<img
class="shadow"
src="resources/images/project_add_class.jpg"
alt="project demo"
/>
</div>
<div class="img-column">
<img
class="shadow"
src="resources/images/project_error.jpg"
alt="project demo"
/>
</div>
</div>
</div>
</div>
<script>
// removes banner on close
document
.querySelector(".banner__close")
.addEventListener("click", function () {
this.closest(".banner").remove();
});
</script>
</body>
</html></code></pre>
</div>
</div>
</p>
|
[] |
[
{
"body": "<p>Not too much jumps out; some comments:</p>\n<ul>\n<li>You're missing your <code>DOCTYPE</code></li>\n<li>On the balance, if I were to be picky <code>&times;</code> is more style than content where you've used it. You can leave your <code>button</code> empty and do a CSS <code>content</code> that achieves the same thing.</li>\n<li>It seems very strange to have an <code>h1</code> embedded in an <code>h2</code>. You probably shouldn't do that.</li>\n<li>To be consistent with your own style, and to maintain legibility, do not break your <code></a></code> onto multiple lines</li>\n<li>Pixels as measurement units in CSS have a contorted, confusing and nonintuitive meaning. Read e.g. <a href=\"https://medium.com/@julienetienne/pixels-are-dead-faa87cd8c8b9\" rel=\"nofollow noreferrer\">this article</a>. The days of browsers actually rendering one pixel as one pixel have been over for many years; so just don't write your measurements this way.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:48:59.530",
"Id": "512968",
"Score": "0",
"body": "Thank you! The multi-line </a>'s are from the prettier extension. I just assumed it was a best practice. I'll definitely change it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:49:42.480",
"Id": "512969",
"Score": "0",
"body": "It's OK to have an anchor on multiple lines; just don't break the closing tag onto multiple lines."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:19:59.523",
"Id": "259952",
"ParentId": "259950",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "259952",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:09:52.373",
"Id": "259950",
"Score": "2",
"Tags": [
"html",
"css"
],
"Title": "Personal Project Download Website"
}
|
259950
|
<p>I am working on building a management interface for an ESL (English as a Second Language) institute, basically it is a language school where people learn English.</p>
<p>I have prepared my models for each app and I really would like someone to review them and provide me with suggestions and possible mistakes in the design.</p>
<ul>
<li>the <strong>models</strong> for an app called <strong>ez_core</strong>:</li>
</ul>
<pre><code>GENDER_CHOICES = [
('Female', 'Female'),
('Male', 'Male')
]
STREET_ADDRESS_CHOICES = [
('A', 'A'),
('B', 'B')
]
EDUCATIONAL_LEVEL_CHOICES = [
('Bachelor\'s Degree', 'Bachelor\'s Degree'),
('Master\'s Degree', 'Master\'s Degree'),
('PhD Degree', 'PhD Degree'),
]
CONTACT_RELATIONSHIP_CHOICES = [
('Brother', 'Brother'),
('Father', 'Father'),
('Mother', 'Mother'),
('Sister', 'Sister'),
('Uncle', 'Uncle'),
('Wife', 'Wife'),
]
MEDICAL_CONDITION_CHOICES = [
('Chronic Disease', 'Chronic Disease'),
('Allergies', 'Allergies')
]
class PersonalInfo(models.Model):
full_name = models.CharField(max_length=100)
phone_number = models.CharField(max_length=100)
email_address = models.EmailField(max_length=100)
birthdate = models.DateField()
gender = models.CharField(max_length=6, choices=GENDER_CHOICES)
personal_id_number = models.CharField(max_length=100)
passport_number = models.CharField(max_length=100)
personal_photo_link = models.CharField(max_length=100)
id_card_attchment_link = models.CharField(max_length=100)
passport_attachment_link = models.CharField(max_length=100)
street_address = models.CharField(
max_length=100, choices=STREET_ADDRESS_CHOICES)
address_reference_point = models.CharField(max_length=100)
educational_level = models.CharField(
max_length=100, choices=EDUCATIONAL_LEVEL_CHOICES)
specialization = models.CharField(max_length=100)
contact_phone_number = models.CharField(max_length=100)
contact_name = models.CharField(max_length=100)
contact_relationship = models.CharField(
max_length=100, choices=CONTACT_RELATIONSHIP_CHOICES)
medical_condition = models.CharField(
max_length=100, choices=MEDICAL_CONDITION_CHOICES)
medication = models.CharField(max_length=100)
class Meta:
abstract = True
</code></pre>
<ul>
<li>The <strong>models</strong> for an app called <strong>ez_course</strong>:</li>
</ul>
<pre><code>COURSE_TYPE_CHOICES = [
('Adults', 'Adults'),
('Kids', 'Kids')
]
COURSE_TITLE_CHOICES = [
('General English', 'General English'),
('Big English', 'Big English'),
('Supermind', 'Supermind'),
('Business', 'Business'),
('UK Visa', 'UK Visa'),
('IELTS', 'IELTS'),
]
class CourseDays(models.Model):
date = models.DateField()
class Course(models.Model):
course_type = models.CharField(max_length=100, choices=COURSE_TYPE_CHOICES)
course_title = models.CharField(
max_length=100, choices=COURSE_TITLE_CHOICES)
course_description = models.TextField()
course_start_time = models.TimeField()
course_end_time = models.TimeField()
# teachers
course_cost = models.IntegerField()
course_days = models.ManyToManyField(CourseDays)
</code></pre>
<ul>
<li>The <strong>models</strong> for an app called <strong>ez_staff</strong>:</li>
</ul>
<pre><code>from ez_core.models import PersonalInfo
from ez_course.models import Course
POSITION_CHOICES = [
('Teacher Assistant', 'Teacher Assistant'),
('Volunteer', 'Volunteer'),
('Teacher', 'Teacher'),
('Service', 'Service'),
('Intern', 'Intern'),
('Admin', 'Admin'),
('Boss', 'Boss'),
]
class Staff(PersonalInfo):
is_married = models.BooleanField(default=False)
number_of_children = models.IntegerField()
start_working_date = models.DateField()
position = models.CharField(max_length=100, choices=POSITION_CHOICES)
taught_courses = models.ManyToManyField(Course, blank=True)
is_active = models.BooleanField(default=True)
inactivity_reason = models.CharField(max_length=100, blank=True, null=True)
</code></pre>
<ul>
<li>The <strong>models</strong> for an app called <strong>ez_student</strong>:</li>
</ul>
<pre><code>from ez_core.models import PersonalInfo
from ez_course.models import Course
class DailyAttendance(models.Model):
date = models.DateField()
first_hour = models.BooleanField(default=False)
second_hour = models.BooleanField(default=False)
leave = models.BooleanField(default=False)
class Test(models.Model):
test_title = models.CharField(max_length=100)
test_max_score = models.IntegerField()
test_score = models.IntegerField()
test_date = models.DateField()
class Student(PersonalInfo):
has_bus_service = models.BooleanField(default=False)
is_postponed = models.BooleanField(default=False)
postpone_reason = models.CharField(max_length=100, blank=True, null=True)
courses = models.ForeignKey(Course, on_delete=models.CASCADE)
daily_attendance = models.ManyToManyField(
DailyAttendance, blank=True)
tests = models.ManyToManyField(Test)
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T17:59:14.720",
"Id": "259954",
"Score": "1",
"Tags": [
"python",
"sql",
"django"
],
"Title": "Django Models for an ESL school"
}
|
259954
|
<h2>Motivation</h2>
<p>I and the company is working on building C++ SDK automatically for several platforms, including Windows.<br />
In summary, I have to test somehow if the private member of function pointers' type is correct, since <code>LoadLibrary</code> in Windows API only uses function names, ignoring its type.<br />
There is some real-world restriction, so I have to access the private/protected members for testing.</p>
<p>I've searched the internet and found that it could be done using templates, but all examples are not generic, unable to check at compile-time.</p>
<p>So I build my own version that can be done more generically.<br />
The whole source code can be also found at <a href="https://github.com/lackhole/Lupin" rel="nofollow noreferrer">https://github.com/lackhole/Lupin</a></p>
<h2>Code</h2>
<p>Any member can be accessed in explicit template instantiation.<br />
And friend injection allows calling without providing the template class, only by the matching argument(ADL).
So we need an <code>Accessor</code> class that holds a pointer to the target class's private member, and the <code>Accessor</code> must be able to gotten using appropriate <code>Tag</code>.</p>
<pre><code>template<typename Tag, typename Class, typename Type, Type ptr_>
struct Accessor {
using class_type = Class;
using access_type = Type;
using pointer_type = decltype(ptr_);
using const_pointer_type = std::add_const_t<pointer_type>;
static constexpr pointer_type ptr = ptr_;
friend auto get_accessor_type_impl(Tag) { return Accessor{}; }
};
template<typename Dummy>
struct Tag {
friend auto get_accessor_type_impl(Tag);
};
</code></pre>
<p>We have to keep the friend function inside of the <code>Accessor</code> since once we instantiate with a private pointer, we can never re-get its type explicitly because we cannot access a private pointer.<br />
So the above declared the same function in <code>Tag</code> and used deduced return type, only to get the <code>Accessor</code>'s type.<br />
C++ only allows the friend injection to be remained inside of the class when the class type and the argument type are the same.<br />
This forces us to use C++14 or above, where C++11 cannot deduce the return type with <code>auto</code> only.</p>
<p>This can be used like</p>
<pre><code>using tag_foo_x = Tag<class foo_x>;
template struct Accessor<tag_foo_x, Foo, decltype(&FOO::x), &Foo::x>;
</code></pre>
<p>And we have to get <code>Accessor<tag_foo_x, ...</code> with <code>tag_foo_x</code>, using the friend function above.</p>
<pre><code>template<typename Tag>
struct TagTraits {
using tag_type = Tag;
using accessor_type = decltype(get_accessor_type_impl(std::declval<tag_type>()));
using class_type = typename accessor_type::class_type;
using access_type = typename accessor_type::access_type;
using pointer_type = typename accessor_type::pointer_type;
};
</code></pre>
<p>Now we can get the <code>Accessor</code>'s type using <code>Tag</code>.</p>
<pre><code>using accessor_type = TagTraits<tag_foo_x>::accessor_type;
</code></pre>
<p>And things are much simple from now.<br />
One has to determine the traits of the pointing type(<code>ptr_</code>'s type in <code>Accessor</code>), we can use some helper templates.</p>
<pre><code>template<typename T>
struct is_function : std::conditional_t<
std::is_member_function_pointer<std::decay_t<T>>::value ||
std::is_function<std::remove_pointer_t<T>>::value,
std::true_type, std::false_type> {};
template<typename T>
struct get_pointing_type {
using type = T;
};
template<typename T>
struct get_pointing_type<T*> {
using type = T;
};
template<typename T, typename Class>
struct get_pointing_type<T Class::*> {
using type = T;
};
template<typename T>
using get_pointing_type_t = typename get_pointing_type<T>::type;
</code></pre>
<p>And for getting the member, one has to vary its return type on the pointing type(variable or a function).</p>
<pre><code>/** get non-static member variable */
template<typename Tag, typename Target>
inline constexpr
std::enable_if_t<!is_function<typename TagTraits<Tag>::access_type>::value,
get_pointing_type_t<typename TagTraits<Tag>::access_type> &>
get(Target& target) {
return target.*TagTraits<Tag>::accessor_type::ptr;
}
template<typename Tag, typename Target>
inline constexpr
std::enable_if_t<!is_function<typename TagTraits<Tag>::access_type>::value,
get_pointing_type_t<typename TagTraits<Tag>::access_type> const &>
get(const Target& target) {
return target.*TagTraits<Tag>::accessor_type::ptr;
}
template<typename Tag, typename Target>
inline constexpr
std::enable_if_t<!is_function<typename TagTraits<Tag>::access_type>::value,
get_pointing_type_t<typename TagTraits<Tag>::access_type>>
get(Target&& target) {
return std::forward<Target>(target).*TagTraits<Tag>::accessor_type::ptr;
}
template<typename Tag, typename Target>
inline constexpr
std::enable_if_t<!is_function<typename TagTraits<Tag>::access_type>::value,
get_pointing_type_t<typename TagTraits<Tag>::access_type>>
get(const Target&& target) {
return std::forward<Target>(target).*TagTraits<Tag>::accessor_type::ptr;
}
/** get non-static member function pointer */
template<typename Tag, typename Target>
inline constexpr
std::enable_if_t<is_function<typename TagTraits<Tag>::access_type>::value,
typename TagTraits<Tag>::access_type>
get(Target& target) {
return TagTraits<Tag>::accessor_type::ptr;
}
template<typename Tag, typename Target>
inline constexpr
std::enable_if_t<is_function<typename TagTraits<Tag>::access_type>::value,
typename TagTraits<Tag>::access_type const>
get(const Target& target) {
return TagTraits<Tag>::accessor_type::ptr;
}
template<typename Tag, typename Target>
inline constexpr
std::enable_if_t<is_function<typename TagTraits<Tag>::access_type>::value,
typename TagTraits<Tag>::access_type>
get(Target&& target) {
return TagTraits<Tag>::accessor_type::ptr;
}
template<typename Tag, typename Target>
inline constexpr
std::enable_if_t<is_function<typename TagTraits<Tag>::access_type>::value,
typename TagTraits<Tag>::access_type const>
get(const Target&& target) {
return TagTraits<Tag>::accessor_type::ptr;
}
/** get static member (both variable and function) */
template<typename Tag>
std::enable_if_t<!is_function<typename TagTraits<Tag>::access_type>::value,
get_pointing_type_t<typename TagTraits<Tag>::access_type> &>
get() {
return *TagTraits<Tag>::accessor_type::ptr;
}
template<typename Tag>
std::enable_if_t<is_function<typename TagTraits<Tag>::access_type>::value,
typename TagTraits<Tag>::access_type>
get() {
return *TagTraits<Tag>::accessor_type::ptr;
}
</code></pre>
<p>And some sugar function for calling the member function directly.</p>
<pre><code>/** call non-static member function */
template<typename Tag, typename Target, typename ...Args>
inline constexpr decltype(auto)
call(Target&& target, Args&&... args) {
using tag_traits = TagTraits<Tag>;
using access_type = typename tag_traits::access_type;
using accessor_type = typename tag_traits::accessor_type;
static_assert(std::is_member_function_pointer<access_type>::value,
"Tag must represent member function, or perhaps the tag represents static member function");
return (std::forward<Target>(target).*accessor_type::ptr)(std::forward<Args>(args)...);
}
/** call static member function */
template<typename Tag, typename ...Args>
inline constexpr decltype(auto)
call(Args&&... args) {
using tag_traits = TagTraits<Tag>;
using access_type = typename tag_traits::access_type;
using accessor_type = typename tag_traits::accessor_type;
static_assert(!std::is_member_function_pointer<access_type>::value &&
std::is_function<std::remove_pointer_t<access_type>>::value,
"Tag must represent static member function");
return (accessor_type::ptr)(std::forward<Args>(args)...);
}
</code></pre>
<p>And last sugar for getting only the type.</p>
<pre><code>template<typename Tag>
struct Type {
using type = get_pointing_type_t<typename TagTraits<Tag>::access_type>;
};
template<typename Tag>
using Type_t = typename Type<Tag>::type;
</code></pre>
<p>The <a href="https://github.com/lackhole/Lupin/blob/master/include/access/macro.h" rel="nofollow noreferrer">macro</a> is just an alias for creating a tag and explicit template instantiation.
The usage is like below</p>
<pre><code>#include "access/access.h"
struct hidden {
private:
int x = 10;
std::string str = "hello";
int func() const &{ return x; }
int sum(int a, int b) { return a + b; }
static int sta() { return y; }
static int y;
};
int hidden::y = 12345;
ACCESS_CREATE_TAG(tag_hidden_x, hidden, x);
ACCESS_CREATE_UNIQUE_TAG(hidden, x);
ACCESS_CREATE_TAG(tag_hidden_str, hidden, str);
ACCESS_CREATE_TAG(tag_hidden_func, hidden, func);
ACCESS_CREATE_TAG(tag_hidden_sum, hidden, sum);
ACCESS_CREATE_TAG(tag_hidden_sta, hidden, sta);
ACCESS_CREATE_TAG(tag_hidden_y, hidden, y);
int main() {
std::cout << std::boolalpha;
hidden h;
std::cout << access::get<tag_hidden_x>(h) << std::endl;
std::cout << access::get<ACCESS_GET_UNIQUE_TAG(hidden, x)>(h) << std::endl;
access::get<tag_hidden_x>(h) = 100;
std::cout << access::get<tag_hidden_x>(h) << std::endl;
access::get<ACCESS_GET_UNIQUE_TAG(hidden, x)>(h) = 200;
std::cout << access::get<ACCESS_GET_UNIQUE_TAG(hidden, x)>(h) << std::endl;
std::cout << access::get<tag_hidden_y>() << std::endl;
access::get<tag_hidden_y>() = -123;
std::cout << access::get<tag_hidden_y>() << std::endl;
access::call<tag_hidden_func>(h);
(h.*access::get<tag_hidden_func>(h))();
access::call<tag_hidden_sum>(h, 1, 2);
access::get<tag_hidden_sta>()();
access::call<tag_hidden_sta>();
std::cout << access::get<tag_hidden_str>(h) << std::endl;
access::get<tag_hidden_str>(std::move(h));
std::cout << access::get<tag_hidden_str>(h) << std::endl;
const hidden h2;
access::get<tag_hidden_x>(h2);
access::call<tag_hidden_func>(h2);
(h.*access::get<tag_hidden_func>(h2))();
std::cout << access::get<tag_hidden_sta>()() << std::endl;
std::cout << access::call<tag_hidden_sta>() << std::endl;
static_assert(std::is_same<access::Type_t<tag_hidden_x>, int>::value, "");
static_assert(std::is_same<access::Type_t<tag_hidden_y>, int>::value, "");
// Note that the below two type is different. Choose your own way.
static_assert(std::is_same<access::Type_t<tag_hidden_func>, int () const&>::value, ""); // function type
static_assert(std::is_same<decltype(access::get<tag_hidden_func>(std::declval<hidden>())), int (hidden::*)() const&>::value, ""); // function pointer type
// Note that these two are different too
static_assert(std::is_same<access::Type_t<tag_hidden_sta>, int()>::value, ""); // function type
static_assert(std::is_same<decltype(access::get<tag_hidden_sta>()), int(*)()>::value, ""); // function pointer type
return 0;
}
</code></pre>
<p>Thanks in advance for your feedbacks!<br />
Is there any more portable or better way to improve this?
Like support C++11 using different friend injection tricks, or some value/template features that I missed.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T12:56:47.333",
"Id": "513019",
"Score": "1",
"body": "Welcome to the Code Review Community. We can answer questions like `And I can't understand why gcc<10 cannot compile the 4 overloads of call`. All we do on this site is review the existing code and provide suggestions on how to improve that working code. We are also unable to review code that contains `...` instead of code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T14:10:05.993",
"Id": "513032",
"Score": "1",
"body": "@pacmaninbw thanks for pointing it out. I Used `...` because the content is almost the same, only differs in parameter type(&, const &, &&, const &&`). So I thought it will drop the readability since it's quite a lot of code. I'll update the content to show all codes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T08:14:21.620",
"Id": "513109",
"Score": "0",
"body": "@김선달, one reason it's good to show nearly-repeated code is that you might get suggestions on how to better arrange it to reduce the duplication."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:38:32.393",
"Id": "513158",
"Score": "0",
"body": "I think I'm missing something... your checking code relies on the class definitions in a header file. This does not actually check that the `LoadLibrary` symbol actually matches the definition in that header; it could be an old version or a different piece of code that happens to have the same name."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:26:06.567",
"Id": "513167",
"Score": "0",
"body": "@JDługosz My situation was: internal source code must be hidden, so it is build to a DLL file with some `extern \"C\"` code. But we must make it portable, so the source code of the wrapper(that loads the C function) is also provided. The wrapper links the DLL file's function to the corresponding function pointer, which is held as private. DLL + wrapper is a single SDK, so the wrapper must not change just for testing. The automated test code can access both `extern \"C\"` header files and the `wrapper.h`, while the wrapper doesn't."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:29:06.937",
"Id": "513168",
"Score": "0",
"body": "@JDługosz I know that the test can be done somehow instead of accessing the private fields, but I thought this is more intuitive(represent intent). My situation was just motivation for writing this library. The point is that this is a generic, standard way to access private fields."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T14:31:20.777",
"Id": "513250",
"Score": "0",
"body": "I still don't see how it tests that the type of pointer is correct... it simply doesn't know what the type is in the `extern \"C\"` function that it loaded from the library."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T01:55:31.253",
"Id": "513293",
"Score": "0",
"body": "`LoadLibrary` doesn't check types. `wrapper.h` doesn't include `extern \"C\"` file. This is my problem here. So the test code includes both `extern \"C\"` header files and `wrapper.h`. So it knows both types, making it able to check if they're the same."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T18:45:34.607",
"Id": "259956",
"Score": "2",
"Tags": [
"c++",
"template-meta-programming"
],
"Title": "Generic way to access private/protected members"
}
|
259956
|
<p>I've always struggled to create and sustainable, organizated, clean code.
I tried to use a Factory method and it's working better now that I created another class.</p>
<p>I know I should write documentation, but that's not the advice I'm looking for yet. Because I don't think documentation will help with organizating my code.</p>
<p>This code is scraping multiple twitch IRC chats and using my Laravel API to count the subscribers of multiple streamers.
The code works but I have the feeling it's getting harder to implement features, change the code and even read it.</p>
<p>Is there any design pattern should I use for this? How can I make it better?</p>
<p>Request:</p>
<pre><code>class Request
{
private $requestUrl;
private $requestFields;
private $requestResult;
private $requestStreamer;
private $requestStatus;
private $requestType;
private $ch;
public function __construct($streamer = null, $status = null, $url = null, $customFields = null)
{
$this->requestStreamer = $streamer;
$this->requestStatus = $status;
$this->requestFields = $customFields;
$this->requestUrl = $url;
$this->start();
}
public function setFields($fields = null)
{
if ($fields != null)
$this->requestFields = $fields;
}
public function start()
{
if ($this->requestUrl == 'online') {
$this->requestUrl = 'http://localhost:8000/api/streamers/changeOnline';
$this->setFields(['streamer' => $this->requestStreamer, 'is_online' => $this->requestStatus]);
$this->request();
return;
}
if ($this->requestUrl == 'status') {
$this->requestUrl = 'http://localhost:8000/api/streamers/changeStatus';
$this->setFields(['streamer' => $this->requestStreamer, 'run' => $this->requestStatus]);
$this->request();
return;
}
if ($this->requestUrl == 'sub') {
$this->requestUrl = 'http://localhost:8000/api/create/sub';
$this->setFields();
$this->request();
dump($this->requestFields);
return;
}
if ($this->requestUrl == 'checkTwitchOnline') {
$this->requestUrl = 'https://api.twitch.tv/helix/streams/?user_login=' . $this->requestStreamer;
$this->requestType = 'get';
$this->setFields(array('Authorization: Bearer gokyy7wxa9apriyjr2evaccv6h71qn', 'Client-ID: gosbl0lt05vzj18la6v11lexhvpwlb'));
$this->request();
return $this->decode();
}
if ($this->requestUrl == 'getStreamers') {
$this->requestUrl = 'http://localhost:8000/api/streamers/getAll';
$this->requestType = 'get';
$this->request();
return $this->decode();
}
if ($this->requestUrl == null) {
$this->requestUrl = 'http://localhost:8000/api/streamers/changeStatus';
$this->setFields(['streamer' => $this->requestStreamer, 'run' => $this->requestStatus]);
$this->request();
$this->requestUrl = 'http://localhost:8000/api/streamers/changeOnline';
$this->setFields(['streamer' => $this->requestStreamer, 'is_online' => $this->requestStatus]);
$this->request();
return;
}
return;
}
public function setRequestType()
{
curl_setopt($this->ch, CURLOPT_URL, $this->requestUrl);
if ($this->requestType == 'get') {
curl_setopt($this->ch, CURLOPT_HTTPGET, true);
$this->setHeader();
} else {
curl_setopt($this->ch, CURLOPT_POST, true);
$this->setHeader();
}
curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, true);
}
public function setHeader()
{
if (!empty($this->requestFields)) {
$fields_string = http_build_query($this->requestFields);
if ($this->requestType == 'get') {
curl_setopt($this->ch, CURLOPT_HTTPHEADER, $this->requestFields);
} else {
curl_setopt($this->ch, CURLOPT_POSTFIELDS, $fields_string);
}
}
}
public function request()
{
$this->ch = curl_init();
$this->setRequestType();
$this->requestResult = curl_exec($this->ch);
return $this->result();
}
public function decode()
{
return json_decode($this->requestResult, true);
}
public function result()
{
//dump($this->requestResult);
return $this->requestResult;
}
}
class RequestFactory
{
public static function create($streamer = null, $status = null, $url = null, $customFields = null)
{
return new Request($streamer, $status, $url, $customFields);
}
}
$changeStatus = RequestFactory::create(null, null, 'getStreamers');
</code></pre>
<p>Main file:</p>
<pre><code>
use GhostZero\Tmi\Client;
use GhostZero\Tmi\ClientOptions;
use GhostZero\Tmi\Events\Twitczh\SubEvent;
use GhostZero\Tmi\Events\Twitch\AnonSubGiftEvent;
use GhostZero\Tmi\Events\Twitch\AnonSubMysteryGiftEvent;
use GhostZero\Tmi\Events\Twitch\ResubEvent;
use GhostZero\Tmi\Events\Twitch\SubGiftEvent;
use GhostZero\Tmi\Events\Twitch\SubMysteryGiftEvent;
include('requestFactory.php');
$streamers = RequestFactory::create(null, null, 'getStreamers');
$streamers = $streamers->decode();
for ($i = 0; $i <= count($streamers) - 1; ++$i) {
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
// pcntl_wait($status); //Protect against Zombie children
} else {
$GLOBALS['streamer'] = ($streamers[$i]['streamer']);
cli_set_process_title($GLOBALS['streamer'] . 'run.php');
$request = RequestFactory::create($GLOBALS['streamer'], '1', 'status');
$request = RequestFactory::create($GLOBALS['streamer'], null, 'checkTwitchOnline');
$data = $request->decode();
if (empty($data['data'])) {
$request = RequestFactory::create($GLOBALS['streamer'], '0');
die();
}
$request = RequestFactory::create($GLOBALS['streamer'], '1', 'online');
$client = new Client(new ClientOptions([
'options' => ['debug' => false],
'connection' => [
'secure' => true,
'reconnect' => true,
'rejoin' => true,
],
'channels' => [$GLOBALS['streamer']]
]));
/**
* @param SubGiftEvent $event
*/
function giftedRequest($event, $type): void
{
$fields = ['recipient' => $event->recipient, 'plan' => $event->plan->plan, 'type' => $type, 'gifter' => $event->user, 'streamer' => $GLOBALS['streamer']];
RequestFactory::create($GLOBALS['streamer'], null,'sub',$fields);
}
/**
* @param SubEvent $event
*/
function subbedRequest($event, $type): void
{
$fields = ['recipient' => $event->user, 'plan' => $event->plan->plan, 'type' => $type, 'gifter' => NULL, 'streamer' => $GLOBALS['streamer']];
RequestFactory::create($GLOBALS['streamer'], null,'sub',$fields);
}
$client->on(SubEvent::class, function (SubEvent $event) {
subbedRequest($event, 'SubEvent');
});
$client->on(AnonSubGiftEvent::class, function (AnonSubGiftEvent $event) {
print_r($event);
});
$client->on(AnonSubMysteryGiftEvent::class, function (AnonSubMysteryGiftEvent $event) {
print_r($event);
});
$client->on(ResubEvent::class, function (ResubEvent $event) {
subbedRequest($event, 'ResubEvent');
});
$client->on(SubGiftEvent::class, function (SubGiftEvent $event) {
giftedRequest($event, 'SubGiftEvent');
});
$client->on(SubMysteryGiftEvent::class, function (SubMysteryGiftEvent $event) {
subbedRequest($event, 'SubMysteryGiftEvent');
});
$client->connect();
}
}
</code></pre>
<p>This is my first question here, let me know how can I make it better.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T20:14:29.067",
"Id": "512989",
"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 [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T20:16:44.253",
"Id": "512990",
"Score": "0",
"body": "If you want more tips on how to write a great question, please start with [Simon's guide to posting questions](https://codereview.meta.stackexchange.com/a/6429/52915)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T20:28:43.997",
"Id": "512992",
"Score": "0",
"body": "@Mast Thanks for your time. I'm really struggling to find a good question. Because, what I really struggle is organizating the code. Although I changed the title, but I don't know if it's better."
}
] |
[
{
"body": "<p>Title idea: How to refactor simple API Client code in PHP CLI</p>\n<p>Here are a couple of tips:</p>\n<ol>\n<li><p>I would add <code>if</code>'s and <code>switch</code>'es as soon as possible. For example, you are setting fields and headers of <code>Request::class</code> inside it, just before the execution of cURL request. Why not at Request::class' creation time? Refactor your factory to add correct parameters at Request instantiation. Parameters could as well be mapped like this:\n<code>public static array $requestMapper = ['online' (something how you determine which request should be created) => [ 'type' => 'GET', 'uri' => '/changeOnline', ... (parameters) ], ...]'</code>\nThen you can do something like:\n<code>IF isset($mapper[$something]) THEN (new Request())->setUri($mapper[$something]['uri'])</code>.\nAt this point you should have a Request class ready to go and just execute it.\nFocus on isolating and extracting/abstracting elements you repeat.</p>\n</li>\n<li><p>Your Request class should either hold the data or do the work. Right now, it executes curl calls and holds the data about the request. This is known as single-responsibility principle (SRP). I would keep the data, and move the execution part to a <code>CustomClient::class</code> for example. There you would also have the instantiation of Guzzle Client so that part from the main file should also be removed. Request should only contain the info needed to do it, and another class should do the actual call using Request::class as data transfer object - which will contain info about URI, headers, etc.</p>\n</li>\n<li><p>I would move event handlers to another class or classes.</p>\n</li>\n<li><p>Any hardcoded strings that are not part of the code should be moved to meaningfully named constants.</p>\n</li>\n</ol>\n<pre><code>public const REQUEST_ONLINE = 'online'; \n...\npublic const EVENT_RESUB = 'ResubEvent';\n...\n</code></pre>\n<ol start=\"4\">\n<li>Try to avoid <code>elses</code> as much as possible, they just give you more stuff to do, can be pain in the ass to test, but that can be case specific and not necessarily true for you. For example:</li>\n</ol>\n<pre><code>$pid = pcntl_fork();\nif ($pid == -1) {\n die('could not fork');\n}\n\n$GLOBALS['streamer'] = ($streamers[$i]['streamer']);\ncli_set_process_title($GLOBALS['streamer'] . 'run.php');\n$request = RequestFactory::create($GLOBALS['streamer'], '1', 'status');\n</code></pre>\n<p>Notice no "else". You may notice this one more impactful when you start writing Unit tests</p>\n<ol start=\"5\">\n<li>Use common solutions to common problems</li>\n</ol>\n<p>Instead of:\n<code>for ($i = 0; $i <= count($streamers) - 1; ++$i) {</code></p>\n<p>You could use <code>for ($i = 0, $streamerIndex = 1; $i < count($streamers); $i++, $streamerIndex++) {</code></p>\n<p>It's a personal preference but when you use common patterns like these, it's much easier for other developers to go through that part without spending much time wrapping a head around a raw code. Now this part also has a little trick, assigning a $streamerIndex there, might cause people to overlook that part i.e. seeing <code>...$i < count($streamers); $i++)</code> I could stop reading right there and miss the part where we assign $streamerIndex, so you might think about that too. :)</p>\n<p>Or to completely remove confusion</p>\n<pre><code>for ($i = 0; $i < count($streamers); $i++) {\n$streamerIndex = $i + 1;\n...\n</code></pre>\n<ol start=\"6\">\n<li>I would advise against using superglobals ($GLOBAL) in a way that they are changed. It may lead to unexpected issues, adds to tech debt, ugly, etc.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T01:09:55.030",
"Id": "513000",
"Score": "1",
"body": "Can you explain the benefit of `$streamerIndex`? I don't follow. Why do you only increment it on the first iteration? I think I am failing to follow the code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T01:21:06.367",
"Id": "513001",
"Score": "0",
"body": "My bad, it was for example purposes. `$streamerIndex` should be incremented as well. Point of extracting it to a variable is to prevent having to do something like `$data[$i +1]` later in code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T01:21:48.500",
"Id": "513002",
"Score": "1",
"body": "...that's what I thought, but I wanted to check. Please [edit] when you have time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T13:37:10.360",
"Id": "513023",
"Score": "0",
"body": "So is there any problem in setting the curl request type in the Request?\nWhat about returning the result?\nI'm very confused because it's hard for me when to apply SRP\nIt looks like this right now:\nhttps://github.com/komen205/twitch-scraper/blob/main/Scraper/requestFactory.php\nI'm trying to move everything to the Factory @Domagoj"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T14:36:08.483",
"Id": "513034",
"Score": "0",
"body": "I wonder if setting my setHeader and setRequestType should be inside the Factory?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T00:31:47.127",
"Id": "259967",
"ParentId": "259957",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259967",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T19:31:44.600",
"Id": "259957",
"Score": "2",
"Tags": [
"php",
"design-patterns",
"factory-method",
"php7"
],
"Title": "Scrape multiple twitch IRC chats"
}
|
259957
|
<p>Given a two-card poker hand and a board of 5 cards, I want to evaluate the player's hand strength as listed <a href="https://en.wikipedia.org/wiki/List_of_poker_hands" rel="nofollow noreferrer">here</a>.</p>
<p>The evaluation of a poker hand was measured to be ~100 microseconds on average. Existing free equity calculators are able to perform this calculation in under 1 microsecond (for example, Equilab). I would like to know how to increase the performance of my algorithm to that level.</p>
<p>The function that evaluates the hand is <code>unique_ptr<ShowdownHand> eval_hand(const PokerHand& hand, const Board& board)</code> in showdown.h.</p>
<p>Here is the complete code:</p>
<p><strong>poker_game.h</strong></p>
<pre><code>#pragma once
#include <string>
#include <vector>
#include <memory>
namespace Poker {
// CardSuit
enum class CardSuit : char {
CLUB = 'c',
HEART = 'h',
SPADE = 's',
DIAMOND = 'd',
PLACEHOLDER = 'x'
};
// CardRank
class CardRank {
public:
const static CardRank C_2;
const static CardRank C_3;
const static CardRank C_4;
const static CardRank C_5;
const static CardRank C_6;
const static CardRank C_7;
const static CardRank C_8;
const static CardRank C_9;
const static CardRank C_T;
const static CardRank C_J;
const static CardRank C_Q;
const static CardRank C_K;
const static CardRank C_A;
const static CardRank PLACEHOLDER;
static CardRank from_val(int val);
static CardRank from_repr(char repr);
int get_val() const { return val; };
char get_repr() const { return repr; };
const CardRank& operator++();
const CardRank& operator--();
private:
constexpr CardRank(int val, char repr) : val{ val }, repr{ repr } {};
int val;
char repr;
};
inline bool operator<(CardRank hero, CardRank vill) { return hero.get_val() < vill.get_val(); }
inline bool operator>(CardRank hero, CardRank vill) { return vill < hero; }
inline bool operator==(CardRank hero, CardRank vill) { return !(hero < vill) && !(hero > vill); }
inline bool operator!=(CardRank hero, CardRank vill) { return !(hero == vill); }
inline bool operator>=(CardRank hero, CardRank vill) { return hero > vill || hero == vill; }
inline bool operator<=(CardRank hero, CardRank vill) { return hero < vill || hero == vill; }
// Card
class Card {
public:
Card() : rank{ CardRank::PLACEHOLDER }, suit{ CardSuit::PLACEHOLDER } {}
Card(CardRank rank, CardSuit suit) : rank{ rank }, suit{ suit } {}
Card(std::string card_str);
CardRank get_rank() const { return rank; }
CardSuit get_suit() const { return suit; }
std::string repr() const { return std::string{} + rank.get_repr() + static_cast<char>(suit); }
const Card& operator++() { ++rank; }
const Card& operator--() { --rank; }
private:
CardRank rank;
CardSuit suit;
};
inline bool operator<(Card hero, Card vill) { return hero.get_rank() < vill.get_rank(); }
inline bool operator>(Card hero, Card vill) { return vill < hero; }
inline bool operator==(Card hero, Card vill) { return !(hero < vill) && !(hero > vill); }
inline bool operator!=(Card hero, Card vill) { return !(hero == vill); }
inline bool operator>=(Card hero, Card vill) { return hero > vill || hero == vill; }
inline bool operator<=(Card hero, Card vill) { return hero < vill || hero == vill; }
// PokerHand
class PokerHand {
public:
PokerHand(Card card1, Card card2);
PokerHand(CardRank rank1, CardSuit suit1, CardRank rank2, CardSuit suit2);
PokerHand(std::string hand_str);
const Card& get_primary() const { return primary; }
const Card& get_secondary() const { return secondary; }
bool is_suited() const { return primary.get_suit() == secondary.get_suit(); }
bool is_pp() const { return primary.get_rank() == secondary.get_rank(); }
std::string repr() const { return primary.repr() + secondary.repr(); }
private:
Card primary;
Card secondary;
};
// Street
enum class Street {
PREFLOP = 0, FLOP = 3, TURN = 4, RIVER = 5
};
// Board
class Board {
public:
Board() { cards.reserve(5); }
Board(const std::vector<Card>& cards) : cards{ cards } {}
Board(const std::vector<Card>&& cards) : cards{ cards } {}
Board(std::string board_str);
void add_card(const Card& card) { cards.push_back(card); }
void pop_card() { cards.pop_back(); }
Street street() const { return static_cast<Street>(cards.size()); }
int count(CardRank rank) const;
int count(CardSuit rank) const;
const Card& operator[](int i) const { return cards[i]; }
Card& operator[](int i) { return cards[i]; }
std::vector<Card>::iterator begin() { return cards.begin(); }
std::vector<Card>::iterator end() { return cards.end(); }
std::vector<Card>::const_iterator begin() const { return cards.cbegin(); }
std::vector<Card>::const_iterator end() const { return cards.cend(); }
std::vector<Card>::reverse_iterator rbegin() { return cards.rbegin(); }
std::vector<Card>::reverse_iterator rend() { return cards.rend(); }
private:
std::vector<Card> cards;
};
}
</code></pre>
<p><strong>poker_game.cpp</strong></p>
<pre><code>#include "poker_game.h"
#include "random.h"
#include <stdexcept>
#include <list>
#include <iostream>
#include <algorithm>
#include <functional>
using std::cout;
using std::endl;
namespace Poker {
// CardRank
const CardRank CardRank::C_2{ 0, '2' };
const CardRank CardRank::C_3{ 1, '3' };
const CardRank CardRank::C_4{ 2, '4' };
const CardRank CardRank::C_5{ 3, '5' };
const CardRank CardRank::C_6{ 4, '6' };
const CardRank CardRank::C_7{ 5, '7' };
const CardRank CardRank::C_8{ 6, '8' };
const CardRank CardRank::C_9{ 7, '9' };
const CardRank CardRank::C_T{ 8, 'T' };
const CardRank CardRank::C_J{ 9, 'J' };
const CardRank CardRank::C_Q{ 10, 'Q' };
const CardRank CardRank::C_K{ 11, 'K' };
const CardRank CardRank::C_A{ 12, 'A' };
const CardRank CardRank::PLACEHOLDER{ -1, 'X' };
CardRank CardRank::from_val(int val)
{
// TODO: Add stacktrace to exception
switch (val) {
case 0: return CardRank::C_2; break;
case 1: return CardRank::C_3; break;
case 2: return CardRank::C_4; break;
case 3: return CardRank::C_5; break;
case 4: return CardRank::C_6; break;
case 5: return CardRank::C_7; break;
case 6: return CardRank::C_8; break;
case 7: return CardRank::C_9; break;
case 8: return CardRank::C_T; break;
case 9: return CardRank::C_J; break;
case 10: return CardRank::C_Q; break;
case 11: return CardRank::C_K; break;
case 12: return CardRank::C_A; break;
default: throw std::invalid_argument("CardRank::from_val - Invalid Argument: val =" + val);
}
}
CardRank CardRank::from_repr(char repr)
{
// TODO: Add stacktrace to exception
switch (repr) {
case '2': return CardRank::C_2; break;
case '3': return CardRank::C_3; break;
case '4': return CardRank::C_4; break;
case '5': return CardRank::C_5; break;
case '6': return CardRank::C_6; break;
case '7': return CardRank::C_7; break;
case '8': return CardRank::C_8; break;
case '9': return CardRank::C_9; break;
case 'T': return CardRank::C_T; break;
case 'J': return CardRank::C_J; break;
case 'Q': return CardRank::C_Q; break;
case 'K': return CardRank::C_K; break;
case 'A': return CardRank::C_A; break;
default: throw std::invalid_argument("CardRank::from_repr - Invalid Argument: repr = " + repr);
}
}
const CardRank& CardRank::operator++()
{
++val;
if (val == 13) val = 0;
repr = from_val(val).repr;
return *this;
}
const CardRank& CardRank::operator--()
{
--val;
if (val == -1) val = 12;
repr = from_val(val).repr;
return *this;
}
// Card
Card::Card(std::string card_str) :
rank{ CardRank::from_repr(card_str[0]) },
suit{ static_cast<CardSuit>(card_str[1]) } {}
// PokerHand
PokerHand::PokerHand(Card card1, Card card2) : primary{ card1 }, secondary{ card2 }
{
if (card1 < card2) {
primary = card2;
secondary = card1;
}
}
PokerHand::PokerHand(CardRank rank1, CardSuit suit1, CardRank rank2, CardSuit suit2) :
PokerHand(Card(rank1, suit1), Card(rank2, suit2)) {}
PokerHand::PokerHand(std::string hand_str) :
PokerHand(Card(hand_str.substr(0, 2)), Card(hand_str.substr(2, 2))) {}
// Board
Board::Board(std::string board_str)
{
cards.reserve(5);
for (unsigned int i = 0; i < board_str.size(); i += 2) {
cards.push_back(Card(board_str.substr(i, 2)));
}
}
int Board::count(CardRank rank) const
{
int count = 0;
for (const Card& c : cards) {
if (c.get_rank() == rank) {
count++;
}
}
return count;
}
int Board::count(CardSuit suit) const
{
int count = 0;
for (const Card& c : cards) {
if (c.get_suit() == suit) {
count++;
}
}
return count;
}
}
</code></pre>
<p><strong>showdown.h</strong></p>
<pre><code>#pragma once
#include "poker_game.h"
#include <string>
#include <vector>
#include <memory>
namespace Poker {
// HandType
enum class HandType : char {
HIGH_CARD = 0,
PAIR = 1,
TWO_PAIR = 2,
TRIPS = 3,
STRAIGHT = 4,
FLUSH = 5,
FULL_HOUSE = 6,
QUADS = 7,
STRAIGHT_FLUSH = 8,
ROYAL_FLUSH = 9
};
inline bool operator<(HandType hero, HandType vill) { return static_cast<int>(hero) < static_cast<int>(vill); }
inline bool operator>(HandType hero, HandType vill) { return vill < hero; }
inline bool operator==(HandType hero, HandType vill) { return !(hero < vill) && !(hero > vill); }
inline bool operator!=(HandType hero, HandType vill) { return !(hero == vill); }
inline bool operator>=(HandType hero, HandType vill) { return hero > vill || hero == vill; }
inline bool operator<=(HandType hero, HandType vill) { return hero < vill || hero == vill; }
// ShowdownHand
enum class Winner {
HERO, VILL, SPLIT
};
class ShowdownHand {
public:
virtual ~ShowdownHand() = default;
HandType get_hand_type() const { return hand_type; }
Winner get_winner(const ShowdownHand& vill) const;
std::string repr() const;
protected:
ShowdownHand(HandType hand_type, std::vector<Card> cards)
: hand_type{ hand_type }, cards{ cards } {}
const std::vector<Card>& get_cards() const { return cards; }
const std::vector<Card>& get_best_hand() const { return best_hand; }
void set_best_hand() const { best_hand = calc_best_hand(); }
private:
virtual Winner v_get_winner(const ShowdownHand& vill) const = 0;
virtual std::vector<Card> calc_best_hand() const = 0;
const HandType hand_type;
const std::vector<Card> cards;
mutable std::vector<Card> best_hand;
};
std::unique_ptr<ShowdownHand> eval_hand(const PokerHand& hand, const Board& board);
// HighCard : ShowdownHand
class HighCard : public ShowdownHand {
public:
HighCard(const std::vector<Card> cards) : ShowdownHand(HandType::HIGH_CARD, cards) {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
};
// Pair : ShowdownHand
class Pair : public ShowdownHand {
public:
Pair(CardRank pair_rank, const std::vector<Card> cards)
: ShowdownHand(HandType::PAIR, cards), pair_rank{ pair_rank } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
void cache_kickers() const;
const CardRank pair_rank;
mutable std::vector<Card> kickers;
};
// TwoPair : ShowdownHand
class TwoPair : public ShowdownHand {
public:
TwoPair(CardRank top_rank, CardRank bot_rank, const std::vector<Card> cards)
: ShowdownHand(HandType::TWO_PAIR, cards), top_rank{ top_rank }, bot_rank{ bot_rank } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
void cache_kicker() const;
const CardRank top_rank;
const CardRank bot_rank;
mutable Card kicker;
};
// Trips : ShowdownHand
class Trips : public ShowdownHand {
public:
Trips(CardRank set_rank, const std::vector<Card> cards)
: ShowdownHand(HandType::TRIPS, cards), trips_rank{ set_rank } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
void cache_kickers() const;
const CardRank trips_rank;
mutable std::vector<Card> kickers;
};
// Straight : ShowdownHand
class Straight : public ShowdownHand {
public:
Straight(CardRank top_rank, const std::vector<Card> cards)
: ShowdownHand(HandType::STRAIGHT, cards), top_rank{ top_rank } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
const CardRank top_rank;
};
// Flush : ShowdownHand
class Flush : public ShowdownHand {
public:
Flush(CardSuit flush_suit, const std::vector<Card> cards)
: ShowdownHand(HandType::FLUSH, cards), flush_suit{ flush_suit } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
const CardSuit flush_suit;
};
// FullHouse : ShowdownHand
class FullHouse : public ShowdownHand {
public:
FullHouse(CardRank trips_rank, CardRank pair_rank, const std::vector<Card> cards)
: ShowdownHand(HandType::FULL_HOUSE, cards), trips_rank{ trips_rank }, pair_rank{ pair_rank } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
const CardRank trips_rank;
const CardRank pair_rank;
};
// Quads : ShowdownHand
class Quads : public ShowdownHand {
public:
Quads(CardRank quads_rank, const std::vector<Card> cards)
: ShowdownHand(HandType::QUADS, cards), quads_rank{ quads_rank } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
void cache_kicker() const;
const CardRank quads_rank;
mutable Card kicker;
};
// StraightFlush : ShowdownHand
class StraightFlush : public ShowdownHand {
public:
StraightFlush(CardRank top_rank, CardSuit flush_suit, const std::vector<Card> cards)
: ShowdownHand(HandType::STRAIGHT_FLUSH, cards), top_rank{ top_rank }, flush_suit{ flush_suit } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
const CardRank top_rank;
const CardSuit flush_suit;
};
class RoyalFlush : public ShowdownHand {
public:
RoyalFlush(CardSuit flush_suit, const std::vector<Card> cards)
: ShowdownHand(HandType::ROYAL_FLUSH, cards), flush_suit{ flush_suit } {}
private:
Winner v_get_winner(const ShowdownHand& inp_vill) const override;
std::vector<Card> calc_best_hand() const override;
const CardSuit flush_suit;
};
Winner showdown(const PokerHand& hero, const PokerHand& vill, const Board& board);
}
</code></pre>
<p><strong>showdown.cpp</strong></p>
<pre><code>#include "showdown.h"
#include <stdexcept>
#include <list>
#include <iostream>
#include <algorithm>
#include <functional>
#include <map>
namespace Poker {
std::vector<Card> get_all_cards(const PokerHand& hand, const Board& board)
{
std::vector<Card> all_cards;
all_cards.reserve(7);
all_cards.push_back(hand.get_primary());
all_cards.push_back(hand.get_secondary());
all_cards.insert(all_cards.end(), board.begin(), board.end());
return all_cards;
}
std::vector<Card> filter_cards(
const std::vector<Card>& cards, const std::function <bool(const Card&)> filter)
{
std::vector<Card> filtered;
filtered.reserve(7);
for (const Card& card : cards) {
if (filter(card)) {
filtered.push_back(card);
}
}
return filtered;
}
// eval_hand
CardSuit check_flush(const std::map<CardSuit, int>& suits)
{
for (std::pair<CardSuit, int> e : suits) {
if (e.second >= 5) {
return e.first;
}
}
return CardSuit::PLACEHOLDER;
}
CardRank check_straight(const std::vector<Card>& all_cards)
{
int counter = 0;
int next_val;
CardRank top_rank = CardRank::PLACEHOLDER;
for (unsigned int i = 0; i < all_cards.size() - 1; i++) {
if (all_cards[i].get_rank() == all_cards[i + 1].get_rank()) {
continue;
}
next_val = all_cards[i].get_rank().get_val() - 1;
if (all_cards[i + 1].get_rank().get_val() == next_val) {
++counter;
if (counter == 1) top_rank = all_cards[i].get_rank();
else if (counter == 4) return top_rank;
}
else {
counter = 0;
}
}
if (counter == 3 &&
all_cards.back().get_rank() == CardRank::C_2 &&
all_cards.front().get_rank() == CardRank::C_A)
{
return CardRank::C_5;
}
return CardRank::PLACEHOLDER;
}
void process_matches(const std::map<CardRank, int>& rank_matches,
std::vector<CardRank>& pairs, std::vector<CardRank>& trips, CardRank& quads)
{
for (std::pair<CardRank, int> match : rank_matches) {
if (match.second == 2) pairs.push_back(match.first);
else if (match.second == 3) trips.push_back(match.first);
else if (match.second == 4) quads = match.first;
}
}
ShowdownHand* make_royal_flush(CardSuit flush_suit, const std::vector<Card>& all_cards)
{
int suit_counter = 0;
for (unsigned int i = 0; i < all_cards.size() - 1; i++) {
if (all_cards[i].get_rank() == all_cards[i + 1].get_rank()) {
continue;
}
if (all_cards[i].get_suit() == flush_suit) {
++suit_counter;
if (suit_counter == 5) {
break;
}
}
else {
return nullptr;
}
}
return new RoyalFlush(flush_suit, all_cards);
}
ShowdownHand* make_straight_flush(CardRank top_rank, CardSuit flush_suit, const std::vector<Card>& all_cards)
{
int suit_counter = 0;
int card_count = all_cards.size();
for (int i = 0; i < card_count; i++) {
if (all_cards[i].get_rank() > top_rank) {
continue;
}
if (i != card_count - 1 &&
all_cards[i].get_rank() == all_cards[i + 1].get_rank() &&
all_cards[i].get_suit() != flush_suit)
{
continue;
}
if (i != 0 &&
all_cards[i - 1].get_rank() == all_cards[i].get_rank() &&
all_cards[i].get_suit() != flush_suit)
{
continue;
}
if (suit_counter == 0 && all_cards[i].get_suit() != flush_suit) {
--top_rank;
continue;
}
if (all_cards[i].get_suit() == flush_suit) {
++suit_counter;
if (suit_counter == 5) {
break;
}
}
else {
suit_counter = 0;
}
}
return new StraightFlush(top_rank, flush_suit, all_cards);
}
std::unique_ptr<ShowdownHand> eval_hand(const PokerHand& hand, const Board& board)
{
std::vector<Card> all_cards = get_all_cards(hand, board);
std::sort(all_cards.rbegin(), all_cards.rend());
std::map<CardRank, int> rank_matches;
std::map<CardSuit, int> suits;
for (const Card& card : all_cards) {
++rank_matches[card.get_rank()];
++suits[card.get_suit()];
}
CardSuit flush_suit = check_flush(suits);
CardRank straight_rank = check_straight(all_cards);
bool is_flush = flush_suit != CardSuit::PLACEHOLDER;
bool is_straight = straight_rank != CardRank::PLACEHOLDER;
ShowdownHand* hand_ptr = nullptr;
// Royal Flush, Straight Flush
if (is_flush && is_straight) {
if (straight_rank == CardRank::C_A) {
hand_ptr = make_royal_flush(flush_suit, all_cards);
if (hand_ptr) return std::unique_ptr<ShowdownHand>(hand_ptr);
}
else {
hand_ptr = make_straight_flush(straight_rank, flush_suit, all_cards);
if (hand_ptr) return std::unique_ptr<ShowdownHand>(hand_ptr);
}
}
std::vector<CardRank> pairs;
std::vector<CardRank> trips;
CardRank quads = CardRank::PLACEHOLDER;
process_matches(rank_matches, pairs, trips, quads);
bool is_trips = trips.size() >= 1;
bool is_pair = pairs.size() >= 1;
if(is_pair) std::sort(pairs.rbegin(), pairs.rend());
if(is_trips) std::sort(trips.rbegin(), trips.rend());
// Quads
if (quads != CardRank::PLACEHOLDER) {
return std::unique_ptr<ShowdownHand>(new Quads(quads, all_cards));
}
// Full house
if (is_trips) {
if (is_pair) {
return std::unique_ptr<ShowdownHand>(new FullHouse(trips[0], pairs[0], all_cards));
}
else if (trips.size() == 2) {
return std::unique_ptr<ShowdownHand>(new FullHouse(trips[0], trips[1], all_cards));
}
}
// Flush
if (is_flush) {
return std::unique_ptr<ShowdownHand>(new Flush(flush_suit, all_cards));
}
// Straight
if (is_straight) {
return std::unique_ptr<ShowdownHand>(new Straight(straight_rank, all_cards));
}
// Trips
if (is_trips) {
return std::unique_ptr<ShowdownHand>(new Trips(trips[0], all_cards));
}
// Two Pair
if (pairs.size() >= 2) {
return std::unique_ptr<ShowdownHand>(new TwoPair(pairs[0], pairs[1], all_cards));
}
// Pair
if (is_pair) {
return std::unique_ptr<ShowdownHand>(new Pair(pairs[0], all_cards));
}
// High Card
return std::unique_ptr<ShowdownHand>(new HighCard(all_cards));
}
// ShowdownHand
std::string hand_type_to_str(HandType hand_type)
{
switch (hand_type) {
case HandType::HIGH_CARD: return "High Card";
case HandType::PAIR: return "Pair";
case HandType::TWO_PAIR: return "Two Pair";
case HandType::TRIPS: return "Trips";
case HandType::STRAIGHT: return "Straight";
case HandType::FLUSH: return "Flush";
case HandType::FULL_HOUSE: return "Full House";
case HandType::QUADS: return "Quads";
case HandType::STRAIGHT_FLUSH: return "Straight Flush";
case HandType::ROYAL_FLUSH: return "Royal Flush";
default: throw std::invalid_argument("hand_type_to_str - Invalid Argument!");
}
}
Winner ShowdownHand::get_winner(const ShowdownHand& vill) const
{
if (hand_type != vill.hand_type) {
return hand_type > vill.hand_type ? Winner::HERO : Winner::VILL;
}
return v_get_winner(vill);
}
std::string ShowdownHand::repr() const
{
if (best_hand.size() != 5) {
set_best_hand();
}
std::string hand_repr = hand_type_to_str(hand_type);
hand_repr += " [";
for (const Card& card : best_hand) {
hand_repr += card.repr() + " ";
}
hand_repr.pop_back();
hand_repr += "]";
return hand_repr;
}
Winner compare_kickers(const std::vector<Card>& kickers_h, const std::vector<Card>& kickers_v) {
for (unsigned int i = 0; i < kickers_h.size(); i++) {
if (kickers_h[i] > kickers_v[i]) {
return Winner::HERO;
}
else if (kickers_h[i] < kickers_v[i]) {
return Winner::VILL;
}
}
return Winner::SPLIT;
}
// HighCard : ShowdownHand
Winner HighCard::v_get_winner(const ShowdownHand& inp_vill) const
{
const HighCard& vill = static_cast<const HighCard&>(inp_vill);
const std::vector<Card>& kickers_h = get_best_hand();
const std::vector<Card>& kickers_v = vill.get_best_hand();
if (kickers_h.size() != 5) {
set_best_hand();
}
if (kickers_v.size() != 5) {
vill.set_best_hand();
}
return compare_kickers(kickers_h, kickers_v);
}
std::vector<Card> HighCard::calc_best_hand() const
{
const std::vector<Card>& cards = get_cards();
std::vector<Card> best_hand(cards.begin(), cards.begin() + 5);
return best_hand;
}
// Pair : ShowdownHand
Winner Pair::v_get_winner(const ShowdownHand& inp_vill) const
{
const Pair& vill = static_cast<const Pair&>(inp_vill);
if (pair_rank > vill.pair_rank) return Winner::HERO;
if (pair_rank < vill.pair_rank) return Winner::VILL;
if (kickers.size() != 3) cache_kickers();
if (vill.kickers.size() != 3) vill.cache_kickers();
return compare_kickers(kickers, vill.kickers);
}
std::vector<Card> Pair::calc_best_hand() const
{
if (kickers.size() != 3) {
cache_kickers();
}
std::vector<Card> best_hand;
best_hand.reserve(5);
for (const Card& card : get_cards()) {
if (card.get_rank() == pair_rank) {
best_hand.push_back(card);
}
}
best_hand.insert(best_hand.end(), kickers.begin(), kickers.end());
return best_hand;
}
void Pair::cache_kickers() const
{
kickers = filter_cards(get_cards(), [this](const Card& card) { return card.get_rank() != pair_rank; });
std::sort(kickers.rbegin(), kickers.rend());
kickers.erase(kickers.begin() + 3, kickers.end());
}
// TwoPair : ShowdownHand
Winner TwoPair::v_get_winner(const ShowdownHand& inp_vill) const
{
const TwoPair& vill = static_cast<const TwoPair&>(inp_vill);
if (top_rank > vill.top_rank) return Winner::HERO;
if (top_rank < vill.top_rank) return Winner::VILL;
if (bot_rank > vill.bot_rank) return Winner::HERO;
if (bot_rank < vill.bot_rank) return Winner::VILL;
if (kicker.get_rank() == CardRank::PLACEHOLDER) cache_kicker();
if (vill.kicker.get_rank() == CardRank::PLACEHOLDER) vill.cache_kicker();
if (kicker > vill.kicker) return Winner::HERO;
if (kicker < vill.kicker) return Winner::VILL;
return Winner::SPLIT;
}
std::vector<Card> TwoPair::calc_best_hand() const
{
if (kicker.get_rank() == CardRank::PLACEHOLDER) {
cache_kicker();
}
const std::vector<Card>& cards = get_cards();
std::vector<Card> best_hand;
best_hand.reserve(5);
for (const Card& card : cards) {
if (card.get_rank() == top_rank) {
best_hand.push_back(card);
}
}
for (const Card& card : cards) {
if (card.get_rank() == bot_rank) {
best_hand.push_back(card);
}
}
best_hand.push_back(kicker);
return best_hand;
}
void TwoPair::cache_kicker() const
{
std::vector<Card> cards = filter_cards(
get_cards(),
[this](const Card& card) {
CardRank rank = card.get_rank();
return rank != top_rank && rank != bot_rank;
});
kicker = *std::max_element(cards.begin(), cards.end());
}
// Trips : ShowdownHand
Winner Trips::v_get_winner(const ShowdownHand& inp_vill) const
{
const Trips& vill = static_cast<const Trips&>(inp_vill);
if (trips_rank > vill.trips_rank) return Winner::HERO;
if (trips_rank < vill.trips_rank) return Winner::VILL;
if (kickers.size() != 2) cache_kickers();
if (vill.kickers.size() != 2) vill.cache_kickers();
return compare_kickers(kickers, vill.kickers);
}
std::vector<Card> Trips::calc_best_hand() const
{
if (kickers.size() != 2) {
cache_kickers();
}
std::vector<Card> best_hand;
best_hand.reserve(5);
for (const Card& card : get_cards()) {
if (card.get_rank() == trips_rank) {
best_hand.push_back(card);
}
}
best_hand.insert(best_hand.end(), kickers.begin(), kickers.end());
return best_hand;
}
void Trips::cache_kickers() const
{
kickers = filter_cards(get_cards(), [this](const Card& card) { return card.get_rank() != trips_rank; });
std::sort(kickers.rbegin(), kickers.rend());
kickers.erase(kickers.begin() + 2, kickers.end());
}
// Straight : ShowdownHand
Winner Straight::v_get_winner(const ShowdownHand& inp_vill) const
{
const Straight& vill = static_cast<const Straight&>(inp_vill);
if (top_rank > vill.top_rank) return Winner::HERO;
if (top_rank < vill.top_rank) return Winner::VILL;
return Winner::SPLIT;
}
std::vector<Card> Straight::calc_best_hand() const
{
const std::vector<Card>& cards = get_cards();
std::vector<Card> best_hand;
best_hand.reserve(5);
CardRank rank = top_rank;
for (const Card& card : cards) {
if (card.get_rank() == rank) {
best_hand.push_back(card);
--rank;
if (best_hand.size() == 5) break;
}
}
if (best_hand.size() == 4 && cards[0].get_rank() == CardRank::C_A) {
best_hand.push_back(cards[0]);
}
return best_hand;
}
// Flush : ShowdownHand
Winner Flush::v_get_winner(const ShowdownHand& inp_vill) const
{
const Flush& vill = static_cast<const Flush&>(inp_vill);
const std::vector<Card>& kickers_h = get_best_hand();
const std::vector<Card>& kickers_v = vill.get_best_hand();
if (kickers_h.size() != 5) {
set_best_hand();
}
if (kickers_v.size() != 5) {
vill.set_best_hand();
}
return compare_kickers(kickers_h, kickers_v);
}
std::vector<Card> Flush::calc_best_hand() const
{
std::vector<Card> best_hand = filter_cards(
get_cards(), [this](const Card& card) { return card.get_suit() == flush_suit; });
std::sort(best_hand.rbegin(), best_hand.rend());
if (best_hand.size() > 5) {
best_hand.erase(best_hand.begin() + 5, best_hand.end());
}
return best_hand;
}
// FullHouse : ShowdownHand
Winner FullHouse::v_get_winner(const ShowdownHand& inp_vill) const
{
const FullHouse& vill = static_cast<const FullHouse&>(inp_vill);
if (trips_rank > vill.trips_rank) return Winner::HERO;
if (trips_rank < vill.trips_rank) return Winner::VILL;
if (pair_rank > vill.pair_rank) return Winner::HERO;
if (pair_rank < vill.pair_rank) return Winner::VILL;
return Winner::SPLIT;
}
std::vector<Card> FullHouse::calc_best_hand() const
{
const std::vector<Card>& cards = get_cards();
std::vector<Card> best_hand;
best_hand.reserve(5);
for (const Card& card : cards) {
if (card.get_rank() == trips_rank) {
best_hand.push_back(card);
}
}
for (const Card& card : cards) {
if (card.get_rank() == pair_rank) {
best_hand.push_back(card);
}
}
return best_hand;
}
// Quads : ShowdownHand
Winner Quads::v_get_winner(const ShowdownHand& inp_vill) const
{
const Quads& vill = static_cast<const Quads&>(inp_vill);
if (kicker.get_rank() == CardRank::PLACEHOLDER) cache_kicker();
if (vill.kicker.get_rank() == CardRank::PLACEHOLDER) vill.cache_kicker();
if (quads_rank > vill.quads_rank) return Winner::HERO;
if (quads_rank < vill.quads_rank) return Winner::VILL;
if (kicker > vill.kicker) return Winner::HERO;
if (kicker < vill.kicker) return Winner::VILL;
return Winner::SPLIT;
}
std::vector<Card> Quads::calc_best_hand() const
{
std::vector<Card> best_hand;
best_hand.reserve(5);
best_hand = filter_cards(
get_cards(), [this](const Card& card) { return card.get_rank() == quads_rank; });
if (kicker.get_rank() == CardRank::PLACEHOLDER) {
cache_kicker();
}
best_hand.push_back(kicker);
return best_hand;
}
void Quads::cache_kicker() const {
std::vector<Card> all_cards = filter_cards(
get_cards(), [this](const Card& card) { return card.get_rank() != quads_rank; });
kicker = *std::max_element(all_cards.begin(), all_cards.end());
}
// StraightFlush : ShowdownHand
Winner StraightFlush::v_get_winner(const ShowdownHand& inp_vill) const
{
const StraightFlush& vill = static_cast<const StraightFlush&>(inp_vill);
if (top_rank > vill.top_rank) return Winner::HERO;
if (top_rank < vill.top_rank) return Winner::VILL;
return Winner::SPLIT;
}
std::vector<Card> StraightFlush::calc_best_hand() const
{
std::vector<Card> all_cards = filter_cards(
get_cards(), [this](const Card& card) { return card.get_suit() == flush_suit; });
std::sort(all_cards.rbegin(), all_cards.rend());
std::vector<Card> best_hand;
best_hand.reserve(5);
CardRank rank = top_rank;
for (const Card& card : all_cards) {
if (card.get_rank() == rank) {
best_hand.push_back(card);
--rank;
if (best_hand.size() == 5) break;
}
}
return best_hand;
}
// RoyalFlush : ShowdownHand
Winner RoyalFlush::v_get_winner(const ShowdownHand& inp_vill) const
{
throw std::logic_error("RoyalFlush::v_get_winner - Cannot compare two Royal Flushes!");
}
std::vector<Card> RoyalFlush::calc_best_hand() const
{
std::vector<Card> best_hand = filter_cards(
get_cards(), [this](const Card& card) { return card.get_suit() == flush_suit; });
std::sort(best_hand.rbegin(), best_hand.rend());
if (best_hand.size() > 5) {
best_hand.erase(best_hand.begin() + 5, best_hand.end());
}
return best_hand;
}
Winner showdown(const PokerHand& hero, const PokerHand& vill, const Board& board) {
return eval_hand(hero, board)->get_winner(*eval_hand(vill, board));
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T02:41:27.243",
"Id": "513003",
"Score": "1",
"body": "Hi @JGrohmann - the Card operator< and other operators are not \"stable\" ... i.e. given two cards with the same rank but different suit they don't make for a comparison that is logically the same ie. a<b is -b<a"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T19:32:51.670",
"Id": "513052",
"Score": "0",
"body": "@MrR, I see what you mean, thanks for catching that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T00:47:55.360",
"Id": "513076",
"Score": "0",
"body": "A quick fix is to use array lookup instead of `switch`."
}
] |
[
{
"body": "<p>Your code looks very well written, following many C++ best practices. The only strange things I found is that you don't use <code>auto</code> inside <code>for</code>-statements, for example I would write <code>for (auto &c: cards)</code> instead of <code>for (const Card &c: cards)</code>, and some missed opportunities for using <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique\" rel=\"nofollow noreferrer\"><code>std::make_unique</code></a>. So I'll focus only on the performance aspect of your code.</p>\n<h1>What should the result of hand strength evaluation be?</h1>\n<p>The <code>ShowdownHand</code> class is quite heavy. It contains two <code>std::vector</code>s, one for all cards, one for the best hand. And to get the result, you have to go via a <code>virtual</code> function that compares it against an opponent's hand. Is all this information necessary? And if it is, does a copy need to be stored in <code>ShowdownHand</code> if this information should still be in the <code>PokerHand</code> and <code>Board</code> that were used as input for <code>eval_hand()</code>?</p>\n<p>Keep the information kept for the result to a minimum, and avoid making unnecessary copies.</p>\n<h1>Use arrays instead of fixed-size vectors and maps</h1>\n<p>You have a lot of <code>std::vectors</code> of a fixed, small size. This means there is a lot of overhead from heap allocations and pointer indirections. Use <a href=\"https://en.cppreference.com/w/cpp/container/array\" rel=\"nofollow noreferrer\"><code>std::array</code></a>s instead in these cases.</p>\n<p>I also see <code>std::map</code>s being used that will only ever contain just a few elements. Consider for example:</p>\n<pre><code>std::map<CardSuit, int> suits;\nfor (const Card& card : all_cards) {\n ...\n ++suits[card.get_suit()];\n}\n</code></pre>\n<p>There are only five possible suits, so it would be much more efficient to write:</p>\n<pre><code>std::array<int, 5> suits{};\nfor (const Card& card : all_cards) {\n ...\n ++suits[card.get_suit_index()];\n}\n</code></pre>\n<p>Where <code>get_suit_index()</code> would return a value between 0 and 5. The latter would be trivial if you just made <code>enum class CardSuit</code> have values from 0 to 5. Which brings me to:</p>\n<h1>Avoid unnecessary conversions</h1>\n<p>The <code>CardRank</code> class is very weird. It has 14 static members of its own type, functions to convert to/from those static members, a <code>repr</code> member that is not useful for the hand evaluation logic itself. Also, why are <code>val</code> and <code>repr</code> not <code>const</code>? The <code>operator++</code> and <code>operator--</code> functions return a pointer to a <code>CardRank</code>, but the class is small enough that it would be better to return a <code>CardRank</code> by value.</p>\n<p>While abstraction is good, you should do it in such a way that it is efficient. A <code>CardRank</code> should just be an integer, nothing more. There should be no <code>static</code> instances of <code>CardRank</code>s. The only slow thing should be converting to/from a character representation, and that conversion should only be done during input/output operations, like reading in the board and hand state, or printing those out.</p>\n<h1>Sorting hands</h1>\n<p>You have to sort cards in several places in your code. The standard library provides <code>std::sort</code> which is optimized for general usage. However, here we have a special case where we have only a few items to sort, and sometimes we know exactly how many items we have. In this case, <a href=\"https://stackoverflow.com/questions/31471951/is-stdsort-optimized-for-sorting-small-amount-of-items-too\"><code>std::sort</code> might not be optimal</a>, and a hand-written sorting function might be faster.</p>\n<p>You might also investigate whether sorting is necessary in all cases. Does it make sense to sort <code>all_cards</code> at the start of <code>eval_hand()</code>? If so, why do you need to sort again in <code>calc_best_hand()</code>, when it seems like you could skip that and just iterate over that <code>all_cards</code> in reverse, or fill the vector <code>best_hand</code> from the back.</p>\n<p>It also looks like sometimes a <a href=\"https://en.cppreference.com/w/cpp/algorithm/partial_sort\" rel=\"nofollow noreferrer\"><code>std::partial_sort()</code></a> is all you need.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T19:49:17.040",
"Id": "513057",
"Score": "0",
"body": "Thanks for the detailed review, I'll implement these changes and see how they change performance. Aside from what was mentioned here, I also noticed my algorithm for straights can be made more efficient, and a lot of performance was lost allocating and deleting memory after each evaluation, rather than allocating once and reusing the memory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T12:09:18.647",
"Id": "259981",
"ParentId": "259959",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259981",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T19:48:13.993",
"Id": "259959",
"Score": "3",
"Tags": [
"c++",
"performance",
"algorithm",
"playing-cards"
],
"Title": "Poker Hand Evaluation (speed optimization)"
}
|
259959
|
<p>I have written a class library for creating timer-based bacground operations in .NET projects. The idea is to be able to create and manage (start/stop/resume/cancel) recurring background operations and also to be able to poll and/or react to changes in the background operation's state.</p>
<p>The library consists mainly of two things:</p>
<p><strong>RecurringOperation</strong> model/class</p>
<ul>
<li>Encapsulates and represents a single action/method which is executed in specified intervals.</li>
<li>Represents the state of the recurring operation, providing properties and events to bind to.</li>
<li>Supports XAML and MVVM pattern to bind UI controls to the state of the recurring operation.</li>
</ul>
<p><strong>RecurringOperationManager</strong> singleton class</p>
<ul>
<li>Responsible for managing all RecurringOperation objects inside an application (starting/stopping/resuming).</li>
<li>Responsible for executing recurring operations in a thread safe way and makes sure that a single recurring operation does not "queue up" if the execution of a recurring operation takes longer than the specified interval for that operation.</li>
</ul>
<p>I'd like your opinion on</p>
<ul>
<li>The overall code quality and readability (any glaring bugs or mistakes)</li>
<li>The architecture and implemenation of the <strong>RecurringOperation</strong> and <strong>RecurringOperationManager</strong> classes</li>
</ul>
<hr>
<p>In order to get the general idea about the usage of the library, please take a look at the readme on the github page at
<a href="https://github.com/TDMR87/Recurop" rel="nofollow noreferrer">https://github.com/TDMR87/Recurop</a></p>
<p>To see the library being used, take a look at this github page. The project creates a stopwatch program in WPF using this library.
<a href="https://github.com/TDMR87/RecuropDemo" rel="nofollow noreferrer">https://github.com/TDMR87/RecuropDemo</a></p>
<hr>
<p>The implementation of the <strong>RecurringOperation</strong> class looks like this:</p>
<pre><code>public class RecurringOperation : INotifyPropertyChanged
{
public RecurringOperation(string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new InvalidOperationException(Constants.UnnamedOperationException);
_name = name;
IsExecuting = false;
IsRecurring = false;
IsNotRecurring = true;
IsPaused = false;
IsIdle = true;
IsCancelled = false;
IsNotCancelled = true;
CallbackLock = new object();
Status = RecurringOperationStatus.Idle;
CanBeStarted = true;
}
private readonly string _name;
/// <summary>
/// Indicates whether the recurring operation can be started.
/// </summary>
public bool CanBeStarted
{
get => canBeStarted;
internal set
{
canBeStarted = value;
OnPropertyChanged();
}
}
private bool canBeStarted;
/// <summary>
/// Indicates whether the recurring background operation is
/// currently executing it's specified action.
/// </summary>
public bool IsExecuting
{
get => isExecuting;
internal set
{
isExecuting = value;
OnPropertyChanged();
}
}
private bool isExecuting;
/// <summary>
/// Indicates whether the recurring background operation is
/// currently in recurring state (and not cancelled, for example).
/// </summary>
public bool IsRecurring
{
get => isRecurring;
internal set
{
isRecurring = value;
OnPropertyChanged();
}
}
private bool isRecurring;
/// <summary>
/// Indicates whether the recurring background operation is
/// currently in recurring state.
/// </summary>
public bool IsNotRecurring
{
get => isNotRecurring;
internal set
{
isNotRecurring = value;
OnPropertyChanged();
}
}
private bool isNotRecurring;
/// <summary>
/// Indicates whether the recurring background operation is
/// currently in cancelled state.
/// </summary>
public bool IsCancelled
{
get => isCancelled;
internal set
{
isCancelled = value;
OnPropertyChanged();
}
}
private bool isCancelled;
/// <summary>
/// Indicates whether the recurring background operation is
/// currently not in cancelled state.
/// </summary>
public bool IsNotCancelled
{
get => isNotCancelled;
internal set
{
isNotCancelled = value;
OnPropertyChanged();
}
}
private bool isNotCancelled;
/// <summary>
/// Indicates whether the recurring operation is currently paused.
/// </summary>
public bool IsPaused
{
get => isPaused;
internal set
{
isPaused = value;
OnPropertyChanged();
}
}
private bool isPaused;
/// <summary>
/// Indicates whether the recurring operation is idle. An idle state means that
/// the operation is not yet started or it has been aborted.
/// </summary>
public bool IsIdle
{
get => isIdle;
set
{
isIdle = value;
OnPropertyChanged();
}
}
private bool isIdle;
/// <summary>
/// The start time of the latest background operation execution.
/// </summary>
public DateTime LastRunStart
{
get => lastRunStart;
internal set
{
lastRunStart = value;
OnPropertyChanged();
}
}
private DateTime lastRunStart;
/// <summary>
/// The start time of the latest background operation execution.
/// </summary>
public DateTime LastRunFinish
{
get => lastRunFinish;
internal set
{
lastRunFinish = value;
OnPropertyChanged();
}
}
private DateTime lastRunFinish;
public RecurringOperationStatus Status
{
get => status;
internal set
{
status = value;
OnStatusChanged();
OnPropertyChanged();
}
}
private RecurringOperationStatus status;
/// <summary>
/// A lock object used to prevent overlapping threads from modifying
/// the properties of the Background Operation object. Use with lock-statement.
/// </summary>
internal object CallbackLock { get; }
/// <summary>
/// When the Background Operation's action delegate throws an exception,
/// the exception is accessible through this property. The next exception
/// in the action delegate will override any previous value in this property.
/// </summary>
public Exception Exception
{
get => exception;
internal set
{
exception = value;
OnOperationFaulted();
}
}
private Exception exception;
/// <summary>
/// The event handler is triggered whenever the status of
/// the background operation changes.
/// </summary>
public event Action StatusChanged;
/// <summary>
/// The event handler is triggered when the
/// Background Operation's action delegate throws an exception.
/// </summary>
public event Action<Exception> OperationFaulted;
/// <summary>
/// The event handler is triggered when properties of the Background Operation
/// change value.
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
protected void OnStatusChanged()
{
StatusChanged?.Invoke();
}
protected void OnOperationFaulted()
{
OperationFaulted?.Invoke(Exception);
}
/// <summary>
/// Returns the identifying name of this background operation.
/// </summary>
/// <returns></returns>
public string GetName()
{
if (string.IsNullOrWhiteSpace(_name))
{
throw new InvalidOperationException(Constants.UninitializedOperationException);
}
return _name;
}
/// <summary>
/// Returns the identifying name of this background operation.
/// </summary>
/// <returns></returns>
public override string ToString()
{
if (string.IsNullOrWhiteSpace(_name))
{
throw new InvalidOperationException(Constants.UninitializedOperationException);
}
return _name;
}
}
</code></pre>
<p>And the RecurringOperationManager class looks like this:</p>
<pre><code>public sealed class RecurringOperations
{
private static RecurringOperations instance = null;
private static readonly object instanceLock = new object();
private readonly List<Operation> recurringOperations;
/// <summary>
/// Private singleton constructor.
/// </summary>
private RecurringOperations()
{
recurringOperations = new List<Operation>();
}
/// <summary>
/// Public singleton instance.
/// </summary>
public static RecurringOperations Manager
{
get
{
lock (instanceLock)
{
if (instance == null) instance = new RecurringOperations();
return instance;
}
}
}
/// <summary>
/// Resumes the execution of the specified recurring operation
/// if currently in Paused state. Resuming a cancelled operation
/// throws an exception.
/// </summary>
/// <param name="operation"></param>
/// <param name="interval"></param>
/// <param name="action"></param>
/// <param name="startImmediately"></param>
public void ResumeRecurring(RecurringOperation operation, bool startImmediately = false)
{
// If an uninitialized background operation object was given as an argument
if (operation == null || string.IsNullOrWhiteSpace(operation.GetName()))
throw new InvalidOperationException(Constants.UninitializedOperationException);
// If cancelled
if (operation.Status == RecurringOperationStatus.Cancelled)
{
var exception = new InvalidOperationException(Constants.CancelledOperationException);
operation.Exception = exception;
throw exception;
}
// Search the Manager's collection of operations for an operation
var recurringOperation =
recurringOperations.Find(op => op.Name.Equals(operation.GetName()));
// If the operation was found and is not recurring
if (recurringOperation != null)
{
// Set background operation status
operation.Status = RecurringOperationStatus.Idle;
operation.IsIdle = true;
operation.IsRecurring = true;
operation.IsNotRecurring = false;
operation.IsPaused = false;
operation.IsExecuting = false;
// Re-start the operation
recurringOperation.Timer.Change(
startImmediately ? TimeSpan.Zero : recurringOperation.Interval, recurringOperation.Interval);
}
}
/// <summary>
/// Creates and/or starts a recurring operation.
/// If an operation has already been started,
/// an exception will be thrown.
/// </summary>
/// <param name="backgroundOperation"></param>
/// <param name="interval"></param>
/// <param name="action"></param>
/// <param name="startImmediately"></param>
public void StartRecurring(RecurringOperation backgroundOperation, TimeSpan interval, Action action, bool startImmediately = false)
{
// If an uninitialized background operation object was given as an argument
if (backgroundOperation == null || string.IsNullOrWhiteSpace(backgroundOperation.GetName()))
throw new InvalidOperationException(Constants.UninitializedOperationException);
// Search the Manager's collection of operations for an operation
// that corresponds with the background operation
var recurringOperation =
recurringOperations.Find(op => op.Name.Equals(backgroundOperation.GetName()));
// If operation has already been registered
if (recurringOperation != null)
{
throw new InvalidOperationException($"{Constants.RecurringOperationException}. " +
$"Operation name '{recurringOperation.Name}'.");
}
// Create a new recurring operation object
var operation = new Operation
{
Name = backgroundOperation.GetName(),
Interval = interval
};
// This is a local function here..
// ..Create a callback function for the timer
void TimerCallback(object state)
{
// To indicate if a thread has entered
// a block of code.
bool lockAcquired = false;
try
{
// Try to acquire a lock.
// Sets the value of the lockAcquired, even if the method throws an exception,
// so the value of the variable is a reliable way to test whether the lock has to be released.
Monitor.TryEnter(backgroundOperation.CallbackLock, ref lockAcquired);
// If lock acquired
if (lockAcquired)
{
// Set background operation status
backgroundOperation.LastRunStart = DateTime.Now;
backgroundOperation.IsExecuting = true;
backgroundOperation.IsIdle = false;
backgroundOperation.Status = RecurringOperationStatus.Executing;
try
{
action();
}
catch (Exception ex)
{
// Set reference to the catched exception in the background operations exception property
backgroundOperation.Exception = ex;
}
finally
{
// Set last run finish time
backgroundOperation.LastRunFinish = DateTime.Now;
// Set background operation state
backgroundOperation.IsExecuting = false;
backgroundOperation.IsIdle = true;
// If not cancelled
if (backgroundOperation.Status != RecurringOperationStatus.Cancelled)
{
// Set status to idle
backgroundOperation.Status = RecurringOperationStatus.Idle;
}
}
}
}
finally
{
// If a thread acquired the lock
if (lockAcquired)
{
// Release the lock
Monitor.Exit(backgroundOperation.CallbackLock);
}
}
} // End local funtion
// Create a timer that calls the action in specified intervals
// and save the timer in the recurring operations Timer property
operation.Timer = new Timer(
new TimerCallback(TimerCallback), null, startImmediately ? TimeSpan.Zero : interval, interval);
// Add the recurring operation to the Manager's collection
recurringOperations.Add(operation);
// Set status of the client-side background operation
backgroundOperation.Status = RecurringOperationStatus.Idle;
backgroundOperation.IsRecurring = true;
backgroundOperation.IsNotRecurring = false;
backgroundOperation.IsPaused = false;
backgroundOperation.IsIdle = false;
backgroundOperation.CanBeStarted = false;
}
/// <summary>
/// Pauses the recurring execution of the operation.
/// Execution can be continued with a call to ResumeRecurring().
/// </summary>
/// <param name="backgroundOperation"></param>
public void PauseRecurring(RecurringOperation backgroundOperation)
{
// Search the Manager's collection of operations for an operation
// that corresponds with the background operation
var privateOperation =
recurringOperations.Find(
operation => operation.Name.Equals(backgroundOperation.GetName()));
// If found
if (privateOperation != null)
{
// Pause the timer
privateOperation.Timer.Change(Timeout.Infinite, Timeout.Infinite);
// Set the status of the client-side background operation
backgroundOperation.Status = RecurringOperationStatus.Idle;
backgroundOperation.IsRecurring = false;
backgroundOperation.IsNotRecurring = true;
backgroundOperation.IsPaused = true;
backgroundOperation.IsIdle = true;
backgroundOperation.IsExecuting = false;
}
}
/// <summary>
/// Cancels the specified recurring operation.
/// Cancelled operations cannot be resumed, they must be restarted
/// with a call to StartRecurring.
/// </summary>
/// <param name="backgroundOperation"></param>
public void Cancel(RecurringOperation backgroundOperation)
{
// Search the Manager's collection of operations for an operation
// that corresponds with the background operation
var privateOperation =
recurringOperations.Find(
operation => operation.Name.Equals(backgroundOperation.GetName()));
// If found
if (privateOperation != null)
{
// Dispose the timer and the operation object
privateOperation.Timer.Dispose();
recurringOperations.Remove(privateOperation);
// Set the status of the client-side background operation
backgroundOperation.Status = RecurringOperationStatus.Cancelled;
backgroundOperation.IsRecurring = false;
backgroundOperation.IsNotRecurring = true;
backgroundOperation.IsPaused = false;
backgroundOperation.IsExecuting = false;
backgroundOperation.IsIdle = true;
backgroundOperation.IsCancelled = true;
backgroundOperation.IsNotCancelled = false;
backgroundOperation.CanBeStarted = true;
}
}
/// <summary>
/// Private operation data structure.
/// </summary>
private class Operation
{
internal string Name { get; set; }
internal Timer Timer { get; set; }
internal TimeSpan Interval { get; set; }
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T21:00:02.323",
"Id": "512997",
"Score": "0",
"body": "Do you aware of existing `System.Threading.Tasks.Task`? [Asynchronous Programming](https://docs.microsoft.com/en-us/dotnet/csharp/async). Looks like inventing yet another wheel. :) In general I mean not a replacement your class with .NET one but it may power the solution making it 10x times smaller/simpler/faster. Also learn something about `CancellationTokenSource` in addition to above link."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T13:55:03.070",
"Id": "513025",
"Score": "0",
"body": "I'm aware of Task and async/await. Do you have an example on how to create a recurring background job using Task and make sure it's thread safe, cancellable, re-startable and managed through a single entity?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T13:59:06.747",
"Id": "513027",
"Score": "0",
"body": "I can't figure out the value of the solution without a reproducible test case. I see the code but don't know what's its special feature that can't be achieved using regular `async` approach to the development."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T14:01:59.330",
"Id": "513029",
"Score": "0",
"body": "Also I must note, that you're able to bind XAML controls into the properties of my RecurringOperation object and make the UI react to the changes in the recurring operation's status. See my demo project where I created a WPF stopwatch program using my library. https://github.com/TDMR87/RecuropDemo"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T14:19:03.833",
"Id": "513033",
"Score": "0",
"body": "What about [this one](https://github.com/MartinZikmund/Uno.WindowsCommunityToolkit/blob/uno/Microsoft.Toolkit/Helpers/NotifyTaskCompletion.cs)? Documentation: [link](https://docs.microsoft.com/en-us/dotnet/api/microsoft.toolkit.helpers.notifytaskcompletion-1?view=win-comm-toolkit-dotnet-6.1), [article](https://docs.microsoft.com/en-us/archive/msdn-magazine/2014/march/async-programming-patterns-for-asynchronous-mvvm-applications-data-binding)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T14:54:54.650",
"Id": "513035",
"Score": "0",
"body": "Thanks, it was certainly an interesting article. It seems it had the same gerenal idea about binding as I did in my library. \n\nIt seemed to lack the possibility of creating recurring operations though, which is the main idea of my library. The RecurringOperation type is not so much used for getting a result (like Task is), but to run any kind of action in certain intervals and to be able to monitor that recurring action. Please take a look at some general examples on the usage on the library's github page readme. https://github.com/TDMR87/Recurop"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T15:05:07.043",
"Id": "513036",
"Score": "0",
"body": "My message was just giving an idea how to power the solution with `async/await`+TAP features. Btw, the solution has not a bubble-sort-complexity. Afm, to rewrite it correctly with TAP can take a long time, the hour that I have isn't enough. Maybe later. For now I suggest you to edit the post adding links and some information from comments there."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-24T20:04:35.347",
"Id": "259960",
"Score": "3",
"Tags": [
"c#",
"thread-safety",
"classes",
"library",
"timer"
],
"Title": "C# class library for managing recurring background operations"
}
|
259960
|
<p>I'm preparing for coding interviews and I wanted to get feedback on this question which asks you to write a simple ratelimiter that can handle 5 requests every 2 seconds for example. Since it is for a coding interview setting, I don't think it needs to be perfect.</p>
<p>I looked at the guava Ratelimiter for inspiration for this.</p>
<p>Please let me know if I have made any errors or any improvements that can be made. Any feedback is appreciated.</p>
<pre><code>public class RateLimit {
private double maxCapacity;
private double refillRate;
private double availableTokens;
private long lastRefill;
public RateLimit(double maxCapacity, long windowInSeconds) {
this.maxCapacity = maxCapacity;
this.lastRefill = Instant.now().toEpochMilli();
this.refillRate = TimeUnit.SECONDS.toMicros(windowInSeconds) / maxCapacity ;
this.availableTokens = maxCapacity;
}
public boolean acquire() {
return acquire(1, true);
}
public boolean acquire(double requiredPermits) {
return acquire(requiredPermits, true);
}
public boolean tryConsume(double requiredPermits) {
return acquire(requiredPermits, false);
}
private synchronized boolean acquire(double requiredToken, boolean shouldBlock) {
refill();
boolean acquired = false;
if (availableTokens >= requiredToken) {
availableTokens -= requiredToken;
acquired = true;
} else if (shouldBlock) {
double missingTokens = requiredToken - availableTokens;
try {
TimeUnit.MICROSECONDS.sleep((long) (refillRate * missingTokens));
availableTokens = 0D;
lastRefill = Instant.now().toEpochMilli();
acquired = true;
} catch (InterruptedException e) {
System.out.println("Sleep interrupted");
}
}
return acquired;
}
private void refill() {
long now = Instant.now().toEpochMilli();
if (now > lastRefill) {
long elapsedTime = now - lastRefill;
double tokensToBeAdded = Math.floor(TimeUnit.MILLISECONDS.toMicros(elapsedTime) / refillRate);
if (tokensToBeAdded > 0) {
availableTokens = Math.min(maxCapacity, availableTokens + tokensToBeAdded);
lastRefill = now;
}
}
}
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T06:58:47.250",
"Id": "513005",
"Score": "3",
"body": "Welcome to Code Review. Would be better to provide an example of usage or some tests. Besides helping reviewers it can be useful for you, since most interview exercises expect unit tests."
}
] |
[
{
"body": "<h2>Testability</h2>\n<p>Whilst not a prerequisite for a review, @Marc is correct that unit tests would be helpful here and you would usually want to include them in your exercise submission. You want to demonstrate both that you know the code works as importantly that you've considered how easy it is to test. Time in particular can be challenging to unit test if classes have not been constructed with it as a consideration. You may wish to take a look at this <a href=\"https://stackoverflow.com/q/27067049/592182\">Stack overflow question</a> for some suggestions about how you could improve your time testability.</p>\n<h2>Naming</h2>\n<p>One of the things that struck me as a little odd was that your blocking methods are called <code>acquire</code> and your non-blocking method is called <code>tryConsume</code>. I'm not sure I understand the disconnect, is there a reason it couldn't be called <code>tryAcquire</code>? Have you been asked to provide both blocking and non-blocking versions of the limiter as part of the exercise?</p>\n<h2>final</h2>\n<p>Fields that don't change after they've been initialized (such as <code>refillRate</code>) should be marked as final to indicate that you're not planning on changing them.</p>\n<h2>Starvation and Flooding</h2>\n<p>Lets take your example of 5 requests every 2 seconds. If I call <code>acquire(500)</code>, nothing happens for 200 seconds, then 500 messages get sent (probably within a single second). Is this the expected behaviour? During the wait time while the number of required allocations are being waited on, no other threads are able to acquire and send either. It's possible that this is expected/desired behaviour, however it seems like a potential flaw, particularly since a greedy blocking call could mean that the non-blocking request is never successful, so something I'd expect them to ask about if you get to interview. Things to consider are do you need to allow a single call to reserve X permits, or would it be better to have them acquire single permits at a time as they send each message? If you need to support multiple permits, should there be a limit on the maximum number of permits that can be requested in one go (such as the size of the window or <code>maxCapacity</code>).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T09:23:52.920",
"Id": "259972",
"ParentId": "259968",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "259972",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T04:21:56.723",
"Id": "259968",
"Score": "1",
"Tags": [
"java",
"thread-safety"
],
"Title": "Simple Ratelimiter Feedback"
}
|
259968
|
<p>I wrote a simple softmax classifier to classify MNIST digit handwriting data set. Feel free to comment anything!</p>
<pre><code>#include <algorithm>
#include <bit>
#include <cassert>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <execution>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include <numeric>
#include <memory>
#include <random>
#include <string>
#include <type_traits>
#include <vector>
struct MNISTObject {
std::vector<double> image;
std::uint8_t label = -1;
static std::uint32_t rows;
static std::uint32_t cols;
static std::uint8_t labels;
};
std::uint32_t MNISTObject::rows = 28;
std::uint32_t MNISTObject::cols = 28;
std::uint8_t MNISTObject::labels = 10;
constexpr std::uint32_t image_code = 2051;
constexpr std::uint32_t label_code = 2049;
void convertBigToLittleEndianIfNecessary(uint32_t& code) {
if constexpr (std::endian::native == std::endian::little) {
code = ((code & 0xFF000000) >> 24) |
((code & 0x00FF0000) >> 8) |
((code & 0x0000FF00) >> 8) |
((code & 0x000000FF) >> 24);
}
}
void read_uint32(std::istream& is, std::uint32_t& code) {
if (!is.read(reinterpret_cast<char*>(&code), sizeof code)) {
std::cerr << "Cannot read uint32\n";
return;
}
convertBigToLittleEndianIfNecessary(code);
}
void fillDataset(std::istream& images, std::istream& labels, std::vector<MNISTObject>& data_set) {
std::uint32_t code;
read_uint32(images, code);
if (code != image_code) {
std::cerr << "Wrong image code : " << code << '\n';
return;
}
read_uint32(labels, code);
if (code != label_code) {
std::cerr << "Wrong label code : " << code << '\n';
return;
}
std::uint32_t cnt_images, cnt_labels;
read_uint32(images, cnt_images);
read_uint32(labels, cnt_labels);
if (cnt_images != cnt_labels) {
std::cerr << "Image/label counts do not match\n";
return;
} else {
std::cout << cnt_images << " images\n";
}
std::uint32_t rows, cols;
read_uint32(images, rows);
read_uint32(images, cols);
if (rows != MNISTObject::rows || cols != MNISTObject::cols) {
std::cerr << "Wrong rows and cols: " << rows << ' ' << cols << '\n';
return;
}
std::cout << rows << " rows " << cols << " cols\n";
std::uint32_t img_size = rows * cols;
data_set.reserve(cnt_images);
for (std::size_t i = 0; i < cnt_images; ++i) {
MNISTObject obj;
obj.image.reserve(img_size);
std::uint8_t pixel;
for (std::size_t p = 0; p < img_size; ++p) {
if (!images.read(reinterpret_cast<char*>(&pixel), sizeof pixel)) {
std::cerr << "Pixel read fail\n";
return;
}
double pixel_val = static_cast<double>(pixel) / 255.0;
obj.image.push_back(pixel_val);
}
std::uint8_t label;
if (!labels.read(reinterpret_cast<char*>(&label), sizeof label)) {
std::cerr << "Label read fail\n";
return;
}
if (label >= MNISTObject::labels) {
std::cerr << "Wrong label : " << static_cast<std::uint32_t>(label) << '\n';
return;
}
obj.label = label;
data_set.push_back(obj);
}
std::cout << cnt_images << " images read success\n";
}
std::pair<std::vector<MNISTObject>, std::vector<MNISTObject>> constructDataSets() {
std::filesystem::path train_images_path = "train-images.idx3-ubyte";
std::filesystem::path train_labels_path = "train-labels.idx1-ubyte";
std::ifstream train_images_ifs {train_images_path, std::ios::binary};
if (!train_images_ifs) {
std::cerr << "Cannot open input file " << train_images_path;
}
std::ifstream train_labels_ifs {train_labels_path, std::ios::binary};
if (!train_labels_ifs) {
std::cerr << "Cannot open input file " << train_labels_path;
}
std::vector<MNISTObject> train_set;
fillDataset(train_images_ifs, train_labels_ifs, train_set);
std::filesystem::path test_images_path = "t10k-images.idx3-ubyte";
std::filesystem::path test_labels_path = "t10k-labels.idx1-ubyte";
std::ifstream test_images_ifs {test_images_path, std::ios::binary};
if (!test_images_ifs) {
std::cerr << "Cannot open input file " << test_images_path;
}
std::ifstream test_labels_ifs {test_labels_path, std::ios::binary};
if (!test_labels_ifs) {
std::cerr << "Cannot open input file " << test_labels_path;
}
std::vector<MNISTObject> test_set;
fillDataset(test_images_ifs, test_labels_ifs, test_set);
return {train_set, test_set};
}
template <typename T>
struct Matrix {
static_assert(std::is_scalar_v<T>);
const int R;
const int C;
std::unique_ptr<T[]> data;
Matrix(int R, int C) : R {R}, C {C}, data(new T[R * C]) {
assert(R > 0 && C > 0);
}
T& operator()(int r, int c) {
assert(0 <= r && r < R && 0 <= c && c < C);
return data[r * C + c];
}
const T& operator()(int r, int c) const {
assert(0 <= r && r < R && 0 <= c && c < C);
return data[r * C + c];
}
};
std::mt19937 gen(std::random_device{}());
std::vector<double> computeProb(const Matrix<double>& W, const MNISTObject& mnist_sample) {
assert(W.R == MNISTObject::labels && W.C == MNISTObject::rows * MNISTObject::cols);
std::vector<double> probs;
probs.reserve(MNISTObject::labels);
double sum_probs = 0.0;
for (int l = 0; l < MNISTObject::labels; l++) {
auto inner_prod = std::transform_reduce(std::execution::par_unseq,
&W.data[l * W.C], &W.data[(l + 1) * W.C],
mnist_sample.image.begin(), 0.0);
auto prob = std::exp(inner_prod);
probs.push_back(prob);
sum_probs += prob;
}
std::for_each(std::execution::par_unseq, probs.begin(), probs.end(), [&sum_probs](auto& p){p /= sum_probs;});
auto real_sum = std::reduce(std::execution::par_unseq, probs.begin(), probs.end(), 0.0);
if (std::fabs(real_sum - 1.0) >= 1e-5) {
std::cerr << "Probability sum failed in softmax: " << real_sum << '\n';
}
return probs;
}
constexpr int num_epochs = 100;
double testSoftmaxClassifier(const Matrix<double>& W, const std::vector<MNISTObject>& test_set) {
int correct = 0;
int incorrect = 0;
for (const auto& test_sample : test_set) {
auto probs = computeProb(W, test_sample);
auto predict = std::distance(probs.begin(), std::ranges::max_element(probs));
if (predict == test_sample.label) {
correct++;
} else {
incorrect++;
}
}
return correct / (correct + incorrect * 1.0);
}
Matrix<double> trainSoftmaxClassifier(const std::vector<MNISTObject>& train_set,
const std::vector<MNISTObject>& test_set,
double lr, double weight_decay) {
std::uniform_real_distribution<> weight_dist(-1.0, 1.0);
const int k = MNISTObject::labels;
const int sz = MNISTObject::rows * MNISTObject::cols;
Matrix<double> W (k, sz);
for (int i = 0; i < k * sz; ++i) {
W.data[i] = weight_dist(gen);
}
for (int epoch = 0; epoch < num_epochs; epoch++) {
auto t1 = std::chrono::high_resolution_clock::now();
for (const auto& train_sample : train_set) {
auto probs = computeProb(W, train_sample);
auto correct = train_sample.label;
for (int l = 0; l < k; ++l) {
for (int p = 0; p < sz; ++p) {
W(l, p) = W(l, p) * (1.0 - lr * weight_decay)
- lr * train_sample.image[p] * probs[l];
}
if (l == correct) {
for (int p = 0; p < sz; ++p) {
W(l, p) += lr * train_sample.image[p];
}
}
}
}
auto t2 = std::chrono::high_resolution_clock::now();
auto dt = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
std::cout << "epoch " << epoch << " finished in " << dt.count() << "ms\n";
auto accu = testSoftmaxClassifier(W, test_set);
std::cout << "Accuracy : " << accu << '\n';
}
return W;
}
int main() {
auto [train_set, test_set] = constructDataSets();
constexpr double lr = 0.0005;
constexpr double weight_decay = 0;
auto W = trainSoftmaxClassifier(train_set, test_set, lr, weight_decay);
}
</code></pre>
<p>You can download the dataset here: <a href="http://yann.lecun.com/exdb/mnist/" rel="noreferrer">http://yann.lecun.com/exdb/mnist/</a></p>
<p>Result in my machine:</p>
<pre><code>60000 images
28 rows 28 cols
60000 images read success
10000 images
28 rows 28 cols
10000 images read success
epoch 0 finished in 1132ms
Accuracy : 0.7536
epoch 1 finished in 1142ms
Accuracy : 0.8176
epoch 2 finished in 987ms
Accuracy : 0.8424
epoch 3 finished in 1094ms
Accuracy : 0.8574
epoch 4 finished in 1038ms
Accuracy : 0.8662
epoch 5 finished in 1191ms
Accuracy : 0.8724
epoch 6 finished in 1087ms
Accuracy : 0.8789
epoch 7 finished in 1020ms
Accuracy : 0.8838
epoch 8 finished in 1170ms
Accuracy : 0.8867
epoch 9 finished in 1150ms
Accuracy : 0.889
epoch 10 finished in 791ms
Accuracy : 0.8908
epoch 11 finished in 815ms
Accuracy : 0.8919
epoch 12 finished in 809ms
Accuracy : 0.8929
epoch 13 finished in 792ms
Accuracy : 0.8934
epoch 14 finished in 798ms
Accuracy : 0.894
epoch 15 finished in 816ms
Accuracy : 0.8959
epoch 16 finished in 826ms
Accuracy : 0.8965
epoch 17 finished in 990ms
Accuracy : 0.8978
epoch 18 finished in 804ms
Accuracy : 0.8983
epoch 19 finished in 907ms
Accuracy : 0.8995
epoch 20 finished in 800ms
Accuracy : 0.9002
...
</code></pre>
|
[] |
[
{
"body": "<p>That's a very big list of includes! It might be a sign that you have functionality that should be split out to separate source files (e.g. filesystem read/write away from the core computation). Keeping the standard library includes alphabetical is a good choice - it allows very easy checking of whether a needed header is already included.</p>\n<p>This looks broken, and suggests you're lacking a good unit test:</p>\n<blockquote>\n<pre><code>void convertBigToLittleEndianIfNecessary(uint32_t& code) {\n if constexpr (std::endian::native == std::endian::little) {\n code = ((code & 0xFF000000) >> 24) |\n ((code & 0x00FF0000) >> 8) |\n ((code & 0x0000FF00) >> 8) |\n ((code & 0x000000FF) >> 24);\n }\n}\n</code></pre>\n</blockquote>\n<p>The last subexpression will always be zero - I think that the last two subexpressions should have <code><<</code> where you've written <code>>></code>.</p>\n<p>The error reporting is poor - a lot of <code>void</code>-returning functions print user warnings to <code>std::cerr</code> (good) but have no way to signal to their callers that they will be working with invalid data (bad). It would be more useful to <code>throw</code> an exception than to simply <code>return</code>. (Again, more unit-testing would be good - I usually start new code by creating a test with invalid input as my very first step.)</p>\n<p>A couple of minor niggles with the matrix class:</p>\n<ul>\n<li>Is there a good reason to use (signed) <code>int</code> for the dimensions?</li>\n<li>I'd prefer to see <code>std::make_unique<T[]>(R*C)</code> than the bare <code>new</code>.</li>\n<li>I don't see why it would only work for scalar <code>T</code>. It's generally better to constrain using Concepts where possible (e.g. <code>template<std::semiregular T> struct Matrix</code>).</li>\n</ul>\n<p>I would write <code>correct++</code>, <code>incorrect++</code> and <code>epoch++</code> using prefix operator, as that's a good general habit (use postfix operator only when we actually need the original value). The code is inconsistent, since we have <code>++i</code> and <code>++p</code> elsewhere.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T10:01:12.297",
"Id": "513008",
"Score": "0",
"body": "Good catch for endian conversion, thanks! I always prefer signed integers for dimensions, because it helps to catch naughty constructs like ```Matrix<double> M(-1, -1)```. I agree all the other things you've pointed out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T19:24:10.983",
"Id": "513051",
"Score": "3",
"body": "Good compiler warnings (`-Wconversion` for GCC, I think) will alert you to such misuses, unless you accept signed values. I prefer to be notified at compile time than at run time (and I use `-Werror` to ensure the issues are addressed). It also reduces the number of unit tests to write and maintain."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T09:50:09.070",
"Id": "259974",
"ParentId": "259970",
"Score": "10"
}
},
{
"body": "<p>Toby Speight and G. Sliepen gave excellent feedbacks from the programmer's perspective;</p>\n<p>A friend of mine gave some feedbacks from the machine learning researcher's perspective, as follows:</p>\n<ul>\n<li><p>User should be able to specify hyperparameters (lr, weight_decay, etc), or the code should include hyperparameter tuning</p>\n</li>\n<li><p>Weight matrix initialization is wrong. It should use a Gaussian distribution with mean 0, stdev <code>sqrt(2/(#fanin + #fanout))</code></p>\n</li>\n<li><p>Training should stop early if converged enough.</p>\n</li>\n<li><p>This softmax implementation is vulnerable to overflow/underflow. Use logsumexp trick instead.</p>\n</li>\n<li><p>It'd be good to include an option to specify batch size and work with it</p>\n</li>\n<li><p><code>double</code> is overkill for such simple jobs like MNIST: use float32 instead</p>\n</li>\n</ul>\n<p><strong>UPDATE</strong>: Addressed most of feedbacks.</p>\n<pre><code>#include <algorithm>\n#include <bit>\n#include <cassert>\n#include <chrono>\n#include <concepts>\n#include <cmath>\n#include <cstdint>\n#include <execution>\n#include <filesystem>\n#include <fstream>\n#include <iostream>\n#include <iterator>\n#include <numeric>\n#include <memory>\n#include <random>\n#include <queue>\n#include <stdexcept>\n#include <string>\n#include <vector>\n\nstruct MNISTObject {\n std::vector<float> image;\n std::uint8_t label = -1;\n static constexpr std::uint32_t rows = 28;\n static constexpr std::uint32_t cols = 28;\n static constexpr std::uint8_t labels = 10;\n};\n\nconstexpr std::uint32_t image_code = 2051;\nconstexpr std::uint32_t label_code = 2049;\n\nstd::uint32_t convertBigToLittleEndianIfNecessary(std::uint32_t code) {\n if constexpr (std::endian::native == std::endian::little) {\n code = ((code & 0xFF000000) >> 24) |\n ((code & 0x00FF0000) >> 8) |\n ((code & 0x0000FF00) << 8) |\n ((code & 0x000000FF) << 24);\n }\n return code;\n}\n\nstd::uint32_t read_uint32(std::istream& is) {\n if (std::uint32_t code; is.read(reinterpret_cast<char*>(&code), sizeof code)) {\n return convertBigToLittleEndianIfNecessary(code);\n } else {\n throw std::runtime_error("Couldn't read uint32\\n");\n }\n}\n\nstd::vector<MNISTObject> readDataset(std::istream& images, std::istream& labels) {\n auto code = read_uint32(images);\n if (code != image_code) {\n std::cerr << code << " : ";\n throw std::runtime_error("Wrong image code\\n");\n }\n code = read_uint32(labels);\n if (code != label_code) {\n std::cerr << code << " : ";\n throw std::runtime_error("Wrong label code\\n");\n }\n\n auto cnt_images = read_uint32(images);\n auto cnt_labels = read_uint32(labels);\n if (cnt_images != cnt_labels) {\n std::cerr << cnt_images << ' ' << cnt_labels << " : ";\n throw std::runtime_error("Image/label counts do not match\\n");\n } else {\n std::cout << cnt_images << " images\\n";\n }\n\n auto rows = read_uint32(images);\n auto cols = read_uint32(images);\n if (rows != MNISTObject::rows || cols != MNISTObject::cols) {\n std::cerr << rows << ' ' << cols << " : ";\n throw std::runtime_error("Wrong rows and cols\\n");\n }\n std::cout << rows << " rows " << cols << " cols\\n";\n\n std::uint32_t img_size = rows * cols;\n\n std::vector<MNISTObject> data_set;\n data_set.reserve(cnt_images);\n auto pixels = std::make_unique<std::uint8_t[]>(img_size);\n for (std::size_t i = 0; i < cnt_images; ++i) {\n MNISTObject obj;\n obj.image.reserve(img_size);\n if (!images.read(reinterpret_cast<char*>(pixels.get()), img_size)) {\n throw std::runtime_error("Image read error\\n");\n }\n\n std::transform(pixels.get(), pixels.get() + img_size, std::back_inserter(obj.image),\n [](std::uint8_t pixel){ return static_cast<float>(pixel) / 255.0f; });\n std::uint8_t label = 0;\n if (!labels.read(reinterpret_cast<char*>(&label), sizeof label)) {\n throw std::runtime_error("Label read error\\n");\n }\n if (label >= MNISTObject::labels) {\n std::cerr << static_cast<std::uint32_t>(label) << " : ";\n throw std::runtime_error("Wrong label\\n");\n }\n obj.label = label;\n data_set.push_back(obj);\n }\n std::cout << cnt_images << " images read success\\n";\n return data_set;\n}\n\nstd::pair<std::vector<MNISTObject>, std::vector<MNISTObject>> constructDataSets() {\n std::filesystem::path train_images_path = "train-images.idx3-ubyte";\n std::filesystem::path train_labels_path = "train-labels.idx1-ubyte";\n std::ifstream train_images_ifs {train_images_path, std::ios::binary};\n if (!train_images_ifs) {\n throw std::runtime_error("Cannot open train images file\\n");\n }\n std::ifstream train_labels_ifs {train_labels_path, std::ios::binary};\n if (!train_labels_ifs) {\n throw std::runtime_error("Cannot open train labels file\\n");\n }\n\n auto train_set = readDataset(train_images_ifs, train_labels_ifs);\n\n std::filesystem::path test_images_path = "t10k-images.idx3-ubyte";\n std::filesystem::path test_labels_path = "t10k-labels.idx1-ubyte";\n std::ifstream test_images_ifs {test_images_path, std::ios::binary};\n if (!test_images_ifs) {\n throw std::runtime_error("Cannot open test images file\\n");\n }\n std::ifstream test_labels_ifs {test_labels_path, std::ios::binary};\n if (!test_labels_ifs) {\n throw std::runtime_error("Cannot open test labels file\\n");\n }\n\n auto test_set = readDataset(test_images_ifs, test_labels_ifs);\n\n return {train_set, test_set};\n}\n\ntemplate <std::regular T>\nstruct Matrix {\n const int R;\n const int C;\n std::unique_ptr<T[]> data;\n\n Matrix(int R, int C) : R {R}, C {C}, data(std::make_unique<T[]>(R * C)) {\n assert(R > 0 && C > 0);\n }\n\n T& operator()(int r, int c) {\n assert(0 <= r && r < R && 0 <= c && c < C);\n return data[r * C + c];\n }\n\n const T& operator()(int r, int c) const {\n assert(0 <= r && r < R && 0 <= c && c < C);\n return data[r * C + c];\n }\n};\n\nstd::mt19937 gen(std::random_device{}());\n\nstd::vector<float> computeProb(const Matrix<float>& W, const MNISTObject& mnist_sample) {\n assert(W.R == MNISTObject::labels && W.C == MNISTObject::rows * MNISTObject::cols);\n std::vector<float> probs;\n probs.reserve(MNISTObject::labels);\n for (int l = 0; l < MNISTObject::labels; l++) {\n auto prob = std::transform_reduce(std::execution::par_unseq,\n &W.data[l * W.C], &W.data[(l + 1) * W.C],\n mnist_sample.image.begin(), 0.0f);\n probs.push_back(prob);\n }\n auto max_prob = *std::ranges::max_element(probs);\n std::for_each(std::execution::par_unseq, probs.begin(), probs.end(), [&max_prob](auto& p){p = std::exp(p - max_prob);});\n auto sum_probs = std::reduce(std::execution::par_unseq, probs.begin(), probs.end(), 0.0f);\n std::for_each(std::execution::par_unseq, probs.begin(), probs.end(), [&sum_probs](auto& p){p /= sum_probs;});\n return probs;\n}\n\nfloat testSoftmaxClassifier(const Matrix<float>& W, const std::vector<MNISTObject>& test_set) {\n int correct = 0;\n int incorrect = 0;\n for (const auto& test_sample : test_set) {\n auto probs = computeProb(W, test_sample);\n auto predict = std::distance(probs.begin(), std::ranges::max_element(probs));\n if (predict == test_sample.label) {\n correct++;\n } else {\n incorrect++;\n }\n }\n return static_cast<float>(correct) / static_cast<float>(correct + incorrect);\n}\n\nconstexpr int num_epochs = 300;\n\nMatrix<float> trainSoftmaxClassifier(const std::vector<MNISTObject>& train_set,\n const std::vector<MNISTObject>& test_set,\n float lr, float weight_decay) {\n const int k = MNISTObject::labels;\n const int sz = MNISTObject::rows * MNISTObject::cols;\n std::normal_distribution<float> weight_dist(0, std::sqrt(2.0f / (k + sz * 1.0f)));\n Matrix<float> W (k, sz);\n for (int i = 0; i < k * sz; ++i) {\n W.data[i] = weight_dist(gen);\n }\n\n std::deque<float> prev_accu;\n constexpr int accu_window_size = 5;\n\n for (int epoch = 0; epoch < num_epochs; epoch++) {\n auto t1 = std::chrono::high_resolution_clock::now();\n for (const auto& train_sample : train_set) {\n auto probs = computeProb(W, train_sample);\n auto correct = train_sample.label;\n for (int l = 0; l < k; ++l) {\n for (int p = 0; p < sz; ++p) {\n W(l, p) = W(l, p) * (1.0f - lr * weight_decay)\n - lr * train_sample.image[p] * probs[l];\n }\n if (l == correct) {\n for (int p = 0; p < sz; ++p) {\n W(l, p) += lr * train_sample.image[p];\n }\n }\n }\n }\n auto t2 = std::chrono::high_resolution_clock::now();\n auto dt = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);\n std::cout << "epoch " << epoch << " finished in " << dt.count() << "ms\\n";\n\n auto accu = testSoftmaxClassifier(W, test_set);\n std::cout << "Accuracy : " << accu << '\\n';\n\n prev_accu.push_back(accu);\n if (prev_accu.size() > accu_window_size) {\n prev_accu.pop_front();\n }\n if (prev_accu.size() == accu_window_size &&\n *std::ranges::max_element(prev_accu) - *std::ranges::min_element(prev_accu) < 3e-4) {\n std::cout << "Converged enough, stopping the training\\n";\n break;\n }\n }\n\n return W;\n}\n\nint main() {\n auto [train_set, test_set] = constructDataSets();\n\n constexpr float lr = 0.0005;\n constexpr float weight_decay = 0;\n\n auto W = trainSoftmaxClassifier(train_set, test_set, lr, weight_decay);\n\n}\n\n</code></pre>\n<p>Result:</p>\n<pre><code>60000 images\n28 rows 28 cols\n60000 images read success\n10000 images\n28 rows 28 cols\n10000 images read success\nepoch 0 finished in 774ms\nAccuracy : 0.8874\nepoch 1 finished in 743ms\nAccuracy : 0.9004\nepoch 2 finished in 847ms\nAccuracy : 0.9045\nepoch 3 finished in 872ms\nAccuracy : 0.9083\nepoch 4 finished in 871ms\nAccuracy : 0.9109\nepoch 5 finished in 849ms\nAccuracy : 0.9124\n...\nepoch 45 finished in 629ms\nAccuracy : 0.9226\nepoch 46 finished in 606ms\nAccuracy : 0.9227\nConverged enough, stopping the training\n</code></pre>\n<p>Better than before! Machine learning is fun.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T19:20:47.807",
"Id": "513050",
"Score": "2",
"body": "Thanks for adding this self-answer. It fills in aspects I'm not qualified to comment on and may be educational if I ever have to venture into this territory."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T10:20:23.100",
"Id": "259978",
"ParentId": "259970",
"Score": "8"
}
},
{
"body": "<p>In addition to Toby Speight's remarks, I would add:</p>\n<h1>Use <code>constexpr</code> for all constants</h1>\n<p>I see you already used <code>constexpr</code> for <code>image_code</code> and <code>label_code</code>, but you didn't use it for the <code>static</code> member variables <code>rows</code>, <code>cols</code> and <code>labels</code> of <code>MNISTObject</code>. But those look like they are constants as well. You can just write:</p>\n<pre><code>struct MNISTObject {\n ...\n static constexpr std::uint32_t rows = 28;\n static constexpr std::uint32_t cols = 28;\n static constexpr std::uint8_t labels = 10;\n};\n</code></pre>\n<h1>Make variables and functions <code>static</code> where appropriate</h1>\n<p>Variables and functions that are only used within the same <a href=\"https://en.wikipedia.org/wiki/Translation_unit_(programming)\" rel=\"noreferrer\">translation unit</a> should be made <code>static</code>. This might help the compiler produce more efficient code, and avoids potential symbol collision at link time.</p>\n<h1>Prefer <code>return</code>ing values from functions</h1>\n<p>I see a lot of functions that return <code>void</code>, but write their result via a parameter passed by reference. I would avoid this pattern and instead use <code>return</code> to return the result. First, passing in a reference is less efficient if the compiler cannot inline the function. But more importantly, it just makes it harder to write code. Consider:</p>\n<pre><code>std::uint32_t code;\nread_uint32(images, code);\nif (code != image_code) {...}\n</code></pre>\n<p>If you instead let <code>read_uint32()</code> <code>return</code> the value it read, you can write the above snippet of code as:</p>\n<pre><code>if (read_uint32(images) != image_code) {...}\n</code></pre>\n<p>Another benefit is that it will now force you to <code>return</code> something, even if an error occured. Because in this code:</p>\n<pre><code>std::uint32_t code;\nread_uint32(images, code);\n</code></pre>\n<p>The value of <code>code</code> is left uninitialized if there is a read error, but your program continues to go on. There is a tiny chance that the value 2051 would have been in the memory reserved for <code>code</code>, so your program might incorrectly go on assuming the right image code was read. I would follow Toby's advice here and <code>throw</code> an exception (preferably a <a href=\"https://en.cppreference.com/w/cpp/error/runtime_error\" rel=\"noreferrer\"><code>std::runtime_error</code></a> or something derived from it):</p>\n<pre><code>uint32_t read_uint32(std::istream& is) {\n if (uint32_t code; is.read(reinterpret_cast<char*>(&code), sizeof code)) {\n return convertBigToLittleEndianIfNecessary(code);\n } else {\n throw std::runtime_error("Read error");\n }\n}\n</code></pre>\n<p>Also note that you should also <code>return</code> for large objects, which is still as efficient as passing it via a reference parameter thanks to <a href=\"https://en.wikipedia.org/wiki/Copy_elision#Return_value_optimization\" rel=\"noreferrer\">return value optimization</a>. So <code>fillDataSet</code> should just <code>return</code> the dataset (and have its name changed to <code>readDataSet()</code> to reflect that).</p>\n<h1>Optimize reading from files</h1>\n<p>You are reading the image data from the input file byte by byte. This is quite inefficient. I suggest you read the whole image in one go instead:</p>\n<pre><code>auto pixels = std::make_unique_for_ovewrite<std::uint8_t[]>(img_size);\nif (!images.read(reinterpret_cast<char*>(pixels.get()), img_size)) {\n throw std::runtime_error("Read error");\n}\n\nstd::transform(pixels.get(), pixels.get() + img_size, std::back_inserter(obj.image),\n [](std::uint8_t pixel){ return pixel / 255.0; });\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T19:18:24.503",
"Id": "513049",
"Score": "0",
"body": "Upvoted. Isn't ```make_unique``` more preferable than ```make_unique_for_overwrite```? There will be unnecessary zero-fill cost."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T21:58:18.857",
"Id": "513061",
"Score": "0",
"body": "`std::make_unique_for_overwrite` is the one that avoids \"zero-fill cost\" if possible; it uses [default-initialization](https://en.cppreference.com/w/cpp/language/default_initialization) for the storage, whereas `std::make_unique` uses [value-initialization](https://en.cppreference.com/w/cpp/language/value_initialization). The name is also a hint: it should be used when you are going to overwrite the values anyway, and that's exactly what we're doing when reading the image data into `pixels`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T18:52:29.497",
"Id": "513179",
"Score": "0",
"body": "I personally think that anonymous namespaces look somewhat nicer than static functions, but functionally they are the same."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T08:35:42.690",
"Id": "513230",
"Score": "0",
"body": "You are worried about the overhead of zero-initialising a memory block when reading a file? Lol. Any gains resulting from would be impossible to measure because they are swamped by the time taken to read the file."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T10:23:26.147",
"Id": "513240",
"Score": "0",
"body": "@Sjoerd A `std::istream` doesn't have to be a file, and even if it is, the file might already be cached in memory."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T10:49:06.290",
"Id": "259979",
"ParentId": "259970",
"Score": "16"
}
},
{
"body": "<h1>function should return values</h1>\n<p>Others have mentioned "return things rather than using output parameters" but here is an elaborated example.</p>\n<pre><code>void read_uint32(std::istream& is, std::uint32_t& code)\n</code></pre>\n<p>In this case, it's providing a primitive type so you don't even have the idea of avoiding large return values, so what's up with that? It's not returning an error code to indicate an <em>optional</em> result either, so why would you not just naturally write it as</p>\n<pre><code>std::uint32_t read_uint32(std::istream& is)\n</code></pre>\n<p>?</p>\n<p>Look at how you need to call it:</p>\n<pre><code>std::uint32_t cnt_images, cnt_labels;\nread_uint32(images, cnt_images);\nread_uint32(labels, cnt_labels);\n\nstd::uint32_t rows, cols;\nread_uint32(images, rows);\nread_uint32(images, cols);\n</code></pre>\n<p>You should <em>initialize variables when defining them</em> and this out-parameter thing gets in the way of that. Having proper initialization also means that you can make them <code>const</code>:</p>\n<pre><code>const auto rows = read_uint32(images);\nconst auto cols = read_uint32(images);\n</code></pre>\n<h1>includes?</h1>\n<p>Your long list of <code>#include</code> directives has some things I don't see being used, and in fact I find are rarely needed, like <code><iterator></code>. Did you paste in a long commonly needed list when you started your file, instead of just naming what you actually needed?\nI'll usually comment on the <code>#include</code> line why I need it, if it's a specific feature that's not pervasive in the file.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:04:09.717",
"Id": "260031",
"ParentId": "259970",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T08:18:53.270",
"Id": "259970",
"Score": "9",
"Tags": [
"c++",
"machine-learning",
"c++20"
],
"Title": "C++20 : Simple Softmax classifier for MNIST dataset"
}
|
259970
|
<p>I have made an Android Tic-Tac-Toe adaptation as a weekend-project.</p>
<p><a href="https://i.stack.imgur.com/ldwqm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ldwqm.png" alt="image1" /></a></p>
<p><a href="https://i.stack.imgur.com/Gn9fL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gn9fL.png" alt="image2" /></a></p>
<p><a href="https://i.stack.imgur.com/jYHEW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jYHEW.png" alt="image3" /></a></p>
<p>Here's the Kotlin-code.</p>
<p><strong>MainActivity:</strong></p>
<pre><code>package com.mizech.tictactoe
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.snackbar.Snackbar
import com.mizech.tictactoe.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var gameState = mutableListOf<FeasibleState>()
private var isPlayerOne = true
private var fieldsUsed = 0
private val imageViews = mutableListOf<ImageView>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
var i = 0
while (i < 9) {
gameState.add(FeasibleState.NOT_SET)
i++
}
// Add the imageViews to the List
imageViews.add(binding.imageView0)
imageViews.add(binding.imageView1)
imageViews.add(binding.imageView2)
imageViews.add(binding.imageView3)
imageViews.add(binding.imageView4)
imageViews.add(binding.imageView5)
imageViews.add(binding.imageView6)
imageViews.add(binding.imageView7)
imageViews.add(binding.imageView8)
// Iterate the list and attach an Listener to each.
imageViews.forEach {
it.setOnClickListener {
processStateChange(it)
}
}
binding.resetGame.setOnClickListener {
val intent = Intent(this, MainActivity::class.java)
val snackbar = Snackbar.make(it, "Game Reset cancelled",
Snackbar.LENGTH_LONG)
val dialog = AlertDialog.Builder(this)
dialog.apply {
setIcon(R.drawable.ic_baseline_priority_high_24)
setTitle("Game Reset")
setMessage("Do you want to continue?")
setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, which ->
startActivity(intent)
})
setNegativeButton("No", DialogInterface.OnClickListener { dialog, which ->
snackbar.show()
})
}.show()
}
}
private fun checkGameState(currentPlayer: FeasibleState): Boolean {
if (gameState[0] === currentPlayer && gameState[1] === currentPlayer
&& gameState[2] === currentPlayer) {
return true
}
if (gameState[3] === currentPlayer && gameState[4] === currentPlayer
&& gameState[5] === currentPlayer) {
return true
}
if (gameState[6] === currentPlayer && gameState[7] === currentPlayer
&& gameState[8] === currentPlayer) {
return true
}
if (gameState[0] === currentPlayer && gameState[3] === currentPlayer
&& gameState[6] === currentPlayer) {
return true
}
if (gameState[1] === currentPlayer && gameState[4] === currentPlayer
&& gameState[7] === currentPlayer) {
return true
}
if (gameState[2] === currentPlayer && gameState[5] === currentPlayer
&& gameState[8] === currentPlayer) {
return true
}
if (gameState[0] === currentPlayer && gameState[4] === currentPlayer
&& gameState[8] === currentPlayer) {
return true
}
if (gameState[2] === currentPlayer && gameState[4] === currentPlayer
&& gameState[6] === currentPlayer) {
return true
}
return false
}
private fun processStateChange(it: View) {
val imgView = it as ImageView
if (isPlayerOne) {
imgView.setImageResource(R.drawable.player_one)
fieldsUsed++
gameState[imgView.tag.toString().toInt()] = FeasibleState.PLAYER_ONE
checkResult(FeasibleState.PLAYER_ONE, R.string.one_won_message, "#64FF64")
} else {
imgView.setImageResource(R.drawable.player_two)
fieldsUsed++
gameState[imgView.tag.toString().toInt()] = FeasibleState.PLAYER_TWO
checkResult(FeasibleState.PLAYER_TWO, R.string.two_won_message, "#FF6464")
}
isPlayerOne = !isPlayerOne
imgView.isEnabled = false
}
private fun checkResult(currentPlayer: FeasibleState, message: Int, winnerColor: String) {
if (checkGameState(currentPlayer)) {
setFinalResult(message, winnerColor)
} else if (fieldsUsed == 9) {
setFinalResult(R.string.tie_message, "#ff00ff")
}
}
private fun setFinalResult(winnerString: Int, winnerColor: String) {
imageViews.forEach {
it.isEnabled = false
}
binding.currentMessage.text = getString(winnerString)
binding.currentMessage.setTextColor(Color.parseColor(winnerColor))
}
}
</code></pre>
<p><strong>The enum-class:</strong></p>
<pre><code>package com.mizech.tictactoe
enum class FeasibleState {
NOT_SET,
PLAYER_ONE,
PLAYER_TWO
}
</code></pre>
<p>The full source-code and additional images on <a href="https://github.com/mizech/tic-tac-toe" rel="nofollow noreferrer">GitHub</a>.</p>
<p>How could my implementation become improved? What would you have done differently and why?</p>
<p><strong>Is there a better possibility to reset the game? Instead of triggering an intent to MainActivity self.</strong></p>
<p>Looking forward to reading your answers and comments.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-09T00:30:18.657",
"Id": "514223",
"Score": "0",
"body": "By the way, you can change the checkmark to forsvarir's answer. His answer is much more useful than mine."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-09T05:15:32.057",
"Id": "514228",
"Score": "0",
"body": "@StephanBranczyk Anyway: Thanks a lot."
}
] |
[
{
"body": "<p><em>Disclaimer: I'm far from being an expert, but since no one has responded to you yet and it's already been a couple of weeks. I thought I would try giving you some feedback.</em></p>\n<p>Your function <code>checkGameState</code> contains a lot of duplicate code. Try using a helper function to get rid of that duplication.</p>\n<p><code>gameState</code> refers to the 9 squares of your grid. Maybe you should rename it to <code>squares</code> or to <code>gridStates</code> instead. Also, I don't think it needs to be mutable either. So I'd use an array and instead of writing this:</p>\n<pre><code> private var gameState = mutableListOf<FeasibleState>()\n ...\n var i = 0\n while (i < 9) {\n gameState.add(FeasibleState.NOT_SET)\n i++\n }\n</code></pre>\n<p>I would declare and initialize this array both at the same time.</p>\n<pre><code> var gridStates = Array(9, {FeasibleState.NOT_SET})\n</code></pre>\n<p>Now, this is probably me being nitpicky, but in my case, I would have used a loop to do <code>imageViews.add(binding.imageViewx)</code> and used an array to store those image names (or I would have generated the names with a string template). And once I had that loop, then I would have done the setting of the <code>onClickListener</code> within that same loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-08T16:57:05.163",
"Id": "514201",
"Score": "0",
"body": "`private` fields/functions aren't accessible from outside of the class they are declared in. By having them private you help to enforce the encapsulation of the class, so for example you know clients will call the public methods to change the game state (and anything related) rather than risking a client updating the game state without this being reflected in the UI."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-09T00:20:54.790",
"Id": "514222",
"Score": "0",
"body": "@forsvarir, Ok, I see. I'll need to start integrating that habit into my own coding. Thank you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-07T20:34:37.593",
"Id": "260470",
"ParentId": "259971",
"Score": "2"
}
},
{
"body": "<h2>Reset</h2>\n<p>Calling back into your MainActivity each time you reset the game creates a stack of the activities, so if the user plays several games and tries to quit by pressing the back button, they'll have to go through each of the previous games until they get out.</p>\n<p>A better approach might be to have a <code>reset</code> method that you call after the user has confirmed, rather than starting a new activity. You essentially need to reset your game state and UI, which should look something like this:</p>\n<pre><code>private fun resetGame() {\n for (idx in 0..8) {\n gameState[idx] = FeasibleState.NOT_SET\n }\n imageViews.forEach { view ->\n view.setImageResource(R.drawable.not_set)\n view.isEnabled = true\n }\n binding.currentMessage.text = ""\n fieldsUsed = 0\n isPlayerOne = true\n}\n</code></pre>\n<h2>checkGameState</h2>\n<p>Your checkGameState function has a lot of duplicate lines, all of which are essentially doing the same thing. You are checking three game states to see if they match the current player. An alternative approach is to create a list of the valid winning combinations. You can then iterate through the list to check the combinations. Something like this:</p>\n<pre><code>private fun checkGameState(currentPlayer: FeasibleState): Boolean {\n val winningCombo = arrayOf(\n intArrayOf(0,1,2),\n intArrayOf(3,4,5),\n intArrayOf(6,7,8),\n intArrayOf(0,3,6),\n intArrayOf(1,4,7),\n intArrayOf(2,5,8),\n intArrayOf(0,4,8),\n intArrayOf(2,4,6)\n )\n\n return winningCombo.filter { it.all { idx-> gameState[idx] == currentPlayer }}.any()\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-08T16:53:55.163",
"Id": "260500",
"ParentId": "259971",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260500",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T08:56:47.567",
"Id": "259971",
"Score": "2",
"Tags": [
"android",
"kotlin"
],
"Title": "Android Tic-Tac-Toe"
}
|
259971
|
<p>As per the title, I'm making a webapp that is intended to use as a JS exercise platform. Problems are shown to users, they submit code, that code is run against a few test cases, and a report of the outcome is given back to the user.</p>
<p>I'm using Django for my backend, but to run the code I have also set up a node script, which is called via <code>subprocess</code> in Django.</p>
<p>The script is given a string containing the user code and a list of assertions.
I'm trying to see if the way I structured that script is sound.</p>
<p>Objective: I need to return to Django a list of objects, one for each assertion passed to node, where each object looks like this:</p>
<pre><code>{
id: Number,
assertion: String,
public: Boolean,
passed: Boolean,
error: String,
}
</code></pre>
<p>Django pretty much needs to know which test cases were passed and which failed.</p>
<p>My idea is the following: in Node, I take each assertion passed by Django, and I turn it into a <code>try ... catch</code> in which I create an object I run that assertion and, if it fails, I collect the error in the object (otherwise I collect the positive outcome), then I push that object to an array which is what I ultimately return. I then take all the <code>try ... catch</code> strings and I inline them after the user code in the code I run in my vm.</p>
<p>As you might imagine, the possible issues with this are all the cases where the user might tamper with the array prototype and whatnot.</p>
<p>So here's my Node code. I'd like some input and feedback on what could be improved, what kind of tampering it might still be vulnerable to, and other ideas as to how I could make it generally safer andb better.</p>
<pre><code>/*
usage:
node runWithAssertions.js programCode assertions
arguments:
programCode is a STRING containing a js program
assertions is an ARRAY of strings representing assertions made using node assertions
output:
an array printed to the console (and collected by Django via subprocess.check_output()) where each entry
corresponds to an assertion and is an object:
{
id: Number,
assertion: String,
public: Boolean,
passed: Boolean,
error: String,
}
where id is the id of the assertion (as in the Django database),
assertion is the string containing the assertion verbatim,
public indicates whether the assertion is to be shown to the user or it's secret,
passed represents the outcome of running the assertion on the program,
and error is only present if the assertion failed
*/
// The VM2 module allows to execute arbitrary code safely using a sandboxed, secure virtual machine
const { VM } = require('vm2')
const assert = require('assert')
const AssertionError = require('assert').AssertionError
const timeout = 1000
// instantiation of the vm that'll run the user-submitted program
const safevm = new VM({
timeout, // set timeout to prevent endless loops from running forever
sandbox: {
prettyPrintError,
prettyPrintAssertionError,
assert,
AssertionError
}
})
function prettyPrintError (e) {
const tokens = e.stack.split(/(.*)at (new Script(.*))?vm.js:([0-9]+)(.*)/)
const rawStr = tokens[0] // error message
if (rawStr.match(/execution timed out/)) {
// time out: no other information available
return `Execution timed out after ${timeout} ms`
}
const formattedStr = rawStr.replace(
/(.*)vm.js:([0-9]+):?([0-9]+)?(.*)/g,
function (a, b, c, d) {
return `on line ${parseInt(c) - 1}` + (d ? `, at position ${d})` : '')
}
) // actual line of the error is one less than what's detected due to an additional line of code injected in the vm
return formattedStr
}
// does the same as prettyPrintError(), but it's specifically designed to work with AssertionErrors
function prettyPrintAssertionError (e) {
const expected = e.expected
const actual = e.actual
const [errMsg, _] = e.stack.split('\n')
return (
errMsg +
' expected value ' +
JSON.stringify(expected) +
', but got ' +
JSON.stringify(actual)
)
}
const userCode = process.argv[2]
const assertions = JSON.parse(process.argv[3])
// turn array of strings representing assertion to a series of try-catch's where those assertions
// are evaluated and the result is pushed to an array - this string will be inlined into the program
// that the vm will run
const assertionString = assertions
.map(
(
a // put assertion into a try-catch
) =>
`
ran = {id: ${a.id}, assertion: '${a.assertion}', is_public: ${a.is_public}}
try {
${a.assertion} // run the assertion
ran.passed = true
} catch(e) {
ran.passed = false
if(e instanceof AssertionError) {
ran.error = prettyPrintAssertionError(e)
} else {
ran.error = prettyPrintError(e)
}
}
output_wquewoajfjoiwqi.push(ran)
`
)
.reduce((a, b) => a + b, '') // reduce array of strings to a string
// support for executing the user-submitted program
// contains a utility function to stringify errors, the user code, and a series of try-catch's
// where assertions are ran against the user code; the program evaluates to an array of outcomes
// resulting from those assertions
const runnableProgram = `const output_wquewoajfjoiwqi = []; const arr_jiodferwqjefio = Array; const push_djiowqufewio = Array.prototype.push; const shift_dfehwioioefn = Array.prototype.shift
${userCode}
// USER CODE ENDS HERE
// restore array prototype and relevant array methods in case user tampered with them
Array = arr_jiodferwqjefio
Array.prototype.push = push_djiowqufewio;
Array.prototype.shift = shift_dfehwioioefn;
if(Object.isFrozen(output_wquewoajfjoiwqi)) {
// abort if user intentionally froze the output array
throw new Error("Malicious user code froze vm's output array")
}
while(output_wquewoajfjoiwqi.length) {
output_wquewoajfjoiwqi.shift() // make sure the output array is empty
}
// inline assertions
${assertionString}
// output outcome object to console
output_wquewoajfjoiwqi`
try {
const outcome = safevm.run(runnableProgram) // run program
console.log(JSON.stringify({ tests: outcome })) // output outcome so Django can collect it
} catch (e) {
console.log(JSON.stringify({ error: prettyPrintError(e) }))
}
</code></pre>
<p>The full repo of this project is available at <a href="https://github.com/samul-1/js-exercise-platform/" rel="nofollow noreferrer">https://github.com/samul-1/js-exercise-platform/</a> if you want to take a look at the whole thing. Advice is welcomed :)</p>
|
[] |
[
{
"body": "<blockquote>\n<h3>what kind of tampering it might still be vulnerable to</h3>\n</blockquote>\n<p>I am working on testing this locally and in the process of getting it set up so I am not sure if these things are actual areas of concern but test tampering with globals like <code>JSON</code>, <code>prettyPrintError </code>, <code>assert</code>, <code>Error</code>, etc... I tried modifying <code>JSON.parse()</code> and was able to change its implementation...</p>\n<p>It would be wise to setup unit tests if you haven’t already. Common frameworks like mocha/chai, jest, etc. offer techniques for ensuring exceptions are or aren’t thrown.</p>\n<p>The code tests if the variable <code>output_wquewoajfjoiwqi</code> is frozen, but I assigned it to a different value and it threw <code>TypeError: Assignment to constant variable.</code> If the goal is to use a variable not used within the user code, then perhaps it would be wise to generate the hash dynamically - repeating if necessary until the user code does not contain the hash.</p>\n<p>Bearing in mind the code is run in a VM instead of a browser, you might be interested to read about how <a href=\"https://meta.stackexchange.com/a/240215/341145\">the StackExchange snippets are designed to prevent XSS attacks</a>. I tried to find a list of restrictions for those but haven't found anything comprehensive yet.</p>\n<h3>Other review points</h3>\n<ul>\n<li><p><strong>constant style</strong>: most style guides recommend constant names be in all caps so anyone reading it can distinguish variables from constants. So instead of:</p>\n<blockquote>\n<pre><code>const timeout = 1000\n</code></pre>\n</blockquote>\n<p>use all capitals - e.g.</p>\n<pre><code>const TIMEOUT = 1000 \n</code></pre>\n</li>\n<li><p><strong>repeated <code>require</code></strong> for dependency <code>assertionError</code>: instead of</p>\n<blockquote>\n<pre><code>const AssertionError = require('assert').AssertionError` \n</code></pre>\n</blockquote>\n<p>just use:</p>\n<pre><code>const AssertionError = assert.AssertionError\n</code></pre>\n<p>since the previous line already loaded <code>assert</code></p>\n</li>\n<li><p><strong>regular expressions class</strong> <code>\\d</code> can be used in place of <code>[0-9]</code></p>\n</li>\n<li><p><strong>scope of variable</strong> Is <code>ran</code> declared with keyword, or okay as global?</p>\n</li>\n<li><p><strong>arrow function for callback</strong> The callback to <code>rawStr.replace()</code> could be simplified to an arrow function</p>\n</li>\n<li><p><strong>assigning <code>ran</code></strong> <code>a</code> in the callback to <code>.map()</code> in <code>assertionString</code> can be stringified with <code>JSON.stringify()</code>- so instead of:</p>\n<blockquote>\n<pre><code>ran = {id: ${a.id}, assertion: '${a.assertion}', is_public: ${a.is_public}}\n</code></pre>\n</blockquote>\n<p>just do this:</p>\n<pre><code>const ran = ${JSON.stringify(a)} \n</code></pre>\n<p><sub><em>initially I was thinking that destructuring <code>a</code> - i.e. <code>{id, assertion, is_public}</code> since <code>a</code> is never passed in its entirety. Before I realized that <code>ran</code> is within a template literal I was thinking the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer#New_notations_in_ECMAScript_2015\" rel=\"nofollow noreferrer\">object initializer shorthand notation</a> could allow for the keys to be omitted - but within the template literal that doesn't seem to make sense.</em></sub></p>\n</li>\n<li><p><strong>call <code>Array.join()</code> instead of <code>Array.reduce()</code></strong> After the assertions are mapped to an array, instead of calling <code>reduce</code> to join them together to a string, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join\" rel=\"nofollow noreferrer\"><code>Array.join()</code></a> can be used.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T09:44:33.680",
"Id": "513714",
"Score": "0",
"body": "Excellent answer. The idea of randomly generating the name for the output array is brilliant. One exploit I found this script is vulnerable to is the following code: https://gist.github.com/samul-1/f4115ad1047bdca6bde66c4f6adbcd2c using this, you can override the `push` method and cause the script to tell the Django backend you passed all tests. How would you tackle this? One thing I thought of is to create an alias of the array prototype (with a random name as well) and use that for the `push`ing of outcome objects. I'm open to exploring other paths. Thank you!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T18:22:46.307",
"Id": "513822",
"Score": "1",
"body": "Hmm... I see the original code assigns `Array` to `arr_jiodferwqjefio`... I would see if freezing `Array` would solve that issue. Otherwise there are [alternatives to the push method](https://www.geeksforgeeks.org/alternatives-of-push-method-in-javascript/) - e.g. elements could be pushed into the array by using the bracket notation: e.g. `output_wquewoajfjoiwqi[output_wquewoajfjoiwqi.length] = ran`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T04:39:08.337",
"Id": "260241",
"ParentId": "259973",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260241",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T09:44:06.777",
"Id": "259973",
"Score": "3",
"Tags": [
"javascript",
"node.js",
"ecmascript-6",
"django",
"virtual-machine"
],
"Title": "Node backend to run user-submitted code in a virtual machine"
}
|
259973
|
<p>I am a beginner, and I'm trying to secure a sign-login system on my website. Is my code good/enough to prevent SQL injection?</p>
<p><em><strong>THIS IS THE SIGN FILES</strong></em></p>
<p><strong>This is the index.php that takes user input:</strong></p>
<pre><code><?php
require('some_path\autoload_class.php');
$pass = $_POST['passwordd'];
$card = $_POST['cardd'];
$hashed_pass = password_hash($pass, PASSWORD_DEFAULT);
$hashed_card = password_hash($card, PASSWORD_DEFAULT);
$user = new User($_POST['emaill'], $hashed_pass, $hashed_card);
$user->insert();
echo("Your <b>Email</b> is: {$_POST['emaill']}<br>");
echo("Your <b>Password</b> is: {$pass}<br>");
echo("Your <b>Card's number</b> is: {$card}");
?>
</code></pre>
<p><strong>This is User.php Class:</strong></p>
<pre><code><?php
class User {
//User and database info
private $email;
private $password;
private $card;
private $host = "localhost";
private $user = "root";
private $dbpassword = "x";
private $dbName = "database";
public function __construct(string $user_email, string $user_password, string $user_card) {
$this->email = $user_email;
$this->password = $user_password;
$this->card = $user_card;
}
public function insert(){
try{
//The connection to the Database
$dsn = "mysql:host={$this->host};dbname={$this->dbName}";
$pdo = new PDO($dsn, $this->user, $this->dbpassword);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo("Connected successfully to database!<br>");
//The code to insert user input into database (table user)
$sql = "INSERT INTO user(email, password, card) VALUES(?, ?, ?)";
$prepared_statement = $pdo->prepare($sql);
$prepared_statement->execute([$this->email, $this->password, $this->card]);
echo("User input stored with success!<br>");
//I did read that this is good practice for closing the connection
$pdo = null;
$prepared_statement = null;
//if there's an error, it will be printed out
}catch (PDOException $e) {
echo("Connection failed!<br>");
echo($e->getMessage());
}
}
}
</code></pre>
<p><em><strong>THIS IS THE LOGIN FILES</strong></em></p>
<p><strong>This is index.php that takes user input and confirm if password is correct:</strong></p>
<pre><code><?php
require('some_path\autoload_class.php');
$user = new login($_POST['emaill'], $_POST['passwordd']);
$user->fetch();
</code></pre>
<p><strong>This is Login.php class:</strong></p>
<pre><code><?php
class login {
private $email;
private $password;
private $host = "localhost";
private $user = "root";
private $dbpassword = "x";
private $dbName = "database";
public function __construct(string $user_email, string $user_password) {
$this->email = $user_email;
$this->password = $user_password;
}
public function fetch(){
try{
//The connection to the database
$dsn = "mysql:host={$this->host};dbname={$this->dbName}";
$pdo = new PDO($dsn, $this->user, $this->dbpassword);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
echo("Connected successfully to database!<br>");
//The query
$sql = "SELECT * FROM user WHERE email = ?";
$prepared_statement = $pdo->prepare($sql);
$prepared_statement->execute([$this->email]);
$user = $prepared_statement->fetchAll();
//Because $user is an assocc array, I use password_verify inside this foreach
foreach ($user as $key) {
//if user password == to hashed password in database where email == user email
if (password_verify($this->password, $key['password'])) {
echo("User Indentity Confirmed with Success!<br>");
echo("<h2>INFO</h2><hr><hr>");
echo("<b>User Id:</b> {$key['user_id']}<br>");
echo("<b>User Email:</b> {$key['email']}<br>");
echo("<b>User Password:</b> {$key['password']}<br>");
echo("<b>User Card number:</b> {$key['card']}");
}else{
echo("<h2>User Indentity Not Confirmed.</h2>");
}
}
$pdo = null;
$prepared_statement = null;
}catch (PDOException $e) {
echo("Oops...Something Went Wrong!<br>");
echo($e->getMessage());
}
}
}
</code></pre>
<p>In the sign files, I'm trying to get user input in the most secure way I possible, hashing password and credit card number, using pdo with prepared statements, and then inserting the user input into database.</p>
<p>In the login files, I'm trying to use the email provided by user, find the row in user table where email = user email provided, and then comparing the hashed password with password provided.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:13:20.363",
"Id": "513358",
"Score": "0",
"body": "`echo` is not a function. Adding parentheses is very confusing"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:14:04.740",
"Id": "513359",
"Score": "0",
"body": "Your PDO connection needs charset. Don't rely on the default one. Set it properly yourself to be `utf8mb4`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-02T20:45:06.250",
"Id": "513754",
"Score": "0",
"body": "@Dharman thank you, sorry I'm late to reply. You're always there! I will google for more information about charset. And I'm just used to use echo as a function because it looks like printf()."
}
] |
[
{
"body": "<p>Your code is good enough at preventing sql injection. But it sucks (pardon me) in everything else.</p>\n<p>Don't print database error to the user.</p>\n<p>Don't put echoes into your logic.</p>\n<p>Don't double last letters of post fields names.</p>\n<p>Don't repeat yourself by integrating your database connection to every class that has nothing to do with db. Prefer composition. User should not insert itself into db. Login should not fetch itself from db. How are you going to connect to a different db without changing every class in your project?</p>\n<p>EDIT: To clarify the last point, your code should look more like this:</p>\n<pre><code>// definitions \nfunction connect() {\n return new \\PDO(/*maybe take it from environemt variables rather then hardcoding it*/);\n}\n\n// services instantiation (your bootstrap, DI container or so...)\n$pdo = connect();\n$users = new UsersService($pdo);\n\n\n// create new user\n$users->createUser($userCreateRequestData);\n\n// to login\n$user = $users->login($userName, $password);\n...\n</code></pre>\n<p>Or in other words, there should be separate objects to represent a user (its data) and to manipulate user objects (ie, creating new users, verifying their password, obtaining their data, updating their data, removing them, etc...). User data dont need to know how, where and when they are persisted. And the persister dont need to carry arund data of a specific user.</p>\n<p>You may actually want to create a separate class for authentication as that's really a bit different layer then the persistance of user data - which is db related, but auth processes dont really need to know the details. On other hand, it may need to access session which is not really a concern of the data access layer. So they should be separate - Auth layer knows session and DA layer but it doesnt care for the actual connection, DA layer knows about the connection but it doesnt care if session or auth layer exists at all.</p>\n<p>Actually creating a user should also be a separate class. Because creating a user often involved other things then just insert a row to database (ie send an email) and those things are again no concern of DA layer.</p>\n<p>Eventually you might end up having more and more one purpose classes (which is good).</p>\n<pre><code>// bootstrap\n$pdo = connect();\n$users = new UsersRepository($pdo);\n\n// create user\n$userFactory = new UserFactory($users, $mailService);\n$userFactory->createUser($userCreateRequestData);\n\n// login user\n$auth = new Authenticator($users, $sessionService);\n$user = $auth->login($userName, $password);\n<span class=\"math-container\">```</span>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:05:13.603",
"Id": "513092",
"Score": "0",
"body": "Thanks for the answer, i really understood everything except: \"User class should not insert() itself... and Login class should not fetch() itself\". What does it mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:08:54.953",
"Id": "513117",
"Score": "0",
"body": "@irtexas19 I have edited my answer with some more detail and code samples, have a look..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:14:34.653",
"Id": "513118",
"Score": "0",
"body": "thank you for all, I'll read up!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T03:44:37.100",
"Id": "260008",
"ParentId": "259975",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "260008",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T10:03:30.833",
"Id": "259975",
"Score": "4",
"Tags": [
"php",
"sql",
"mysql",
"security",
"pdo"
],
"Title": "Storing and confirming user input"
}
|
259975
|
<p>I have wrote a <code>MutableLiveList</code> class for android, similar to existing <code>MutableLiveData</code>, but this class instead handles a list and notifies its observers on structural changes like adding items and removing items. It is intended to be used inside viewModels similar to <code>MutableLiveData</code>. Class implementation is like this:</p>
<pre><code>class MutableLiveList<E> : MutableList<E> {
private val list = mutableListOf<E>()
private val listChange = MutableLiveData<Triple<Int, Int, ListEvent>>()
fun observe(owner: LifecycleOwner, observer: ListObserver) {
//newly added observer must not listen to old changeEvents
/*EDIT*/listChange.value = Triple(-1, 0, NONE)
listChange.observe(owner, {
when (it.third) {
/*EDIT*/ NONE -> {}
ADD -> observer.onAdded(it.first, it.second)
REMOVE -> observer.onRemoved(it.first, it.second)
}
})
}
//List methods : delegate to corresponding list.methods
override val size get() = list.size
override fun contains(element: E) = list.contains(element)
override fun containsAll(elements: Collection<E>) = list.containsAll(elements)
override fun get(index: Int) = list[index]
override fun indexOf(element: E) = list.indexOf(element)
override fun lastIndexOf(element: E) = list.lastIndexOf(element)
override fun isEmpty() = list.isEmpty()
override fun iterator() = list.iterator()
override fun listIterator() = list.listIterator()
override fun listIterator(index: Int) = list.listIterator(index)
override fun subList(fromIndex: Int, toIndex: Int) = list.subList(fromIndex, toIndex)
//MutableList methods : trigger list observers.
override fun add(element: E) = add(size, element).run { true }
override fun add(index: Int, element: E) = list.add(index, element).also {
listChange.value = Triple(index, 1, ADD)
}
override fun addAll(elements: Collection<E>) = addAll(size, elements)
override fun addAll(index: Int, elements: Collection<E>) = list.addAll(index, elements).also {
listChange.value = Triple(index, elements.size, ADD)
}
override fun clear() {
val size = size
list.clear()
listChange.value = Triple(0, size, REMOVE)
}
override fun remove(element: E): Boolean {
val index = list.indexOf(element)
if (index == -1)
return false
removeAt(index)
return true
}
override fun removeAt(index: Int) = list.removeAt(index).also {
listChange.value = Triple(index, 1, REMOVE)
}
override fun retainAll(elements: Collection<E>): Boolean {
var modified = false
for (ele in list.toList()) {
if (ele !in elements) {
remove(ele)
modified = true
}
}
return modified
}
override fun removeAll(elements: Collection<E>): Boolean {
var modified = false
for (ele in list.toList()) {
if (ele in elements) {
remove(ele)
modified = true
}
}
return modified
}
override fun set(index: Int, element: E) = list.set(index, element).also {
listChange.value = Triple(index, 1, REMOVE)
listChange.value = Triple(index, 1, ADD)
}
}
interface ListObserver {
fun onAdded(start: Int, size: Int)
fun onRemoved(start: Int, size: Int)
}
private enum class ListEvent {
NONE, ADD, REMOVE;
}
</code></pre>
<p>Example usage:</p>
<pre><code>val userList = MutableLiveList<User>()
.
.
.
userListAdapter = UserListAdapter(userList)
userList.observe(this, object : ListObserver {
override fun onAdded(start: Int, size: Int) {
userListAdapter.notifyItemRangeInserted(start, size)
}
override fun onRemoved(start: Int, size: Int) {
userListAdapter.notifyItemRangeRemoved(start, size)
}
})
</code></pre>
<p>This is working fine for now in main thread. I suspect would this work on background thread or not! Is this good enough? Are there any lurking bugs?</p>
<p><strong>EDIT</strong>: Added two lines in the code. I don't know if these two lines are necessarily required (I tried with and without, both worked well). Without this line, whenever a new observer is added, it will get a redundant <code>onAdded</code>/<code>onRemoved</code> event depending on the recent change made to the list, before attaching the observer.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T16:13:36.580",
"Id": "513039",
"Score": "0",
"body": "@Tenfour04 huh.. kindof. I don't know how to write unit tests. Actually I doubt something in this code, which I have asked [here](https://stackoverflow.com/questions/67255037/is-there-any-guarenteed-way-to-mimic-some-action-between-ondestroy-and-oncr). If possible answer that please."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T17:15:37.103",
"Id": "513041",
"Score": "1",
"body": "Oops, sorry, I missed which Exchange site we’re on because I’m using the app. Nothing wrong with what you’re asking here."
}
] |
[
{
"body": "<p>You could define the class constructor this way to avoid manually delegating those basic functions:</p>\n<pre><code>class MutableLiveList<E> private constructor(private val list: MutableList<E>) : MutableList<E> by list {\n constructor(): this(mutableListOf())\n\n //...\n}\n</code></pre>\n<p>If you want to be able to modify the list from a background thread, you should use <code>postValue</code> instead of <code>setValue</code> on the MutableLiveData.</p>\n<p>You might consider designing this to be observed using a LifecycleCoroutineScope instead of a LifecycleOwner. Then you can back it with a MutableFlow and eliminate the <code>NONE</code> case. Your observe function could use <code>launchWhenStarted</code> and collect the flow to the passed listener.</p>\n<p>One possible gotcha I see is if <code>retainAll</code> or <code>removeAll</code> is used on this List, it will fire the observer for each individual item removed. Not just with the class functions, but also the inline extension function overloads that take a lambda. But maybe that's the design intent.</p>\n<p>Since your <code>removeAll</code> and <code>retainAll</code> rely on <code>remove</code>, they run in <em>O(m*n^2)</em> time. You might want to remove directly using the iterator so you can avoid copying the list and searching for each removed element.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T17:22:04.090",
"Id": "514556",
"Score": "0",
"body": "Thank you for that interface delegation suggestion. But I didn't quite get that paragraphs about `removeAll` and `retainAll`. Mainly that thing about avoiding copying the list. Btw, I know implementation of those two function will have worst performance. But since those removed elements are not continuous, I have to fire observer for individual elements. Otherwise I have to throw `UnsupportedOperationException`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T17:43:53.437",
"Id": "514559",
"Score": "0",
"body": "`toList()` copies the list into another list. Then each `in` call searches the list. Then each `remove` call indirectly uses `indexOf`, so you have *O(m\\*n^2)* complexity. If you do something like `override fun removeAll(elements: Collection<E>) = list.removeAll { it in elements }`, then it will only be *O(m\\*n)* complexity and no list copy is required."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T17:55:23.500",
"Id": "514560",
"Score": "0",
"body": "I don't know how `removeAll(predicate:..)` is implemented. But here, for every being removed, observer should be fired. Does that happen when using `removeAll`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T18:08:28.603",
"Id": "514561",
"Score": "0",
"body": "Oh, good point. It won't trigger the observer for everything because it directly sets values. You would have to write your own implementation if you want to improve efficiency"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T18:15:47.483",
"Id": "514562",
"Score": "0",
"body": "Can you write something better with the requirement that it should trigger observers?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T18:24:11.330",
"Id": "514563",
"Score": "1",
"body": "You can pretty much copy the code from the standard library for `retainAll`/`removeAll` which both use a private function `filterInPlace`. You just need to be sure that you trigger the observer correctly when removing and adding items. Also, you might want to add `removeAll(predicate)` and `retainAll(predicate)` as members of your class to prevent the standard library extension functions from accidentally being used since they will trigger your observers incorrectly."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-13T15:52:20.230",
"Id": "260715",
"ParentId": "259977",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T10:18:43.063",
"Id": "259977",
"Score": "1",
"Tags": [
"android",
"kotlin"
],
"Title": "MutableLiveList class for android"
}
|
259977
|
<p>I have a object list like below. I want to join every two rows into single row based on column B. It is sure that only two rows would be there for every single column B value.</p>
<p><strong>Input</strong></p>
<p><a href="https://i.stack.imgur.com/cd0dV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cd0dV.png" alt="enter image description here" /></a></p>
<p><strong>Output</strong></p>
<p><a href="https://i.stack.imgur.com/CBVe2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CBVe2.png" alt="enter image description here" /></a></p>
<p>However, my solution works. but I am looking for more better solution. I am not much happy with my solution.</p>
<p>My solution:</p>
<pre><code>var groupByItems = items.GroupBy(x => x.ColumnB).Select(x => new MappingClass
{
ColumnA= x.FirstOrDefault().ColumnA,
ColumnB= x.FirstOrDefault().ColumnB,
ColumnC= x.Where(r=> !string.IsNullOrEmpty(r.ColumnC)).Select(r=>r.ColumnC).FirstOrDefault(),
ColumnD= x.Where(r => !string.IsNullOrEmpty(r.ColumnD)).Select(r => r.ColumnD).FirstOrDefault(),
}).ToList();
</code></pre>
<p>Now groupByItems object returns me two rows as expected.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T12:33:55.783",
"Id": "513017",
"Score": "4",
"body": "Welcome to the Code Review Community. Can you provide more context about this code in the question. Why are you merging multiple rows? What does the rest of the program do? Why do you want to improve this code, is it too slow, using too much memory? It is very hard to help you improve the code without more context."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T18:05:19.407",
"Id": "513044",
"Score": "0",
"body": "IMHO Your input nor your output make sense WRT ColumnA. Why would they be the same for all lines in Input or in Output, and where is the Output value supposed to be coming from? Also, what is your input? Because if is is the result of a DB call, you might consider a custom query instead."
}
] |
[
{
"body": "<p>If you want to reduce the iteration to get the value for ColumnC and ColumnD and make the code cleaner, you can try using Aggregate instead.</p>\n<pre><code>var output = input\n .GroupBy(d => new {d.ColumnA, d.ColumnB})\n .Select(\n g => g.Aggregate(\n new MappingClass {ColumnA = g.Key.ColumnA, ColumnB = g.Key.ColumnB},\n (result, next) =>\n {\n result.ColumnC ??= next.ColumnC;\n result.ColumnD ??= next.ColumnD;\n return result;\n }))\n .ToList();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T16:22:41.513",
"Id": "513040",
"Score": "0",
"body": "+1 neat. you've just forgot to add `ToList()` to match OP final result. ;). Also, I think you will get the same results without `new MappingClass { .... }` line."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T03:10:29.143",
"Id": "513077",
"Score": "0",
"body": "@iSR5 thanks for noticing that, I've updated the code. And the problem with removing the `new MappingClass` is that you're modifying the input data in the enumerable operation which is not a good practice."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:01:57.463",
"Id": "513162",
"Score": "0",
"body": "totally missed the reference type behavior ;).. thanks for the explanation"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T13:49:12.347",
"Id": "259983",
"ParentId": "259980",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T11:10:12.840",
"Id": "259980",
"Score": "0",
"Tags": [
"c#",
"linq",
"linq-expressions"
],
"Title": "Merging every two objects into single single object making group by a property C# LINQ"
}
|
259980
|
<p>I wrote a working program in C that takes an array with size 2ⁿ, and separates all the even numbers from the odd numbers.<br />
For example: Input: {1,2,3,4,5,6,7,8}, Output: {8,2,6,4,5,3,7,1}<br />
I want my program to be as efficient as possible and to have space complexity O(log n) and time complexity of O(n log n).</p>
<p>This is the code in C:</p>
<pre><code>#include <stdio.h>
void swap(int*, int*);
void arrange(int arr[], int n);
int main() {
int arr[] = {1,2,3,4,5,6,7,8};
int size = sizeof(arr)/sizeof(arr[0]);
arrange(arr,size);
return 0;
}
void arrange(int arr[], int n) {
if (n==1) return;
int istart = 0, iend = n-1;
while (istart <= iend) {
if (arr[istart] % 2 == 0) {
istart++;
return arrange(arr+istart,n-1);
}
else if (arr[iend] % 2 == 1) {
iend--;
return arrange(arr,n-1);
}
else {
swap(&arr[istart++],&arr[iend--]);
return arrange(arr+istart,n-1);
}
}
}
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
</code></pre>
<p>How can I improve my code? Maybe make it run faster with a better complexity?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T17:25:47.263",
"Id": "513043",
"Score": "1",
"body": "Does the order matter?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:49:16.523",
"Id": "513108",
"Score": "1",
"body": "The accepted terminology is that this function __partitions__ its input. It's used as part of quicksort, with the the _partition function_ being a `<` comparison, but it's reasonable to partition an array on any predicate, including modular residue. Knowing this might help you find other implementations to learn from."
}
] |
[
{
"body": "<h1>Efficiency</h1>\n<p>Your code is already more efficient than you think. It has time complexity <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, and thanks to <a href=\"https://en.wikipedia.org/wiki/Tail_call\" rel=\"nofollow noreferrer\">tail recursion</a>, it also has space complexity <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span>.</p>\n<h1>Avoid forward declarations</h1>\n<p>I recommend that you avoid the need to forward-declare <code>arrange()</code> and <code>swap()</code> by reversing the order in which the functions appear in your source file. This avoids repeating yourself.</p>\n<h1>Don't <code>return</code> a <code>void</code></h1>\n<p>Unfortunately, the C standard <a href=\"https://stackoverflow.com/questions/22508978/can-a-void-returning-function-g-return-f-when-f-returns-void\">explicitly forbids</a> calling <code>return</code> with an expression in a function returning <code>void</code>, even if the result of that expression itself is also <code>void</code>. While both GCC and Clang allow it, they will produce a warning when the <code>-pedantic</code> option is used. Just separate the call to <code>arrange()</code> from calling the <code>return</code> statement.</p>\n<h1>Simplify the code</h1>\n<p>Without making any changes to the algorithm, you can simplify the code. For example, the <code>while</code>-statement is redundant, since its condition will always be true in the first iteration, and you always call <code>return</code> inside the body, so it won't ever repeat. Furthermore, you can avoid having to declare the variables <code>istart</code> and <code>iend</code>. Here is how it could look:</p>\n<pre><code>void arrange(int arr[], int n) {\n if (n <= 1)\n return;\n\n if (arr[0] % 2 == 0) {\n arrange(arr + 1, n - 1);\n } else if (arr[n - 1] % 2 != 0) {\n arrange(arr, n - 1);\n } else {\n swap(&arr[0], &arr[n - 1]);\n arrange(arr + 1, n - 2);\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:24:48.577",
"Id": "513099",
"Score": "3",
"body": "Note that `arr[n - 1] % 2 == 1` is false for negative odd numbers. (Which makes it slower to compute when the compiler can't prove that the int is non-negative, so you want to avoid it even if it's not a correctness problem: https://godbolt.org/z/PYzzqE1ec). `arr[n-1] & 1` would actually work fine here, as long as you don't care about one's complement machines, but `x % 2 != 0` is perhaps equally idiomatic, and portable even to 1's complement."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T08:37:02.173",
"Id": "513115",
"Score": "0",
"body": "@PeterCordes Thanks for pointing that out, I updated my answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:27:05.250",
"Id": "513119",
"Score": "1",
"body": "Wrote that up into an answer, since neither existing answer explicitly mentions that efficiency / correctness point."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T11:10:08.650",
"Id": "513128",
"Score": "0",
"body": "Is there a guarantee that a C compiler will eliminate tail recursive calls?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T11:12:01.447",
"Id": "513129",
"Score": "0",
"body": "@CarstenS There is no guarantee, and with optimizations disabled it will probably not eliminate them. However, with optimizations enabled all mainstream compilers will."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T15:17:26.820",
"Id": "259985",
"ParentId": "259982",
"Score": "9"
}
},
{
"body": "<p>A more natural type for <code>n</code>, the number of elements, is <strong><code>size_t</code></strong> (from <code><stdint.h></code>). This is also the type yielded by the <code>sizeof</code> operator, which means you would avoid a narrowing, signedness-changing conversion when calling.</p>\n<p>It's good practice to make all your function definitions <em>prototypes</em>. In this case specify that <code>main()</code> takes no arguments: <code>int main(void)</code>.</p>\n<p>In <code>main()</code> (but only <code>main()</code>, and no other non-<code>void</code> function), we are allowed to omit the <code>return</code> statement, and the function will automatically return <code>0</code>.</p>\n<p>The loop condition can be <code>istart <= iend</code>, since if the indices are equal, we have finished. This means that we don't need to special-case <code>n==1</code>.</p>\n<p>As not all compilers will eliminate tail-recursion (often it depends on the enabled optimisations), it may be worth reducing the call depth. One very simple method would be to skip over <em>all</em> leading even numbers and <em>all</em> trailing odd numbers before swapping and recursing:</p>\n<pre><code>while (arr[istart] % 2 == 0 && istart < iend) {\n ++istart;\n}\nwhile (arr[iend] % 2 != 0 && istart < iend) {\n --iend;\n}\nif (istart >= iend) {\n /* we're done */\n return;\n}\nswap(&arr[istart++],&arr[iend--]);\n</code></pre>\n<p>This leads us towards an iterative solution, which ends up looking something like this (using pointers rather than indices, for simplicity):</p>\n<pre><code>void arrange(int arr[], size_t n)\n{\n int *a = arr;\n int *z = arr + n;\n\n for (;;) {\n while (a < z && *a % 2 == 0) {\n ++a;\n }\n while (a < z && *--z % 2 != 0) {\n ;\n }\n if (a >= z) {\n return; /* finished */\n }\n\n swap(a++, z);\n }\n}\n</code></pre>\n<p>Here, I've made <code>z</code> point to <em>one after</em> the right-hand element, to avoid adjusting by ±1 in places, but at the expense of some symmetry.</p>\n<p>The test is a good start. It would be better if it checked the result of the function, and returned a failure status if the array was not correctly partitioned. Consider also testing some edge cases (empty array, a single element, all odd, all even).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T00:43:09.950",
"Id": "513075",
"Score": "0",
"body": "That can probably be sped up by testing for even via `& 1` instead of `% 2 != 0`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T03:35:26.043",
"Id": "513082",
"Score": "0",
"body": "@RickJames Pretty much any compiler will optimize those to the same thing."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:05:42.523",
"Id": "513093",
"Score": "1",
"body": "@RickJames: Unlike `x % 2 == 1` for signed int, `x % 2 != 0` is equivalent to `x & 1` (at least on two's complement machines), and compilers know this unless you disable optimization (GCC: https://godbolt.org/z/senxE4Gc3). Using `x & 1` would I think be a bug on one's complement machines for negative integers, because `-x` uses the same bit-pattern as `~x`. e.g. `-1` is `0xFE` in 1's complement, unlike `0xFF` in 2's complement. Of course most people don't give a rats ass about one's complement, so if you wanted to test for odd numbers, `x & 1 == 1` would be ok and works even for negative."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:23:06.763",
"Id": "513098",
"Score": "0",
"body": "(But `x % 2 != 0` is idiomatic and portable.) Actually, GCC uses AND even at `-O0`, but clang doesn't. https://godbolt.org/z/zsovsEPfh (updated with `(x&1) == 1` semi-bugfix over missing parens, reposted). Note the `register int` is just to reduce noise of `gcc -O0` unoptimized code, avoiding the spill/reload."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T20:14:17.457",
"Id": "513190",
"Score": "0",
"body": "And, isn't `== 1` redundant if you are simply doing a boolean test? Will the optimizer simplify that? And maybe `!= 0` is more optimizable?"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T16:07:47.907",
"Id": "259988",
"ParentId": "259982",
"Score": "7"
}
},
{
"body": "<p>What you're doing is a partition function. That's most commonly seen as part of <a href=\"https://en.wikipedia.org/wiki/Quicksort\" rel=\"nofollow noreferrer\">Quick Sort</a> (partitioning based on the condition <code>x < some_value</code>), but it works equally well with a condition like <code>x % 2 != 0</code>. (And your condition doesn't require choosing a "pivot"). So you can find non-recursive (iterative) implementations if you go looking. For example, scanning two pointers towards each other as shown in @Toby's answer is an implementation of <a href=\"https://en.wikipedia.org/wiki/Quicksort#Hoare_partition_scheme\" rel=\"nofollow noreferrer\">Hoare's partition scheme</a></p>\n<hr />\n<h3>Use <code>x % 2 != 0</code> to check for odd with signed types like <code>int</code></h3>\n<p><strong><code>arr[iend] % 2 == 1</code> is false for negative odd numbers</strong>. e.g. <code>-3 % 2 == -1</code> in C, unlike Python where <code>%</code> is a positive modulus.</p>\n<p><code>x % 2 != 0</code> is very cheap to compute even for signed <code>int</code> (on a 2's complement machine), because compilers know that it's equivalent to <code>x & 1</code> (e.g. x86 <code>test reg, 1</code> to set FLAGS). Compilers will reliably do that optimization as long as you don't disable optimization generally (e.g. <code>clang -O0</code>, or forgetting to enable optimization because <code>-O0</code> is the default for most compilers.)</p>\n<p>But <strong><code>x % 2 == 1</code> is slower</strong> to compute when the compiler can't prove that the int is non-negative, so you want to <strong>avoid it even if it's not a correctness problem</strong>: <a href=\"https://godbolt.org/z/PYzzqE1ec\" rel=\"nofollow noreferrer\">https://godbolt.org/z/PYzzqE1ec</a>.</p>\n<p><code>x & 1</code> would actually work fine here, as long as you don't care about one's complement machines, but <code>x % 2 != 0</code> is perhaps equally idiomatic, and portable even to 1's complement.</p>\n<p>On a <a href=\"https://en.wikipedia.org/wiki/Ones%27_complement\" rel=\"nofollow noreferrer\">one's complement</a> machine, <code>-1</code> is represented by <code>0x...FE</code>, not the <code>0x...FF</code> we're used to on two's complement machines. <code>-x</code> is the same binary operation as <code>~x</code> on a one's complement machine. ISO C allows signed integer types like <code>int</code> to have an object-representation of 2's complement, 1's complement, or sign/magnitude. (ISO C defines enough stuff that you can read with <code>unsigned char*</code> to see the raw bits.)</p>\n<p>If you had <code>unsigned int</code>, or any other unsigned type, <code>x & 1</code> would be idiomatic, because C integers are binary.</p>\n<p>(I left comments about this on other answers, but the code in the question had this bug so I wanted to put it in an answer.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:06:04.300",
"Id": "260017",
"ParentId": "259982",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T13:20:00.470",
"Id": "259982",
"Score": "5",
"Tags": [
"performance",
"c",
"array",
"recursion"
],
"Title": "Separating the even and odd numbers in an array in C"
}
|
259982
|
<p>I made a function that directly calculates the discrete Fourier transform in dimension two, as well as functions that automatically initialize a 2D array to either something random, or specific basis elements (when viewing multidimensional arrays as tensors, but that's not important). Also an approximate equality checker. This would be used to verify a more sophisticated implementation of the Fourier transform.</p>
<p>I am mainly looking for feedback on C best practices, proper documentation and code safety, but also on test-design. Is this the proper way to write a test unit?</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <complex.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#include <assert.h>
// For a 2D FFT of size N0 x N1, both powers of two.
#define N0 8
#define N1 4
// Initializes weights
void weightInit(double complex* weights, int length)
{
for (int j = 0; j < length; j++) {
weights[j] = cexp(-2.0 * M_PI * j / length * I);
}
}
// Calculates the N0 x N1 2D FFT directly. Input is overwritten by output.
void naiveFFT2D(double complex input[N0][N1])
{
// We temporarily write the output here. This is disgusting, but
// the only way to allocate a multidimensional array on the heap.
double complex (*output)[N1] = malloc( sizeof(double complex[N0][N1]) );
assert(output); // malloc returns a null pointer when the memory is not available
// and this is the only pointer that gets type casted to 0, so
// this terminates the program iff there is not sufficient memory.
// Initialize the weights
double complex* weightsN0 = malloc(N0 * sizeof(double complex));
double complex* weightsN1 = malloc(N1 * sizeof(double complex));
assert(weightsN0);
assert(weightsN1);
weightInit(weightsN0, N0);
weightInit(weightsN1, N1);
// Compute the FFT, (k0, k1) corresponds to output
for (int k0 = 0; k0 < N0; k0++) {
for (int k1 = 0; k1 < N1; k1++) {
output[k0][k1] = 0;
for (int j0 = 0; j0 < N0; j0++) {
for (int j1 = 0; j1 < N1; j1++) {
output[k0][k1] += input[j0][j1] * weightsN0[j0 * k0 % N0] * weightsN1[j1 * k1 % N2];
}
}
}
}
// Overwite input with output
for (int k0 = 0; k0 < N0; k0++) {
for (int k1 = 0; k1 < N1; k1++) {
input[k0][k1] = output[k0][k1];
}
}
free(weightsN0);
free(weightsN1);
free(output);
}
// Prints an N0 x N1 array.
void printArray(double complex arr[N0][N1])
{
for (int j0 = 0; j0 < N0; j0++) {
printf("\n");
for (int j1 = 0; j1 < N1; j1++) {
printf("%f + %fi | ", creal(arr[j0][j1]), cimag(arr[j0][j1]));
}
}
}
// Initializes input to array with a 1 on place (k0, k1) and 0's elsewhere.
void initBasisElement(int k0, int k1, double complex input[N0][N1])
{
for (int j0 = 0; j0 < N0; j0++) {
for (int j1 = 0; j1 < N1; j1++) {
input[j0][j1] = 0.0;
}
}
input[k0][k1] = 1.0;
}
// Initializes input to random array.
void initRandom(double complex input[N0][N1])
{
srand((unsigned int) clock());
for (int j0 = 0; j0 < N0; j0++) {
for (int j1 = 0; j1 < N1; j1++) {
// a + bi with 0 <= a, b < 1 random doubles
input[j0][j1] = (double) rand() / (double) RAND_MAX + ((double) rand() / (double) RAND_MAX) * I;
}
}
}
// Takes N0 x N1 arrays a and b, and returns true if and only if
// a and b differ less than error at every entry.
bool testEquality(double error, double complex a[N0][N1], double complex b[N0][N1])
{
bool equal = true;
for (int j0 = 0; j0 < N0; j0++) {
for (int j1 = 0; j1 < N1; j1++) {
if (cabs(a[j0][j1] - b[j0][j1]) > error) {
equal = false;
}
}
}
return equal;
}
int main()
{
double complex (*input)[N1] = malloc( sizeof(double complex[N0][N1]) );;
initBasisElement(2, 2, input);
double complex (*b)[N1] = malloc( sizeof(double complex[N0][N1]) );;
initRandom(b);
naiveFFT2D(input);
printArray(input);
if (testEquality(0.001, input, b)) {
printf("\n\nEquality!");
}
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>This is not how to correctly use <code>assert()</code>:</p>\n<blockquote>\n<pre><code>double complex (*output)[N1] = malloc( sizeof(double complex[N0][N1]) );\nassert(output); // malloc returns a null pointer when the memory is not available\n // and this is the only pointer that gets type casted to 0, so\n // this terminates the program iff there is not sufficient memory.\n</code></pre>\n</blockquote>\n<p>Asserts are for documenting (and incidentally testing) code invariants, not for runtime checks. Remember that <code>assert()</code> expands to a no-op in production builds!</p>\n<p>Instead of claiming that <code>malloc()</code> never fails, we need to write an actual <code>if</code> statement there - ideally, it should return a status value to the caller, who is in a better position to decide whether to terminate the whole program, or to do some other work first (saving the user's data, perhaps).</p>\n<p>In passing, we can simplify the size computation, and make it more robust, by using the dereferenced variable as argument to <code>sizeof</code>, rather than having to write a matching type.</p>\n<p>It's a bit inconvenient to be stuck with fixed sizes for our array. The usual way to dynamically allocate a 2-dimensional matrix of values is to <code>malloc()</code> storage for <em>rows</em> ✕ <em>columns</em> elements, and then access elements using an index computed as <em>x</em> + <em>y</em> ✕ <em>rows</em>.</p>\n<p>I get a lot of Valgrind reports of reading off the end of allocated memory:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==1197== Invalid read of size 8\n==1197== at 0x109484: naiveFFT2D (259984.c:49)\n==1197== by 0x109953: main (259984.c:126)\n==1197== Address 0x4b79800 is 0 bytes after a block of size 64 alloc'd\n==1197== at 0x483877F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==1197== by 0x1092D4: naiveFFT2D (259984.c:35)\n==1197== by 0x109953: main (259984.c:126)\n==1197== \n==1197== Invalid read of size 8\n==1197== at 0x109488: naiveFFT2D (259984.c:49)\n==1197== by 0x109953: main (259984.c:126)\n==1197== Address 0x4b79808 is 8 bytes after a block of size 64 alloc'd\n==1197== at 0x483877F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==1197== by 0x1092D4: naiveFFT2D (259984.c:35)\n==1197== by 0x109953: main (259984.c:126)\n</code></pre>\n<p>These should be corrected (I don't think you really intended to index element <code>j0 * k0</code>, for example, but don't immediately see what you actually meant). There's also leakage of memory from <code>main()</code>, which is easy to clean up:</p>\n<pre class=\"lang-none prettyprint-override\"><code>==1197== 512 bytes in 1 blocks are definitely lost in loss record 1 of 2\n==1197== at 0x483877F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==1197== by 0x109913: main (259984.c:122)\n==1197== \n==1197== 512 bytes in 1 blocks are definitely lost in loss record 2 of 2\n==1197== at 0x483877F: malloc (in /usr/lib/x86_64-linux-gnu/valgrind/vgpreload_memcheck-amd64-linux.so)\n==1197== by 0x109937: main (259984.c:124)\n</code></pre>\n<p>I don't see why there are empty statements following the allocations in <code>main()</code> - are those <code>;;</code> just typos?</p>\n<p>The test looks totally flawed to me. Why are we comparing against a randomly-populated matrix? That's unlikely to be correct. And why do we always return zero (i.e. success), even when the actual and expected results are different?</p>\n<p>If we have a function available that implements the reverse transform, a useful test would be that we can apply that and get back the original input, within rounding error. It's not sufficient as a test of both functions, but it's certainly helpful.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T16:42:59.583",
"Id": "259990",
"ParentId": "259984",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259990",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T15:06:49.203",
"Id": "259984",
"Score": "2",
"Tags": [
"beginner",
"c"
],
"Title": "C test functions for 2D FFT"
}
|
259984
|
<p>I've been assigned the following Python homework:</p>
<blockquote>
<p>Implement myrange that acts like <code>range</code> using iterators. Define a function <code>myrange</code>and define a class <code>MyRange</code>.</p>
</blockquote>
<p>We've just seen iterators, so I think I'm asked to use them. I am not required to write a sophisticated code, but only something that allows the range-for loop syntax.</p>
<p>Professor said that, roughly, an iterator is an object for which the dunder method <code>__next__</code> is provided. I've seen there are similar questions here. However, none of them is defining the <code>__next__</code> method in a class.</p>
<hr />
<p>So, here's what I did: first I implemented <code>MyRange</code> class and then <code>my range</code>. After that, I did two tests.</p>
<p><strong>Question:</strong> It works, but I'd like to be sure from you if I solved correctly the question, I mean, if this is what I was supposed to do :-) As I said, I've just seen what is an iterator.</p>
<pre><code>class MyRange():
def __init__(self,data):
self.data = data
self.check()
self.index = -1
def check(self):
assert len(self.data)>0, "Not enough data"
def __iter__(self):
return self
def __next__(self):
if self.index == len(self.data)-1:
raise StopIteration
self.index= self.index+1
return self.data[self.index]
def my_range(*args):
return MyRange((args))
print("Tests using MyRange class \n")
for i in MyRange((1,2,3,4)):
print(i)
print("Tests with range for loop \n")
for i in my_range(1,2,3,4,5,"Hello"):
print(i)
r = MyRange((1,2,3,4,"Last Value"))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
print(next(r))
</code></pre>
<p>I'll show here the output, which seems the correct one:</p>
<pre><code>1
2
3
4
Tests with range for loop
1
2
3
4
5
Hello
1
2
3
4
Last Value
Traceback (most recent call last):
File "Untitled3.py", line 45, in <module>
print(next(r)) #<-- Raises StopIteration
File "Untitled3.py", line 16, in __next__
raise StopIteration
StopIteration
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T17:25:04.010",
"Id": "513042",
"Score": "3",
"body": "If `myrange()` is supposed to act like `range()`, shouldn't it take similar arguments: `start`, `stop`, and `step`? It doesn't seem like your implementation is following the instructions, but you obviously have more context than I do. A range is a device to generate integers (integers often used to index into a data collection), but you have implemented `myrange()` to take the data collection itself as an argument. Perhaps you can edit your question to clarify."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T18:37:33.997",
"Id": "513047",
"Score": "0",
"body": "@FMc Unfortunately the text of the assignment was the short one I wrote at the beginning of my post. So far what we know is only that we need to use `__next__` in our class. I think I can fix this point. For the moment, assuming that the class `MyRange` is correct, do you think that `my_range` is implemented correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T19:36:38.603",
"Id": "513053",
"Score": "0",
"body": "The assignment seems to be asking to implement `range` two different ways (1) as a function (e.g. using `yield` in a loop), and (2) as a class (e.g. having `__iter__` and `__next__` methods)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T19:36:42.403",
"Id": "513054",
"Score": "0",
"body": "No, based on my reading of the assignment, I think both `MyRange` and `my_range()` are incorrect. You have successfully implemented an iterable object (`MyRange`), but it is **not** an iterable object that behaves at all like `range()`."
}
] |
[
{
"body": "<h1>You have an iterator</h1>\n<p>Your code implements an iterator, you are right. You have defined a <code>__next__</code> method and it works well.</p>\n<p>I would tweak your code slightly, though:</p>\n<ul>\n<li>remove the <code>check</code> because iterators can be empty and that is okay;</li>\n<li>fix minor spacing issues around operators, etc;</li>\n<li>use augmented assignment to increment;</li>\n<li>change order of statements in <code>__next__</code> to be more idiomatic.</li>\n</ul>\n<p>All in all, <code>MyRange</code> would end up looking like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>class MyRange():\n def __init__(self,data):\n self.data = data\n self.index = -1\n \n def __iter__(self):\n return self\n \n def __next__(self):\n self.index += 1\n if self.index == len(self.data):\n raise StopIteration\n return self.data[self.index]\n</code></pre>\n<p>In particular, the changes to <code>__next__</code> are because you start by setting <code>self.index</code> to the value of the index <em>you would like to read</em>. Then, just before reading the value from <code>data</code>, you ensure you can actually use that index and raise <code>StopIteration</code> if you can't.</p>\n<h1><code>range</code> is not any iterator</h1>\n<p>However, the "problem statement" says to implement an iterator <em>that behaves like <code>range</code></em>, and as brought to your attention in the comments, <code>range</code> is a very specific iterator that can take up to 3 arguments: <code>start</code>, <code>stop</code>, and <code>step</code>.</p>\n<p>Take a look at the docs for the range function <a href=\"https://docs.python.org/3/library/functions.html#func-range\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>Having said that, solving this "issue" does not need to be very difficult.\nYou could do something as simple as having <code>my_range</code> take the three arguments,\ngenerate the <code>data</code> you need, and then feed it into <code>MyRange</code> to iterate, but that seems like a waste.</p>\n<p>What <em>I think</em> is more or less the intended approach, is to define <code>MyRange</code> to expect the <code>start</code>, <code>stop</code>, and <code>step</code> values, and the <code>my_range</code> function is what the user calls, which then fills in the <code>start</code>, <code>stop</code>, and <code>step</code> values that are used by default and calls <code>MyRange</code>.</p>\n<p>E.g.,</p>\n<ul>\n<li><code>my_range(10)</code> would call <code>MyRange(0, 10, 1)</code>;</li>\n<li><code>my_range(4, 12)</code> would call <code>MyRange(4, 12, 1)</code>;</li>\n<li><code>my_range(0, 13, -3)</code> would call <code>MyRange(0, 13, -3)</code>.</li>\n</ul>\n<p>(In the examples above, I assumed you changed <code>MyRange</code> to do what I described.)</p>\n<p>Therefore, just for the sake of clarity: what would be happening is that the <code>__next__</code> method would use the three arguments <code>start</code>, <code>stop</code>, and <code>step</code> (and possibly other auxiliary variables you create) to <em>compute</em> the successive values, instead of generating all of them at once and then returning one by one.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T06:35:31.073",
"Id": "513087",
"Score": "0",
"body": "Thanks for your answer, I got the point! So the signature of `my_range` should be `my_range(start, stop,step)` too, right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T06:37:03.880",
"Id": "513088",
"Score": "0",
"body": "@bobinthebox yes, that is _my interpretation_ of the problem statement :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T06:37:53.003",
"Id": "513089",
"Score": "0",
"body": "Thanks, I'll try to fix this :-) @RGS"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T06:39:46.717",
"Id": "513090",
"Score": "0",
"body": "@bobinthebox good luck! But sorry, just to be clear, probably your `my_range` function also has to work with a single argument, `my_range(stop)` and two arguments, `my_range(start, stop)`, just like `range` does, yeah?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:34:42.917",
"Id": "513107",
"Score": "0",
"body": "I agree, I should use default arguments to achieve this behaviour, right? @RGS"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T08:31:50.973",
"Id": "513112",
"Score": "0",
"body": "Yes @bobinthebox , default arguments are probably the way to go here. Just be careful with what values you choose as the default arguments ;)"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T19:15:51.563",
"Id": "259993",
"ParentId": "259987",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "259993",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T16:07:05.100",
"Id": "259987",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"iterator",
"interval"
],
"Title": "Implement a range behaviour in Python using iterators"
}
|
259987
|
<p>This is a follow-up question for <a href="https://codereview.stackexchange.com/q/259780/231235">GetNeighborhood function for 3D cells structure in MATLAB</a>. Based on the existing <a href="https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.374.7899&rep=rep1&type=pdf" rel="nofollow noreferrer">2D non-local algorithm</a>, I am attempting to implement 3D non-local mean algorithm in MATLAB and <code>GetNeighborhood</code> function is used here for extracting sub-region of 3D cells.</p>
<p><strong>The experimental implementation</strong></p>
<p>The experimental implementation of <code>NonLocalMean3D</code>(main function), <code>NonLocalMeanWeight</code>, <code>NonLocalMeanSimilarity</code> and <code>GetNeighborhood</code> functions are as below.</p>
<ul>
<li><code>NonLocalMean3D</code> function:</li>
</ul>
<pre><code>function [outputCells] = NonLocalMean3D(Sigma, inputCells)
% NonLocalMean implementation
IntermediateFilename = "NonLocalMean.mat";
if isfile(IntermediateFilename)
load(IntermediateFilename);
X = X + 1;
while X < size(inputCells, 1)
for Y = 1:size(inputCells, 2)
for Z = 1:size(inputCells, 3)
%TargetCube = inputCells{X, Y, Z};
SingleOutput = {zeros([size(inputCells{X, Y, Z}, 1) size(inputCells{X, Y, Z}, 2) size(inputCells{X, Y, Z}, 3)])};
SumOfWeight = 0.0;
for x = 1:size(inputCells, 1)
for y = 1:size(inputCells, 2)
for z = 1:size(inputCells, 3)
weight = NonLocalMeanWeight(Sigma, inputCells, ...
[X Y Z], ...
[x y z]);
SingleOutput = {cell2mat(SingleOutput) + cell2mat(inputCells{x, y, z}) .* weight};
SumOfWeight = SumOfWeight + weight;
end
end
end
SingleOutput = {cell2mat(SingleOutput) ./ SumOfWeight};
outputCells{X, Y, Z} = SingleOutput;
fprintf('3D non-local mean: The %d_%d_%d / %d_%d_%d block calculation has done. \n' , X, Y, Z, size(inputCells, 1), size(inputCells, 2), size(inputCells, 3));
end
end
save("NonLocalMean.mat", '-v7.3');
X = X + 1;
end
return;
else
outputCells = inputCells;
for X = 1:size(inputCells, 1)
for Y = 1:size(inputCells, 2)
for Z = 1:size(inputCells, 3)
%TargetCube = inputCells{X, Y, Z};
SingleOutput = {zeros([size(inputCells{X, Y, Z}, 1) size(inputCells{X, Y, Z}, 2) size(inputCells{X, Y, Z}, 3)])};
SumOfWeight = 0.0;
for x = 1:size(inputCells, 1)
for y = 1:size(inputCells, 2)
for z = 1:size(inputCells, 3)
weight = NonLocalMeanWeight(Sigma, inputCells, ...
[X Y Z], ...
[x y z]);
SingleOutput = {cell2mat(SingleOutput) + cell2mat(inputCells{x, y, z}) .* weight};
SumOfWeight = SumOfWeight + weight;
end
end
end
SingleOutput = {cell2mat(SingleOutput) ./ SumOfWeight};
outputCells{X, Y, Z} = SingleOutput;
fprintf('3D non-local mean: The %d_%d_%d / %d_%d_%d block calculation has done. \n' , X, Y, Z, size(inputCells, 1), size(inputCells, 2), size(inputCells, 3));
end
end
save("NonLocalMean.mat", '-v7.3');
end
return;
end
end
</code></pre>
<ul>
<li><code>NonLocalMeanWeight</code> function:</li>
</ul>
<pre><code>function [outputDistance] = NonLocalMeanWeight(Sigma, inputCells, location1, location2)
%NonLocalMeanDistance function
% Calculate 3D data weight for non-local mean algorithm
SigmaForGaussian = Sigma;
MeanForGaussian = 0;
NeighborhoodDist = 1;
NormalDistance = NonLocalMeanSimilarity(inputCells, location1, location2, NeighborhoodDist);
outputDistance = gaussmf(NormalDistance, [SigmaForGaussian MeanForGaussian]);
end
</code></pre>
<ul>
<li><code>NonLocalMeanSimilarity</code> function:</li>
</ul>
<pre><code>function [output] = NonLocalMeanSimilarity(inputCells, location1, location2, sizeInput)
% NonLocalMeanSimilarity Calculate the similarity between two
% locations for non-local mean algorithm
output = 0.0;
block1 = GetNeighborhood(inputCells, sizeInput, location1);
block2 = GetNeighborhood(inputCells, sizeInput, location2);
for x = 1:size(block1, 1)
for y = 1:size(block1, 2)
for z = 1:size(block1, 3)
if (x == sizeInput + 1) && (y == sizeInput + 1) && (z == sizeInput + 1) % Central location
continue;
end
object1 = block1(x, y, z);
object2 = block2(x, y, z);
if iscell(object1{1})
matBlock1 = cell2mat(object1{1});
else
matBlock1 = object1{1};
end
if iscell(block2{1})
matBlock2 = cell2mat(object2{1});
else
matBlock2 = object2{1};
end
output = output + sum(abs(matBlock1 - matBlock2), 'all');
end
end
end
end
</code></pre>
<ul>
<li><code>GetNeighborhood</code> function:</li>
</ul>
<pre><code>function [output] = GetNeighborhood(inputCells, sizeInput, centralLocation)
% Get neighborhood of fixed size and centered at centralLocation
output = cell( sizeInput ,sizeInput ,sizeInput );
X = centralLocation(1);
Y = centralLocation(2);
Z = centralLocation(3);
for x = -sizeInput:sizeInput
for y = -sizeInput:sizeInput
for z = -sizeInput:sizeInput
xLocation = min(max(X + x, 1), size(inputCells, 1));
yLocation = min(max(Y + y, 1), size(inputCells, 2));
zLocation = min(max(Z + z, 1), size(inputCells, 3));
output{sizeInput + x + 1, sizeInput + y + 1, sizeInput + z + 1} = ...
inputCells{xLocation, yLocation, zLocation};
end
end
end
end
</code></pre>
<p><strong>Test cases</strong></p>
<p>For testing purpose, a simple test for three-dimensional non-local mean algorithm script is created as below.</p>
<pre><code>%% Create test cells
testCellsSize = 10;
test = cell(testCellsSize, testCellsSize, testCellsSize);
for x = 1:size(test, 1)
for y = 1:size(test, 2)
for z = 1:size(test, 3)
test{x, y, z} = {[x * 100 + y * 10 + z]};
end
end
end
%% Specify test parameters
Sigma = 20;
%% Perform test
result = NonLocalMean3D(Sigma, test);
%% Print output
for z = 1:size(result, 3)
fprintf('3D non-local mean result: %d plane\n' , z);
for x = 1:size(result, 1)
for y = 1:size(result, 2)
fprintf('%f\t' , result{x, y, z}{1});
end
fprintf('\n');
end
fprintf('\n');
end
</code></pre>
<p>Note: Each element in the three-dimensional data structure <code>test</code> in the test script above is a single number, it can be a vector / multidimensional data in different scenarios.</p>
<p>The output of the above testing code:</p>
<pre><code>3D non-local mean: The 1_1_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_1_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_2_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_3_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_4_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_5_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_6_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_7_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_8_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_9_10 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_1 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_2 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_3 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_4 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_5 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_6 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_7 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_8 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_9 / 10_10_10 block calculation has done.
3D non-local mean: The 1_10_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_1_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_2_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_3_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_4_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_5_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_6_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_7_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_8_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_9_10 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_1 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_2 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_3 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_4 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_5 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_6 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_7 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_8 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_9 / 10_10_10 block calculation has done.
3D non-local mean: The 2_10_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_1_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_2_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_3_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_4_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_5_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_6_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_7_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_8_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_9_10 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_1 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_2 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_3 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_4 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_5 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_6 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_7 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_8 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_9 / 10_10_10 block calculation has done.
3D non-local mean: The 3_10_10 / 10_10_10 block calculation has done.
...
3D non-local mean result: 1 plane
111.502034 121.502033 131.418892 141.418892 151.418892 161.418892 171.418892 181.418892 191.418892 201.502033
211.502034 221.502033 231.418892 241.418892 251.418892 261.418892 271.418892 281.418892 291.418892 301.502033
311.502034 321.502033 331.418892 341.418892 351.418892 361.418892 371.418892 381.418892 391.418892 401.502033
411.502034 421.502033 431.418892 441.418892 451.418892 461.418892 471.418892 481.418892 491.418892 501.502033
511.502034 521.502033 531.418892 541.418892 551.418892 561.418892 571.418892 581.418892 591.418892 601.502033
611.502034 621.502033 631.418892 641.418892 651.418892 661.418892 671.418892 681.418892 691.418892 701.502033
711.502034 721.502033 731.418892 741.418892 751.418892 761.418892 771.418892 781.418892 791.418892 801.502033
811.502034 821.502033 831.418892 841.418892 851.418892 861.418892 871.418892 881.418892 891.418892 901.502033
911.502034 921.502033 931.418892 941.418892 951.418892 961.418892 971.418892 981.418892 991.418892 1001.502033
1011.502034 1021.502033 1031.418892 1041.418892 1051.418892 1061.418892 1071.418892 1081.418892 1091.418892 1101.502033
3D non-local mean result: 2 plane
111.908532 121.908532 131.899467 141.899467 151.899467 161.899467 171.899467 181.899467 191.899467 201.908532
211.908532 221.908532 231.899467 241.899467 251.899467 261.899467 271.899467 281.899467 291.899467 301.908532
311.908532 321.908532 331.899467 341.899467 351.899467 361.899467 371.899467 381.899467 391.899467 401.908532
411.908532 421.908532 431.899467 441.899467 451.899467 461.899467 471.899467 481.899467 491.899467 501.908532
511.908532 521.908532 531.899467 541.899467 551.899467 561.899467 571.899467 581.899467 591.899467 601.908532
611.908532 621.908532 631.899467 641.899467 651.899467 661.899467 671.899467 681.899467 691.899467 701.908532
711.908532 721.908532 731.899467 741.899467 751.899467 761.899467 771.899467 781.899467 791.899467 801.908532
811.908532 821.908532 831.899467 841.899467 851.899467 861.899467 871.899467 881.899467 891.899467 901.908532
911.908532 921.908532 931.899467 941.899467 951.899467 961.899467 971.899467 981.899467 991.899467 1001.908532
1011.908532 1021.908532 1031.899467 1041.899467 1051.899467 1061.899467 1071.899467 1081.899467 1091.899467 1101.908532
3D non-local mean result: 3 plane
112.935427 122.935427 132.935310 142.935310 152.935310 162.935310 172.935310 182.935310 192.935310 202.935427
212.935427 222.935427 232.935310 242.935310 252.935310 262.935310 272.935310 282.935310 292.935310 302.935427
312.935427 322.935427 332.935310 342.935310 352.935310 362.935310 372.935310 382.935310 392.935310 402.935427
412.935427 422.935427 432.935310 442.935310 452.935310 462.935310 472.935310 482.935310 492.935310 502.935427
512.935427 522.935427 532.935310 542.935310 552.935310 562.935310 572.935310 582.935310 592.935310 602.935427
612.935427 622.935427 632.935310 642.935310 652.935310 662.935310 672.935310 682.935310 692.935310 702.935427
712.935427 722.935427 732.935310 742.935310 752.935310 762.935310 772.935310 782.935310 792.935310 802.935427
812.935427 822.935427 832.935310 842.935310 852.935310 862.935310 872.935310 882.935310 892.935310 902.935427
912.935427 922.935427 932.935310 942.935310 952.935310 962.935310 972.935310 982.935310 992.935310 1002.935427
1012.935427 1022.935427 1032.935310 1042.935310 1052.935310 1062.935310 1072.935310 1082.935310 1092.935310 1102.935427
3D non-local mean result: 4 plane
113.996732 123.996732 133.996732 143.996732 153.996732 163.996732 173.996732 183.996732 193.996732 203.996732
213.996732 223.996732 233.996732 243.996732 253.996732 263.996732 273.996732 283.996732 293.996732 303.996732
313.996732 323.996732 333.996732 343.996732 353.996732 363.996732 373.996732 383.996732 393.996732 403.996732
413.996732 423.996732 433.996732 443.996732 453.996732 463.996732 473.996732 483.996732 493.996732 503.996732
513.996732 523.996732 533.996732 543.996732 553.996732 563.996732 573.996732 583.996732 593.996732 603.996732
613.996732 623.996732 633.996732 643.996732 653.996732 663.996732 673.996732 683.996732 693.996732 703.996732
713.996732 723.996732 733.996732 743.996732 753.996732 763.996732 773.996732 783.996732 793.996732 803.996732
813.996732 823.996732 833.996732 843.996732 853.996732 863.996732 873.996732 883.996732 893.996732 903.996732
913.996732 923.996732 933.996732 943.996732 953.996732 963.996732 973.996732 983.996732 993.996732 1003.996732
1013.996732 1023.996732 1033.996732 1043.996732 1053.996732 1063.996732 1073.996732 1083.996732 1093.996732 1103.996732
3D non-local mean result: 5 plane
114.999977 124.999977 134.999977 144.999977 154.999977 164.999977 174.999977 184.999977 194.999977 204.999977
214.999977 224.999977 234.999977 244.999977 254.999977 264.999977 274.999977 284.999977 294.999977 304.999977
314.999977 324.999977 334.999977 344.999977 354.999977 364.999977 374.999977 384.999977 394.999977 404.999977
414.999977 424.999977 434.999977 444.999977 454.999977 464.999977 474.999977 484.999977 494.999977 504.999977
514.999977 524.999977 534.999977 544.999977 554.999977 564.999977 574.999977 584.999977 594.999977 604.999977
614.999977 624.999977 634.999977 644.999977 654.999977 664.999977 674.999977 684.999977 694.999977 704.999977
714.999977 724.999977 734.999977 744.999977 754.999977 764.999977 774.999977 784.999977 794.999977 804.999977
814.999977 824.999977 834.999977 844.999977 854.999977 864.999977 874.999977 884.999977 894.999977 904.999977
914.999977 924.999977 934.999977 944.999977 954.999977 964.999977 974.999977 984.999977 994.999977 1004.999977
1014.999977 1024.999977 1034.999977 1044.999977 1054.999977 1064.999977 1074.999977 1084.999977 1094.999977 1104.999977
3D non-local mean result: 6 plane
116.000023 126.000023 136.000023 146.000023 156.000023 166.000023 176.000023 186.000023 196.000023 206.000023
216.000023 226.000023 236.000023 246.000023 256.000023 266.000023 276.000023 286.000023 296.000023 306.000023
316.000023 326.000023 336.000023 346.000023 356.000023 366.000023 376.000023 386.000023 396.000023 406.000023
416.000023 426.000023 436.000023 446.000023 456.000023 466.000023 476.000023 486.000023 496.000023 506.000023
516.000023 526.000023 536.000023 546.000023 556.000023 566.000023 576.000023 586.000023 596.000023 606.000023
616.000023 626.000023 636.000023 646.000023 656.000023 666.000023 676.000023 686.000023 696.000023 706.000023
716.000023 726.000023 736.000023 746.000023 756.000023 766.000023 776.000023 786.000023 796.000023 806.000023
816.000023 826.000023 836.000023 846.000023 856.000023 866.000023 876.000023 886.000023 896.000023 906.000023
916.000023 926.000023 936.000023 946.000023 956.000023 966.000023 976.000023 986.000023 996.000023 1006.000023
1016.000023 1026.000023 1036.000023 1046.000023 1056.000023 1066.000023 1076.000023 1086.000023 1096.000023 1106.000023
3D non-local mean result: 7 plane
117.003268 127.003268 137.003268 147.003268 157.003268 167.003268 177.003268 187.003268 197.003268 207.003268
217.003268 227.003268 237.003268 247.003268 257.003268 267.003268 277.003268 287.003268 297.003268 307.003268
317.003268 327.003268 337.003268 347.003268 357.003268 367.003268 377.003268 387.003268 397.003268 407.003268
417.003268 427.003268 437.003268 447.003268 457.003268 467.003268 477.003268 487.003268 497.003268 507.003268
517.003268 527.003268 537.003268 547.003268 557.003268 567.003268 577.003268 587.003268 597.003268 607.003268
617.003268 627.003268 637.003268 647.003268 657.003268 667.003268 677.003268 687.003268 697.003268 707.003268
717.003268 727.003268 737.003268 747.003268 757.003268 767.003268 777.003268 787.003268 797.003268 807.003268
817.003268 827.003268 837.003268 847.003268 857.003268 867.003268 877.003268 887.003268 897.003268 907.003268
917.003268 927.003268 937.003268 947.003268 957.003268 967.003268 977.003268 987.003268 997.003268 1007.003268
1017.003268 1027.003268 1037.003268 1047.003268 1057.003268 1067.003268 1077.003268 1087.003268 1097.003268 1107.003268
3D non-local mean result: 8 plane
118.064573 128.064690 138.064690 148.064690 158.064690 168.064690 178.064690 188.064690 198.064573 208.064573
218.064573 228.064690 238.064690 248.064690 258.064690 268.064690 278.064690 288.064690 298.064573 308.064573
318.064573 328.064690 338.064690 348.064690 358.064690 368.064690 378.064690 388.064690 398.064573 408.064573
418.064573 428.064690 438.064690 448.064690 458.064690 468.064690 478.064690 488.064690 498.064573 508.064573
518.064573 528.064690 538.064690 548.064690 558.064690 568.064690 578.064690 588.064690 598.064573 608.064573
618.064573 628.064690 638.064690 648.064690 658.064690 668.064690 678.064690 688.064690 698.064573 708.064573
718.064573 728.064690 738.064690 748.064690 758.064690 768.064690 778.064690 788.064690 798.064573 808.064573
818.064573 828.064690 838.064690 848.064690 858.064690 868.064690 878.064690 888.064690 898.064573 908.064573
918.064573 928.064690 938.064690 948.064690 958.064690 968.064690 978.064690 988.064690 998.064573 1008.064573
1018.064573 1028.064690 1038.064690 1048.064690 1058.064690 1068.064690 1078.064690 1088.064690 1098.064573 1108.064573
3D non-local mean result: 9 plane
119.091468 129.100533 139.100533 149.100533 159.100533 169.100533 179.100533 189.100533 199.091468 209.091468
219.091468 229.100533 239.100533 249.100533 259.100533 269.100533 279.100533 289.100533 299.091468 309.091468
319.091468 329.100533 339.100533 349.100533 359.100533 369.100533 379.100533 389.100533 399.091468 409.091468
419.091468 429.100533 439.100533 449.100533 459.100533 469.100533 479.100533 489.100533 499.091468 509.091468
519.091468 529.100533 539.100533 549.100533 559.100533 569.100533 579.100533 589.100533 599.091468 609.091468
619.091468 629.100533 639.100533 649.100533 659.100533 669.100533 679.100533 689.100533 699.091468 709.091468
719.091468 729.100533 739.100533 749.100533 759.100533 769.100533 779.100533 789.100533 799.091468 809.091468
819.091468 829.100533 839.100533 849.100533 859.100533 869.100533 879.100533 889.100533 899.091468 909.091468
919.091468 929.100533 939.100533 949.100533 959.100533 969.100533 979.100533 989.100533 999.091468 1009.091468
1019.091468 1029.100533 1039.100533 1049.100533 1059.100533 1069.100533 1079.100533 1089.100533 1099.091468 1109.091468
3D non-local mean result: 10 plane
119.497967 129.581108 139.581108 149.581108 159.581108 169.581108 179.581108 189.581108 199.497967 209.497966
219.497967 229.581108 239.581108 249.581108 259.581108 269.581108 279.581108 289.581108 299.497967 309.497966
319.497967 329.581108 339.581108 349.581108 359.581108 369.581108 379.581108 389.581108 399.497967 409.497966
419.497967 429.581108 439.581108 449.581108 459.581108 469.581108 479.581108 489.581108 499.497967 509.497966
519.497967 529.581108 539.581108 549.581108 559.581108 569.581108 579.581108 589.581108 599.497967 609.497966
619.497967 629.581108 639.581108 649.581108 659.581108 669.581108 679.581108 689.581108 699.497967 709.497966
719.497967 729.581108 739.581108 749.581108 759.581108 769.581108 779.581108 789.581108 799.497967 809.497966
819.497967 829.581108 839.581108 849.581108 859.581108 869.581108 879.581108 889.581108 899.497967 909.497966
919.497967 929.581108 939.581108 949.581108 959.581108 969.581108 979.581108 989.581108 999.497967 1009.497966
1019.497967 1029.581108 1039.581108 1049.581108 1059.581108 1069.581108 1079.581108 1089.581108 1099.497967 1109.497966
</code></pre>
<p>Another test case with three-dimensional elements:</p>
<pre><code>%% Create test cells
testCellsSize = 10;
testElementSize = 5;
test = cell(testCellsSize, testCellsSize, testCellsSize);
for x = 1:size(test, 1)
for y = 1:size(test, 2)
for z = 1:size(test, 3)
test{x, y, z} = {ones(testElementSize, testElementSize) .* (x * 100 + y * 10 + z)};
end
end
end
%% Specify test parameters
Sigma = 20;
%% Perform test
result = NonLocalMean3D(Sigma, test);
%% Print output
for z = 1:size(result, 3)
fprintf('3D non-local mean result: %d plane\n' , z);
for x = 1:size(result, 1)
for y = 1:size(result, 2)
fprintf('%f\t' , result{x, y, z}{1});
end
fprintf('\n');
end
fprintf('\n');
end
</code></pre>
<p><strong>Test Platform Information</strong></p>
<p>Matlab version: '9.10.0.1629609 (R2021a)'</p>
<p><strong>Reference</strong></p>
<ul>
<li>A. Buades, B. Coll and J. -. Morel, "A non-local algorithm for image denoising," 2005 IEEE Computer Society Conference on Computer Vision and Pattern Recognition (CVPR'05), 2005, pp. 60-65 vol. 2, doi: 10.1109/CVPR.2005.38.</li>
</ul>
<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/259780/231235">GetNeighborhood function for 3D cells structure in MATLAB</a></p>
</li>
<li><p>What changes has been made in the code since last question?</p>
<p><code>NonLocalMean3D</code>, <code>NonLocalMeanWeight</code>, <code>NonLocalMeanSimilarity</code> functions are implemented here.</p>
</li>
<li><p>Why a new review is being asked for?</p>
<p>The run-time performance of the testing code above is Total time: 619.584 s on a desktop with an AMD 3950x CPU (16C / 32T) and 64GB of 3600MHz RAM. Is it a good way to use <code>parfor</code> like the following version <code>NonLocalMeanSimilarity</code>?</p>
<pre><code>function [output] = NonLocalMeanSimilarity(inputCells, location1, location2, sizeInput)
% NonLocalMeanSimilarity Calculate the similarity between two
% locations for non-local mean algorithm
output = 0.0;
block1 = GetNeighborhood(inputCells, sizeInput, location1);
block2 = GetNeighborhood(inputCells, sizeInput, location2);
parfor x = 1:size(block1, 1)
for y = 1:size(block1, 2)
for z = 1:size(block1, 3)
if (x == sizeInput + 1) && (y == sizeInput + 1) && (z == sizeInput + 1) % Central location
continue;
end
object1 = block1(x, y, z);
object2 = block2(x, y, z);
if iscell(object1{1})
matBlock1 = cell2mat(object1{1});
else
matBlock1 = object1{1};
end
if iscell(block2{1})
matBlock2 = cell2mat(object2{1});
else
matBlock2 = object2{1};
end
output = output + sum(abs(matBlock1 - matBlock2), 'all');
end
end
end
end
</code></pre>
<p>On the other hand, is it good idea to save intermediate calculation result like the performed method above?</p>
<p>If there is any possible improvement, please let me know.</p>
</li>
</ul>
<p><strong>May 13, 2021 Update</strong></p>
<p>Another version <code>NonLocalMean3D</code> function with short period intermediate file updating.</p>
<pre><code>function [outputCells] = NonLocalMean3D(Sigma, inputCells)
% NonLocalMean implementation
IntermediateFilename = "NonLocalMean.mat";
if isfile(IntermediateFilename)
load(IntermediateFilename);
X = X + 1;
Y = Y + 1;
while X < size(inputCells, 1)
while Y < size(inputCells, 2)
for Z = 1:size(inputCells, 3)
%TargetCube = inputCells{X, Y, Z};
SingleOutput = {zeros([size(inputCells{X, Y, Z}, 1) size(inputCells{X, Y, Z}, 2) size(inputCells{X, Y, Z}, 3)])};
SumOfWeight = 0.0;
for x = 1:size(inputCells, 1)
for y = 1:size(inputCells, 2)
for z = 1:size(inputCells, 3)
weight = NonLocalMeanWeight(Sigma, inputCells, ...
[X Y Z], ...
[x y z]);
SingleOutput = {cell2mat(SingleOutput) + cell2mat(inputCells{x, y, z}) .* weight};
SumOfWeight = SumOfWeight + weight;
end
end
end
SingleOutput = {cell2mat(SingleOutput) ./ SumOfWeight};
outputCells{X, Y, Z} = SingleOutput;
fprintf('3D non-local mean: The %d_%d_%d / %d_%d_%d block calculation has done. \n' , X, Y, Z, size(inputCells, 1), size(inputCells, 2), size(inputCells, 3));
end
save("NonLocalMean.mat", '-v7.3');
Y = Y + 1;
end
Y = 1;
X = X + 1;
end
return;
else
outputCells = inputCells;
for X = 1:size(inputCells, 1)
for Y = 1:size(inputCells, 2)
for Z = 1:size(inputCells, 3)
%TargetCube = inputCells{X, Y, Z};
SingleOutput = {zeros([size(inputCells{X, Y, Z}, 1) size(inputCells{X, Y, Z}, 2) size(inputCells{X, Y, Z}, 3)])};
SumOfWeight = 0.0;
for x = 1:size(inputCells, 1)
for y = 1:size(inputCells, 2)
for z = 1:size(inputCells, 3)
weight = NonLocalMeanWeight(Sigma, inputCells, ...
[X Y Z], ...
[x y z]);
SingleOutput = {cell2mat(SingleOutput) + cell2mat(inputCells{x, y, z}) .* weight};
SumOfWeight = SumOfWeight + weight;
end
end
end
SingleOutput = {cell2mat(SingleOutput) ./ SumOfWeight};
outputCells{X, Y, Z} = SingleOutput;
fprintf('3D non-local mean: The %d_%d_%d / %d_%d_%d block calculation has done. \n' , X, Y, Z, size(inputCells, 1), size(inputCells, 2), size(inputCells, 3));
end
save("NonLocalMean.mat", '-v7.3');
end
end
return;
end
end
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T18:31:31.707",
"Id": "259992",
"Score": "1",
"Tags": [
"performance",
"algorithm",
"array",
"matrix",
"matlab"
],
"Title": "3D Non-local Mean Algorithm in MATLAB"
}
|
259992
|
<p>I would like to have a <em>minimal</em> storable class in Python that I can use as ORM. I quite thinking my approach is bad, but I would like to have your opinion.</p>
<p>I do not want to use SQLAlchemy or PeeWee as it is too complex for my application.</p>
<p>I wrote a <code>Model</code> class from which I can derivate storable items:</p>
<pre><code>from tinydb import TinyDB, Query
from typing import NamedTuple
class NotNull:
pass
class Column(NamedTuple):
name: str
type: type = str
default: any = NotNull
class Model():
__tablename__: str
__attrs__: [Column]
__primary_key__: str
__hidden__: [str]
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '__tablename__'):
cls.__tablename__ = cls.__name__.lower()
if not hasattr(cls, '__hidden__'):
cls.__hidden__ = []
return super().__new__(cls)
def __init__(self, *args, **kwargs):
# Fill attributes in order
for attr, arg in zip(self.__attrs__, args):
if attr.name in self.__hidden__:
continue
if not isinstance(arg, attr.type):
raise ValueError(f"{attr.name} has not type {str(attr.type)}")
setattr(self, attr.name, arg)
# Fill conditional attributes
for attr, value in kwargs.items():
u = [attrs for attrs in self.__attrs__ if attrs[0] == attr]
if not u:
continue
type = u[0].type
if not isinstance(value, type):
raise ValueError(f"{attr} isn't type {str(type)}")
setattr(self, attr, value)
# Fill remaining attributes with None
for attr in self.__attrs__:
if getattr(self, attr.name, None) is None:
if len(attr) == 2:
raise ValueError(f"{attr.name} has no default value")
self._post_init()
def _post_init(self, *args, **kwargs):
pass
@classmethod
def _db(cls):
table = getattr(cls, '__tablename__', cls.__name__.lower())
return TinyDB(data_dir(table + '.json'))
@classmethod
def all(cls):
"""Get all users from the database."""
return [cls(**user) for user in cls._db().all()]
def save(self):
"""Save a new user into the database."""
pk = self.__primary_key__
pk_value = getattr(self, pk)
if self.find(pk_value):
query = getattr(Query(), pk)
self._db().update(self.to_dict(), query == pk_value)
return
self._db().insert(self.to_dict())
@classmethod
def truncate(cls):
cls._db().truncate()
@classmethod
def find(cls, name):
"""Find a user into the database."""
user = Query()
results = cls._db().search(user.name == name)
return cls(**results[0]) if results else []
def __repr__(self):
data = ','.join([
'='.join([attr[0], str(getattr(self, attr[0]))])
for attr in self.__attrs__ if attr[0] not in self.__hidden__
])
return f'{self.__class__.__name__}({data})'
def to_dict(self):
return {attr[0]: getattr(self, attr[0]) for attr in self.__attrs__}
def to_json(self):
return to_json(self.to_dict())
</code></pre>
<p>For example if I want to store articles:</p>
<pre><code>class Article(Model):
__attrs__ = [
('name', str),
('type', str, 'sausage'),
('price', float, 0.0)
]
__primary_key__ = 'name'
</code></pre>
<p>Then I can use it as follow:</p>
<pre><code>>>> Article('apple'^, 'vegetable', 1.12).save()
>>> Article.all()
[Article(name=apple,type=vegetable,price=1.12)]
</code></pre>
<p>Would it be better to use <code>shelve</code>?</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T03:30:45.033",
"Id": "513081",
"Score": "1",
"body": "A truly tiny persistent class is just a normal class serialised via pickle. Why not just do that?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T03:53:05.450",
"Id": "513403",
"Score": "0",
"body": "Seems like `Article` could be a `dataclass`. `dataclasses provide a way to specify fields, types, and values and `__init__()`, `__repr__()`, and `asdict()` methods. So `Model` just needs to provide the database methods."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T20:21:52.847",
"Id": "259995",
"Score": "1",
"Tags": [
"python",
"database"
],
"Title": "Tiny persistent storable class"
}
|
259995
|
<p>This small programme is an exercise that my teacher gave us.</p>
<p><code>n</code> is an alphabetic input that its length must be between 5 and 10. You have to insert the characters of the input one by one to a list called <code>T</code>. Then, add the reverse case of letters to another list called <code>V</code>. So if there is a capital letter in <code>T</code> it would be lower in list <code>V</code> and you have to only print <code>V</code> at the end.</p>
<p>This is my code, is there any better solution or cleaner one perhaps?</p>
<pre><code>T = []
V = []
n = input("Enter a character")
while len(n) not in range(5, 11) or n.isalpha() == False:
n = input("Enter a characters between 5 and 11, and only characters ")
print(n)
for i in range(len(n)):
T.append(n[i])
for i in range(len(T)):
if T[i].isupper():
V.append(T[i].lower())
else:
V.append(T[i].upper())
print(V)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T21:54:09.800",
"Id": "513060",
"Score": "0",
"body": "Welcome to Code Review! The current question title is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T22:20:23.943",
"Id": "513062",
"Score": "2",
"body": "Your \"*N is a alphabetic input that is between 5 and 10*\" does not really make sense. Are you sure you copied your task correctly?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:02:32.217",
"Id": "513065",
"Score": "0",
"body": "N is basically a string input that have 5 characters atleast and doesn't go beyond 10 characters, it should not be numbers or symbols."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:02:47.703",
"Id": "513066",
"Score": "0",
"body": "There is no `N` in your code snippet, and it is unclear what \"between 5 and 10\" means."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:04:02.630",
"Id": "513067",
"Score": "0",
"body": "i'm sorry if i couldn't explain more clearly, im not a native english speaker."
}
] |
[
{
"body": "<p>A flexible approach to getting user input is to use a while-true loop, breaking\nwhen conditions are met. The structure is easy to remember and allows you to\nhandle user mistakes without awkward setup or code repetition:</p>\n<pre><code>while True:\n x = input('...')\n if x is OK:\n break\n</code></pre>\n<p>I realize the variable names are coming from your teacher's instructions, but\nboth of you should strive for better variable names. Better does not always\nmean longer (brevity and clarity are both worthy goals and they are at odds\nsometimes); but it does mean using variable names that are <em>meaningful\nin context</em>. For example, <code>letters</code> is a better name for a string of letters\nthan <code>n</code>, which is a purely abstract name (even worse, it adds confusion\nbecause <code>n</code> is often/conventionally used for numeric values).</p>\n<p>There is no need to build <code>T</code> character by character. Python strings are\niterable and therefore directly convertible to lists.</p>\n<p>Python strings, lists, and tuples are directly iterable: just iterate over the\nvalues and don't bother with the soul-crushing tedium imposed by many less-cool\nprogramming languages where you must iterate over indexes. And for cases when\nyou need both values and indexes, use <code>enumerate()</code>.</p>\n<p>Use simple comments as sign-posts and organizational devices to make\nyour code more readable. This habit will serve you well as you try\nto write bigger, more complex programs.</p>\n<pre><code># Get user input.\nwhile True:\n prompt = 'Enter 5 to 10 letters, without spaces or punctuation: '\n letters = input(prompt)\n if len(letters) in range(5, 11) and letters.isalpha():\n break\n\n# List of the original letters.\nT = list(letters)\n\n# List of letters with case flipped.\nV = []\nfor c in letters:\n c2 = c.lower() if c.isupper() else c.upper()\n V.append(c2)\n\n# Same thing, in one shot.\nV = [\n c.lower() if c.isupper() else c.upper()\n for c in letters\n]\n\n# Check.\nprint(T) \nprint(V) \n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:00:01.080",
"Id": "513064",
"Score": "0",
"body": "Writing comments really came in handy, I am working on this keylogger, i end up giving up because its a 110 line and its literally a mess. I truly appreciate your help, you deserve to be a teacher."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T22:55:28.447",
"Id": "259999",
"ParentId": "259996",
"Score": "5"
}
},
{
"body": "<p>The first answer already gave great advice, but here are some additional suggestions.</p>\n<p>First I suggest you use more functions. That makes your code more organised and allows you to reuse code later. It also provides an overview to what each piece of code does. I would create a function for getting the user input, one for swapping cases and one for printing the output.</p>\n<p>Separate the user input from what your code does. Also, separate this from the output. This will create a nice structure of your code.</p>\n<p>Don't reinvent the wheel. Python has a built-in <a href=\"https://www.programiz.com/python-programming/methods/string/swapcase\" rel=\"nofollow noreferrer\">function</a> for swapping cases which is aptly named:<code>string.swapcase()</code>. If you are not allowed by your teacher to use the built-in function, then forget this point.</p>\n<p>Wrap your code in a <code>main()</code> method. This will allow you to import your module somewhere else and use the functions you have defined. Then add the following to run main:</p>\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n<p>Putting this all together:</p>\n<pre><code>def ask_for_string() -> str:\n """ask the user for a string containing 5 to 10 characters"""\n while True:\n my_str = input("Enter a string of length 5 to 10, consisting of only characters: ")\n if my_str.isalpha() and 4 < len(my_str) < 11:\n return my_str\n\ndef print_output(T:list, V: list):\n """print user input and list of swapcased characters """\n print("List of characters you entered:", T)\n print("your list of swapped characters is:", V)\n\ndef main():\n user_input = ask_for_string()\n T = list(user_input)\n V = list(user_input.swapcase())\n print_output(T, V)\n \nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T17:34:00.807",
"Id": "513172",
"Score": "0",
"body": "I truly appreciate everyone, i'm so dedicated to this. Thanks for your help again !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:22:57.423",
"Id": "260015",
"ParentId": "259996",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "259999",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T21:45:24.660",
"Id": "259996",
"Score": "3",
"Tags": [
"python"
],
"Title": "Get 5 to 10 characters and flip their case"
}
|
259996
|
<h2>Background</h2>
<p>I am writing a custom library whose keywords can be used with Robot Framework to verify configuration files, check running processes, and eventually other things tailored to a project I work on. The Robot tests would eventually be included as part of a Jenkins job.</p>
<p>I'm not used to writing Python or using OOP and I would love any feedback at all. Here are some specific things I'm worried about:</p>
<ul>
<li>The organization and correctness of my functions and classes.</li>
<li>Is anything obviously missing or bad or confusing?</li>
<li>Am I properly cleaning up any created paramiko ssh connections?</li>
<li>Am I doing things in a "pythonic" way?</li>
</ul>
<p>In advanced, I greatly appreciated your time. Thanks.</p>
<h3>Directory layout</h3>
<p>Note, I did not include the unit tests.</p>
<pre><code>.
├── Intrepid.py
├── SSHClient.py
└── tests
├── main.py
├── test_Intrepid.py
└── test_SSHClient.py
</code></pre>
<h3>An example main.py</h3>
<p>Here is an example of using the <code>create_new_session()</code> function in the Python code.</p>
<pre><code>import os, sys
sys.path.append(os.path.dirname(os.path.dirname(
os.path.abspath(__file__))))
from Intrepid import Intrepid
server ='localhost'
# Set to a valid local user on your machine.
username ='validusername'
password ='validpassword'
running_process ='sys-kernel-debug.mount'
intrepid = Intrepid(server, username, password)
intrepid.create_new_session(server, username, password)
intrepid.is_process_running(running_process)
intrepid.close_session()
</code></pre>
<h3>Robot Framework example</h3>
<p>Using the above python function in Robot would look like:</p>
<pre><code>Create new session ${HOST} ${USER} ${PASSWORD}
Check service on host ${HOST} ${service}
Close session
</code></pre>
<h2>The Code</h2>
<h3>The Intrepid Class</h3>
<p>This class is where custom keywords could be defined which could be called from the Robot Framework.</p>
<pre><code>import subprocess
import logging
import xml.etree.ElementTree as ET
from SSHClient import SSHClient
LOGGING_LEVEL = logging.INFO
class Intrepid:
def __init__(self, server = 'localhost', username = 'defaultuser', password = 'defaultpassword'):
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
level=LOGGING_LEVEL)
self.log = logging.getLogger(__name__)
self.ssh_client = None
self.create_new_session(server, username, password)
# Downloaded files will go here
self.working_directory = '/tmp'
self.downloaded_files = []
def create_new_session(self, server, username, password):
"""
Robot users call this function to begin an SSH session.
"""
self.log.info('Creating new ssh session')
self.ssh_client = SSHClient(server, username, password)
def is_process_running(self, process_name):
"""
Check if a process is running on a remote system.
Use from Robot like so:
Is process running | ing-flowgen
"""
cmd = 'systemctl status' + ' ' + str(process_name)
if self.ssh_client.run_remote_command(cmd) == 0:
self.log.info('Found process %s', process_name)
return True
# The Robot framework uses exceptions to
# figure out whether a keyword test passed.
error_string = "Process " + process_name + " is not running."
self.log.info(error_string)
raise ServiceNotRunning(error_string)
def xml_file_contains(self, xml_file, expected_text, xpath):
"""
Search for text in an XML file. Raise an exception
if it doesn't exist.
Use from Robot like so:
XML file contains | Full path to XML file | Expected text | XPath to xml element
"""
xml_file = self.ssh_client.download_file(xml_file, self.working_directory)
tree = ET.parse(xml_file)
root = tree.getroot()
value = root.find(xpath)
if value is None:
message = "Could not find: " + xpath
self.log.info(message)
raise XMLElementNotFound(message)
elif value.text != str(expected_text):
message = "Expected value " + expected_text + " does not match actual value " + value.text
self.log.info(message)
raise XMLElementDoesNotMatch(message)
print("Values match")
return True
def close_session(self):
"""
Robot users must choose when to close the connection.
"""
self.ssh_client.close()
self.log.info('Closing ssh session')
class ServiceNotRunning(Exception):
pass
"""
If Robot catches an exception it reports
that the test has failed.
"""
class XMLElementNotFound(Exception):
pass
class XMLElementDoesNotMatch(Exception):
pass
</code></pre>
<h3>The SSHClient Class</h3>
<pre><code>import paramiko
from paramiko.ssh_exception import BadHostKeyException, AuthenticationException, SSHException
import socket
from time import sleep
from sys import exit
import os
import logging
LOGGING_LEVEL = logging.WARNING
class SSHClient:
def __init__(self, server, username, password,
print_stdout=None, retries=None,
interval=None, timeout=None):
logging.basicConfig(format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
level=LOGGING_LEVEL)
self.log = logging.getLogger(__name__)
self.username = username
self.password = password
self.server = server
self.print_stdout = print_stdout if print_stdout is not None else True
self.retries = retries if retries is not None else 3
# interval and timeout are in seconds.
self.interval = interval if interval is not None else 2
self.timeout = timeout if timeout is not None else 5
try:
self.ssh_client = self._get_ssh_client(server, username, password)
except:
raise ConnectionError('Could not establish an SSH connection. Exiting')
def __enter__(self):
return self
def _get_ssh_client(self, server, username, password):
ssh_client = paramiko.SSHClient()
# No need to enforce host key checking. Testing is done on
# a private network.
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.load_system_host_keys()
for attempt in range(self.retries):
try:
ssh_client.connect(server, username=username,
password=password, timeout=self.timeout)
self.log.info('Successfully started ssh_client')
return ssh_client
except (BadHostKeyException, AuthenticationException,
SSHException, socket.error) as e:
error_message = "Failed to connect on attempt " + str(attempt) + " " + str(e)
self.log.warning(error_message)
sleep(self.interval)
# Could not successfully create an ssh session
ssh_client.close()
raise Exception('Failed to establish ssh connection')
def download_file(self, remote_file, local_path):
filename = os.path.basename(remote_file)
local_file = os.path.join(local_path, filename)
sftp = self.ssh_client.open_sftp()
self.log.info('Downloading remote file: %s from server %s to %s',
filename, self.server, local_file)
try:
sftp.get(remote_file, local_file)
self.log.info('Successfully saved file %s', local_file)
return local_file
except Exception as e:
raise Exception('Failed to download file ', e)
finally:
if sftp: sftp.close()
def close(self):
self.username = None
self.password = None
self.server = None
self.print_stdout = None
self.retries = None
self.interval = None
self.timeout = None
self.ssh_client.close()
self.log.info('Closing ssh connection.')
def run_remote_command(self, cmd_to_execute):
'''Run a command on a remote machine.
We do not explicitly close the ssh connection here incase we want to chain
multiple commands over one ssh connection. Leave the decision to close
the connection to the user.
'''
self.log.info('Attempting to run command %s on server %s',
cmd_to_execute, self.server)
try:
stdin, stdout, stderr = self.ssh_client.exec_command(cmd_to_execute)
self.log.info('Command succeeded')
except (BadHostKeyException, AuthenticationException, SSHException, socket.error) as e:
self._print_output(stderr)
self.warning("Failed to run ssh command with error: ", e)
self.close()
error_message = "Failed to run ssh command " + e
raise Exception(error_message)
if self.print_stdout == True:
self._print_output(stdout)
remote_return_code = stdout.channel.recv_exit_status()
if remote_return_code != 0:
print("Remote command failed with return code: ", remote_return_code)
return remote_return_code
def _print_output(self, command_output):
for line in iter(command_output.readline, ""):
print(line, end="")
def __exit__(self, exc_type, exc_value, traceback):
self.close()
<span class="math-container">```</span>
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T22:50:57.393",
"Id": "259998",
"Score": "0",
"Tags": [
"python",
"python-3.x",
"object-oriented",
"robotframework"
],
"Title": "Python Classes for Robot Test Framework which Open Paramiko SSH Connections and Run Commands"
}
|
259998
|
<p>As a purely pedagogical exercise, I've been trying to use Rust's (very expressive) type system to define the bare minimum one might expect from an <strong>ordinary</strong> list type.</p>
<p>While there's likely a higher-level argument here about mutable vs immutable lists, and <a href="https://rust-unofficial.github.io/too-many-lists/first-layout.html" rel="nofollow noreferrer">how lists should be implemented in Rust</a>, please note that this is purely an educational exercise.</p>
<p>One thing I've encountered, is that Rust lends itself to quite some verbosity with respect to the number of different logical blocks of code one might need in order to comply with prevailing conventions. I'm unsure as to whether this is actually true of Rust itself, or due to my own misunderstandings about Rust as a language and as an ecosystem.</p>
<hr />
<p><code>list.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>use std::fmt::Debug;
use std::ops::{Index, IndexMut};
pub trait List<T: Sized + Clone + Eq + Debug>:
Eq + Index<usize> + IndexMut<usize> + IntoIterator + Debug
{
type Error;
fn insert(&mut self, pos: usize, elem: T) -> Result<(), Self::Error>;
fn remove(&mut self, pos: usize) -> Result<T, Self::Error>;
fn length(&self) -> usize;
fn contains(&self, elem: T) -> bool;
}
</code></pre>
<p><code>veclist.rs</code>:</p>
<pre class="lang-rust prettyprint-override"><code>#![allow(clippy::unit_arg)]
use std::cmp::Ordering;
use std::fmt::Debug;
use std::ops::{Index, IndexMut};
use crate::list::List;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct VecList<T: Clone + Debug + Eq> {
pub elems: Vec<T>,
}
impl<T: Clone + Debug + Eq> List<T> for VecList<T> {
type Error = String;
fn insert(&mut self, pos: usize, elem: T) -> Result<(), Self::Error> {
match pos.cmp(&self.elems.len()) {
Ordering::Less => Ok(self.elems.insert(pos, elem)),
Ordering::Equal => Ok(self.elems.push(elem)),
Ordering::Greater => Err("Out of bounds".to_string()),
}
}
fn remove(&mut self, pos: usize) -> Result<T, Self::Error> {
match pos.cmp(&self.elems.len()) {
Ordering::Less => Ok(self.elems.remove(pos)),
_ => Err("Out of bounds".to_string()),
}
}
fn length(&self) -> usize {
self.elems.len()
}
fn contains(&self, elem: T) -> bool {
self.iter().any(|x| x == elem)
}
}
impl<T: Clone + Debug + Eq> VecList<T> {
pub fn iter(&self) -> VecListIterator<T> {
self.into_iter()
}
}
impl<T: Clone + Debug + Eq> Index<usize> for VecList<T> {
type Output = T;
fn index(&self, pos: usize) -> &Self::Output {
&self.elems[pos]
}
}
impl<T: Clone + Debug + Eq> IndexMut<usize> for VecList<T> {
fn index_mut(&mut self, pos: usize) -> &mut Self::Output {
&mut self.elems[pos]
}
}
pub struct VecListIterator<T: Clone + Debug + Eq> {
pos: usize,
list: VecList<T>,
}
impl<T: Clone + Debug + Eq> Iterator for VecListIterator<T> {
type Item = T;
fn next(&mut self) -> Option<Self::Item> {
if self.pos < self.list.length() {
self.pos += 1;
Some(self.list[self.pos - 1].clone())
} else {
None
}
}
}
impl<T: Clone + Debug + Eq> IntoIterator for VecList<T> {
type Item = T;
type IntoIter = VecListIterator<T>;
fn into_iter(self) -> Self::IntoIter {
VecListIterator { pos: 0, list: self }
}
}
impl<T: Clone + Debug + Eq> IntoIterator for &VecList<T> {
type Item = T;
type IntoIter = VecListIterator<T>;
fn into_iter(self) -> Self::IntoIter {
VecListIterator {
pos: 0,
list: self.clone(),
}
}
}
impl<T: Clone + Debug + Eq> IntoIterator for &mut VecList<T> {
type Item = T;
type IntoIter = VecListIterator<T>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
</code></pre>
<hr />
<ol>
<li>Is the definition of the list type, <code>List<T></code>, sensible?</li>
<li>Is the implementation of the list type, <code>VecList<T></code>, sensible?</li>
<li>Are there any defects in the codebase itself?</li>
</ol>
|
[] |
[
{
"body": "<h2>Don't force unnecessary bounds on your trait</h2>\n<p>You're requiring many bounds on your trait that simply aren't necessary. For example, it's nice to have the <code>Debug</code> trait so you can easily print out debug information, but you're currently having that as a <strong>requirement</strong> in order to implement your trait <code>List</code>. So try to reduce the trait bounds to just what's necessary and let the actual implementation decide on what trait they want to implement.</p>\n<p>Your <code>List</code> trait actually doesn't need any trait bounds. It could be just:</p>\n<pre><code>pub trait List<T>: Eq + Index<usize> + IndexMut<usize> + IntoIterator\n</code></pre>\n<p>Logically, methods like <code>contains</code> will probably need to implement the trait <code>Eq</code>, but they don't have to. If someone came up with a perfect hash function, then it would be quite annoying to still require all types to be comparable. Times when you need to add the trait are when you want to create default implementations that requires it.</p>\n<h2>Your iterators are not correct</h2>\n<p>Neither your immutable nor mutable iterator iterates over your actual data! Your immutable iterator is cloning <strong>the whole list</strong> and gives immutable references to your copied list. While semantically correct, it's very wasteful in respect to both memory and speed. Your mutable iterator calls <code>iter</code> which in turn calls <code>into_iter</code> for <code>&VecList</code> which then copies your vector. This is wasteful as well but is also semantically wrong. Modifying the values will not change the original list. A simple test confirms this:</p>\n<pre><code>#[test]\nfn modify_values() {\n let mut x = VecList { elems: vec![1, 2, 3] };\n \n for mut i in &mut x {\n i += 1;\n }\n \n assert_eq!(x.elems, vec![2, 3, 4]);\n}\n</code></pre>\n<p>Gives:</p>\n<pre><code>thread 'modify_values' panicked at 'assertion failed: `(left == right)`\n left: `[1, 2, 3]`,\n right: `[2, 3, 4]`', src/lib.rs:127:5\n</code></pre>\n<p>Implementing an immutable iterator is quite easy:</p>\n<pre><code>pub struct ImmutableVecListIterator<'a, T: Eq + Clone> {\n pos: usize,\n list: &'a VecList<T>,\n}\n\nimpl<'a, T: Eq + Clone> Iterator for ImmutableVecListIterator<'a, T> {\n type Item = &'a T;\n\n fn next(&mut self) -> Option<Self::Item> {\n if self.pos < self.list.length() {\n self.pos += 1;\n Some(&self.list[self.pos - 1])\n } else {\n None\n }\n }\n}\n\n\nimpl<'a, T: Eq + Clone> IntoIterator for &'a VecList<T> {\n type Item = &'a T;\n type IntoIter = ImmutableVecListIterator<'a, T>;\n\n fn into_iter(self) -> Self::IntoIter {\n ImmutableVecListIterator {\n pos: 0,\n list: self,\n }\n }\n}\n</code></pre>\n<p>Note that you probably need 3 different iterators: 1 that owns <code>VecList</code>, 1 that borrows <code>VecList</code>, and one that mutably borrows <code>VecList</code>.</p>\n<p>Implementing the other one's are harder. The mutable iterator requires unsafe code. What you can do is to rely on already existing implementations, like the one that already exists on <code>Vec</code>.</p>\n<pre><code>impl<'a, T: Eq + Clone> IntoIterator for &'a mut VecList<T> {\n type Item = &'a mut T;\n type IntoIter = std::slice::IterMut<'a, T>;\n\n fn into_iter(self) -> Self::IntoIter {\n self.elems.iter_mut() // Use the `Vec`'s mutable iterator.\n }\n}\n</code></pre>\n<h2>Always write tests!</h2>\n<p>As shown in the example above, it's quite easy to verify if you've done something correctly by writing simple tests. It also helps other to understand your code better as it both documents how to use our code and what the expected result should be.</p>\n<h2>An example</h2>\n<p>Here's an simple example on some of the improvements that can be made, but more could be made to improve soundness, like for example specifying that <code>IntoIterator</code> on the <code>List</code> trait should return <code>T</code> with <code>IntoIterator<Item=T></code>, among others.</p>\n<pre><code>use std::ops::{Index, IndexMut};\nuse std::cmp::Ordering;\n\n\npub trait List<T>: \n Eq + Index<usize> + IndexMut<usize> + IntoIterator\n{\n type Error;\n\n fn insert(&mut self, pos: usize, elem: T) -> Result<(), Self::Error>;\n fn remove(&mut self, pos: usize) -> Result<T, Self::Error>;\n fn length(&self) -> usize;\n fn contains(&self, elem: T) -> bool;\n}\n\n\n#[derive(Clone, Eq, PartialEq)]\npub struct VecList<T: Eq + Clone> {\n pub elems: Vec<T>,\n}\n\n\nimpl<T: Eq + Clone> List<T> for VecList<T> {\n type Error = String;\n\n fn insert(&mut self, pos: usize, elem: T) -> Result<(), Self::Error> {\n match pos.cmp(&self.elems.len()) {\n Ordering::Less => Ok(self.elems.insert(pos, elem)),\n Ordering::Equal => Ok(self.elems.push(elem)),\n Ordering::Greater => Err("Out of bounds".to_string()),\n }\n }\n\n fn remove(&mut self, pos: usize) -> Result<T, Self::Error> {\n match pos.cmp(&self.elems.len()) {\n Ordering::Less => Ok(self.elems.remove(pos)),\n _ => Err("Out of bounds".to_string()),\n }\n }\n\n fn length(&self) -> usize {\n self.elems.len()\n }\n\n fn contains(&self, elem: T) -> bool {\n self.iter().any(|x| *x == elem)\n }\n}\n\n\nimpl<T: Eq + Clone> VecList<T> {\n pub fn iter(&self) -> RefVecListIterator<T> {\n self.into_iter()\n }\n}\n\n\nimpl<T: Eq + Clone> Index<usize> for VecList<T> {\n type Output = T;\n\n fn index(&self, pos: usize) -> &Self::Output {\n &self.elems[pos]\n }\n}\n\nimpl<T: Eq + Clone> IndexMut<usize> for VecList<T> {\n fn index_mut(&mut self, pos: usize) -> &mut Self::Output {\n &mut self.elems[pos]\n }\n}\n\n\npub struct VecListIterator<T: Eq + Clone> {\n pos: usize,\n list: VecList<T>,\n}\n\nimpl<T: Eq + Clone> Iterator for VecListIterator<T> {\n type Item = T;\n\n fn next(&mut self) -> Option<Self::Item> {\n if self.pos < self.list.length() {\n self.pos += 1;\n Some(self.list[self.pos - 1].clone())\n } else {\n None\n }\n }\n}\n\nimpl<T: Eq + Clone> IntoIterator for VecList<T> {\n type Item = T;\n type IntoIter = VecListIterator<T>;\n\n fn into_iter(self) -> Self::IntoIter {\n VecListIterator { pos: 0, list: self }\n }\n}\n\n\npub struct RefVecListIterator<'a, T: Eq + Clone> {\n pos: usize,\n list: &'a VecList<T>,\n}\n\nimpl<'a, T: Eq + Clone> Iterator for RefVecListIterator<'a, T> {\n type Item = &'a T;\n\n fn next(&mut self) -> Option<Self::Item> {\n if self.pos < self.list.length() {\n self.pos += 1;\n Some(&self.list[self.pos - 1])\n } else {\n None\n }\n }\n}\n\n\nimpl<'a, T: Eq + Clone> IntoIterator for &'a VecList<T> {\n type Item = &'a T;\n type IntoIter = RefVecListIterator<'a, T>;\n\n fn into_iter(self) -> Self::IntoIter {\n RefVecListIterator {\n pos: 0,\n list: self,\n }\n }\n}\n\nimpl<'a, T: Eq + Clone> IntoIterator for &'a mut VecList<T> {\n type Item = &'a mut T;\n type IntoIter = std::slice::IterMut<'a, T>;\n\n fn into_iter(self) -> Self::IntoIter {\n self.elems.iter_mut()\n }\n}\n\n\n\n#[test]\nfn modify_values() {\n let mut x = VecList { elems: vec![1, 2, 3] };\n \n for i in &mut x {\n *i += 1;\n }\n \n assert_eq!(x.elems, vec![2, 3, 4]);\n}\n</code></pre>\n<p><a href=\"https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=265ea08063045eb9e28e3c21400cb918\" rel=\"nofollow noreferrer\">Rust Playground</a></p>\n<h2>TL;DR</h2>\n<ul>\n<li><em>Is the definition of the list type, List, sensible?</em></li>\n</ul>\n<p>You should reduce the amount of trait bounds.</p>\n<ul>\n<li><em>Is the implementation of the list type, VecList, sensible?</em></li>\n</ul>\n<p>Your iterators are not, and once again, you should reduce the amount of trait bounds. Also, it's usually standard practice to add constructors like <code>new</code> or with the <code>Default</code> trait. Just some way to create an instance from a function.</p>\n<ul>\n<li><em>Are there any defects in the codebase itself?</em></li>\n</ul>\n<p>See above.</p>\n<p>And to answer your implicit question: yes, Rust is very verbose if you want to implement everything yourself. This is however greatly reduced if you utilize already existing solutions, like just providing a wrapper over <code>Vec</code>'s iterators instead of writing your own, use macros, or use other people's crates.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T21:51:01.407",
"Id": "513192",
"Score": "0",
"body": "Thanks for the thorough feedback - I really appreciate it! With respect to the bounds on the type `T` itself, surely `Sized` is a reasonable one, or am I misunderstanding the point of marking a type as `Sized`? In C, we obviously avoid this issue by `void*` being the maximum valid width for the system, at the cost of bypassing the type system, of course."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T13:54:49.377",
"Id": "513247",
"Score": "1",
"body": "@jmcph4 [*\"All type parameters have an implicit bound of Sized\"*](http://web.mit.edu/rust-lang_v1.25/arch/amd64_ubuntu1404/share/doc/rust/html/core/marker/trait.Sized.html). `Sized` is an auto bound, so you need to **opt-out** of the `Sized` trait with `?Sized`. You usually need `Sized` if you want to pass in or return `Self` by value, as it's marked as `?Sized` by default."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T06:26:44.127",
"Id": "513311",
"Score": "0",
"body": "Another thing is that, as of Rust 1.51.0, `impl<'a, T: Eq + Clone> IntoIterator for VecList<T>` fails as `'a` is unconstrained?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T08:36:33.637",
"Id": "513320",
"Score": "0",
"body": "@jmcph4 Yes, because you're declaring a lifetime `'a` but not using it. Don't know what you're trying to do with including that lifetime. The traits in the answer are `impl<T: Eq + Clone> IntoIterator for VecList<T>`, `impl<'a, T: Eq + Clone> IntoIterator for &'a VecList<T>`, and `impl<'a, T: Eq + Clone> IntoIterator for &'a mut VecList<T>`."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T02:08:32.120",
"Id": "260005",
"ParentId": "260000",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "260005",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-25T23:21:00.660",
"Id": "260000",
"Score": "1",
"Tags": [
"design-patterns",
"rust",
"library",
"trait"
],
"Title": "Minimal list definition in Rust"
}
|
260000
|
<blockquote>
<p>Create a class template named <code>ValueStore</code> that has a member variable,
to store a value and a member variable, <code>hasValue</code> that holds a true
value if there is data in the value member variable and false
otherwise. Use the class to store three values of different types.</p>
</blockquote>
<pre class="lang-cpp prettyprint-override"><code>#include <iostream>
using namespace std;
template <typename T>
class ValueStore {
private:
T value;
public:
bool hasValue = false;
ValueStore(T val) {
value = val;
hasValue = true;
}
ValueStore() {
value = {};
}
T getValue() {
return value;
}
};
int main ()
{
ValueStore<string> v1("hello, world");
if (v1.hasValue) {
cout << "The value stored is: " << v1.getValue() << endl;
}
else {
cout << "v1 has no value." << endl;
}
ValueStore<int>v2(1000);
if (v2.hasValue) {
cout << "The value stored is: " << v2.getValue() << endl;
}
else {
cout << "v2 has no value." << endl;
}
ValueStore<double> v3;
if (v3.hasValue) {
cout << "The value stored is: " << v2.getValue() << endl;
}
else {
cout << "v3 has no value." << endl;
}
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T03:26:42.757",
"Id": "513078",
"Score": "7",
"body": "You should separate this into two questions."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T03:26:56.307",
"Id": "513079",
"Score": "3",
"body": "Please separate this question into 2 questions, since there are 2 different programs to be reviewed."
}
] |
[
{
"body": "<h1>About these assignments</h1>\n<p>As someone who’s been teaching C++ for <del>15</del> holy shit, almost 20 years now, I have to say that these assignments are pretty terrible… especially the “vector” one. (To be clear, I mean the <em>assignments</em> are terrible… not the <em>attempts</em>. The attempts aren’t bad at all.)</p>\n<p>I’ve always found the logic of “let’s teach by reimplementing what’s in the standard library” to beginners to be a little idiotic. As far as teaching useful skills goes:</p>\n<ol>\n<li>it just wastes the learner’s time learning how to do something they (almost certainly) will <em>never</em> need to do again; and</li>\n<li>in the <em>vast</em> majority of cases, it requires such terrifyingly advanced C++ knowledge to properly replicate a standard library facility, that in order to make it doable at all you have to dumb it down to the point where it’s almost broken… which only gives the learner a false sense of confidence thinking they understand how to do the thing when they really don’t.</li>\n</ol>\n<p>In this case, it looks like the goal is to reimplement <code>std::optional</code> and <code>std::vector</code>… but only half-assed, broken, functionally-useless variants of both. I see beginners attempting these things all the time, but what they don’t seem to understand is that those are <em>INCREDIBLY</em> difficult tasks, requiring knowledge of C++ that is <em>WAY</em> beyond what any beginner should be expected to have. Even some <em>expert</em> level C++ programmers don’t have the knowledge necessary to do these things. In particular, reimplementing <code>std::vector</code> <em>properly</em> is among <em>the hardest things you can possibly do in C++</em>. Just because it’s easy to <em>use</em> doesn’t mean it’s easy to make.</p>\n<p>I wish it would become more commonly understood that reimplementing standard library facilities is a pants-crappingly stupid way of teaching C++. Reimplementing standard library facilities is an excellent project… for highly <em>advanced</em> C++ programmers. But beginners? No. Don’t teach beginners to reimplement the standard library… teach them to fricken’ <em>use</em> it!</p>\n<p>Anywho, the problem here isn’t the learner—it’s the teacher who gave these crappy assignments—so I won’t rant any more about that. Instead I’ll just focus on the code.</p>\n<p>I’m only going to review the first program here. <del>The second program, I’ll review in a second reply.</del> It looks like the recommendation is to split the two programs into two separate questions; so you should probably do that.</p>\n<h1>Code review</h1>\n<pre><code>using namespace std;\n</code></pre>\n<p>Never, ever do this at file scope. This is a terrible practice. In fact, you should probably never do this <em>ever</em>, not even at function scope.</p>\n<p>Among the many reasons this is bad: Today your code compiles because there is nothing called <code>ValueStore</code> in the standard library. But if some future version of the standard adds something with that name… boom, your code is now broken. And that’s if you’re lucky. What might also happen is that something new gets added to the standard library that silently changes the behaviour of your code. That’s a nightmare scenario.</p>\n<p>Just use <code>std::</code> where necessary.</p>\n<pre><code> ValueStore(T val) {\n value = val;\n hasValue = true;\n }\n</code></pre>\n<p>The first issue with this constructor is that it’s not <code>explicit</code>. That makes it dangerous, because it will silently convert <em>anything</em> that is implicitly convertible to a <code>T</code>. At the very least, that is likely to be inefficient.</p>\n<p>In general, any constructor that takes a single argument should be <code>explicit</code>. (Yes, that should actually be the default, but unfortunately, the default was set to implicit way back when C++ was first standardized, and now it’s too late to change.)</p>\n<p>The second issue with this constructor is that it doesn’t use member initializer lists. What’s actually happening above is this:</p>\n<pre><code>ValueStore(T val)\n:\n value{}, // value is default-constructed\n hasValue{false} // hasValue is initialized to false (because of the member initializer where it is declared)\n{\n value = val; // value is copy-assigned using val\n hasValue = true; // hasValue is move-assigned using true\n}\n</code></pre>\n<p>As you can see, <code>value</code> is set up <em>twice</em>. First it is default constructed, then it is assigned (with the actual contents of <code>val</code>).</p>\n<p>What you should do, as a start, is this:</p>\n<pre><code>explicit ValueStore(T val)\n:\n value{val}, // value is copy-constructed using val\n hasValue{true} // hasValue is initialized to true\n{\n // nothing to do here\n}\n</code></pre>\n<p>Here you can see <code>value</code> is only set up <em>once</em>: it is initialized right from the start with <code>val</code>, rather than being initialized “empty” (technically default-constructed) then assigned.</p>\n<p>But there’s one more improvement you could make. To understand it, consider the following code:</p>\n<pre><code>ValueStore<std::string> v1("hello, world");\n</code></pre>\n<p>What’s happening here is:</p>\n<ol>\n<li>Before the <code>ValueStore</code> constructor is called:\n<ol>\n<li>A temporary <code>std::string</code> is constructed with the contents “hello, world”.</li>\n<li>The temporary string is moved to <code>val</code>. (It is <em>moved</em>, not <em>copied</em>, because it is a temporary. As a practical matter, this whole step is usually elided as an optimization, meaning the temporary string is constructed <em>directly</em> into <code>val</code>.)</li>\n</ol>\n</li>\n<li>The <code>ValueStore</code> constructor is called:\n<ol>\n<li>The member initializer list runs:\n<ol>\n<li><code>val</code> is copied into <code>value</code>.</li>\n<li><code>hasValue</code> is set to <code>true</code>.</li>\n</ol>\n</li>\n<li>The constructor body is called:\n<ol>\n<li>Nothing happens here, because it’s empty.</li>\n</ol>\n</li>\n</ol>\n</li>\n</ol>\n<p>So a temporary string is constructed, and then moved into <code>val</code>, and then <em>copied</em> into <code>value</code>. The copy is the problem there, because copying a string is expensive. Copying is generally expensive compared to moving, so you want to move whenever possible.</p>\n<p>This is an easy fix; just <em>move</em> <code>val</code> into <code>value</code>:</p>\n<pre><code>explicit ValueStore(T val)\n:\n value{std::move(val)}, // value is move-constructed using val\n hasValue{true} // hasValue is initialized to true\n{\n // nothing to do here\n}\n</code></pre>\n<p>That’s all you need to do. Now a temporary string is constructed, then moved into <code>val</code>, then moved into <code>value</code>. In all likelihood, those moves can be elided. But even if not, moves are (usually) <em>fast</em>, especially for strings, and are usually no-fail.</p>\n<p>There are a few other improvements you could make to this constructor:</p>\n<pre><code>constexpr explicit ValueStore(T val)\n noexcept(std::is_nothrow_move_constructible_v<T>)\n:\n value{std::move(val)},\n hasValue{true}\n{}\n</code></pre>\n<p>Making the constructor <code>constexpr</code> means you can construct <code>ValueStore</code> objects at compile-time, which can be <em>enormously</em> useful.</p>\n<p>If move-constructing <code>value</code> cannot possibly fail, then the whole constructor cannot possibly fail. Adding the <code>noexcept</code> tells the compiler that, allowing it to make additional optimizations. (If move-constructing <code>value</code> <em>can</em> fail, then <code>std::is_nothrow_move_constructible_v<T></code> will be <code>false</code>.)</p>\n<pre><code> ValueStore() {\n value = {};\n }\n</code></pre>\n<p>This has the same problem as the previous constructor: you’re setting the value of <code>value</code> <em>twice</em>. What’s really happening is this:</p>\n<pre><code>ValueStore()\n:\n value{}, // value is default-constructed\n hasValue{false} // hasValue is initialized to false\n{\n value = {}; // a temporary T object is default-constructed,\n // then move-assigned into value\n}\n</code></pre>\n<p>As you can see, that entire <code>value = {};</code> is just a complete waste of time. All it does is take the already default-constructed <code>value</code>, default-constructs a whole new object, and then moves that into <code>value</code>. If you’d just left <code>value</code> alone, it would already be default-constructed:</p>\n<pre><code>ValueStore()\n/*\n:\n value{}, // value is default-constructed\n hasValue{false} // hasValue is initialized to false\n*/\n{\n // nothing to do here\n}\n</code></pre>\n<p>But wait, there’s more!</p>\n<p>Writing the default constructor like <code>ValueStore() {}</code> is actually a bad idea, because if it were possible to trivially-construct <code>ValueStore</code> objects… you just broke that functionality. Trivial construction means the compiler doesn’t actually have to do anything to construct a <code>ValueStore</code>, which means a lot of potential optimizations. It is better to leave the default constructor alone unless you actually need it to do something specific… which you don’t in this case.</p>\n<p>So what you should write is:</p>\n<pre><code>ValueStore() = default;\n</code></pre>\n<p>And of course, you can add the extra decorations mentioned for the previous constructor to get even more benefits:</p>\n<pre><code>constexpr ValueStore() noexcept(std::is_nothrow_default_constructible_v<T>) = default;\n</code></pre>\n<p>(<code>is_nothrow_default_constructible_v<T></code> is <code>true</code> only if default-constructing a <code>T</code> cannot fail.)</p>\n<pre><code> T getValue() {\n return value;\n }\n</code></pre>\n<p>Since this function doesn’t change the state of the object, it should be <code>const</code>.</p>\n<p>You could also add <code>constexpr</code> and maybe <code>noexcept(std::is_nothrow_copy_constructible_v<T> and std::is_nothrow_copy_assignable_v<T>)</code>.</p>\n<p>Now, this is really getting into complicated territory… but as the <em>default</em> choice for a new API, doing what you’ve done—returning a copy of <code>value</code>—is probably the right choice. <em>However</em>… this is not optimal, because if you don’t actually <em>want</em> a copy of <code>value</code>—if you just want to see what that value is (for example, just to print it like you’re doing in <code>main()</code>—you’re wasting resources by creating the copy.</p>\n<p>What you really want to do is return a reference to <code>value</code>… <em>but</em> you have to be careful what kind of reference you return. If the <code>ValueStore</code> object is <code>const</code>, you don’t want to return a non-<code>const</code> reference to <code>value</code>… that would (theoretically) allow users to change the value of your <code>const</code> object, which is absurd. So you need two functions: one for <code>const</code> objects, and one for non-<code>const</code> objects:</p>\n<pre><code>constexpr T const& getValue() const noexcept { return value; }\nconstexpr T& getValue() noexcept { return value; }\n</code></pre>\n<p>Oh, but we’re not done yet, not by a long shot. Because there’s still the problem of temporaries. If you have a temporary <code>ValueStore</code> object, and you call <code>getValue()</code> on it, you’ll get a reference to <code>value</code>… but that reference will be dangling because the temporary is destroyed.</p>\n<p>So you need to return rvalue references to <code>value</code> when the <code>ValueStore</code> is an rvalue (temporary, basically), and lvalue references when the <code>ValueStore</code> is an lvalue… <em>and</em> you need to take <code>const</code> into account. So what you really need is:</p>\n<pre><code>constexpr T const& getValue() const& noexcept { return value; }\nconstexpr T& getValue() & noexcept { return value; }\nconstexpr T const&& getValue() const&& noexcept { return std::move(value); }\nconstexpr T&& getValue() && noexcept { return std::move(value); }\n</code></pre>\n<p>(Yes, you have to basically write the same function 2–4 times. That’s an unfortunate situation that some people are currently working to fix.)</p>\n<p>((Rant mode again: See, complicated crap like this is why reimplementing <code>std::optional</code> is such a terrible project for beginners. And we haven’t even scratched the surface of just how complicated this really gets! You see, your class actually lies: it says <code>hasValue</code> is <code>false</code> if you do <code>ValueStore<double> v3;</code> But <code>v3</code> <em>does</em> have a value: it is holding a <code>double</code> whose value is <code>0.0</code>. Zero is a perfectly valid value for a <code>double</code>. Similarly, if you do <code>ValueStore<std::string> v;</code>, <code>v.hasValue</code> will say <code>false</code>… but <code>v</code> <em>does</em> have a value… it is holding a string whose current contents are just “”, but an empty string is still a string.))</p>\n<p>That’s pretty much it for the <code>ValueStore</code> class. The only other comments I have are for the <code>main()</code> function.</p>\n<p>First: Don’t use <code>std::endl</code>. Just don’t. Ever. Pretty much every use of <code>std::endl</code> I’ve ever seen is wrong… and yes, every single use in your program is wrong.</p>\n<p>In particular, this is absurd:</p>\n<pre><code> cout << "v1 has no value." << endl;\n</code></pre>\n<p>If you want a newline, just use a newline:</p>\n<pre><code> std::cout << "v1 has no value.\\n";\n</code></pre>\n<p>I know, every tutorial you’ve ever seen probably uses <code>std::endl</code>. Yes, I’m saying they’re <em>all</em> wrong. There is almost never a right time to use <code>std::endl</code>… and for those very, <em>very</em> rare situations where it has a purpose, you’re probably better off calling <code>std::cout.flush()</code> directly anyway, to make clear that’s what you want.</p>\n<p>Finally: there is no need for <code>return 0;</code> in <code>main()</code>. <code>main()</code> automatically returns zero. (This is <em>only</em> true for <code>main()</code>; <code>main()</code> is special in a lot of ways.)</p>\n<h1>Summary</h1>\n<p>The problem I have with deciding whether this is a solid attempt at this problem or not is that the problem itself is stupid. Given a stupid problem, if someone’s solution isn’t great, is that because the solution is bad or because the problem is bad? It’s not easy to say.</p>\n<p>I suppose this is a decent swing at the problem for a beginner. But really, this is <em>not</em> a beginner problem. Not if you take it seriously, anyway.</p>\n<p>So long as you understand that <code>hasValue</code> is a lie, I suppose you can walk away from this having learned <em>something</em>. The truth is that your <code>ValueStore</code> <em>always</em> has a value. It can’t <em>not</em> have a value, so long as it has a <code>T</code> data member. Doing <code>value = {}</code> doesn’t set <code>value</code> to “not a value”; it sets it to <em>the default value</em>. Which is a value. There is literally no way to set <code>value</code> to “not a value”; that is literally impossible in C++.</p>\n<p>You could cheat a little and do something like this:</p>\n<pre><code>template <typename T>\nclass ValueStore\n{\nprivate:\n std::optional<T> value;\n\npublic:\n bool hasValue = false;\n\n constexpr explicit ValueStore(T val)\n :\n value{std::move(val)},\n hasValue{true}\n {}\n\n constexpr ValueStore() noexcept = default;\n\n constexpr T const& getValue() const& noexcept { return value.value(); }\n constexpr T& getValue() & noexcept { return value.value(); }\n constexpr T const&& getValue() const&& noexcept { return std::move(value).value(); }\n constexpr T&& getValue() && noexcept { return std::move(value).value(); }\n};\n</code></pre>\n<p><em>Now</em> <code>ValueStore</code> can have no value, because it is no longer holding a <code>T</code>, it’s holding a <code>std::optional<T></code>… but now <code>hasValue</code> is redundant: it’s just duplicating <code>value.has_value()</code>. You could just do:</p>\n<pre><code>template <typename T>\nclass ValueStore\n{\nprivate:\n std::optional<T> value;\n\npublic:\n constexpr explicit ValueStore(T val) : value{std::move(val)} {}\n\n constexpr ValueStore() noexcept = default;\n\n constexpr T const& getValue() const& noexcept { return value.value(); }\n constexpr T& getValue() & noexcept { return value.value(); }\n constexpr T const&& getValue() const&& noexcept { return std::move(value).value(); }\n constexpr T&& getValue() && noexcept { return std::move(value).value(); }\n\n constexpr bool hasValue() const noexcept { return value.has_value(); }\n};\n</code></pre>\n<p>Anywho, back to your code: As I said, I think it’s a decent attempt at a very, <em>very</em> hard problem. In particular, your code is <em>correct</em>, for the vast majority of use cases… it’s just not <em>efficient</em>. Which is not a bad start! It’s always good to get it right first, and get it fast later, if possible.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:57:13.553",
"Id": "513124",
"Score": "1",
"body": "Amazing answer. I'll point people to here next time they ask me why I don't program in C++."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T19:16:46.883",
"Id": "513183",
"Score": "1",
"body": "@WimDeblauwe Heh. From the review: *\"Even some expert level C++ programmers don’t have the knowledge necessary to do these things.*\" C++ is the tar-baby of programming languages."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T19:27:55.237",
"Id": "513186",
"Score": "0",
"body": "@WimDeblauwe @aghast Sure but what if someone would ask you to reimplement a `list` in Python? That would also be very pointless as indi mentioned, and if you really wanted to do that, it would also be very difficult. The only fault of C++ here is that containers are not built-in language features, and that it is actually possible for a novice to give it a try to reimplement them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T20:05:37.033",
"Id": "513189",
"Score": "3",
"body": "@G.Sliepen I wouldn’t bother wasting my time taking the comments from the peanut gallery seriously. The bottom line is that implementing `vector` to get the level of efficiency promised by C++ is going to be a herculean task in *any* language; in most languages it’s straight-up impossible. Anyone who thinks the problem here is C++ and not the complexity of the task is simply clueless about both."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T04:10:11.057",
"Id": "260009",
"ParentId": "260004",
"Score": "15"
}
},
{
"body": "<p>Your <code>ValueStore</code> template class <em>always</em> has a value. If you don't call the one-argument constructor, it holds a default-constructed value.</p>\n<p>That might work OK if the type <code>T</code> <em>has</em> a default. Just chalk it up to your teacher's language being imprecise, as we see with other phrases like "Use the class to store three values of different types." (Instantiate the template to make three classes.)</p>\n<p>To actually do what it stated, you would need to use a pointer.</p>\n<p>You don't need a separate flag, since you can check for the pointer being null.</p>\n<pre><code> template <typename T>\n class ValueStore {\n ValueStore() = default;\n explicit ValueStore (T val) : p{make_unique<T>(std::move(val)} {}\n bool hasvalue() const { return p; }\n T getvalue() \n {\n if (!p) throw // .... something\n return *p;\n }\n private:\n std::unique_ptr<T> p;\n };\n</code></pre>\n<p>I think the instructor meant that <code>hasvalue</code> is a member function that the user can call to determine whether there is a stored value. You have it as an implementation detail that is not accessible, and is <em>useless</em> since <code>getValue</code> always returns what's stored even if it's the default.</p>\n<p>It makes more sense to be able to tell whether a value is stored and then the code can avoid fetching it if not present. But what happens if the caller fetches it anyway? Presumably it ought to throw an exception.</p>\n<p>Note that the real implementation of <code>std::optional</code> will avoid the inefficiency of allocating heap memory by including a buffer as part of the class. But it still uses <code>new</code> to construct the object (using placement new syntax) <em>when</em> it exists and has no object constructed at all when empty.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:59:09.207",
"Id": "260034",
"ParentId": "260004",
"Score": "3"
}
},
{
"body": "<p>Once thing that I feel particularly strongly about:</p>\n<pre><code>if (v3.hasValue) {\n cout << "The value stored is: " << v2.getValue() << endl;\n}\nelse {\n cout << "v3 has no value." << endl;\n}\n</code></pre>\n<p>The duplication of this code should be removed if at all possible. It's a maintenance nightmare, it makes life harder for the reader, and it's prone to errors (the example I copied does in fact have a cut/paste error, in that it prints the value of <code>v2</code> rather than <code>v3</code>). Putting similar code into a <code>ValueStore::Print()</code> method is arguably the best way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T18:33:54.780",
"Id": "260045",
"ParentId": "260004",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T02:02:52.800",
"Id": "260004",
"Score": "1",
"Tags": [
"c++",
"reinventing-the-wheel",
"homework"
],
"Title": "Value store (\"optional\" type)"
}
|
260004
|
<p>I have extensively consulted Raku documentation and have tried many combinations to finally arrive at this working solution.</p>
<pre><code>#!/usr/bin/perl6
use v6;
my $a;
my $b = 34;
my $c;
$a = prompt "enter number: ";
$c = ($a * $b);
say "$a multiplied by $b is $c";
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:16:13.930",
"Id": "513097",
"Score": "0",
"body": "Hey there, welcome to the community! CodeReview.SE is to ask for peer reviews of code that is _working as intended_! For help with problems in your code, like the ones you seem to be exhibiting, you are better off [asking at StackOverflow](https://stackoverflow.com) :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T20:47:08.127",
"Id": "513277",
"Score": "1",
"body": "@AlexV The flawed code wasn't reviewed, so I threw it out and left the working code it. That should take care of it."
}
] |
[
{
"body": "<p>To tighten your code a bit, you can declare <code>my $a</code> and assign in the same line:</p>\n<pre><code>my $a = prompt "enter number: ";\nmy $b = 34;\nmy $c;\n$c = ($a * $b);\nsay "$a multiplied by $b is $c";\n</code></pre>\n<p>The above seems to solve your question, however a user might not respond with the proper input. If a user replies to the prompt with <code>Hello</code> you'll get an ungraceful error:</p>\n<pre><code>Cannot convert string to number: base-10 number must begin with valid digits or '.' in '⏏Hello' (indicated by ⏏) in block <unit> at Pedr_Ap_Glyn.p6 line 7\n</code></pre>\n<p>You can add a Type declaration to obviate this issue:</p>\n<pre><code>my Int $a = prompt "enter number: ";\n</code></pre>\n<p>...which, if an <code>Int</code> is not returned, will error with the message:</p>\n<pre><code>Type check failed in assignment to $a; expected Int but got [WHAT RAKU GOT IS HERE] in block <unit> at Pedr_Ap_Glyn.p6 line 5\n</code></pre>\n<p>Maybe a different pre-declared Type is more useful for your case:</p>\n<pre><code>my Numeric $a = prompt "enter number: ";\n</code></pre>\n<p>...which will work with non-Integer input (e.g. <code>3.14159265</code>).</p>\n<p>Or you could declare your own Type subset (below, "PosInt"):</p>\n<pre><code>subset PosInt of Int where * > 0;\nmy PosInt $a = prompt "enter number: ";\n</code></pre>\n<p>...which will only accept <code>Int</code>s greater that zero. Above are just a few options that the Raku language offers--and that you may wish to take advantage of.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T17:29:57.867",
"Id": "260039",
"ParentId": "260006",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T03:31:06.787",
"Id": "260006",
"Score": "2",
"Tags": [
"raku"
],
"Title": "Raku multiplication using prompt and say"
}
|
260006
|
<p>I have written a merge sort in C and would like any advice on how to improve it. Any advice helps to make the code better!</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
static void mergesort_helper(void *array, uint32_t index, uint32_t length, size_t size_element, int32_t compare(void *, void *), void *storage)
{
uint32_t i, j, k;
if(length == 1)
{
/*printf("\n%d, %d\n", index, length);*/
return;
}
mergesort_helper(array, index, length / 2, size_element, compare, storage);
if(length % 2 == 0)
mergesort_helper(array, (index + (index + length)) / 2, length / 2, size_element, compare, storage);
else
mergesort_helper(array, (index + (index + length)) / 2, length / 2 + 1, size_element, compare, storage);
/*sorting part*/
i = index;
j = (index + (index + length)) / 2;
k = 0;
while(i < (index + (index + length)) / 2 || j < (index + length))
{
if(i < (index + (index + length)) / 2 && (compare(array + i * size_element, array + j * size_element) <= 0 || j >= (index + length)))
{
memcpy(storage + k * size_element, array + i * size_element, size_element);
i++;
}
else if(j < (index + length) && (compare(array + i * size_element, array + j * size_element) > 0) || i >= (index + (index + length)) / 2)
{
memcpy(storage + k * size_element, array + j * size_element, size_element);
j++;
}
k++;
}
memcpy(array + index * size_element, storage, length * size_element);
}
/*
array - to be sorted
length - exclusive
size_element - how big is one element
*/
void mergesort(void *array, uint32_t length, size_t size_element, int32_t compare(void *, void *))
{
void *storage;
if(length == 0)
return;
storage = malloc(size_element * length);
mergesort_helper(array, 0, length, size_element, compare, storage);
free(storage);
}
/*user code*/
int32_t compare(void *ptr1, void *ptr2)
{
int32_t *temp_ptr1, *temp_ptr2;
temp_ptr1 = (int32_t *)ptr1;
temp_ptr2 = (int32_t *)ptr2;
if(*temp_ptr1 < *temp_ptr2)
return -1;
else if(*temp_ptr1 > *temp_ptr2)
return 1;
return 0;
}
int main(void)
{
uint32_t i;
int32_t array[] = {6, 4, 3, 2, 7, -100, 1, 0, 5, 8, -100, 8};
for(i = 0; i < sizeof(array) / sizeof(array[0]); i++)
{
printf("%d ", array[i]);
}
printf("\n");
mergesort(array, sizeof(array) / sizeof(array[0]), sizeof(array[0]), &compare);
for(i = 0; i < sizeof(array) / sizeof(array[0]); i++)
{
printf("%d ", array[i]);
}
printf("\n");
return 0;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:10:38.740",
"Id": "513149",
"Score": "2",
"body": "Merge sort makes little sense for random-access arrays."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:26:42.833",
"Id": "513154",
"Score": "0",
"body": "What would you recommend that I use for sorting a random-access arrays?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:38:13.037",
"Id": "513157",
"Score": "6",
"body": "If this isn't homework, you must know about the `qsort` function which is already in the standard C library. Your `mergesort` function has almost identical conventions to `qsort` (except for the missing `const` on the comparison function's parameters) which is probably no coincidence. The only drawback of `qsort` is that it's not required to be a stable sort."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T23:19:26.213",
"Id": "513201",
"Score": "1",
"body": "@Kaz Another drawback is that it's generic. If you *know* the type, you can do your comparisons and assignments directly instead of needing to call `cmp` and `memmove`, at which point it's fairly easy to write a merge sort that'll beat `qsort` by a decent margin. (Although a handwritten quicksort with random pivot would presumably do even better, on average.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T09:37:17.677",
"Id": "513235",
"Score": "2",
"body": "@Kaz In the GLibc qsort() is actually implemented as mergesort because it performs better than quicksort. Therefore it makes sense to implement mergesort for associative arrays. Moreover quicksort is not stable which sucks for any interactive use, such as in a GUI."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T23:35:40.313",
"Id": "513287",
"Score": "0",
"body": "Don't mix C++ concepts with C one major code smell, others mentioned by G. Sliepen. The code will compile but its hybrid C and C++"
}
] |
[
{
"body": "<p>I'm not too confident with my knowledge on (void) pointers so I will avoid giving feedback on the pointer related stuff.</p>\n<h2>Unnecessary if...else statement.</h2>\n<pre class=\"lang-c prettyprint-override\"><code>if(length % 2 == 0)\n mergesort_helper(array, (index + (index + length)) / 2, length / 2, size_element, compare, storage);\nelse\n mergesort_helper(array, (index + (index + length)) / 2, length / 2 + 1, size_element, compare, storage);\n</code></pre>\n<p>Can be turned into:</p>\n<pre class=\"lang-c prettyprint-override\"><code>mergesort_helper(array, (index + (index + length)) / 2, length / 2 + (length % 2), size_element, compare, storage);\n</code></pre>\n<h2>Minor improvement to the length check in <code>mergesort</code>.</h2>\n<p>When the array is of length 1 it is possible to return early as well, because an array of length 1 is already sorted.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void mergesort(void *array, const uint32_t length, const size_t size_element, int32_t compare(void *, void *))\n{\n ...\n if (length <= 1) { return; }\n ...\n}\n</code></pre>\n<h2>Use const</h2>\n<p><code>length</code> and <code>size_element</code> don't change in the <code>mergesort</code> and <code>mergesort_helper</code> functions. This is also the case for <code>index</code> in the <code>mergesort_helper</code> function. It would be best to use the const keyword to indicate this, this can also be helpful to the compiler.</p>\n<pre class=\"lang-c prettyprint-override\"><code>void mergesort(void *array, const uint32_t length, const size_t size_element, int32_t compare(int32_t *, int32_t *))\nstatic void mergesort_helper(void *array, const uint32_t index, const uint32_t length, const size_t size_element, int32_t compare(int32_t *, int32_t *), void *storage)\n</code></pre>\n<h2>Styling & Readability</h2>\n<p>Some of these are opinionated so you can use what you see fit.</p>\n<ul>\n<li>Use an indentation of 4 spaces instead of 3.</li>\n<li>Use a space between <code>if/while/for</code> and <code>(</code></li>\n<li>Use brackets on if...else statements even if they are one line. There's a chance more lines will be added to the if...else statement later on. Forgetting to add brackets when this happens can lead to bugs that could have been avoided if brackets where added from the start.</li>\n<li>Merge sort consists of two words so <code>merge_sort</code> would be more appropriate.</li>\n<li><code>(index + (index + length)) / 2</code> represents the middle index it would make the code easier to read if it was assigned to a const variable.</li>\n</ul>\n<pre class=\"lang-c prettyprint-override\"><code>static void mergesort_helper(void *array, const uint32_t index, const uint32_t length, const size_t size_element, int32_t compare(void *, void *), void *storage)\n{\n uint32_t i, j, k;\n if (length == 1)\n {\n /*printf("\\n%d, %d\\n", index, length);*/\n return;\n }\n\n const uint32_t m_index = (index + (index + length)) / 2;\n\n mergesort_helper(array, index, length / 2, size_element, compare, storage);\n\n mergesort_helper(array, m_index, length / 2 + length % 2, size_element, compare, storage);\n\n /*sorting part*/\n i = index;\n j = m_index;\n k = 0;\n\n while (i < m_index || j < (index + length))\n {\n if (i < m_index && (compare(array + i * size_element, array + j * size_element) <= 0 || j >= (index + length)))\n {\n memcpy(storage + k * size_element, array + i * size_element, size_element);\n i++;\n }\n else if (j < (index + length) && (compare(array + i * size_element, array + j * size_element)> 0 || i >= m_index))\n {\n memcpy(storage + k * size_element, array + j * size_element, size_element);\n j++;\n }\n\n k++;\n }\n\n memcpy(array + index * size_element, storage, length * size_element);\n}\n</code></pre>\n<p>Maybe it is possible to make the if..else statement in the while loop of mergesort_helper more clean. If it is 100% certain either the <code>if</code> or <code>if else</code> is true, it would be possible to just make the <code>if else</code> statement an <code>else</code> statement.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:11:26.837",
"Id": "260018",
"ParentId": "260010",
"Score": "3"
}
},
{
"body": "<h1>Avoid code duplication</h1>\n<p>Your code is more verbose than necessary, because you are repeating a lot of things unnecessarily, or write things in a more complex way than necessary. For example:</p>\n<pre><code>(index + (index + length)) / 2\n</code></pre>\n<p>This looks really weird, and is actually equivalent to:</p>\n<pre><code>index + length / 2\n</code></pre>\n<p>Which makes much more sense. Even with that change, that expression is used a lot in the code, so it's best to give it a name:</p>\n<pre><code>uint32_t middle = index + length / 2;\n</code></pre>\n<p>You also duplicated a call to <code>mergesort_helper()</code> in order to handle odd and even cases of <code>length</code>. However, you don't have to if you write it like so:</p>\n<pre><code>uint32_t middle = index + length / 2;\nuint32_t end = index + length;\n\nmergesort_helper(array, index, middle - index, size_element, compare, storage);\nmergesort_helper(array, middle, end - middle, size_element, compare, storage);\n</code></pre>\n<p>You might also want to consider renaming <code>index</code> to <code>start</code>.</p>\n<h1>Use <code>const</code> for pointer arguments in <code>compare()</code></h1>\n<p>Since the function <code>compare()</code> should not modify the elements it is comparing, the arguments should be pointers to <code>const</code>:</p>\n<pre><code>int32_t compare(const void *ptr1, const void *ptr2) {\n const int32_t *temp_ptr1 = ptr1;\n const int32_t *temp_ptr2 = ptr2;\n ...\n}\n</code></pre>\n<h1>Optimizing the <code>while</code>-loop</h1>\n<p>There are a few minor changes that can be made to speed up the <code>while</code>-loop a little bit. First, calling <code>compare()</code> is probably going to be the most expensive operation, so you would want to avoid calling it if possible. Rearrange the order in which you check things to make use of <a href=\"https://en.wikipedia.org/wiki/Short-circuit_evaluation\" rel=\"noreferrer\">short-circuiting</a>:</p>\n<pre><code>if(i < middle && (j >= end || compare(...)))\n</code></pre>\n<p>In the above, <code>compare()</code> will only be called if <code>i < middle</code> is <code>true</code> and <code>j >= end</code> is <code>false</code>.</p>\n<p>Another possible optimization is realizing that if <code>i >= middle || j >= end</code>, you know you only need to copy the remainder of one side of the midpoint. Instead of doing that element by element, you could do that in one large <code>memcpy()</code>. It also simplifies the <code>if</code>-statements in the <code>while</code>-loop, like so:</p>\n<pre><code>while (i < middle && j < end) {\n if (compare(array + i * size_element, array + j * size_element) <= 0) {\n memcpy(storage + k * size_element, array + i * size_element, size_element);\n i++;\n } else {\n memcpy(storage + k * size_element, array + j * size_element, size_element);\n j++;\n }\n\n k++;\n}\n\n/* Copy the remainder */\nif (i < middle) {\n memcpy(storage + k * size_element, array + i * size_element, size_element * (middle - i));\n} else {\n memcpy(storage + k * size_element, array + j * size_element, size_element * (end - j));\n}\n</code></pre>\n<p>The above has also the advantage that <code>compare()</code> is only called once every iteration, whereas in your original code it could have been called twice.</p>\n<h1>Avoid <code>void</code> pointer arithmetic</h1>\n<p>Lau G mentioned void pointers, and indeed doing <a href=\"https://stackoverflow.com/questions/3523145/pointer-arithmetic-for-void-pointer-in-c\">arithmetic on <code>void</code> pointers is illegal</a>. The simple workaround is to cast it to a <code>char *</code> first:</p>\n<pre><code>static void mergesort_helper(void *array_ptr, ...)\n{\n char *array = array_ptr;\n ...\n</code></pre>\n<p>To catch these sort of issues, enable strict compiler warnings. For GCC and Clang, use <code>-Wall -pedantic</code>. Fix all the warnings the compiler produces.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:49:25.343",
"Id": "513170",
"Score": "1",
"body": "Any reason not to use `const void * const` type arguments to compare()?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T17:00:38.100",
"Id": "513171",
"Score": "1",
"body": "@spuck The only argument I can think of to not use that would be that adding `const` to everything makes the code more verbose. The chance of accidentily changing the pointer itself is small, and making the address `const` does not help the compiler produce better code, whereas making the value pointed to `const` does allow better code to be generated and it protects the caller from mistakes inside `compare()`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T13:34:37.497",
"Id": "513246",
"Score": "1",
"body": "@G.Sliepen More to the point, it doesn't matter if it changes the pointer itself, since that copy of the pointer is local to `compare`. Changing the local copy will not change the copy in `mergesort_helper`. Whereas changing the value it points to would."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:15:56.293",
"Id": "260020",
"ParentId": "260010",
"Score": "11"
}
},
{
"body": "<h1>Interface</h1>\n<p>A more appropriate type for <code>length</code> would be <code>size_t</code>. And I'd expect the <code>compare</code> argument to be a function returning plain <code>int</code>, and accepting pointers to <code>const void</code>.</p>\n<h1>Test program</h1>\n<p>The test program could be improved with the addition of a <code>is_sorted()</code> function to confirm the result and return the appropriate success/failure value. I would recommend saving the repeated calculation of array length into a variable:</p>\n<pre><code>const size_t length = sizeof array / sizeof array[0];\n</code></pre>\n<p>I suggest reducing the scope of <code>i</code> to just the loops:</p>\n<pre><code>for (size_t i = 0; i < length; ++i)\n</code></pre>\n<h1>Comparator</h1>\n<p>We don't need to declare and assign separately, and we don't need to write a cast to convert from <code>void*</code>:</p>\n<blockquote>\n<pre><code> int32_t *temp_ptr1, *temp_ptr2;\n temp_ptr1 = (int32_t *)ptr1;\n temp_ptr2 = (int32_t *)ptr2;\n</code></pre>\n</blockquote>\n<p>I would write that as:</p>\n<pre><code> int32_t const *a = ptr1;\n int32_t const *b = ptr2;\n</code></pre>\n<p>I took the liberty to use shorter and more distinct names, which are easier to tell apart where they are used.</p>\n<p>There's a well-known trick for returning -1, 0 or +1 from comparisons, relying on the fact that boolean values are 0 and 1:</p>\n<pre><code> return (*a > *b) - (*a < *b);\n</code></pre>\n<h1>Helper function</h1>\n<p>Again, reduce the scope of variables, and declare them where they are assigned, to reduce chance of using uninitialised values.</p>\n<p>We have a repeated calculation of <code>(index + (index + length)) / 2</code>. Not only could this be given a name, but we can remove the error caused when the sum is large enough to overflow:</p>\n<pre><code>const size_t mid_index = index + length / 2;\n</code></pre>\n<p>We have a lot of invalid pointer arithmetic such as <code>array + i * size_element</code>. Because <code>array</code> is pointer to void, addition is not defined - we probably want to change the argument's type to <code>char*</code>. Similarly, <code>storage</code> should also be <code>char*</code>.</p>\n<h1>Sort function</h1>\n<p>We allocate memory, but blindly continue when <code>malloc()</code> returns a null pointer, leading to Undefined Behaviour. Don't do that!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:17:46.237",
"Id": "513164",
"Score": "0",
"body": "If in the interface you saw \"void const *ptr\" instead of \"const void *ptr\" would that also be fine as both produce the same result of the data being const right? Which syntax do you recommend?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:22:03.137",
"Id": "513165",
"Score": "1",
"body": "Either is fine - but try to stay consistent! FWIW, the C Standard writes `const` first."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:32:42.983",
"Id": "260022",
"ParentId": "260010",
"Score": "4"
}
},
{
"body": "<ol>\n<li><p>Keep your includes ordered for maintainability and shorter diffs.<br />\nThe separate sorted groups should be in order: This files header (first to ensure it remains self-contained), external libraries (standard and additional), this project's headers.</p>\n<pre><code>#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n</code></pre>\n</li>\n<li><p>There are many ways to represent an array-slice, but fundamentally you only need a pointer to the first element, and the count. The first element of the underlying array, if you even know it, is of no interest at all.</p>\n</li>\n<li><p>If the only way to get to some memory is by a function-argument, marking that <a href=\"//en.cppreference.com/w/c/language/restrict\" rel=\"nofollow noreferrer\"><code>restrict</code></a> allows better optimization and is good documentation.</p>\n</li>\n<li><p>Instead of special-casing remainder / no remainder when determining half the count, just subtract the range handled from the whole. It's less error-prone.</p>\n</li>\n<li><p>Your code for merging is over-complicated because you don't handle all the rest at once when one of the sorted sequences runs empty. That's also inefficient.</p>\n</li>\n<li><p>You only need half the scratch-space if you move the left sequence out before merging to the destination, instead of merging in the scratch-space and copying the result back.</p>\n</li>\n<li><p>There is a type in C dedicated for object-size and thus also array-indices: <code>size_t</code>.<br />\nUse it where appropriate.</p>\n</li>\n<li><p><code>void*</code>-arithmetic (assuming <code>sizeof(void) == 1</code>) is a gcc extension. There is no reason to use it as you could just use a <code>char*</code> instead and be strictly conformant.</p>\n</li>\n<li><p>Comparison-functions in C traditionally return <code>int</code>, the significance being smaller, equal, or bigger to zero. So, why would you ever consider anything else?</p>\n</li>\n<li><p>If a function should not modify arguments passed by pointer, let the type reflect it. Const-correctness allows the compiler to help catch errors.</p>\n</li>\n<li><p>Consider adding a typedef to avoid repeating the comparator's type.</p>\n</li>\n<li><p>Even though zero is an invalid input for <code>mergesort_helper()</code>, I personally think reasoning is easier if the guard-clause reads <code>< 2</code> than <code>== 1</code>.</p>\n</li>\n<li><p>Avoid overly long lines. Horizontal scrolling kills readability and thus maintainability.</p>\n</li>\n<li><p>While mixing declarations and statements is strictly speaking not allowed before C99, everybody already implemented it already because it is so useful.</p>\n<p>Defer declaring a variable until you have the proper value to initialize it to. Don't initialize it to some arbitrary value, and don't leave it uninitialized if you can help it. That avoids errors and makes eases understanding.</p>\n</li>\n</ol>\n<pre><code>typedef int (*comparator)(const void*, const void*);\n\nstatic void mergesort_helper(\n char* restrict p,\n size_t n,\n size_t s,\n comparator f,\n char* restrict scratch\n) {\n if (n < 2) return;\n const size_t mid = n / 2;\n mergesort_helper(p, mid, s, f, scratch);\n mergesort_helper(p + mid * s, n - mid, s, f, scratch);\n memcpy(scratch, p, mid * s);\n char *aa = scratch, *ab = scratch + mid * s, *ba = p + mid * s, *bb = p + n * s;\n while (aa != ab && ba != bb) {\n char** x = f(aa, ba) <= 0 ? &aa : &ba;\n memcpy(p, *x, s);\n p += s;\n *x += s;\n }\n memcpy(p, aa, ab - aa);\n}\n</code></pre>\n<ol start=\"15\">\n<li><p>While immediately returning if no elements should be sorted is enough to preserve the invariants of your code, I would also do so for a single element. That is, if I optimized for the trivial case at all, which is a pessimization of the far more important common case. Thanks to changing the guard-clause in <code>mergesort_helper()</code> and thus its invariants, doing so is no longer needed.</p>\n</li>\n<li><p>You really should handle insufficient memory, if only by calling <code>abort()</code>.</p>\n</li>\n<li><p>As <code>mergesort()</code> is the entry-point, I would set a few <code>assert()</code>s for sanity-testing during development.</p>\n</li>\n</ol>\n<pre><code>/*\n p - array to be sorted\n n - number of elements\n s - size of each element\n f - comparator\n*/\nvoid mergesort(void * restrict p, size_t n, size_t s, comparator f) {\n assert(s && n <= (size_t)-1 / s && (!n || (f && p)));\n void* scratch = malloc(n / 2 * s);\n if (!scratch && n / 2) {\n fprintf(stderr, "malloc() failed for mergesort().\\n");\n abort();\n }\n mergesort_helper(p, n, s, f, scratch);\n free(scratch);\n}\n</code></pre>\n<ol start=\"18\">\n<li><p>There is a simpler idiomatic way to define three-way-comparison even if simply subtracting doesn't fit.</p>\n</li>\n<li><p>Do not cast from or to <code>void*</code>. Implicit conversions work and are less error-prone.</p>\n</li>\n</ol>\n<pre><code>static int compare(const void* pa, const void* pb) {\n const int32_t *a = pa, *b = pb;\n return (*a > *b) - (*a < *b);\n}\n</code></pre>\n<ol start=\"20\">\n<li><p>You have exactly one test-case, and that for the typical case. Automate it (by adding a corresponding <code>is_sorted()</code> tester), and try with one and zero elements to at least test the obvious corner cases.</p>\n</li>\n<li><p>Using the wrong format-specifier for <a href=\"//en.cppreference.com/w/c/io/fprintf\" rel=\"nofollow noreferrer\"><code>printf</code></a> is a bug.</p>\n</li>\n<li><p><code>return 0;</code> is implicit for <code>main()</code> since C99.</p>\n</li>\n<li><p>Return an error if your program ends with a detected failure.</p>\n</li>\n</ol>\n<pre><code>int is_sorted(const void * restrict p, size_t n, size_t s, comparator f) {\n assert(s && n <= (size_t)-1 / s && (!n || (f && p)));\n if (n--)\n for (const char* q = p; n--; q += s)\n if (f(q, q + s) > 0)\n return 0;\n return 1;\n}\n\nstatic int test(int32_t array[], size_t n) {\n printf("%zu: ", n);\n for (size_t i = 0; i < n; ++i)\n printf("%" PRId32 " ", array[i]);\n printf("\\n");\n\n mergesort(array, n, sizeof *array, &compare);\n\n int res = is_sorted(array, n, sizeof *array, &compare);\n\n printf(res ? "OK: " : "FAIL: ");\n for (size_t i = 0; i < n; ++i)\n printf("%" PRId32 " ", array[i]);\n printf("\\n");\n\n return res;\n}\n\nint main() {\n int32_t array[] = {6, 4, 3, 2, 7, -100, 1, 0, 5, 8, -100, 8};\n\n return !test(array, sizeof array / sizeof *array)\n || !test(array, 1)\n || !test(array, 0)\n || !test(0, 0);\n}\n</code></pre>\n<p>See it all coming together <a href=\"//coliru.stacked-crooked.com/a/c1928def9a3cec5a\" rel=\"nofollow noreferrer\">live on coliru</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T19:16:32.947",
"Id": "513182",
"Score": "1",
"body": "Your code contains a LOT of one-letter variables. Some are OK (like `n` and `i`, and `a` and `b` in the comparison function), but I would recommend giving them better names so it is clear what they stand for."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T03:43:22.227",
"Id": "513212",
"Score": "0",
"body": "Is it okay to use asserts in \"real code\" or should those be avoided when not testing the program?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T06:31:36.810",
"Id": "513223",
"Score": "1",
"body": "Do you mean in a release? There it will be compiled to nothing. In a debug build? There it should fire. Both are \"real code\"."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T18:29:56.973",
"Id": "260044",
"ParentId": "260010",
"Score": "3"
}
},
{
"body": "<p>TLDR: in order to improve performance while keeping it simple, switch to insertion sort for small arrays.</p>\n<p>Congratulations on choosing mergesort! This is a great choice. It is very elegant, stable and can achieve great performance without the code turning in an horrible mess as is typically the case with quicksort.</p>\n<p>There are many answers already so I will chose a different angle.</p>\n<p>I do not know what kind of improvement you are looking for, but if performance is a concern, the cost of recursion is going to be prohibitive for small (sub-)arrays.</p>\n<p>One good way to fix this is to test for the size of the array and use insertion sort instead if the number of entries is below a limit. Start with a limit of 8 and then try other values later if you are into performance tuning.</p>\n<p>You could alternatively write a non-recursive version of mergesort. All you would achieve is that the code would be less readable, though. Don't do it! And insertion sorts makes fewer comparisons than merge sort on smalls arrays anyway.</p>\n<p>Another more complex way would be to investigate timsort. Timsort is the state of the art of adaptative merge algorithms nowadays. Many language runtimes implement the standard sorting algorithm as timsort. The complexity of the code increase greatly, though.</p>\n<p>Finally, if you enjoy experimentation, here is a last idea. You could figure out that internal sorts only exist nowadays in the special case where the array is small enough to fit in the CPU's level 1 cache. In all other cases, what you are doing is actually an external sort. And guess which algorithm shines particularly for this purpose? Yes, right, it is indeed mergesort! Thus you could try to implement a cache-aware k-way mergesort or a cache-aware timsort. This would some extra layers of complexity as you would need to write some architecture-dependent code. But who knows what results such an experiment would yield?</p>\n<p>Another way to improve performance for large item sizes could be to check for the size of elements and apply mergesort to an array of pointers to the elements instead of the array of elements itself. As I recall, the implementation of qsort() in glibc does this.</p>\n<p>Anyway, these are only a few ideas from the top of my head. Do what suits you best and have fun!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T10:11:36.733",
"Id": "260067",
"ParentId": "260010",
"Score": "3"
}
},
{
"body": "<p>Create simple code for simple tasks don't overcomplicate it, and better name your functions</p>\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n \nvoid merge (int *a, int n, int m) {\n int i, j, k;\n int *x = malloc(n * sizeof (int));\n for (i = 0, j = m, k = 0; k < n; k++) {\n x[k] = j == n ? a[i++]\n : i == m ? a[j++]\n : a[j] < a[i] ? a[j++]\n : a[i++];\n }\n for (i = 0; i < n; i++) {\n a[i] = x[i];\n }\n free(x);\n}\n \nvoid merge_sort (int *a, int n) {\n if (n < 2)\n return;\n int m = n / 2;\n merge_sort(a, m);\n merge_sort(a + m, n - m);\n merge(a, n, m);\n}\n</code></pre>\n<p>Reference code <a href=\"http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#C\" rel=\"nofollow noreferrer\">http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#C</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T23:47:37.460",
"Id": "260093",
"ParentId": "260010",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T04:11:00.537",
"Id": "260010",
"Score": "11",
"Tags": [
"c",
"sorting",
"mergesort"
],
"Title": "Mergesort Criticism in C"
}
|
260010
|
<p>I am trying to filter the events table to get ongoing events and complete events, but pycharm keeps underlining my code because of duplicated code. How do I prevent for loop code duplicates on the two functions below?
Better yet, how do I optimally refactor these two functions?
Thanks</p>
<pre><code>
def get_ongoing_events():
ongoing_events = Events.objects.filter(
Q(event_begin_datetime__lte=current_time),
Q(event_end_datetime__gt=current_time),
)
for event in ongoing_events:
event.event_status = 'ongoing'
event.save()
event.venue.status = 'booked'
event.venue.save()
reserve_data = dict()
reserve_data["sensor_id"] = event.venue.sensor_id
reserve_data["status"] = event.venue.status
return reserve_data
def get_complete_reservation():
"""
Update reservations and sensors
:return:
"""
completed_events = Events.objects.filter(
Q(reservation_begin_datetime__lt=current_time),
Q(reservation_end_datetime__lte=current_time),
)
for event in completed_events:
event.reservation_status ='complete'
event.save()
event.venue.status = 'free'
event.venue.save()
reserve_data = dict()
reserve_data["sensor_id"] = event.venue.sensor_id
reserve_data["status"] = event.venue.status
return reserve_data
<span class="math-container">```</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:30:44.427",
"Id": "513100",
"Score": "5",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:30:56.687",
"Id": "513101",
"Score": "6",
"body": "Please [**follow the tour**](https://CodeReview.StackExchange.com/tour), and read [**\"What topics can I ask about here?\"**](https://CodeReview.StackExchange.com/help/on-topic), [**\"How do I ask a good question?\"**](https://CodeReview.StackExchange.com/help/how-to-ask) and [**\"What types of questions should I avoid asking?\"**](https://CodeReview.StackExchange.com/help/dont-ask)."
}
] |
[
{
"body": "<h1>Factoring duplication out</h1>\n<p>Whenever I have (near-)duplicate code, what I do is take a look at the repeated code. The parts that change ever so slightly are going to be controlled with arguments to functions and etc, whereas the parts that remain the same will just be left more-or-less as-is.</p>\n<p>Having said that, here is what I see:</p>\n<ul>\n<li>the queries being used change, so those are function arguments;</li>\n<li>the attributes of the event being updated change, so those are function arguments;</li>\n<li>the final dict being generated is the same, so we leave it the same.</li>\n</ul>\n<p>From your code alone, here is a suggested modification:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def filter_and_update_events(Qs, event_changes, venue_changes):\n for event in Events.objects.filter(*Qs)\n for attr, new_value in event_changes.items():\n setattr(event, attr, new_value)\n event.save()\n for attr, new_value in venue_changes.items():\n setattr(event.venue, attr, new_value)\n event.venue.save()\n\n reserve_data = dict()\n reserve_data["sensor_id"] = event.venue.sensor_id\n reserve_data["status"] = event.venue.status\n return reserve_data\n\ndef get_ongoing_events():\n return filter_and_update_events(\n [\n Q(event_begin_datetime__lte=current_time),\n Q(event_end_datetime__gt=current_time),\n ],\n {"event_status": "ongoing"},\n {"status": "booked"},\n )\n\ndef get_complete_reservation():\n """\n Update reservations and sensors\n :return:\n """\n return filter_and_update_events(\n [\n Q(reservation_begin_datetime__lt=current_time),\n Q(reservation_end_datetime__lte=current_time),\n ],\n {"reservation_status": "complete"},\n {"status": "free"},\n )\n</code></pre>\n<p>Notice that I used <code>setattr</code> <a href=\"https://docs.python.org/3/library/functions.html#setattr\" rel=\"nofollow noreferrer\">docs</a> to set the attributes of the event and the venue.\nAlso notice that my new function has a bit of duplication in the loops, but that is the easiest way to deal with the fact that <code>venue</code> is inside <code>event</code> and there is no obvious way to use <code>setattr</code> to deal with the nesting.\nIf you need to expand your function to update even more things inside <code>event</code>, then I would also recommend creating a helper function that takes an <code>event</code> and a "setting name" and sets it, so that <code>filter_and_update_events</code> doesn't need to take one dictionary per object inside <code>event</code>.</p>\n<p>Does this make sense?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T12:18:11.877",
"Id": "513132",
"Score": "0",
"body": "If there is already an answer, it might be better not to edit the question, especially the code in the question since everyone needs to be able to see the code as the first reviewer saw it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T08:04:12.620",
"Id": "513229",
"Score": "0",
"body": "This makes sense and works like a charm, thankyou @RGS, just add .index() during filter so as to avoid the unpacking elements error. `for attr, new_value in event_changes.index():`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T08:37:08.707",
"Id": "513231",
"Score": "1",
"body": "@pythonista woops that slipped, I meant `for attr, new_value in event_changes.items():`, and similarly for the venues, sorry for that. Answer has been fixed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T11:30:43.663",
"Id": "513459",
"Score": "1",
"body": "oops meant .items(), thanks for the fix"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T07:10:21.620",
"Id": "260014",
"ParentId": "260012",
"Score": "1"
}
},
{
"body": "<p>although your code has duplication, but it is also modular. Depending on code functionality, you can trade-off this modularity with less duplication.</p>\n<p>how about merging the 2 functions and returning two lists like as follows? this will remove code duplication, however, the trade-off would be less code-modularity.</p>\n<p>Also, rather than using a dictionary to store booked and free sensor ids, you can just use lists with descriptive names as I have done.</p>\n<pre><code>def get_booked_and_free_events():\nongoing_events = Events.objects.filter(\n Q(event_begin_datetime__lte=current_time),\n Q(event_end_datetime__gt=current_time),\n )\ncompleted_events = Events.objects.filter(\n Q(reservation_begin_datetime__lt=current_time),\n Q(reservation_end_datetime__lte=current_time),\n )\nfor event in ongoing_events:\n event.event_status = 'ongoing'\n event.save()\n\n event.venue.status = 'booked'\n event.venue.save()\n\n booked_sensors = []\n booked_sensors.append(event.venue.sensor_id)\n\nfor event in completed_events:\n event.reservation_status ='complete'\n event.save()\n\n event.venue.status = 'free'\n event.venue.save()\n\n free_sensors = []\n free_sensors.append(event.venue.sensor_id)\n \nreturn booked_sensors, free_sensors\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:15:53.543",
"Id": "260019",
"ParentId": "260012",
"Score": "-1"
}
},
{
"body": "<p>Duplication could be a non-problem, but is often an alarm that something is misplaced.</p>\n<p>This repeated piece of code</p>\n<pre><code> for event in completed_events:\n event.reservation_status = 'complete'\n event.save()\n\n event.venue.status = 'free'\n event.venue.save()\n reserve_data = dict()\n reserve_data["sensor_id"] = event.venue.sensor_id\n reserve_data["status"] = event.venue.status\n return reserve_data\n</code></pre>\n<p>Is problematic because the action to be taken when an even is ongoing/reserved/etc should be performed by the event itself; that's why the <code>status</code> and the <code>venue</code> objects are inside the event, because they are in its domain. I see that you already have a <code>Events</code> class, maybe there is also an <code>Event</code> class?. I suggest you to have a Event class that would do something like this</p>\n<pre><code># Perhaps this constants could be stored in the Events class?\nONGOING = 'ongoing'\nCOMPLETE = 'complete'\nVENUES_STATUS = {\n ONGOING: 'booked',\n COMPLETE: 'free'\n}\n\n\n\nclass Event:\n def trigger(self, new_status, save=True):\n if new_status == ONGOING:\n self.event_status = ONGOING\n # What about reservation_status ?\n elif new_status == COMPLETE:\n self.reservation_status = COMPLETE\n # What about event_status ?\n else:\n pass # you may have other statuses here?\n if new_status in VENUES_STATUS:\n self.venue.status = VENUES_STATUS[new_status]\n if save:\n self.save()\n self.venue.save()\n\n def data(self): # this could be moved to the Venue class, also a better name can be definitely found.\n return {\n "sensor_id": self.venue.sensor_id,\n "status": self.venue.status\n }\n</code></pre>\n<p>(Comments are more for you than the real code comments).</p>\n<p>Having that the loop becomes (Here I'm guessing what you're trying to collect, because in your code you have a return inside the for loop; that would always return the first event data.)</p>\n<pre><code>def get_complete_reservation():\n completed_events = Events.objects.filter(\n Q(reservation_begin_datetime__lt=current_time),\n Q(reservation_end_datetime__lte=current_time),\n )\n data = []\n\n for event in completed_events:\n event.trigger(ONGOING)\n data.append(event.data())\n return data\n\n</code></pre>\n<p>The name of the function doesn't really say what you're doing, your not just "getting" the events, you are triggering a transaction of status from one to another, so I would rewrite that like this:</p>\n<pre><code>def trigger_new_status(selected_events, new_status):\n for event in selected_events:\n event.trigger(new_status)\n return [event.data() for event in selected_events]\n\n\ndef main():\n completed_events = Events.objects.filter(\n Q(reservation_begin_datetime__lt=current_time),\n Q(reservation_end_datetime__lte=current_time),\n )\n ongoing_events = Events.objects.filter(\n Q(event_begin_datetime__lte=current_time),\n Q(event_end_datetime__gt=current_time),\n )\n completed_events_data = trigger_new_status(completed_events, COMPLETE)\n ongoing_events_data = trigger_new_status(ongoing_events, ONGOING)\n\n</code></pre>\n<p>Another thing: if you have the possibility to modify the <code>filter</code> method, it would be better to use a functional approach:</p>\n<pre><code>def filter(self, filter_function):\n return [event for event in self.events if filter_function(event)]\n</code></pre>\n<p>and that would be used like</p>\n<pre><code>events.filter(lambda e: e.reservation_end < today and e.reservation_begin> today)\n\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T10:48:11.080",
"Id": "260024",
"ParentId": "260012",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "260014",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T06:42:13.970",
"Id": "260012",
"Score": "1",
"Tags": [
"python-3.x"
],
"Title": "I am trying to filter a queryset based on dates, I keep getting a duplicate error on the for loops,How do I refactor these code to remove duplicates?"
}
|
260012
|
<p>I have the problem, my methods become slower and slower after many data. My methods can generate 100 rows with 20 columns around 1-3s, but after that my methods become slower and slower.</p>
<p>And for another information, i'm still using NPOI ver 2.4.1 in ASP.NET Web Form (Target framework 4.6.1)</p>
<p>Here's my code:</p>
<p>this is the extensions for generating the excel</p>
<pre><code>public static class ExcelHelper
{
public static void GenerateReportExcel<T>(this IWorkbook workbook, List<T> dataList, string sheetName = "Sheet1")
where T : IReportModel
{
try
{
// Create Sheet
var sheet = workbook.CreateSheet(sheetName);
// Set Header Style
var headerCellStyle = workbook.CreateCellStyle();
headerCellStyle.BorderTop = BorderStyle.Thin;
headerCellStyle.BorderBottom = BorderStyle.Thin;
headerCellStyle.BorderLeft = BorderStyle.Thin;
headerCellStyle.BorderRight = BorderStyle.Thin;
var headerFontStyle = workbook.CreateFont();
headerFontStyle.Boldweight = (short)FontBoldWeight.Bold;
headerCellStyle.SetFont(headerFontStyle);
headerCellStyle.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
headerCellStyle.FillPattern = FillPattern.SolidForeground;
// Generate Header Row
var props = typeof(T).GetProperties();
var headerRow = sheet.CreateRow(0);
int columnIndex = 0;
foreach (var prop in props.Where(p => p.GetSetMethod() != null).OrderBy(x => x.GetAttributeValue<ExcelColumnAttribute, int>(y => y.Order)))
{
var name = prop.GetAttributeValue<ExcelColumnAttribute, string>(x => x.Name);
if (!string.IsNullOrEmpty(name))
{
headerRow.CreateCell(columnIndex).SetValue(workbook, name);
headerRow.Cells[columnIndex].CellStyle = headerCellStyle;
sheet.AutoSizeColumn(columnIndex);
columnIndex++;
}
}
// Generate Item Row
if (dataList != null && dataList.Any())
{
int rowNumber = 1;
foreach (var item in dataList)
{
item.RowNumber = rowNumber;
var row = sheet.CreateRow(rowNumber);
columnIndex = 0;
foreach (var prop in props.Where(p => p.GetSetMethod() != null).OrderBy(x => x.GetAttributeValue<ExcelColumnAttribute, int>(y => y.Order)))
{
var name = prop.GetAttributeValue<ExcelColumnAttribute, string>(x => x.Name);
if (!string.IsNullOrEmpty(name))
{
var value = prop.GetValue(item);
if (value != null)
{
row.CreateCell(columnIndex).SetValue(workbook, value);
sheet.AutoSizeColumn(columnIndex);
}
columnIndex++;
}
}
rowNumber++;
}
}
}
finally
{
ExcelExtensions.ClearStyles();
}
}
}
</code></pre>
<p>this is the extensions to help set value to the cell</p>
<pre><code>public static class ExcelExtensions
{
private static Dictionary<string, ICellStyle> cellStyles = new Dictionary<string, ICellStyle>();
public static void ClearStyles()
{
cellStyles.Clear();
}
public static void SetValue(this ICell cell, IWorkbook workbook, object value)
{
if (value != null)
{
var type = value.GetType();
if (type == typeof(bool))
{
var boolValue = Convert.ToBoolean(value);
cell.SetCellValue(boolValue);
cell.SetCellType(CellType.Boolean);
}
else if (type == typeof(int) || type == typeof(long))
{
var longValue = Convert.ToInt64(value);
cell.SetCellValue(longValue);
cell.SetCellType(CellType.Numeric);
cell.CellStyle = GetCellStyleForFormat(workbook, "#,##0");
}
else if (type == typeof(double) || type == typeof(decimal))
{
var doubleValue = Convert.ToDouble(value);
cell.SetCellValue(doubleValue);
cell.SetCellType(CellType.Numeric);
cell.CellStyle = GetCellStyleForFormat(workbook, "#,##0.00");
}
else if (type == typeof(DateTime) || type == typeof(DateTime?))
{
var dateValue = (DateTime?)value;
if (dateValue != null && dateValue != DateTime.MinValue)
{
cell.SetCellValue(dateValue.Value);
cell.CellStyle = GetCellStyleForFormat(workbook, "dd/MM/yyyy HH:mm:ss");
}
else
{
cell.SetCellValue("");
}
}
else
{
var stringValue = value.ToString();
cell.SetCellValue(stringValue);
cell.SetCellType(CellType.String);
}
}
}
private static ICellStyle GetCellStyleForFormat(IWorkbook workbook, string dataFormat)
{
if (!cellStyles.ContainsKey(dataFormat))
{
var style = workbook.CreateCellStyle();
// check if this is a built-in format
var builtinFormatId = HSSFDataFormat.GetBuiltinFormat(dataFormat);
if (builtinFormatId != -1)
{
style.DataFormat = builtinFormatId;
}
else
{
// not a built-in format, so create a new one
var newDataFormat = workbook.CreateDataFormat();
style.DataFormat = newDataFormat.GetFormat(dataFormat);
}
cellStyles[dataFormat] = style;
}
return cellStyles[dataFormat];
}
}
</code></pre>
<p>this is the Attribute to determine the column name and column index</p>
<pre><code>public class ExcelColumnAttribute : Attribute
{
public ExcelColumnAttribute(string name, int order)
{
Name = name;
Order = order;
}
public string Name { get; }
public int Order { get; }
}
</code></pre>
<p>and the last one is extensions to get attribute value</p>
<pre><code>public static class AttributeExtensions
{
public static TValue GetAttributeValue<TAttribute, TValue>(this PropertyInfo prop, Func<TAttribute, TValue> valueSelector)
where TAttribute : Attribute
{
var att = prop.GetCustomAttributes(typeof(TAttribute), false).FirstOrDefault() as TAttribute;
if (att != null)
{
return valueSelector(att);
}
return default(TValue);
}
}
</code></pre>
<p>I put stopwatch each 100 data in Generate Item Row loop (because I think the problem in this loop), here's the result:</p>
<pre><code>Row 100 : 2980ms
Row 200 : 8283ms
Row 300 : 13836ms
Row 400 : 19654ms
Row 500 : 25237ms
Row 600 : 30673ms
Row 700 : 37554ms
Row 800 : 42548ms
Row 900 : 47646ms
Row 1000 : 52820ms
Row 1100 : 59280ms
</code></pre>
<p>Thanks in advance.</p>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:40:25.053",
"Id": "513121",
"Score": "3",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:43:41.330",
"Id": "513122",
"Score": "0",
"body": "@TobySpeight thank you for the information, i'll try to improve the question title."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T11:03:06.557",
"Id": "513126",
"Score": "0",
"body": "Could you provide a test case example?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T13:54:45.517",
"Id": "513142",
"Score": "0",
"body": "`props.Where(p => p.GetSetMethod() != null).OrderBy(x => x.GetAttributeValue<ExcelColumnAttribute, int>(y => y.Order))`, and `prop.GetAttributeValue<ExcelColumnAttribute, string>(x => x.Name)`, you could create dictionary/cache to prevent redundant enumerable and get attribute operation: `Dictionary<string, (PropertyInfo prop, ExcelColumnAttribute attr)>`. I saw couple of things that can be improved, but I suggest start from there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T02:11:41.680",
"Id": "513209",
"Score": "0",
"body": "@aepot I'm not exactly know how to test case example, but I put some stopwatch test for Generate Item Row loop. I already added in the description, is that enough?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T02:12:17.597",
"Id": "513210",
"Score": "0",
"body": "@MochYusup Thank you! I'll try again after editing that using dictionary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T07:31:39.443",
"Id": "513317",
"Score": "0",
"body": "Please explain in the English section of your question what your code is doing."
}
] |
[
{
"body": "<p>I already found the problem, in the generate item row loop here</p>\n<pre><code>// Generate Item Row\nif (dataList != null && dataList.Any())\n{\n int rowNumber = 1;\n foreach (var item in dataList)\n {\n item.RowNumber = rowNumber;\n var row = sheet.CreateRow(rowNumber);\n\n columnIndex = 0;\n foreach (var prop in props.Where(p => p.GetSetMethod() != null).OrderBy(x => x.GetAttributeValue<ExcelColumnAttribute, int>(y => y.Order)))\n {\n var name = prop.GetAttributeValue<ExcelColumnAttribute, string>(x => x.Name);\n if (!string.IsNullOrEmpty(name))\n {\n var value = prop.GetValue(item);\n if (value != null)\n {\n row.CreateCell(columnIndex).SetValue(workbook, value);\n sheet.AutoSizeColumn(columnIndex);\n }\n columnIndex++;\n }\n }\n\n rowNumber++;\n }\n}\n</code></pre>\n<p>this AutoSizeColumn is taking so much time.</p>\n<pre><code>sheet.AutoSizeColumn(columnIndex);\n</code></pre>\n<p>My Solution is complete the document first, and do <code>AutoSizeColumn</code> later with separate loop after the document is ready.</p>\n<p>Also thanks to @Moch Yusup, I'm using Dictionary for getting the attribute, It also increase the time.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T18:34:47.637",
"Id": "513272",
"Score": "0",
"body": "You could just wait until the document is complete and THEN autosize all or specific columns."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T02:14:30.043",
"Id": "513296",
"Score": "0",
"body": "@JeffC yes, that what I do. that's what I mean when I said move to another loop. I'm gonna edit the answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T02:21:00.123",
"Id": "513297",
"Score": "0",
"body": "You have `sheet.AutoSizeColumn(columnIndex);` in the deepest loop... that's the line I was talking about. I would move that out of the outermost loop."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T05:14:11.357",
"Id": "260060",
"ParentId": "260021",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T09:20:38.013",
"Id": "260021",
"Score": "0",
"Tags": [
"c#",
"performance",
"excel"
],
"Title": "Improvement for generating excel with many data"
}
|
260021
|
<p>Any suggestions on improving the speed of below code. My dictionary is rather large in fold of * 100000 and expected to grow larger every day.</p>
<p>I am open to completely new ideas or approaches to do the below operation.</p>
<pre><code>from pyxdameraulevenshtein import damerau_levenshtein_distance, normalized_damerau_levenshtein_distance
name = 'john doe'
word_dict = {
'john' : ['ID1','ID2', 'AB2' ,'AS1']
,'doe' : ['ID1','ID4', 'AB2' ,'AS6']
,'jahn' : ['ID3','ID2', 'AB2' ,'AS5']
}
# perform iteration on dictionary keys . compute and filter if damerau edit distance is less than 2
all_matches = []
for nWord in set(name.split()):
match = []
match += [(word,list(word_dict[word]), int((1-normalized_damerau_levenshtein_distance(nWord,word))* 100))\
for word in word_dict if damerau_levenshtein_distance(nWord,word) in [0,1,2]]
all_matches.append(match)
</code></pre>
|
[] |
[
{
"body": "<p>Take a look at <a href=\"https://en.wikipedia.org/wiki/BK-tree\" rel=\"nofollow noreferrer\">BKTrees</a>. <a href=\"http://nullwords.wordpress.com/2013/03/13/the-bk-tree-a-data-structure-for-spell-checking/\" rel=\"nofollow noreferrer\">Here</a> is a less technical description. There is a Python library on PyPI: <a href=\"https://pypi.org/project/pybktree/\" rel=\"nofollow noreferrer\">pybktree</a>.</p>\n<p>You create the BKTree once (once a day?) from the keys in the dictionary. Then run all the queries against the BKTree.</p>\n<p>It would look something like this untested code:</p>\n<pre><code>import pybktree\nfrom pyxdameraulevenshtein import damerau_levenshtein_distance\n\ntree = pybktree.BKTree(damerau_levenshtein_distance, word_dict.keys())\n\nall_matches = []\n\nfor target in set(name.split()):\n all_matches.extend(tree.find(target, MAX_DISTANCE))]\n</code></pre>\n<p><code>all_matches</code> would be a list of (distance, word) tuples.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-03T06:21:34.560",
"Id": "513784",
"Score": "0",
"body": "Thank you. This has helped me a lot . Any suggestions on how to store the tree structure ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-05-04T06:35:41.243",
"Id": "513862",
"Score": "0",
"body": "@abhilashDasari, you can use the `pickle` module from the standard library to save it to orload it from a file."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T07:01:51.837",
"Id": "260151",
"ParentId": "260023",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "260151",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T10:38:10.910",
"Id": "260023",
"Score": "0",
"Tags": [
"performance",
"python-3.x"
],
"Title": "perform fuzzy matching on a large set of dictionary keys"
}
|
260023
|
<p>I wrote a C++ program that merges two convex hulls in linear time.
The algorithm is based on <a href="http://cgm.cs.mcgill.ca/%7Egodfried/teaching/cg-projects/97/Plante/CompGeomProject-EPlante/algorithm.html" rel="nofollow noreferrer">http://cgm.cs.mcgill.ca/~godfried/teaching/cg-projects/97/Plante/CompGeomProject-EPlante/algorithm.html</a></p>
<p>Feel free to comment anything!</p>
<p>Point.h</p>
<pre><code>#include <cassert>
#include <cmath>
#include <iostream>
constexpr double tolerance = 1e-6;
struct Point2d {
double x = 0.0;
double y = 0.0;
Point2d() = default;
Point2d(double x, double y) : x {x}, y {y} {}
};
bool isClose(double x, double d) {
return std::fabs(x - d) < tolerance;
}
std::ostream& operator<<(std::ostream& os, const Point2d& point) {
os << '{' << point.x << ", " << point.y << '}';
return os;
}
Point2d operator+(const Point2d& lhs, const Point2d& rhs) {
return Point2d(lhs.x + rhs.x, lhs.y + rhs.y);
}
Point2d operator-(const Point2d& lhs, const Point2d& rhs) {
return Point2d(lhs.x - rhs.x, lhs.y - rhs.y);
}
bool operator==(const Point2d& lhs, const Point2d& rhs) {
return isClose(lhs.x, rhs.x) && isClose(lhs.y, rhs.y);
}
bool operator!=(const Point2d& lhs, const Point2d& rhs) {
return !(lhs == rhs);
}
bool operator<(const Point2d& lhs, const Point2d& rhs) {
return rhs.x - lhs.x > tolerance ||
(isClose(lhs.x, rhs.x) && rhs.y - lhs.y > tolerance);
}
bool operator>=(const Point2d& lhs, const Point2d& rhs) {
return !(lhs < rhs);
}
bool operator>(const Point2d& lhs, const Point2d& rhs) {
return lhs.x - rhs.x > tolerance ||
(isClose(lhs.x, rhs.x) && lhs.y - rhs.y > tolerance);
}
bool operator<=(const Point2d& lhs, const Point2d& rhs) {
return !(lhs > rhs);
}
double Dot(const Point2d& lhs, const Point2d& rhs) {
return lhs.x * rhs.x + lhs.y * rhs.y;
}
double Cross(const Point2d& lhs, const Point2d& rhs) {
return lhs.x * rhs.y - lhs.y * rhs.x;
}
static const Point2d orig {0.0, 0.0};
double dist(const Point2d& lhs, const Point2d& rhs = orig) {
return std::hypot(lhs.x - rhs.x, lhs.y - rhs.y);
}
double Cos(const Point2d& p1, const Point2d& p2) {
assert(p1 != orig && p2 != orig);
auto dot = Dot(p1, p2);
auto r = dist(p1) * dist(p2);
return dot / r;
}
double Orientation(const Point2d& p0, const Point2d& p1, const Point2d& p2) {
auto cross = Cross(p1 - p0, p2 - p0);
return cross;
}
</code></pre>
<p>ConvexHull.h</p>
<pre><code>#include "Point.h"
#include <algorithm>
#include <cassert>
#include <cmath>
#include <iostream>
#include <iterator>
#include <random>
#include <set>
#include <vector>
#include <ranges>
namespace sr = std::ranges;
enum class Order {
Before,
EqualSrc,
Between,
EqualDst,
After,
};
Order getOrder(const Point2d& p1, const Point2d& p2, const Point2d& q) {
assert(p1 != p2);
if (q == p1) {
return Order::EqualSrc;
} else if (q == p2) {
return Order::EqualDst;
}
if (!isClose(p1.x, p2.x)) {
if (p2.x - p1.x > tolerance) { // p1 - p2
if (p1.x - q.x > tolerance) { // q - p1 - p2
return Order::Before;
} else if (p2.x - q.x > tolerance) { // p1 - q - p2
return Order::Between;
} else { // p1 - p2 - q
return Order::After;
}
} else { // p2 - p1
if (q.x - p1.x > tolerance) { // p2 - p1 - q
return Order::Before;
} else if (q.x - p2.x > tolerance) { // p2 - q - p1
return Order::Between;
} else { // q - p2 - p1
return Order::After;
}
}
} else {
if (p2.y - p1.y > tolerance) { // p1 - p2
if (p1.y - q.y > tolerance) { // q - p1 - p2
return Order::Before;
} else if (p2.y - q.y > tolerance) { // p1 - q - p2
return Order::Between;
} else { // p1 - p2 - q
return Order::After;
}
} else { // p2 - p1
if (q.y - p1.y > tolerance) { // p2 - p1 - q
return Order::Before;
} else if (q.y - p2.y > tolerance) { // p2 - q - p1
return Order::Between;
} else { // q - p2 - p1
return Order::After;
}
}
}
}
std::vector<Point2d> ConvexHullAdd(std::vector<Point2d>& CH, const Point2d& p) {
if (CH.empty()) {
CH.push_back(p);
return CH;
} else if (CH.size() == 1) {
if (CH[0] != p) {
CH.push_back(p);
}
return CH;
} else if (CH.size() == 2) {
const auto& p0 = CH[0];
const auto& p1 = CH[1];
auto cross = Cross(p1 - p0, p - p0);
if (isClose(cross, 0.0)) { // colinear
auto d1 = dist(p0, p);
auto d2 = dist(p1, p);
auto d3 = dist(p0, p1);
auto d = std::max({d1, d2, d3});
if (isClose(d, d1)) {
return std::vector<Point2d>{p0, p};
} else if (isClose(d, d2)) {
return std::vector<Point2d>{p1, p};
} else {
return std::vector<Point2d>{p0, p1};
}
} else if (cross > tolerance) { // left turn
return std::vector<Point2d>{p0, p, p1};
} else { // right turn
return std::vector<Point2d>{p0, p1, p};
}
}
// make clockwise convex hull
const std::size_t m = CH.size();
std::size_t i = 0;
// while right turn
while (true) {
if (i >= m) {
break;
}
auto cross = Cross(p - CH[i % m], CH[(i + 1) % m] - CH[i % m]);
if (isClose(cross, 0.0)) {
// special case: colinear
auto ord = getOrder(CH[i % m], CH[(i + 1) % m], p);
if (ord == Order::Before) {
CH[i % m] = p;
} else if (ord == Order::After) {
CH[(i + 1) % m] = p;
}
return CH;
} else if (cross > tolerance) {
i++;
} else {
break;
}
}
if (i == m) { // interior point
return CH;
}
if (i == 0) {
// first turn is left, turn back to where left turn begins
while (true) {
auto cross = Cross(p - CH[i % m], CH[(i + 1) % m] - CH[i % m]);
if (isClose(cross, 0.0)) {
// special case: colinear
auto ord = getOrder(CH[i % m], CH[(i + 1) % m], p);
if (ord == Order::Before) {
CH[i % m] = p;
} else if (ord == Order::After) {
CH[(i + 1) % m] = p;
}
return CH;
} else if (cross < -tolerance) {
i = (i + m - 1) % m;
} else {
break;
}
}
i = (i + 1) % m;
}
std::size_t j = (i + 1) % m;
// while left turn
while (true) {
auto cross = Cross(p - CH[j % m], CH[(j + 1) % m] - CH[j % m]);
if (isClose(cross, 0.0)) {
// special case: colinear
auto ord = getOrder(CH[j % m], CH[(j + 1) % m], p);
if (ord == Order::Before) {
CH[j % m] = p;
} else if (ord == Order::After) {
CH[(j + 1) % m] = p;
}
return CH;
} else if (cross < -tolerance) {
j = (j + 1) % m;
} else {
break;
}
}
// replace p_(i, j) with p
if (j < i) {
CH.erase(CH.begin() + i + 1, CH.end());
CH.push_back(p);
CH.erase(CH.begin(), CH.begin() + j);
} else if (j > i) {
CH.erase(CH.begin() + i + 1, CH.begin() + j);
CH.insert(CH.begin() + i + 1, p);
} else { // cannot happen
assert(0);
}
return CH;
}
using ColinearPair = std::pair<std::optional<Point2d>, std::optional<Point2d>>;
void UpdateColinearPair(ColinearPair& curr_minmax, const Point2d& new_min, const Point2d& new_max) {
auto& [curr_min, curr_max] = curr_minmax;
if (curr_min.has_value()) {
auto ord = getOrder(new_min, new_max, *curr_min);
if (ord != Order::Before) {
curr_min = new_min;
}
} else {
curr_min = new_min;
}
if (curr_max.has_value()) {
auto ord = getOrder(new_min, new_max, *curr_max);
if (ord != Order::After) {
curr_max = new_max;
}
} else {
curr_max = new_max;
}
}
void HandleColinearCase(ColinearPair& curr_minmax, const Point2d& p1, const Point2d& p2, const Point2d& q) {
auto ord = getOrder(p1, p2, q);
if (ord == Order::Before || ord == Order::EqualSrc) { // (q, p2)
UpdateColinearPair(curr_minmax, q, p2);
} else if (ord == Order::Between) { // (p1, p2)
UpdateColinearPair(curr_minmax, p1, p2);
} else if (ord == Order::EqualDst || ord == Order::After) { // (p1, q)
UpdateColinearPair(curr_minmax, p1, q);
} else { // cannot happen
assert(0);
}
}
std::vector<Point2d> MergeTwoConvexHulls(const std::vector<Point2d>& CH1, const std::vector<Point2d>& CH2) {
if (std::min(CH1.size(), CH2.size()) <= 2) { // base case: just do online update.
if (CH1.size() < CH2.size()) {
auto CH = CH2;
for (const auto& p : CH1) {
CH = ConvexHullAdd(CH, p);
}
return CH;
} else {
auto CH = CH1;
for (const auto& p : CH2) {
CH = ConvexHullAdd(CH, p);
}
return CH;
}
}
const std::size_t m = CH1.size();
const std::size_t n = CH2.size();
std::size_t start1 = std::distance(CH1.begin(), sr::min_element(CH1));
std::size_t start2 = std::distance(CH2.begin(), sr::min_element(CH2));
std::size_t i = start1;
std::size_t j = start2;
// compare angle with vertical axis to decide first edge vs vertex pair
enum class Edge {
CH1,
CH2,
};
Edge currEdge = (Cos(Point2d{0.0, 1.0}, CH1[(i + 1) % m] - CH1[i % m])
>= Cos(Point2d{0.0, 1.0}, CH2[(j + 1) % n] - CH2[j % n]))
? Edge::CH1 : Edge::CH2;
std::vector<Point2d> CH;
ColinearPair colinear_minmax;
while (i < start1 + m || j < start2 + n) {
const auto& p_i = CH1[i % m];
const auto& q_j = CH2[j % n];
const auto& p_i1 = CH1[(i + 1) % m];
const auto& q_j1 = CH2[(j + 1) % n];
if (currEdge == Edge::CH1) {
// compare p_i-p_(i+1) vs q_j
auto dir = Orientation(p_i, p_i1, q_j);
if (dir > tolerance) { // q_j is in the left side: add q_j
CH.push_back(q_j);
} else if (dir < -tolerance) { // q_j is in the right side: add p_i, p_(i+1)
CH.push_back(p_i);
CH.push_back(p_i1);
} else { // colinear: determine the order
HandleColinearCase(colinear_minmax, p_i, p_i1, q_j);
}
// choose one to advance
auto curr_edge = p_i1 - p_i;
const auto& p_i2 = CH1[(i + 2) % m];
auto next_edge_p = p_i2 - p_i1;
auto next_edge_q = q_j1 - q_j;
auto cos_p = Cos(curr_edge, next_edge_p);
auto cos_q = Cos(curr_edge, next_edge_q);
if (cos_p - cos_q > 0.0) { // advance p
i++;
} else { // advance q
currEdge = Edge::CH2;
i++;
}
if (isClose(std::max(cos_p, cos_q), 1.0)
&& colinear_minmax.first.has_value()) { // next edge is parallel with curr edge, and in fact colinear
// do nothing, keep colinear pairs
} else if (colinear_minmax.first.has_value()) {
// add this colinear pair to CH
CH.push_back(*colinear_minmax.first);
CH.push_back(*colinear_minmax.second);
colinear_minmax = {{}, {}}; // discard colinear pair
}
} else if (currEdge == Edge::CH2) {
// compare q_j-q_(j+1) vs p_i
auto dir = Orientation(q_j, q_j1, p_i);
if (dir > tolerance) { // p_i is in the left side: add p_i
CH.push_back(p_i);
} else if (dir < -tolerance) { // p_i is in the right side: add q_j, q_(j+1)
CH.push_back(q_j);
CH.push_back(q_j1);
} else { // colinear: determine the order
HandleColinearCase(colinear_minmax, q_j, q_j1, p_i);
}
// choose one to advance
auto curr_edge = q_j1 - q_j;
const auto& q_j2 = CH2[(j + 2) % n];
auto next_edge_p = p_i1 - p_i;
auto next_edge_q = q_j2 - q_j1;
auto cos_p = Cos(curr_edge, next_edge_p);
auto cos_q = Cos(curr_edge, next_edge_q);
if (cos_q - cos_p > 0.0) { // advance q
j++;
} else { // advance p
currEdge = Edge::CH1;
j++;
}
if (isClose(std::max(cos_p, cos_q), 1.0)
&& colinear_minmax.first.has_value()) { // next edge is parallel with curr edge, and in fact colinear
// do nothing, keep colinear pairs
} else if (colinear_minmax.first.has_value()) {
// add this colinear pair to CH
CH.push_back(*colinear_minmax.first);
CH.push_back(*colinear_minmax.second);
colinear_minmax = {{}, {}}; // discard colinear pair
}
} else { // cannot happen
assert(0);
}
}
CH.erase(std::unique(CH.begin(), CH.end()), CH.end());
if (CH.back() == CH.front()) {
CH.pop_back();
}
return CH;
}
</code></pre>
<p>Test code:</p>
<pre><code>#include "Point.h"
#include "ConvexHull.h"
#include <iostream>
#include <vector>
int main() {
// Test case 1: ◇□
{
std::vector<Point2d> CH1{{0.0, 0.0},
{2.0, 2.0},
{4.0, 0.0},
{2.0, -2.0}};
std::vector<Point2d> CH2{{5.0, -1.0},
{5.0, 1.0},
{7.0, 1.0},
{7.0, -1.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 2: □ □
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{4.0, 0.0},
{4.0, 2.0},
{6.0, 2.0},
{6.0, 0.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 3: □◇ overlapping
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{-0.5, 1.0},
{1.0, 2.5},
{2.5, 1.0},
{1.0, -0.5}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 4: □ inscribes ◇
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{-1.0, 1.0},
{1.0, 3.0},
{3.0, 1.0},
{1.0, -1.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 5: □□ overlapping
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{1.0, 0.0},
{1.0, 2.0},
{3.0, 2.0},
{3.0, 0.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 6: □ □ meets at corner
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{2.0, 2.0},
{2.0, 4.0},
{4.0, 4.0},
{4.0, 2.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 7: □ contains □, two □ intersects at edges
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{0.0, 0.0},
{0.0, 1.0},
{1.0, 1.0},
{1.0, 0.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 8: □ contains □ with no intersection
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{0.5, 0.5},
{0.5, 1.5},
{1.5, 1.5},
{1.5, 0.5}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 9: □ and interior point
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{1.0, 1.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 10: □ and exterior point
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{3.0, 1.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 11: □ and boundary point
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{2.0, 1.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 12: □ and exterior point colinear
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{2.0, 3.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 13: □ and exterior point colinear 2
{
std::vector<Point2d> CH1{{0.0, 0.0},
{0.0, 2.0},
{2.0, 2.0},
{2.0, 0.0}};
std::vector<Point2d> CH2{{2.0, -1.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
// Test case 14: regular octagon and ▷ that intersects at 4 points
{
auto sq2 = std::sqrt(2);
std::vector<Point2d> CH1{{-2.0, 0.0},
{-sq2, sq2},
{0.0, 2.0},
{sq2, sq2},
{2.0, 0.0},
{sq2, -sq2},
{0.0, -2.0},
{-sq2, -sq2}};
std::vector<Point2d> CH2{{-2.0, 4.0 - 4.0 * sq2},
{-2.0, -4.0 + 4.0 * sq2},
{2.0, 0.0}};
auto CH = MergeTwoConvexHulls(CH1, CH2);
std::cout << "Convex hull:\n";
for (const auto& p : CH) {
std::cout << p << '\n';
}
std::cout << '\n';
}
}
<span class="math-container">````</span>
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:06:45.540",
"Id": "513146",
"Score": "0",
"body": "Are you required to use a specific (non-current) version of C++? That is, if you can't use C++20 features we won't point out that you're doing things the old (hard, verbose) way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:14:57.217",
"Id": "513151",
"Score": "1",
"body": "@JDługosz No, the opposite is true: I prefer to use the most recent version of C++, because the codes I'm posting here is purely for fun and hobby projects, not for production code that should consider backward compatibility. If you see outdated practices in my code, then the reason is simply I don't know the best up-to-date practice. Pointing out that would be welcomed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:32:07.843",
"Id": "513155",
"Score": "0",
"body": "see https://en.cppreference.com/w/cpp/language/default_comparisons for a welcome improvement! See Number 4 on https://en.cppreference.com/w/cpp/language/overload_resolution#Call_to_an_overloaded_operator"
}
] |
[
{
"body": "<p>General impression when starting to read your code is that it's good! You're using <code>constexpr</code>, defining your constructors nicely, etc.</p>\n<h1>includes</h1>\n<p>Generally, I'll list standard includes <em>first</em>, and project-local includes at the end of the list.</p>\n<h1>scope and namespaces</h1>\n<p>Your point header is defining <code>tolerance</code> as a global variable, which may have nothing to do with other classes or even conflict with other headers. You ought to make it a member of the class, or make everything go inside a namespace.</p>\n<p>The various operators are more efficient when declared as "hidden friends" rather than non-members. This makes overload resolution faster and more well behaved when you have complex interactions.</p>\n<h1>operators</h1>\n<p>Normally, you would define <code>+</code> in terms of <code>+=</code> etc. You defined <code>+</code> only, rather than all related operations.</p>\n<p>All the relational operations can be defined, as of C++20, as a single <code>operator<=></code> function, and some of them can be automatically generated from others rather than you doing the exact same thing explicitly; in particular, <code>operator!=</code> will be automatically generated from <code>operator==</code>.</p>\n<h1>constexpr</h1>\n<p>You write</p>\n<pre><code>static const Point2d orig {0.0, 0.0};\n</code></pre>\n<p>(which is polluting the global namespace, as indicated in the first point above)\nwhy isn't it <code>constexpr</code>? Well, your constructors are not constexpr-friendly. There's no reason why it can't be! Same with many other functions; if the compiler can simplify things at compile-time, why not let it?!</p>\n<h1>constructors</h1>\n<p>User <a href=\"https://codereview.stackexchange.com/users/170106/indi\">indi</a> points out that if you leave off both constructors, you'll automatically get the same result anyway. Thanks to the inline initializers on the fields, the default constructor will apply those, and the newer updated rules for aggregate initializers means you can still use curly-brace syntax like a plain struct. I agree that for a class like this, that's perfectly OK, and would include a comment in lieu of the constructor indicating that it's meant to be used that way.</p>\n<h1>test code</h1>\n<p>Your test code is repeated, with only the actual input changing. Your block of work</p>\n<pre><code> auto CH = MergeTwoConvexHulls(CH1, CH2);\n std::cout << "Convex hull:\\n";\n for (const auto& p : CH) {\n std::cout << p << '\\n';\n }\n std::cout << '\\n';\n</code></pre>\n<p>should be a function call. You're even using the same variable names (<code>CH1</code> and <code>CH2</code>) in every case!</p>\n<h1>const</h1>\n<pre><code>std::vector<Point2d> ConvexHullAdd(std::vector<Point2d>& CH, const Point2d& p)\n</code></pre>\n<p>Is the function modifying <code>CH</code> as it works? I don't think it ought to, so define the parameter to be <code>const</code>. I noticed you have repetitive code, not just <code>i%m</code> (expensive division) being repeated but the subscripting of the input vector being repeated: <code>CH[i%m]</code>. Making things <code>const</code> will help ensure that the compiler can eliminate the repeated work automatically.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:42:00.483",
"Id": "513169",
"Score": "1",
"body": "Your first point is interesting, because I go the opposite way - include the project-specific libraries first, to help spot any hidden dependencies they may have."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T19:43:26.117",
"Id": "513187",
"Score": "1",
"body": "@TobySpeight That makes sense in testing code (and that’s how I do it: header-under-test first, usually), but it causes problems generally. Including std headers first, and in a specific order (usually alphabetical, with some tweaks sometimes (like maybe `<version>` first)) makes for better build consistency, and makes it easier to cache/precompile std headers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T19:59:52.357",
"Id": "513188",
"Score": "1",
"body": "“Well, your constructors are not constexpr-friendly. There's no reason why it can't be!” Rather than making the constructors `constexpr`, it would be better to just delete them. They’re unnecessary."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T13:56:14.267",
"Id": "513248",
"Score": "0",
"body": "@indi hmm, is an implicitly declared (or defaulted on first declaration) default constructor going to be `constexpr`? Yes, it is. But no such wording is present for the aggregate initializer, so the two-argument constructor (and by extension a vector of them that's all literal) won't be done at compile time."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T14:10:15.627",
"Id": "513249",
"Score": "0",
"body": "hmm again... I see https://en.cppreference.com/w/cpp/named_req/LiteralType indicates that it may be an aggregate. So the aggregate initializer would be allowed in a variable declared as `constexpr`."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T15:21:17.820",
"Id": "260032",
"ParentId": "260027",
"Score": "5"
}
},
{
"body": "<p>In addition to JDługosz's excellent answer, I'd like to add these remarks:</p>\n<h1>Use <code>switch</code>-statements where appropriate</h1>\n<p>Replace chains of <code>if</code>-<code>else</code>-statements that check the value of an <code>enum</code> type variable with a <code>switch</code>-statement. This usually makes the code more readable, and also has the advantage that the compiler can warn you if you don't explicitly handle all the possible values that variable can have. For example:</p>\n<pre><code>void HandleColinearCase(ColinearPair& curr_minmax, const Point2d& p1, const Point2d& p2, const Point2d& q) {\n switch (getOrder(p1, p2, q)) {\n case Order::Before:\n case Order::EqualSrc:\n UpdateColinearPair(curr_minmax, q, p2);\n break;\n case Order::Between;\n UpdateColinearPair(curr_minmax, p1, p2);\n break;\n case Order::EqualDst:\n case Order::After:\n UpdateColinearPair(curr_minmax, p1, q);\n break;\n }\n}\n</code></pre>\n<p>In the above, there is no need for a <code>default</code> case; the compiler can see that you handle all possible results.</p>\n<h1>Inefficient adding to a convex hull</h1>\n<p>JDługosz already mentioned that the first argument to <code>ConvexHullAdd()</code> should probably made <code>const</code>. Indeed that looks the case from how it is used:</p>\n<pre><code>for (const auto& p : CH1) {\n CH = ConvexHullAdd(CH, p);\n}\n</code></pre>\n<p>On the right-hand side of the assignment, <code>p</code> is added to <code>CH</code> if possible, and then a <em>copy</em> of <code>CH</code> is returned. This copy then replaces the original contents of <code>CH</code>. The end result is what you expect, but the copy was made unnecessarily. It would be more efficient to make <code>ConvexHullAdd()</code> <code>void</code>, and to replace the above loop with:</p>\n<pre><code>for (const auto& p : CH1) {\n ConvexHullAdd(CH, p);\n}\n</code></pre>\n<h1>About that <code>tolerance</code></h1>\n<p>You hardcoded the <code>tolerance</code> to be <code>1e-6</code>. This works fine if the spread of your points is much larger than the tolerance. But what if the coordinates are all much smaller than <code>1e-6</code>? Then <code>isClose()</code> wil always return <code>true</code>, and all expressions of the form <code>a - b > tolerance</code> will be false. The result of <code>getOrder()</code> will then never be <code>Order::Before</code> or <code>Order::Between</code> anymore.</p>\n<p>Hardcoding a tolerance value is almost never a good idea. If you have encountered issues (perhaps <code>Cos()</code> is returning infinity or NaN if points are too close), then you should try to solve them in a different way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T18:29:25.747",
"Id": "260082",
"ParentId": "260027",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T12:42:47.257",
"Id": "260027",
"Score": "0",
"Tags": [
"c++",
"algorithm",
"computational-geometry"
],
"Title": "C++ : Merging two convex hulls"
}
|
260027
|
<p>My primary coding language is C++, but I occasionally use C. I wrote some simple image segmentation using Union-Find algorithm. Feel free to comment anything!</p>
<pre><code>#include <stdlib.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <string.h>
static size_t const MERGE_CRITERION = 50;
typedef struct Segment Segment;
struct Segment {
unsigned char value;
size_t parent;
double average;
size_t size;
};
size_t FindCompress(size_t N, Segment pixels[static N], size_t i) {
if (i >= N) return SIZE_MAX;
if (pixels[i].parent != i) {
pixels[i].parent = FindCompress(N, pixels, pixels[i].parent);
}
return pixels[i].parent;
}
bool Union(size_t N, Segment pixels[static N], size_t i, size_t j) {
if (i >= N || j >= N) return false;
size_t root_i = FindCompress(N, pixels, i);
size_t root_j = FindCompress(N, pixels, j);
if (root_i == root_j) return false;
if (fabs(pixels[root_i].average - pixels[root_j].average) > MERGE_CRITERION) {
return false;
}
if (pixels[root_i].size < pixels[root_j].size) {
size_t temp = root_i;
root_i = root_j;
root_j = temp;
}
pixels[root_j].parent = root_i;
double new_average = ((pixels[root_i].average * pixels[root_i].size)
+ (pixels[root_j].average * pixels[root_j].size)) / (double)(pixels[root_i].size + pixels[root_j].size);
pixels[root_i].average = new_average;
pixels[root_i].size += pixels[root_j].size;
return true;
}
int main() {
FILE* img = fopen("sample.bmp", "rb");
FILE* outimg = fopen("sample_gray.bmp", "wb");
unsigned char header[54] = {0};
fread(header, sizeof(unsigned char), 54, img);
fwrite(header, sizeof(unsigned char), 54, outimg);
uint32_t width = *(uint32_t*)&header[18];
uint32_t height = *(uint32_t*)&header[22];
uint32_t stride = (width * 3 + 3u) & ~(3u);
uint32_t padding = stride - width * 3;
printf("width %u, height %u, stride %u, padding %u\n", width, height, stride, padding);
size_t image_size = width * height;
Segment greyscaled[image_size];
unsigned char pixel[3] = {0};
for (uint32_t i = 0; i < height; i++) {
for (uint32_t j = 0; j < width; j++) {
fread(pixel, 3, 1, img);
unsigned char gray = (unsigned char)(pixel[0] * 0.3 + pixel[1] * 0.58 + pixel[2] * 0.11);
greyscaled[i * width + j] = (Segment){.value = gray, .parent = (i * width + j),
.average = gray, .size = 1};
}
fread(pixel, padding, 1, img);
}
size_t change_count = 1;
size_t iteration = 0;
while (change_count > 0) {
change_count = 0;
for (uint32_t j = 1; j < width; j++) {
if (Union(image_size, greyscaled, j, j - 1)) {
change_count++;
}
}
for (uint32_t i = 1; i < height; i++) {
if (Union(image_size, greyscaled, i * width, (i - 1) * width)) {
change_count++;
}
for (uint32_t j = 1; j < width; j++) {
if (Union(image_size, greyscaled, i * width + j, (i - 1) * width + j)) {
change_count++;
}
if (Union(image_size, greyscaled, i * width + j, i * width + j - 1)) {
change_count++;
}
}
}
printf("Iteration %zu, change_count %zu\n", ++iteration, change_count);
}
for (uint32_t i = 0; i < height; i++) {
for (uint32_t j = 0; j < width; j++) {
size_t root = FindCompress(image_size, greyscaled, i * width + j);
unsigned char gray = (unsigned char) greyscaled[root].average;
memset(pixel, gray, sizeof(pixel));
fwrite(&pixel, 3, 1, outimg);
}
fwrite(pixel, padding, 1, outimg);
}
fclose(img);
fclose(outimg);
return EXIT_SUCCESS;
}
</code></pre>
<p>Original example image:</p>
<p><a href="https://i.stack.imgur.com/MCBK4.png" rel="noreferrer"><img src="https://i.stack.imgur.com/MCBK4.png" alt="Original example image" /></a></p>
<p>Using <code>MERGE_CRITERION = 10</code>:</p>
<p><a href="https://i.stack.imgur.com/Jz9uX.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Jz9uX.png" alt="Merge criterion 10" /></a></p>
<p>Using <code>MERGE_CRITERION = 20</code>:</p>
<p><a href="https://i.stack.imgur.com/T1e1p.png" rel="noreferrer"><img src="https://i.stack.imgur.com/T1e1p.png" alt="Merge criterion 20" /></a></p>
|
[] |
[
{
"body": "<h2>Use const</h2>\n<p>In <code>FindCompress</code> and <code>Union</code> the parameters <code>N</code>, <code>i</code> and <code>j</code> could be passed as const as they are not changed in the functions.</p>\n<h2>Avoid using keywords as function names.</h2>\n<p>In C <code>union</code> is a keyword, even though the function name is currently in CamelCase I would still recommend against it.</p>\n<h2>Styling</h2>\n<ul>\n<li>Segment struct definition</li>\n</ul>\n<pre class=\"lang-c prettyprint-override\"><code>typedef struct Segment Segment;\n\nstruct Segment {\n unsigned char value;\n size_t parent;\n double average;\n size_t size;\n};\n</code></pre>\n<p>Can be written as:</p>\n<pre class=\"lang-c prettyprint-override\"><code>typedef struct {\n unsigned char value;\n size_t parent;\n double average;\n size_t size;\n} Segment;\n</code></pre>\n<ul>\n<li>CamelCase for functions and variables is uncommon in C usually snake_case is preferred, however this is of course an opinionated item.</li>\n<li>Use brackets on <code>if...else</code> statements even if they are one line. There's a chance more lines will be added to the if...else statement later on. Forgetting to add brackets when this happens can lead to bugs that could have been avoided if brackets where added from the start.</li>\n<li>Make use of empty lines for readability. Before return statements and around <code>for/while/if...else</code> statements are good places for this.</li>\n</ul>\n<p>Example with these points applied to the <code>FindCompress</code> function:</p>\n<pre class=\"lang-c prettyprint-override\"><code>size_t find_compress(const size_t n, Segment pixels[static n], const size_t i) {\n if (i >= n) { return SIZE_MAX; }\n\n if (pixels[i].parent != i) {\n pixels[i].parent = find_compress(n, pixels, pixels[i].parent);\n }\n\n return pixels[i].parent;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T14:53:16.793",
"Id": "260030",
"ParentId": "260028",
"Score": "2"
}
},
{
"body": "<p>As the Standard Library headers are independent of each other, it makes sense to include them in consistent order - alphabetical is a good choice.</p>\n<p>The <code>main()</code> function here is very long - more than a screenful. That's usually a sign that it should be split into functions for the different responsibilities. In particular, the file reading seems worthy of its own reusable function.</p>\n<p>We need to be much more robust when reading files. If either <code>fopen()</code> fails, we very soon use the returned null pointer, causing Undefined Behaviour. If <code>fread()</code> or <code>fwrite()</code> fail, then the program continues regardless, likely producing meaningless results.</p>\n<p>It's unwise to assume that the file format's endianness agrees with the host endianness like this:</p>\n<blockquote>\n<pre><code> uint32_t width = *(uint32_t*)&header[18];\n uint32_t height = *(uint32_t*)&header[22];\n</code></pre>\n</blockquote>\n<p>It's better to compose values explicitly from the byte stream.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:39:17.013",
"Id": "260038",
"ParentId": "260028",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T13:04:27.127",
"Id": "260028",
"Score": "5",
"Tags": [
"algorithm",
"c",
"image"
],
"Title": "C : Image Segmentation"
}
|
260028
|
<p>I have a database, with tens of thousands of records, which I wish to represent in python. The python 2.x version has tables in which each record is an instance of a class and the values in the record are held in attributes of the object. Some of the attributes are terms which are used to classify records. The classifications in my database relate to some technical metadata structures, so here, to concentrate on the essential coding question.</p>
<p><strong>If I have a collection of objects which are classified by, for example, colour and year, does it make sense to represent the colour and year as python super-classes (perhaps as illustrated below) rather than as attribute values?</strong></p>
<p>In the following example I've created a potential implementation:</p>
<pre><code>import time
## Cars will be classified Colour and Year
class Colour(type): pass
class Year(type):
description = 'Year of purchase'
## A class for cars classified by year and colour
class Car(Colour,Year): pass
## colours for classification
#
# Duplication in specification of colour could be removed by using a factory to
# generate these classes from tabulated information.
#
Red = Colour( 'red', (object,), dict(description='The primary colour red',colour='red') )
Blue = Colour( 'blue', (object,), dict(description='The primary colour blue',colour='blue') )
Green = Colour( 'green', (object,), dict(description='The primary colour green',colour='green') )
# years for classification.
Y2015 = Year( '2015', (object,), dict(description='2015 AD' ) )
Y2016 = Year( '2016', (object,), dict(description='2016 AD' ) )
Y2017 = Year( '2017', (object,), dict(description='2017 AD' ) )
Y2018 = Year( '2018', (object,), dict(description='2018 AD' ) )
# for each
class CarRecord(object):
def __init__(self,comment):
self.record_date=time.ctime()
self.comment=comment
#
# records are classified by the colour and year classes.
#
MyCar = Car( 'MyCar', (CarRecord,Blue,Y2018), dict( comment='car number 1' ) )
HisCar = Car( 'HisCar', (CarRecord,Green,Y2016), dict( comment='car number 2' ) )
## instantiation creates a specific metadata record, with timestamp
my_car = MyCar('A very good car')
his_car = HisCar("Someone else's car")
</code></pre>
<p>This example appears to work smoothly, but I have arrived at this point by trial-and-error and have some concerns that I may not fully understand the implications of some of the coding structures used.</p>
<h2>Advantages</h2>
<ul>
<li>The categories <code>Blue</code>, <code>Red</code> etc are python objects and can carry additional descriptive information and helper methods as needed;</li>
<li>There is a clear separation between properties such as <code>Colour</code>, which are part of a classification scheme, and <code>description</code>, which is a free-text attribute;</li>
<li>Ability to add attributes and methods to categories (<code>Red</code>, <code>Blue</code> etc) and category groups (<code>Colour</code>, <code>Year</code>) in a transparent way;</li>
</ul>
<h2>Disadvantages</h2>
<ul>
<li>Could there be hidden performance overheads when expanding the number of category groups to 10 and the number of categories to hundreds?</li>
<li>Is there a better way of handling the relationship between concepts being categorised (the cars hers) and concepts being used for categorisation?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:24:21.930",
"Id": "513166",
"Score": "1",
"body": "How are you using your code? I can write a review without seeing how you're actually using the code. However my review may not factor in your usage and be sub-optimal. Can you show why you need custom types and abnormal metaclasses."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T08:50:36.230",
"Id": "513233",
"Score": "0",
"body": "@Peilonrayz : I'm sorry if the question is too vague to answer. My code as it stands is, I think, too complex/untidy to post here. I was trying to ask a general question about use of meta-classes to classify concepts which are expressed as python classes. In UML terms, I can declare that `MyCar` is `Red` through either an association (e.g. by giving `MyCar` an attribute `colour=Red` or derivation/specialisation (`MyCar` is a sub-class of `RedObjects`). Can you clarify what you mean by \"abnormal metaclasses\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T09:40:56.913",
"Id": "513237",
"Score": "0",
"body": "\"too complex/untidy to post here.\" No, your actual real code is far better for you and me to discuss. To build metaclasses normally you just use `class Red(metaclass=Colour): color = \"red\"` however you're using the interface used only by [six](https://pypi.org/project/six/). If you change to normal metaclass usage then you should be able to see your custom types don't do anything."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T04:54:32.040",
"Id": "513409",
"Score": "0",
"body": "If I understand correctly, there will be a class for every combination of categories across all groups: 3 colors x 4 years = 12 classes. You suggest there could be 10 groups, each with 100 categories = 100*100*100,,,*100 = 10^20 classes! That seems rather unwieldly. What happens when a red car gets painted blue? I think `Enum`s as class attributes gets you all the advantages you listed above."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-30T06:37:07.503",
"Id": "513563",
"Score": "0",
"body": "@RooTwo -- a fair point, but 10^20 `Enum`s is also going to be a problem. It is true that a can use `Enum`s .. and the justification for looking for an alternative is not clear in the example. The reason I'm looking at this is that I'm classifying concepts, and representing this in python code. In UML terms (based on a limited understanding of UML) I think of class attributes as expressing an association relationship. If I go down that route I have two sets of class relationships in my code: one set of functional python classes and a 2nd set of associations for classification of colour etc."
}
] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:10:13.260",
"Id": "260036",
"Score": "0",
"Tags": [
"python-3.x",
"classes",
"classification"
],
"Title": "Using python classes to classify database records"
}
|
260036
|
<p>I have made the decision to move the storing of session data to the database.</p>
<p>Any new ideas, suggestions are welcome.</p>
<p>Please also give security suggestions.</p>
<p>Like SQL injection is possible here, etc...</p>
<pre><code><?php
/**
* MySQL/MariaDB Session Handler - Handle Sessions using Database
* Copyright (c) 2021 Baal Krshna
* PHP Version 5.4
*
* @author Puneet Gopinath (PuneetGopinath) <baalkrshna@gmail.com>
* @copyright 2021 Baal Krshna
*/
namespace BaalKrshna\SessionHandler;
/**
* MySQL/MariaDB Session Handler - Handle Sessions using Database
*
* @author Puneet Gopinath (PuneetGopinath) <baalkrshna@gmail.com>
*/
class MySQLHandler implements \SessionHandlerInterface
{
/**
* MySQL/MariaDB Session Handler Version number
* Used for easier checks, like if SessionHandler is up to date or not
*
* @var string VERSION The Version number
*/
const VERSION = "0.1.0";
/**
* Session Lifetime, default 2 hrs
*
* @var integer $expiry The expiry time in seconds
*/
private $expiry = 7200;
/**
* Session Id
*
* @var string $sessionId The session id
*/
private $sessionId = null;
/**
* User Agent
*
* @var string $userAgent The User Agent
*/
private $userAgent = null;
/**
* DB connection object
*
* @var object $db_conn The DB connection object
*/
private $db_conn = null;
/**
* DB table name for storing session info
*
* @var string $tablename The Table name
*/
private $tablename = "sessions";
/**
* Session name
*
* @var string $sessionName The Session name
*/
private $sessionName = "PHPSESSID";
/**
* MySQLHandler class constructor.
*
* @param array $config The config settings
* @return MySQLHandler The MySQLHandler class
*/
public function __construct($config)
{
/*session_set_save_handler(
array($this, "open"),
array($this, "close"),
array($this, "read"),
array($this, "write"),
array($this, "destroy"),
array($this, "gc")
);*/
session_set_save_handler($this, true);
$this->setConfig($config);
session_start();
}
/**
* Set config
*
* @param array $config The config settings
* @return bool The return value (usually TRUE on success, FALSE on failure).
*/
private function setConfig($config)
{
if (empty($config["db_conn"])) {
error_log("DB connection not set in config!!");
return false;
}
$this->db_conn = $config["db_conn"];
$this->tablename = empty($config["tablename"]) ? $this->tablename : $config["tablename"];
$this->expiry = empty($config["expiry"]) ? $this->expiry : $config["expiry"];
$this->userAgent = $_SERVER["HTTP_USER_AGENT"];
ini_set("session.gc_maxlifetime", $this->expiry);
ini_set("session.gc_probability", "0");
if (
$stmt = $this->db_conn->prepare(
"CREATE TABLE IF NOT EXISTS $this->tablename (" .
"session_id VARCHAR( 255 ) NOT NULL ," .
"data TEXT NOT NULL ," .
"userAgent VARCHAR( 255 ) NOT NULL ," .
"lastModified DATETIME NOT NULL ," .
"PRIMARY KEY ( session_id )" .
")"
)
) {
if (!$stmt->execute()) {
return false;
}
$stmt->close();
} else {
return false;
}
return true;
}
/**
* Refresh the session
*
* @return bool The return value (usually TRUE on success, FALSE on failure).
*/
private function refresh()
{
$currentId = session_id();
session_regenerate_id();
$this->sessionId = session_id();
if (
$stmt = $this->db_conn->prepare(
"UPDATE $this->tablename SET session_id=? WHERE session_id=?"
)
) {
$stmt->bind_param(
"ss",
$currentId,
$this->sessionId
);
if (!$stmt->execute()) {
return false;
}
$stmt->close();
} else {
return false;
}
return true;
}
/**
* Open/Start session
*
* @param string $savePath The path where to store/retrieve the session.
* @param string $sessionName The session name
* @return bool The return value (usually TRUE on success, FALSE on failure).
*/
public function open($savePath, $sessionName)
{
$this->sessionName = $sessionName;
return true;
}
/**
* Close session
*
* @return bool The return value (usually TRUE on success, FALSE on failure).
*/
public function close()
{
if (!$this->gc()) {
return false;
}
return true;
}
/**
* Read session data
*
* @param string $id The session id
* @return string The data read from database
*/
public function read($id)
{
if (
$stmt = $this->db_conn->prepare(
"SELECT data, session_id FROM $this->tablename WHERE session_id=?"
)
) {
$stmt->bind_param("s", $id);
$stmt->execute();
$stmt->bind_result($data, $sessionId);
$stmt->close();
if (empty($sessionId)) {
$this->refresh();
return "";
}
return $data;
} else {
return "";
}
}
/**
* Write data to session
*
* @param string $id The session id
* @param string $data The data to write
* @return bool The return value (usually TRUE on success, FALSE on failure).
*/
public function write($id, $data)
{
$date = date("Y-m-d H:i:s");
$read = $this->read($id);
if (empty($read) || !$read) {
if (
$stmt = $this->db_conn->prepare(
"INSERT INTO $this->tablename (
session_id,
data,
lastModified,
userAgent
)
VALUES
(?, ?, ?, ?)"
)
) {
$stmt->bind_param(
"ssss",
$id,
$data,
$date,
$this->userAgent
);
if (!$stmt->execute()) {
return false;
}
$stmt->close();
} else {
return false;
}
} else {
if (
$stmt = $this->db_conn->prepare(
"UPDATE $this->tablename SET data=?, lastModified=?, userAgent=? WHERE session_id=?"
)
) {
$stmt->bind_param(
"ssss",
$data,
$date,
$this->userAgent,
$id
);
if (!$stmt->execute()) {
return false;
}
$stmt->close();
} else {
return false;
}
}
return true;
}
/**
* Destroy the session
*
* @param string $id The session id
* @return bool The return value (usually TRUE on success, FALSE on failure).
*/
public function destroy($id)
{
if (
$stmt = $this->db_conn->prepare(
"DELETE FROM $this->tablename WHERE session_id=?"
)
) {
$stmt->bind_param(
"s",
$id
);
if (!$stmt->execute()) {
return false;
}
$stmt->close();
} else {
return false;
}
return true;
}
/**
* Do garbage collection
*
* @param int $max_lifetime Sessions that have not updated for the last maxlifetime seconds will be removed.
* @return int|bool The return value (usually TRUE on success, FALSE on failure).
*/
public function gc($max_lifetime = null)
{
if (empty($max_lifetime)) {
$max_lifetime = $this->expiry;
}
$sessionLife = time() - $max_lifetime;
if (
$stmt = $this->db_conn->prepare(
"DELETE FROM $this->tablename WHERE lastModified < ?"
)
) {
$stmt->bind_param(
"s",
$sessionLife
);
if (!$stmt->execute()) {
return false;
}
$stmt->close();
} else {
return false;
}
return true;
}
}
</code></pre>
<p>The above code follows PSR12.
Even though it follows PSR12, the only thing it doesn't follow is about the visibility of constant.</p>
<p>I have some questions:</p>
<ol>
<li>Is not closing the connection going to have problems?</li>
<li>If question 1 is yes, then how can I get a new mysqli object in the next time I need to use mysqli</li>
<li>I want to know whether the write function will not be used to update existing fields in dB?</li>
</ol>
<p>Testing the above code:
You have to edit the MySQL credentials in the mysqli_connect function's args.</p>
<pre><code>$connection = mysqli_connect(
"localhost", //Hostname
"root", //Username
"password", //Password
"test" //DB name
);
$handler = new \BaalKrshna\SessionHandler\MySQLHandler(
array(
"db_conn" => $connection
)
);
//Session handler already set in construct method
$_SESSION["foo"] = "bar";
echo $_SESSION["foo"];
session_write_close();
session_gc();
session_destroy();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T18:45:04.243",
"Id": "513178",
"Score": "0",
"body": "The `gc()` metod is broken. It looks like a copy of destroy method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T22:07:33.200",
"Id": "513194",
"Score": "0",
"body": "So your code is not working as intended?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T04:43:37.360",
"Id": "513213",
"Score": "0",
"body": "Yes, my code is not working as intended"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T04:45:20.657",
"Id": "513215",
"Score": "0",
"body": "@slepic Yes, I forgot to edit it, one sec"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-27T09:50:43.013",
"Id": "513238",
"Score": "0",
"body": "Are you sure it is **NOT** working as intended? I ask because one of the criteria of Code Review is: _\"The code must **not** error or contain known bugs\"_. Asking us to review code that's not working could get your question closed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T03:05:57.843",
"Id": "513300",
"Score": "0",
"body": "Actually, there was a small bug, which is fixed now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T03:06:44.450",
"Id": "513301",
"Score": "0",
"body": "The bug was that, instead of $stmt->execute() I wrote $stmt->excute()"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T12:40:27.517",
"Id": "513335",
"Score": "0",
"body": "Ah, but that's a very small bug. So, I assume the code has now been tested and is working."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-28T14:11:30.810",
"Id": "513357",
"Score": "0",
"body": "You need to stop manually checking for errors. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) and [Should I manually check for errors when calling “mysqli_stmt_prepare”?](https://stackoverflow.com/q/62216426/1839439)"
}
] |
[
{
"body": "<ul>\n<li><p>Use the null coalescing operator for all occurrences where you want to provide fallback values for undeclared/<code>null</code> variables.</p>\n<pre><code>$this->tablename = $config["tablename"] ?? $this->tablename;\n</code></pre>\n</li>\n<li><p>I agree with @Dharman's comment under the question, don't bother with manually checking for mysqli errors. See the commented links.</p>\n<pre><code>private function refresh(): int\n{\n $currentId = session_id();\n session_regenerate_id();\n $this->sessionId = session_id();\n $stmt = $this->db_conn->prepare("UPDATE $this->tablename SET session_id=? WHERE session_id=?");\n $stmt->bind_param("ss", $currentId, $this->sessionId);\n $stmt->execute();\n return $this->db_conn->affected_rows;\n}\n</code></pre>\n</li>\n<li><p>I don't personally ever bother manually closing prepared statements. PHP is going to automatically do that for you when I knows it is done using them.</p>\n</li>\n<li><p>Simplify boolean return by not manually typing the <code>true</code>/<code>false</code>. Your IDE might even be alerting you to this.</p>\n<pre><code>public function close()\n{\n return (bool) $this->gc();\n}\n</code></pre>\n</li>\n<li><p>Set up your database table(s) to have <code>lastModified</code> DEFAULT to the current timestamp, this way you don't have to manually write that in your sql when INSERTing a new row.</p>\n</li>\n<li><p>Inside of <code>write()</code>, the following is unnecessary/redundant:</p>\n<pre><code>if (empty($read) || !$read) {\n</code></pre>\n<p>Instead, just do a falsey check because you <em>know</em> that the variable will be unconditionally declared.<br><code>if (!$read) {</code></p>\n</li>\n<li><p>As a general rule, when a method is performing an INSERT, I typically return the autogenerated id (whenever possible) -- even if I don't need it <em>right now</em>, it is possible that I may want it in the future. For UPDATE and DELETE queries, I return the affected rows as an integer -- this allows me to verify that a change had actually occurred from the executed query and knowing how many rows were affected can sometimes help with diagnostics. In both all "database writing" cases, the return value is easily compared as truthy/falsey if your method call doesn't need the excessive specificity in the outcome.</p>\n</li>\n<li><p>Again, in <code>gc()</code>, <code>if (empty($max_lifetime)) {</code> is not necessary -- the variable WILL be declared, do a falsey / function-less check here. Or even better avoid the single-use variable declarations and use the null coalescing operator again.</p>\n<pre><code>public function gc($max_lifetime = null): int\n{\n $stmt = $this->db_conn->prepare("DELETE FROM $this->tablename WHERE lastModified < ?");\n $modifiedTime = time() - ($max_lifetime ?? $this->expiry);\n $stmt->bind_param("s", $modifiedTime);\n $stmt->execute();\n $this->db_conn->affected_rows;\n}\n</code></pre>\n</li>\n<li><p>Security suggestion:<br>\nDon't support PHP 5.3 instead support the versions of php which still receive security updates, See <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">supported\nversions of php here</a></p>\n<p>PHP 5.3 has a lot of security issues.</p>\n</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:13:01.073",
"Id": "513415",
"Score": "0",
"body": "You said \"Set up your database table(s) to have lastModified DEFAULT to the current timestamp, this way you don't have to manually write that in your sql when INSERTing a new row.\", how to do that"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:13:59.987",
"Id": "513416",
"Score": "0",
"body": "https://stackoverflow.com/q/168736/2943403"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:15:29.827",
"Id": "513419",
"Score": "0",
"body": "PHP 5.3 doesn't support null coalescing operator"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:15:48.903",
"Id": "513420",
"Score": "2",
"body": "PHP5.3!!!! Leave that job!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:17:47.820",
"Id": "513421",
"Score": "1",
"body": "Ok i should use DEFAULT CURRENT_TIMESTAMP right?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:19:00.780",
"Id": "513424",
"Score": "0",
"body": "some extra code is not wrong"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:20:13.563",
"Id": "513426",
"Score": "0",
"body": "Can you answer my questions :Is not closing the connection going to have problems?\nIf question 1 is yes, then how can I get a new mysqli object in the next time I need to use mysqli\nI want to know whether the write function will not be used to update existing fields in dB?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:20:26.673",
"Id": "513427",
"Score": "2",
"body": "By being stuck in 5.3 you are missing out on an enormous sea of beautiful enhancements and security. There is no excuse for work in the dark ages -- convince the stakeholders that their application is not secure and funds/time must be appropriated to upgrade the site."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:21:51.247",
"Id": "513428",
"Score": "0",
"body": "You should be re-using a connection over and over. Don't worry about closing your statements or connections -- that will be done for you by php."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:22:11.647",
"Id": "513429",
"Score": "0",
"body": "ok, i am going to use latest php, but my users or who use my project can decide themselves"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:22:58.723",
"Id": "513430",
"Score": "2",
"body": "Don't let them decide -- force them to use non-deprecated versions of php! You may let them choose between different non-deprecated versions of php."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:23:05.187",
"Id": "513431",
"Score": "0",
"body": "\"You should be re-using a connection over and over. Don't worry about closing your statements or connections -- that will be done for you by php.\" how can i reopen a closeed object"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:23:24.440",
"Id": "513432",
"Score": "0",
"body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/123568/discussion-between-puneet-gopinath-and-mickmackusa)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T06:24:11.937",
"Id": "513433",
"Score": "0",
"body": "I'm not interested in a chat. I didn't think this was going to turn into a thread. I am at work right now. Don't close the object. Good luck."
}
],
"meta_data": {
"CommentCount": "14",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-29T02:15:28.730",
"Id": "260144",
"ParentId": "260037",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "260144",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-26T16:26:02.837",
"Id": "260037",
"Score": "2",
"Tags": [
"php",
"mysql",
"database",
"mysqli",
"session"
],
"Title": "MySQL database custom session handler using PHP with MySQLi extension"
}
|
260037
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.