text stringlengths 1 2.12k | source dict |
|---|---|
java, mysql
Title: Is it good practice to have all my back end in one single file with all functions being static?
Question: package LoginSystem;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
//data base consists of columns [ID, username, password, numOfPasswordChanges, passwordChangeTimer]
public class DataBaseController {
private static final int MAX_USERNAME_LENGTH = 20;
private static final int MIN_USERNAME_LENGTH = 5;
private static final int MAX_PASSWORD_LENGTH = 30;
private static final int MIN_PASSWORD_LENGTH = 7;
public static final int CORRECT_PASSWORD_RETURN_VAL = 1;
public static final int INCORRECT_PASSWORD_RETURN_VAL = 2;
public static final int MAX_PASSWORD_RESETS_REACHED_RETURN_VAL = 3;
public static final int WEAK_PASSWORD_RETURN_VAL = 4;
public static final int WEAK_USERNAME_RETURN_VAL = 5;
public static final int USER_ALREADY_EXISTS_RETURN_VAL = 6;
public static final int USER_NOT_EXISTS_RETURN_VAL = 7;
private static final int ID_INDEX = 1;
private static final int USERNAME_INDEX = 2;
private static final int PASSWORD_INDEX = 3;
private static final int PASSWORD_RESET_INDEX = 4;
private static final int RESET_TIMER_INDEX = 5;
private static final int MAX_PASSWORD_RESETS = 3;
private static final long RESET_TIME_TO_ADD = 20000L;
private static final String ROOT_NAME = "root";
private static final String DB_PASSWORD = "root";
private static final String DB_NAME = "mydb";
public DataBaseController() throws SQLException {
} | {
"domain": "codereview.stackexchange",
"id": 44950,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, mysql",
"url": null
} |
java, mysql
public DataBaseController() throws SQLException {
}
public static boolean authorizeUser(String username, String password) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME, ROOT_NAME,DB_PASSWORD);
Statement stmt = con.createStatement();
String query = "SELECT * FROM users WHERE username = " + "'" + username + "'" + " AND password = " + "'" + password + "'";
ResultSet rs = stmt.executeQuery(query);
boolean userExists = rs.next();
if(rs.next()) {
throw new Exception("Duplicate username in database!");
}
rs.previous();
boolean correctLogin = false;
if(userExists) {
correctLogin = rs.getString(USERNAME_INDEX).equals(username) && rs.getString(PASSWORD_INDEX).equals(password);
}
return correctLogin;
} | {
"domain": "codereview.stackexchange",
"id": 44950,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, mysql",
"url": null
} |
java, mysql
return correctLogin;
}
public static int register(String username, String password) throws ClassNotFoundException, SQLException {
if(!checkIfUsernameValid(username)) {
return WEAK_USERNAME_RETURN_VAL;
}
if(!checkIfPasswordValid(password)) {
return WEAK_PASSWORD_RETURN_VAL;
}
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME + "?verifyServerCertificate=false&useSSL=true", ROOT_NAME, DB_PASSWORD);
Statement stmt = con.createStatement();
String query = "SELECT * FROM users WHERE username = " + "'" + username + "'";
ResultSet rs = stmt.executeQuery(query);
boolean doesUserExists = rs.next();
if(!doesUserExists) {
String numberOfUsersQuery = "SELECT COUNT(*) FROM users";
ResultSet userIDRs = stmt.executeQuery(numberOfUsersQuery);
String addUserSql = "";
userIDRs.next();
int newID = 1 + userIDRs.getInt(1);
addUserSql = "INSERT INTO users(ID, username, password) VALUES(" + newID +", " + "'" + username + "'" + ", " + "'" + password + "');";
stmt.executeUpdate(addUserSql);
}
if(doesUserExists) {
return USER_ALREADY_EXISTS_RETURN_VAL;
}
return USER_NOT_EXISTS_RETURN_VAL;
} | {
"domain": "codereview.stackexchange",
"id": 44950,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, mysql",
"url": null
} |
java, mysql
public static int resetPassword(String username, String oldPassword, String newPassword) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME + "?verifyServerCertificate=false&useSSL=true", ROOT_NAME, DB_PASSWORD);
Statement stmt = con.createStatement();
String checkUserQuery = "SELECT * FROM users WHERE username = " + "'" + username + "'" + " AND " + "password = " + "'" + oldPassword + "'";
ResultSet rs = stmt.executeQuery(checkUserQuery);
if(!rs.next()) {
return INCORRECT_PASSWORD_RETURN_VAL;
}
if(!checkIfPasswordValid(newPassword)) {
return WEAK_PASSWORD_RETURN_VAL;
}
int numOfChanges = rs.getInt(PASSWORD_RESET_INDEX);
Timestamp usersResetTimer = rs.getTimestamp(RESET_TIMER_INDEX);
System.out.println(usersResetTimer + " **** " + new Timestamp(System.currentTimeMillis()) + " **** " + usersResetTimer.after(new Timestamp(System.currentTimeMillis())));
if(!usersResetTimer.after(new Timestamp(System.currentTimeMillis()))) {
numOfChanges = 0;
}
if(numOfChanges >= MAX_PASSWORD_RESETS) {
return MAX_PASSWORD_RESETS_REACHED_RETURN_VAL;
} | {
"domain": "codereview.stackexchange",
"id": 44950,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, mysql",
"url": null
} |
java, mysql
String query = "UPDATE users SET password = " + "'" + newPassword + "'" + " WHERE username = " + "'" + username + "'";
try {
stmt.executeUpdate(query);
numOfChanges += 1;
query = "UPDATE users SET numOfPasswordChanges = " + numOfChanges + " WHERE username = " + "'" + username + "'";
stmt.executeUpdate(query);
Timestamp newUserResetTimer = new Timestamp(System.currentTimeMillis() + RESET_TIME_TO_ADD);
System.out.println(newUserResetTimer);
String timeWithoutMillis = newUserResetTimer.toString().split("\\.")[0];
System.out.println(newUserResetTimer.toString());
query = "UPDATE users SET passwordChangeTimer = " + "'" + timeWithoutMillis + "'" + " WHERE username = " + "'" + username + "'";
stmt.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
return CORRECT_PASSWORD_RETURN_VAL;
}
private static boolean checkIfUsernameValid(String username) {
if( username == null || username.length() > MAX_USERNAME_LENGTH || username.length() < MIN_USERNAME_LENGTH)
{
return false;
}
for(int i = 0; i < username.length(); i++) {
if(!Character.isLetter(username.charAt(i)) && !Character.isDigit(username.charAt(i))) {
return false;
}
}
return true;
}
private static boolean checkIfPasswordValid(String password) {
if(password == null || password.length() > MAX_PASSWORD_LENGTH || password.length() < MIN_PASSWORD_LENGTH) {
return false;
}
boolean symbolFlag = false;
boolean digitFlag = false;
boolean letterFlag = false; | {
"domain": "codereview.stackexchange",
"id": 44950,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, mysql",
"url": null
} |
java, mysql
for(int i = 0; i < password.length(); i++) {
if(!Character.isLetter(password.charAt(i)) && !Character.isDigit(password.charAt(i))) {
symbolFlag = true;
}
if(Character.isLetter(password.charAt(i))) {
letterFlag = true;
}
if(Character.isDigit(password.charAt(i))) {
digitFlag = true;
}
if(symbolFlag && digitFlag && letterFlag) {
return true;
}
}
return false;
}
}
I have a bunch of classes that uses this to register/change password etc...
and this is basically all of my backend in one class almost all of it static aside from a simple checks if username and passwords aren't weak (although nothing will change if it were static), so is it good practice? I can add here the rest of the files but all of them are just simple front end swing GUI pages with no server running in this project.
Answer: cache your DB connection
public static boolean authorizeUser(String username, String password)
...
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/" + DB_NAME, ROOT_NAME, DB_PASSWORD);
It looks like this gets called on pretty much every GET request.
MySQL, Oracle, and other backends take a performance hit
if you create a brand new connection for each query.
Some folks will cache in a locked singleton,
some have instances of their application class hang onto it,
while others will opt for a connection pool.
I will typically use a connection pool in my
SqlAlchemy /
flask apps.
Not knowing your parameters, I won't tell you what to do here.
Consider benching how many GETs per second
you can get from your app with & without caching connections. | {
"domain": "codereview.stackexchange",
"id": 44950,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, mysql",
"url": null
} |
java, mysql
report error properly
String query = "SELECT * FROM users WHERE username = " + "'" + username + "'"
+ " AND password = " + "'" + password + "'";
...
if (rs.next()) {
throw new Exception("Duplicate username in database!");
}
Suppose we attempt
authorizeUser("scott", "tiger") which succeeds, and then attempt
authorizeUser("scott", "hunter"), for which zero rows match.
The userExists = rs.next() positioned us at end-of-results, and the
docs
say this about the subsequent if (rs.next()) call:
When a call to the next method returns false, the cursor is positioned after the last row.
Any invocation of a ResultSet method which requires a current row will result in a SQLException being thrown.
I guess we can call next; next; next repeatedly.
But the test should have been if (userExists).
And rather than vanilla raise Exception...,
please throw something more specific like IllegalArgumentException,
or much better, an app-specific exception that you define.
Then a caller that knows how to recover
can choose to catch the narrower anticipated error
rather than catching broadly.
In any event, the AND password = 'tiger' clause
isn't really appropriate.
You're delegating the security decision to the RDBMS.
Better to just retrieve the user's attributes, such as password,
and make the security decision at app level.
use prepared statements
"SELECT * FROM users WHERE username = " + "'" + username + "'" ...
Little Bobby Tables' mom
just loves queries like that.
Avoid sql injection attacks.
Habitually use the bind-parameter interface when submitting queries.
salt your credentials
correctLogin =
rs.getString(USERNAME_INDEX).equals(username)
&& rs.getString(PASSWORD_INDEX).equals(password); | {
"domain": "codereview.stackexchange",
"id": 44950,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, mysql",
"url": null
} |
java, mysql
Assume that your users table leaks out at some point to a hacker.
Now all those cleartext passwords are exposed, which is Bad,
enabling attacks on other servers frequented by your users.
We usually store a hash of password to mitigate such a threat.
But that still admits of offline dictionary attacks.
Salt
your password hashes to make it harder for attackers
to launch such an attack. | {
"domain": "codereview.stackexchange",
"id": 44950,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, mysql",
"url": null
} |
java
Title: Code to find a similar RGB color to an input RGB color
Question: Given an input color string in the format "#ABCDEF", representing a red-green-blue color, find the shorthand representation of that color that is most similar to the given color. Shorthand representation is in the form "#XYZ", where X, Y, and Z are one of the 16 possible hexadecimal values \$(0-9, A-F)\$.
The similarity between two colors "#ABCDEF" and "#UVWXYZ" is calculated as \$-(AB - UV)^2 - (CD - WX)^2 - (EF - YZ)^2\$.
Example 1:
Input: color = "#09f166"
Output: "#11ee66"
Explanation: The similarity is calculated as \$-(0x09 - 0x11)^2 - (0xf1 - 0xee)^2 - (0x66 - 0x66)^2\$ = -64 - 9 - 0 = -73. The shorthand color "#11ee66" has the highest similarity.
Example 2:
Input: color = "#4e3fe1"
Output: "#5544dd"
Constraints:
The input color has a length of 7 characters.
The first character of color is '#'.
The remaining characters of color are either digits or lowercase characters in the range ['a', 'f'].
Question: I am asked to return the shorthand representation of the color that has the highest similarity to the given color.
Approach 1: wrong solution as it seems where I tried to loop over all possible values r=r+1, g=g+1, b=b+1 in 3 for loops and then find the similarity after combing rgb in one color and finding similarity with input color.
public class Solution {
public String similarRGB(String color) {
// Convert the given color to its RGB representation
int[] rgb = new int[3];
for (int i = 1; i <= 5; i += 2) {
rgb[(i - 1) / 2] = Integer.parseInt(color.substring(i, i + 2), 16);
}
// Initialize variables to keep track of the highest similarity and the best shorthand color
int maxSimilarity = Integer.MIN_VALUE;
String bestShorthand = ""; | {
"domain": "codereview.stackexchange",
"id": 44951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
// Iterate through all possible shorthand colors
for (int r = 0; r <= 255; r += 1) {
for (int g = 0; g <= 255; g += 1) {
for (int b = 0; b <= 255; b += 1) {
// Calculate the similarity with the given color
int similarity = -(squareDiff(r, rgb[0]) +
squareDiff(g, rgb[1]) +
squareDiff(b, rgb[2]));
// Update the best shorthand color if the current similarity is higher
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestShorthand = "#" + toHex(r) + toHex(g) + toHex(b);
}
}
}
}
return bestShorthand;
}
// Helper method to calculate the squared difference between two numbers
private int squareDiff(int a, int b) {
return (a - b) * (a - b);
}
// Helper method to convert a decimal number to its two-digit hexadecimal representation
private String toHex(int num) {
String hex = Integer.toHexString(num);
return hex.length() == 1 ? "0" + hex : hex;
}
}
Approach 2: correct solution as it seems. We have to loop in a step of 17 r=r+17, g=g+17, b=b+17 in 3 for loops and then find the similarity after combing rgb in one color and finding similarity with input color. This seems to be the correct solution. We keep the code above as its but we just change the increment of the inner 3 for loops:
// Iterate through all possible shorthand colors
for (int r = 0; r <= 255; r += 17) {
for (int g = 0; g <= 255; g += 17) {
for (int b = 0; b <= 255; b += 17) {
// Calculate the similarity with the given color
int similarity = -(squareDiff(r, rgb[0]) +
squareDiff(g, rgb[1]) +
squareDiff(b, rgb[2])); | {
"domain": "codereview.stackexchange",
"id": 44951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
// Update the best shorthand color if the current similarity is higher
if (similarity > maxSimilarity) {
maxSimilarity = similarity;
bestShorthand = "#" + toHex(r) + toHex(g) + toHex(b);
}
}
}
}
I am not sure why my approach is wrong and approach 2 is right?
Answer: Not having run it, Approach 1 looks like it would
just be the identity function, spitting out exactly what went in.
That is, there's no rounding.
An input like #ABCDEF should be rounded off to #BBDDFF.
A smaller value like #234567 would round in the
other direction to #224466,
and color values in the neighborhood of 0x80 might
go up or down depending on what the other two colors are doing.
Approach 2 produces correct results but it seems expensive,
going through 2 ** 12 loops.
After quantizing to multiples of 0x11 (multiples of 17),
surely we only need to go up or down a single value, right?
So testing eight candidates, instead of four thousand, should suffice. | {
"domain": "codereview.stackexchange",
"id": 44951,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
python, performance, numpy, numba
Title: Find the first value bigger than a threshold
Question: This function takes two inputs: A is 2D (N,5) while B is 1D (N).
It tries to find the smallest j such that A[i,j] > B[i] for all i.
Using numpy with argmax trick is slower than this version where I loop manually through all i and compile it with numba. I think the reason why is because as N gets much bigger (~60000), it's more expensive to index on the first dimension, rather than to just loop and hoping to stop at small j, e.g., j=2 or j=3.
Any ideas how to further speed things up?
@nb.jit(nb.int64[:](nb.float32[:,:],nb.float32[:]),nopython=True,cache=True)
def find_passed_hz(A, B):
C = np.empty(len(B), dtype=np.int64)
_, m = A.shape # m=5
n = len(current_times)
for i in range(n):
for j in range(m):
if A[i,j] > B[i]:
C[i] = j
break
return C
NOTE: every row of A is sorted in ascending order, but because m=5 very small for numpy search_sorted or binary search to have any effect (or not? I tried but it seems to have no effect). | {
"domain": "codereview.stackexchange",
"id": 44952,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, numba",
"url": null
} |
python, performance, numpy, numba
Answer: If the dimension was (N, 4), I'd feel invited to open code a binary search.
(N, 5) is one of the "worst" cases: one more value to check than ideal for a binary search.
Just the same:
def find_passed_hz(A, thresholds): # ToDo: check name is suggestive. Type hints?
""" Return an array C of
smallest elements of A[i, j] exceeding thresholds[i] for each i.
A[i, j] <= A[i, j + 1]; A[i, 4] is known to exceed thresholds[i].
"""
C = np.empty(len(thresholds), dtype=np.int64)
n = len(current_times) # ToDo: explain current_times
for i in range(n): # i, threshold in enumerate(thresholds)
threshold = thresholds[i]
if threshold < A[i, 2]: # A[i, 2] would do: how about A[i, 0/1]?
if threshold < A[i, 1]: # A[i, 1] would do: how about A[i, 0]?
C[i] = A[i, 0 if threshold < A[i, 0] else 1]
else
C[i] = A[i, 2] # known good
else:
C[i] = A[i, 3 if threshold < A[i, 3] else 4]
return C | {
"domain": "codereview.stackexchange",
"id": 44952,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, numba",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
Title: Design an algorithm to predict words based on a skeleton from a given dictionary
Question: The model I'm building first selects a secret word at random from a list. The model which uses an API then returns a row of underscores (space separated)—one for each letter in the secret word—and asks the user to guess a letter. If the user guesses a letter that is in the word, the word is redisplayed with all instances of that letter shown in the correct positions, along with any letters correctly guessed on previous turns. If the letter does not appear in the word, the user is charged with an incorrect guess. The user keeps guessing letters until either (1) the user has correctly guessed all the letters in the word or (2) the user has made six incorrect guesses.
I'm working on an algorithm which is permitted to use a training set of approximately 250,000 dictionary words.
I have built and providing here with a basic, working algorithm. This algorithm will match the provided masked string (e.g. a _ _ l e) to all possible words in the dictionary, tabulate the frequency of letters appearing in these possible words, and then guess the letter with the highest frequency of appearence that has not already been guessed. If there are no remaining words that match then it will default back to the character frequency distribution of the entire dictionary.
This benchmark strategy is successful approximately 18% of the time. I aim to design an algorithm that significantly outperforms this benchmark.
import random
import string
import time
import re
import collections
import math
import json
import requests
import numpy as np
from urllib.parse import parse_qs, urlencode, urlparse
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from sklearn.tree import DecisionTreeClassifier
from sklearn.feature_extraction.text import CountVectorizer | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
####This is a part of the larger code and this code is written by the according to the API mode here
try:
from urllib.parse import parse_qs, urlencode, urlparse
except ImportError:
from urlparse import parse_qs, urlparse
from urllib import urlencode
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
######Start of the code up for review
class HangmanAPI(object):
def __init__(self, access_token=None, session=None, timeout=None):
self.hangman_url = self.determine_hangman_url()
self.access_token = access_token
self.session = session or requests.Session()
self.timeout = timeout
self.guessed_letters = []
full_dictionary_location = "words_250000_train.txt"
self.full_dictionary = self.build_dictionary(full_dictionary_location)
self.full_dictionary_common_letter_sorted = collections.Counter("".join(self.full_dictionary)).most_common()
self.current_dictionary = []
# Initialize the decision tree model and vectorizer here
self.decision_tree_model = DecisionTreeClassifier()
self.vectorizer = CountVectorizer(analyzer='char', lowercase=False, binary=True)
self.target_labels = [chr(ord('a') + i) for i in range(26)]
# Fit the decision tree model with the full dictionary once during initialization
X = self.vectorizer.fit_transform(self.full_dictionary)
y = np.array([word[-1] for word in self.full_dictionary])
self.decision_tree_model.fit(X, y)
@staticmethod
def determine_hangman_url():
links = ['https://trexsim.com', 'https://sg.trexsim.com']
data = {link: 0 for link in links}
for link in links:
requests.get(link)
for i in range(10):
s = time.time()
requests.get(link)
data[link] = time.time() - s | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
link = sorted(data.items(), key=lambda x: x[1])[0][0]
link += '/trexsim/hangman'
return link
def guess(self, word):
# Clean the word so that we strip away the space characters
# Replace "_" with "." as "." indicates any character in regular expressions
clean_word = word[::2].replace("_", ".")
# Find length of the passed word
len_word = len(clean_word)
# Grab current dictionary of possible words from self object, initialize a new possible words dictionary to empty
current_dictionary = self.current_dictionary
new_dictionary = []
# Iterate through all of the words in the old plausible dictionary
for dict_word in current_dictionary:
# Continue if the word is not of the appropriate length
if len(dict_word) != len_word:
continue
# If dictionary word is a possible match, then add it to the current dictionary
if re.match(clean_word, dict_word):
new_dictionary.append(dict_word)
# Overwrite old possible words dictionary with the updated version
self.current_dictionary = new_dictionary
# If there are no remaining words that match, default back to the ordering of the full dictionary
if not new_dictionary:
sorted_letter_count = self.full_dictionary_common_letter_sorted
else:
# Update the current dictionary with the new_dictionary
self.current_dictionary = new_dictionary
# Get the count of each letter at each position in the current dictionary
letter_counts = [{letter: sum(1 for word in self.current_dictionary if word[i] == letter) for letter in self.target_labels}
for i in range(len(clean_word))] | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
# Choose the character with the highest count at the next position
next_position = len(self.guessed_letters)
guessed_letter = max(letter_counts[next_position], key=letter_counts[next_position].get)
# Remove the guessed letter from the possible letters in current_dictionary
self.current_dictionary = [word for word in self.current_dictionary if guessed_letter not in word]
return guessed_letter
# Return the letter with the highest information gain that hasn't been guessed yet
for letter, info_gain in sorted_letter_count:
if letter not in self.guessed_letters:
return letter
# If all letters have been guessed, revert to ordering of full dictionary (fallback)
return self.full_dictionary_common_letter_sorted[0][0]
def make_decision(self, word_pattern):
# Use decision tree model to make a prediction
X = self.vectorizer.transform(self.current_dictionary)
# Get the target labels (last character of each word) for the decision tree model
y = np.array([word[-1] for word in self.current_dictionary])
self.decision_tree_model.fit(X, y)
# Transform the word pattern using the vectorizer
pattern_vectorized = self.vectorizer.transform([word_pattern])
# Make a prediction for the next letter probabilities
next_letter_probabilities = self.decision_tree_model.predict_proba(pattern_vectorized)[0]
# Get the index of the predicted letter (letter with the highest probability)
next_letter_index = np.argmax(next_letter_probabilities)
# Convert the predicted index back to the letter
guessed_letter = self.target_labels[next_letter_index]
return guessed_letter | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
return guessed_letter
def compute_conditional_probabilities(self, word_pattern):
# Count the occurrence of each letter in the possible words
full_dict_string = "".join(self.current_dictionary)
c = collections.Counter(full_dict_string)
# Calculate the total count of letters in the possible words
total_letter_count = sum(c.values())
# Calculate the conditional probabilities of each letter given the word pattern
letter_probabilities = {}
for letter in string.ascii_lowercase:
if letter not in self.guessed_letters:
pattern_with_letter = word_pattern.replace(".", letter)
matching_words_count = sum(1 for word in self.current_dictionary if re.match(pattern_with_letter, word))
conditional_probability = matching_words_count / total_letter_count
# Calculate the information gain using entropy (log2)
information_gain = -conditional_probability * math.log2(conditional_probability) if conditional_probability > 0 else 0
letter_probabilities[letter] = information_gain
return letter_probabilities
def build_dictionary(self, dictionary_file_location):
text_file = open(dictionary_file_location, "r")
full_dictionary = text_file.read().splitlines()
text_file.close()
return full_dictionary | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
####This is a part of the larger code and this code is written by the according to the API mode here
def start_game(self, practice=True, verbose=True):
# reset guessed letters to empty set and current plausible dictionary to the full dictionary
self.guessed_letters = []
self.current_dictionary = self.full_dictionary
response = self.request("/new_game", {"practice":practice})
if response.get('status')=="approved":
game_id = response.get('game_id')
word = response.get('word')
tries_remains = response.get('tries_remains')
if verbose:
print("Successfully start a new game! Game ID: {0}. # of tries remaining: {1}. Word: {2}.".format(game_id, tries_remains, word))
while tries_remains>0:
# get guessed letter from user code
guess_letter = self.guess(word)
# append guessed letter to guessed letters field in hangman object
self.guessed_letters.append(guess_letter)
if verbose:
print("Guessing letter: {0}".format(guess_letter))
try:
res = self.request("/guess_letter", {"request":"guess_letter", "game_id":game_id, "letter":guess_letter})
except HangmanAPIError:
print('HangmanAPIError exception caught on request.')
continue
except Exception as e:
print('Other exception caught on request.')
raise e
if verbose:
print("Sever response: {0}".format(res))
status = res.get('status')
tries_remains = res.get('tries_remains')
if status=="success":
if verbose: | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
if status=="success":
if verbose:
print("Successfully finished game: {0}".format(game_id))
return True
elif status=="failed":
reason = res.get('reason', '# of tries exceeded!')
if verbose:
print("Failed game: {0}. Because of: {1}".format(game_id, reason))
return False
elif status=="ongoing":
word = res.get('word')
else:
if verbose:
print("Failed to start a new game")
return status=="success"
def my_status(self):
return self.request("/my_status", {})
def request(self, path, args=None, post_args=None, method=None):
if args is None:
args = dict()
if post_args is not None:
method = "POST" | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
# Add `access_token` to post_args or args if it has not already been included.
if self.access_token:
# If post_args exists, we assume that args either does not exist or it does not need `access_token`.
if post_args and "access_token" not in post_args:
post_args["access_token"] = self.access_token
elif "access_token" not in args:
args["access_token"] = self.access_token
time.sleep(0.2)
num_retry, time_sleep = 50, 2
for it in range(num_retry):
try:
response = self.session.request(
method or "GET",
self.hangman_url + path,
timeout=self.timeout,
params=args,
data=post_args,
verify=False
)
break
except requests.HTTPError as e:
response = json.loads(e.read())
raise HangmanAPIError(response)
except requests.exceptions.SSLError as e:
if it + 1 == num_retry:
raise
time.sleep(time_sleep)
headers = response.headers
if 'json' in headers['content-type']:
result = response.json()
elif "access_token" in parse_qs(response.text):
query_str = parse_qs(response.text)
if "access_token" in query_str:
result = {"access_token": query_str["access_token"][0]}
if "expires" in query_str:
result["expires"] = query_str["expires"][0]
else:
raise HangmanAPIError(response.json())
else:
raise HangmanAPIError('Maintype was not text, or querystring') | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
if result and isinstance(result, dict) and result.get("error"):
raise HangmanAPIError(result)
return result
class HangmanAPIError(Exception):
def __init__(self, result):
self.result = result
self.code = None
try:
self.type = result["error_code"]
except (KeyError, TypeError):
self.type = ""
try:
self.message = result["error_description"]
except (KeyError, TypeError):
try:
self.message = result["error"]["message"]
self.code = result["error"].get("code")
if not self.type:
self.type = result["error"].get("type", "")
except (KeyError, TypeError):
try:
self.message = result["error_msg"]
except (KeyError, TypeError):
self.message = result
Exception.__init__(self, self.message)
I am trying to implement a unique method which is under the "guess" method.
The dataset to try the training can be found: here
Answer: Overall, the source code looks structured - some lines are overly long, comments as well as code.
There is more to the Style Guide for Python Code than Limit all lines to a maximum of 79 characters. and Use 4 spaces per indentation level. [optional for continuation lines]; in particular,
use Documentation Strings. (I wish it strongly recommended including doctests.)
There are useful comments like
# Clean the word by stripping away the space characters
clean_word = word[::2]
, useless ones
# Find length of the passed word
len_word = len(word)
, and there are comments from irritating to misleading
# Find length of the passed word
len_word = len(clean_word) | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, algorithm, strings, mathematics, machine-learning
- clean_word is neither the parameter passed, nor is its value the value passed (unless len(word) < 2).
(This particular one might have happened to me - I might have written "pseudo code comments" first, to later code the parts: one needs to take care detail comments&code are consistent.)
And there are restricting comments:
Following # Iterate through all of the words in the old plausible dictionary,
who'd expect anything but for ‹word› in current_dictionary:?
# Need a dictionary of words still possible allows filter() as well as comprehensions.
HangmanAPI as a name suggests a single responsibility, which would be a good thing.
I see business logic here, too.
.full_dictionary currently is an instance variable - fine if the contents can be selected at instantiation (e.g. make full_dictionary_location an __init__() parameter with a default). Otherwise I'd prefer a class data member.
In guess(), you check the length of every word in every dictionary considered.
Length doesn't change: have build_dictionar…() return dictionaries by length.
You use lists for dictionaries: measure the impact of using sets instead. Or strings (words separated by a non-character), to be used with finditer().
26 is a magic number:
self.target_labels = [chr(o) for o in range(ord('a'), ord('z')+1)]
In guess(), the else: statement starts with a redundant assignment - and ends with a return: use if new_dictionary: instead.
if not going dictionary is a string&finditer, it may pay to compile REs while there are lots of strings to check | {
"domain": "codereview.stackexchange",
"id": 44953,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, algorithm, strings, mathematics, machine-learning",
"url": null
} |
python, performance
Title: Python Script to Calculate Historical S&P 500 Returns over Requested Time Span
Question: I have a Python script that calculates the historical S&P 500 returns from a starting balance and annual contribution. The script also outputs interesting statistics (mean/min/max/stddev/confidence intervals) related to the historical returns. I'm seeking feedback on how the code could be refactored more efficiently.
sp500_time_machine.py
import os, sys, time
import datetime
import argparse
import statistics
import math
from sp500_data import growth
MONTHS_PER_YEAR = 12
FIRST_YEAR = 1928 # This is the first year of data from the dataset
# Given an initial investment, an annual contribution and a span in years, show how the investment would mature
# based on historical trends of the S&P 500
def sp500_time_machine(starting_balance, span, annual_contribution):
realized_gain_list = []
average_gain = 0
current_year = datetime.date.today().year # Grab this from the OS
total_spans = (current_year - FIRST_YEAR - span) + 1
# Adjust the starting year for each span
for base_year in range(total_spans):
realized_gains = starting_balance
# Loop through each span, month by month
for month in range(span * MONTHS_PER_YEAR):
realized_gains = (realized_gains + (annual_contribution / MONTHS_PER_YEAR)) * (1 + growth[month + base_year] / 100)
# Store each realized gain over the requested span in a list for later processing
realized_gain_list.append(realized_gains)
print("S&P realized gains plus principle from %s to %s for %s starting balance = %s" % ((FIRST_YEAR + base_year), (FIRST_YEAR + base_year + span), f'{starting_balance:,}', f'{int(realized_gains):,}'))
average_gain = average_gain + realized_gains | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
# Display the average, minimum and maximum gain over the requested time span
mean = int(average_gain / total_spans)
print("Average %s year realized gains plus principle over %d years is %s" % (span, total_spans, f'{mean:,}'))
# Calculate the standard deviation
std_dev = statistics.stdev(realized_gain_list)
print("Standard Deviation = %s" % f'{int(std_dev):,}')
# Determine the 99% confidence interval
#
# Stock market returns are not normally distributed, so this is a simplification of actual real-world data
# https://klementoninvesting.substack.com/p/the-distribution-of-stock-market
#
# z-score values are based on normal distributions
# The value of 1.96 is based on the fact that 95% of the area of a normal distribution is within 1.96 standard deviations of the mean
# Likewise, 2.58 standard deviations contain 99% of the area of a normal distribution
# 90% confidence z-value = 1.65
# 95% confidence z-value = 1.96
# 99% confidence z-value = 2.58
upper_interval = mean + 2.58 * (std_dev / math.sqrt(total_spans))
print("99%% Confidence Interval (Upper) = %s" % f'{int(upper_interval):,}')
lower_interval = mean - 2.58 * (std_dev / math.sqrt(total_spans))
print("99%% Confidence Interval (Lower) = %s" % f'{int(lower_interval):,}')
# Find the min/max values
min_gain = min(realized_gain_list)
min_gain_index = realized_gain_list.index(min_gain)
print("Minimum realized gain plus principle over %d years occurred from %s to %s with a final balance of %s" %
(span, min_gain_index + FIRST_YEAR, min_gain_index + FIRST_YEAR + span, f'{int(min_gain):,}'))
max_gain = max(realized_gain_list)
man_gain_index = realized_gain_list.index(max_gain)
print("Maximum realized gain plus principle over %d years occurred from %s to %s with a final balance of %s" %
(span, man_gain_index + FIRST_YEAR, man_gain_index + FIRST_YEAR + span, f'{int(max_gain):,}')) | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--span", help="The number of consecutive years (span) to iterate over")
parser.add_argument("-p", "--principle", help="The initial investment amount")
parser.add_argument("-a", "--annual", help="The annual contribution amount")
args = parser.parse_args()
sp500_time_machine(int(args.principle), int(args.span), int(args.annual)) | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
sp500_data.py
# Monthly growth data taken from https://www.officialdata.org/us/stocks/s-p-500/ and based upon http://www.econ.yale.edu/~shiller/data.htm
# This data contains reinvested dividends
# This data does NOT adjust for inflation! | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
growth = [-0.83, 5.75, 6.66, 3.44, -4.57, 1.09, 3.59, 7.37, 2.36, 7.08, 0.70, 7.69, 0.81, 2.05, -0.30, 1.80, 2.20, 9.20, 5.96, 4.24, -10.32, -26.19, 4.37, 1.83, 6.64, 4.12, 6.69, -5.65, -9.77, -1.76, -0.90, 0.34, -13.37, -6.80, -6.19, 3.56, 8.14, 2.38, -9.08, -9.16, -2.68, 3.86, -2.49, -14.37, -12.75, 2.05, -18.10, -0.85, -0.05, 1.14, -23.22, -11.31, -12.39, 6.18, 51.35, 10.37, -13.22, -0.34, -2.64, 4.57, -11.27, 0.33, 11.24, 29.32, 17.58, 8.46, -4.64, -0.48, -9.38, 2.80, 2.32, 6.08, 7.75, -4.80, 2.02, -9.83, 1.70, -4.36, -3.51, -2.01, 1.21, 3.21, 1.06, 0.40, -2.62, -5.93, 7.94, 8.27, 4.17, 5.60, 7.10, 2.43, 2.99, 9.71, 0.29, 5.82, 6.03, 2.41, 0.41, -5.02, 4.57, 6.23, 2.30, 1.44, 5.55, 3.10, -1.40, 3.46, 3.30, 0.23, -5.62, -4.09, -3.34, 6.39, 1.44, -13.76, -14.10, -8.27, -1.02, 3.24, -1.80, -6.02, -3.44, 1.56, 2.93, 20.49, 1.06, -4.08, 11.62, 0.47, -2.55, -1.16, -0.46, 0.27, -12.24, 4.10, 2.17, 2.84, -1.07, 11.06, 1.38, -1.41, -1.97, -0.15, -0.23, -0.15, 1.42, -13.34, -8.09, 3.87, 2.65, 4.76, 1.47, 2.85, -3.59, 0.72, -5.72, 1.18, -2.55, -1.59, 4.11, 5.71, 0.08, 0.86, -3.43, -4.08, -5.88, 2.62, -2.48, -4.76, -3.45, 1.87, 5.75, 4.38, 0.05, 1.66, 7.97, 2.15, 1.06, 6.50, 6.43, 4.01, 3.79, 4.36, 2.18, 2.47, -4.54, 2.55, -0.50, -4.21, 1.77, 3.67, -0.24, 3.24, -1.31, 2.20, 5.14, 3.02, -1.06, -1.23, 2.88, -0.28, 2.60, 3.38, 3.73, 0.31, 2.90, 4.16, 2.19, -1.70, 0.71, 7.18, 4.51, 3.61, 2.02, 4.30, 0.59, -2.68, 6.77, 0.52, -0.34, -2.55, -1.62, -14.42, -1.87, -0.01, 3.39, 0.92, 4.27, -3.67, -3.30, -1.36, 3.92, 6.69, -1.56, -2.17, 3.03, -0.73, -1.12, -0.86, -4.45, 1.92, 8.19, 5.33, 4.59, -1.96, -2.49, -0.68, 3.19, -5.10, -0.16, 1.63, -3.33, 1.49, 0.41, -0.18, -4.91, 6.26, 4.17, 1.87, 3.14, 1.95, 3.24, 2.63, 2.52, 1.38, 3.39, 3.91, 2.16, -6.72, 6.64, 4.11, 4.72, 0.38, 0.19, 8.01, 4.31, -1.11, 1.93, 0.63, -1.15, 2.37, 4.97, 3.14, 0.03, -2.25, 3.61, 3.83, -1.33, 0.75, 0.20, 0.46, 3.24, 3.37, 0.88, -1.11, -1.61, 3.67, 4.51, 0.99, -0.77, 0.96, -4.47, 1.00, -3.11, 1.91, 0.90, -4.11, | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
3.37, 0.88, -1.11, -1.61, 3.67, 4.51, 0.99, -0.77, 0.96, -4.47, 1.00, -3.11, 1.91, 0.90, -4.11, 3.52, 2.71, 1.84, 3.02, 2.68, 2.58, 4.45, 4.42, 1.22, 4.46, 2.39, 2.74, 2.71, 4.30, 4.95, 2.17, 3.70, -0.44, 3.81, -0.08, 6.15, 7.64, -0.30, 4.82, -4.72, 7.07, 1.24, -2.39, 0.95, 7.21, 1.48, -2.84, -0.26, 5.75, -0.28, -3.09, -0.95, -0.71, 1.81, -1.86, -4.00, 1.62, 2.64, 4.16, 1.95, 2.32, -5.21, -3.74, -5.90, -1.80, 0.32, 2.33, 0.70, 2.42, 0.90, 3.56, 2.74, 3.07, 4.05, 2.94, 4.36, 3.33, 2.16, 4.25, -1.27, 2.81, 1.94, 1.77, -0.61, 4.23, -0.32, -3.70, 0.18, 0.67, 3.46, -1.49, -3.61, -1.08, 1.58, -0.62, 3.99, -2.20, 1.49, -2.72, -1.67, 3.54, 2.69, 5.43, 4.37, 3.40, 2.92, 1.26, -1.08, -0.03, 3.84, -0.54, 1.34, 4.77, 1.16, -3.49, 1.91, 0.34, -2.94, -7.19, -11.41, 2.72, 3.02, -0.59, -2.86, 7.20, 4.62, 4.15, 1.60, -0.11, 4.98, 2.27, 0.22, -1.22, 3.03, 2.89, 0.50, -0.31, 2.39, 3.33, 1.48, 2.07, 1.69, 1.22, -0.35, 3.96, -1.23, 1.97, 1.97, 0.94, -1.49, 2.82, 0.98, 0.34, 1.56, 1.73, -4.51, 0.10, 2.12, 3.60, 2.50, 1.08, -0.21, 1.98, -0.43, -3.86, 3.32, -5.01, -0.56, 0.02, -5.77, -3.22, -0.56, 5.32, 0.72, 4.13, 3.73, 2.63, 1.99, 2.06, -0.99, 1.99, 1.85, 1.65, 0.10, -2.88, 3.11, -0.02, -4.26, -1.56, 7.66, 2.56, 2.94, 0.05, -1.93, 3.51, 2.72, 1.79, 1.29, -3.99, -0.24, -1.91, 2.27, 3.51, -4.97, -4.21, -0.28, 0.63, 1.35, 1.00, -5.03, -0.59, -3.20, 2.01, -2.75, -11.20, -0.27, 0.52, 3.26, 6.32, 2.49, 0.21, 7.16, 4.11, 4.15, 2.83, 3.67, -1.11, -1.60, -0.46, -1.52, 2.49, -1.86, -4.37, 7.16, 4.42, 2.09, 2.62, 1.26, -0.78, 0.52, -0.50, 3.78, -1.21, 0.42, 5.25, 2.31, 0.99, -3.33, -1.35, -1.63, -2.57, -1.99, 1.21, -1.64, 2.00, 4.24, -6.85, -6.81, 1.70, -2.47, 4.57, -4.82, -2.71, 0.46, -11.35, -3.76, -10.01, 2.38, 3.74, -6.09, 8.63, 10.81, 4.97, 1.49, 6.71, 2.89, 0.43, -7.00, -0.85, 4.97, 2.04, -1.18, 9.55, 4.18, 0.80, 1.10, -0.38, 0.90, 2.67, -0.56, 2.44, -3.11, -0.37, 3.79, -0.54, -2.37, -0.05, -1.19, 0.06, 0.90, 1.28, -2.08, -1.18, -2.20, 0.98, -0.08, -3.39, -0.97, 0.27, 4.83, 5.50, 0.67, -0.06, | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
0.06, 0.90, 1.28, -2.08, -1.18, -2.20, 0.98, -0.08, -3.39, -0.97, 0.27, 4.83, 5.50, 0.67, -0.06, 7.33, 0.40, -2.77, -5.44, 1.92, 4.19, -1.06, 2.34, 2.43, -1.89, 2.42, 1.42, 5.01, 1.54, -3.35, -0.32, 4.40, 3.31, 4.40, -8.78, -1.16, 5.04, 6.86, 4.97, 3.50, 2.84, 3.32, 4.61, -1.24, 0.01, -3.07, 4.14, 1.29, -1.62, 0.86, -2.02, 0.80, -8.30, 1.73, 3.04, 1.18, -4.80, -1.91, -2.74, 5.47, 0.57, -5.27, 0.24, 0.79, 12.10, 8.88, 4.50, 1.36, 3.93, 2.13, 3.87, 4.20, 4.42, 1.75, 0.71, -2.41, 3.31, 0.65, -1.14, -0.13, 1.58, -5.11, 0.44, 0.51, -0.25, -1.85, -0.91, 9.21, 1.41, -0.41, 1.29, -0.71, 4.70, 5.79, -0.48, 1.02, 2.74, 2.51, 2.25, -1.85, -1.88, 1.50, 6.42, 5.29, 0.75, 5.70, 6.18, 2.74, 0.49, 3.13, -1.80, 2.28, -2.46, -0.09, 3.53, 1.71, 6.67, 6.46, 4.38, -0.86, 0.17, 4.50, 3.12, 6.45, -3.03, -11.85, -12.30, -1.33, 4.25, 3.33, 3.23, -0.89, -2.19, 6.00, -0.31, -1.72, 1.93, 3.80, -2.02, 2.33, 3.51, 3.30, -0.16, 3.56, 4.12, 3.39, 2.80, 4.69, 0.46, 0.29, -1.81, 2.74, -2.21, -2.53, 2.71, 0.20, 3.85, 3.17, 0.17, -7.86, -4.34, -2.32, 2.98, 4.59, -0.69, 11.61, 3.04, 2.26, -0.18, 0.35, 0.78, 2.68, -0.30, 0.18, 0.02, 0.94, 7.36, -0.60, -1.01, 0.26, 2.07, -1.33, 1.91, 0.94, 0.38, -1.18, 2.76, 3.27, 0.14, 1.72, 2.15, -1.34, 0.72, 0.87, 0.06, 1.76, 1.35, 1.24, 0.01, 0.89, 1.74, -0.08, -1.42, -3.35, 1.06, 1.11, -0.52, 3.08, 0.82, -0.44, -0.37, -1.03, 2.45, 3.82, 2.56, 3.22, 3.35, 3.18, 3.55, 0.51, 3.72, 0.91, 2.36, 3.39, 0.16, 5.90, -0.20, 0.20, 2.35, 1.28, -3.48, 3.08, 2.02, 4.12, 5.05, 1.20, 3.26, 4.36, -0.62, -3.41, 9.22, 5.34, 5.74, 0.35, 1.19, 1.65, -1.15, 2.63, 0.24, 6.40, 5.31, 3.41, -0.22, 0.12, 4.47, -6.97, -4.90, 1.29, 10.97, 4.10, 5.05, -0.07, 2.92, 4.25, -0.10, -0.61, 4.52, -3.77, -0.60, -1.27, 7.11, 2.81, -0.12, -2.48, 3.94, 1.42, -2.84, 3.16, 0.85, 0.94, -1.08, -5.21, -0.77, -3.32, 0.46, -2.14, -9.08, 0.45, 6.88, -2.39, -2.66, -2.05, -11.25, 3.18, 5.05, 1.47, -0.30, -3.35, 4.95, -3.51, -2.82, -5.92, -10.76, 1.14, -4.76, -1.37, 6.63, -1.04, -0.22, -6.41, 1.31, 5.29, 5.31, 5.70, | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
-3.51, -2.82, -5.92, -10.76, 1.14, -4.76, -1.37, 6.63, -1.04, -0.22, -6.41, 1.31, 5.29, 5.31, 5.70, 0.60, -0.17, 3.16, 2.03, 1.21, 3.06, 4.93, 1.09, -1.57, 0.97, -2.56, 2.86, -2.24, -1.39, 2.78, 0.10, 4.77, 2.73, -1.35, 1.68, -0.26, -2.41, 1.34, 2.18, 1.81, 0.31, 0.28, -2.62, 3.96, 2.14, 1.47, -0.02, 1.49, 0.80, -0.79, -2.71, 0.72, 2.29, 2.53, 3.62, 2.00, 2.15, 0.69, 1.60, -2.47, 4.18, 3.39, 0.34, 0.57, -4.20, 3.07, 2.99, -4.81, 1.24, -6.64, -1.56, -2.63, 4.24, 2.56, -4.25, -6.08, 2.11, -4.85, -20.19, -8.61, -0.35, -1.10, -6.70, -5.69, 12.32, 6.66, 2.87, 1.28, 8.12, 3.65, 2.40, 2.09, 2.23, 1.36, -2.90, 5.94, 4.09, -5.88, -3.54, -0.16, 0.86, 3.37, 4.58, 2.49, 3.71, 3.46, 3.15, -1.11, 2.22, 0.66, -3.66, 3.10, -10.40, -0.79, 3.02, 1.77, 1.55, 4.78, 4.16, 2.88, -0.04, -3.09, -1.15, 2.92, 3.39, 3.02, -0.22, -2.84, 2.18, 4.27, 2.33, 2.72, 1.45, 4.57, -1.12, 3.25, 0.25, 1.19, 2.12, 3.86, 1.52, 0.97, -0.13, 2.72, 0.20, 1.53, 3.20, 1.50, -0.43, 1.78, -2.65, 5.71, 0.63, -1.11, 2.83, 0.06, 0.88, 0.98, -0.44, -0.08, -2.42, -4.51, 4.32, 2.93, -1.10, -6.42, -0.55, 6.36, 2.83, -0.30, 1.07, 3.30, 1.20, -0.44, -0.51, 1.20, 3.95, 1.44, 2.58, 1.75, -0.15, 1.69, 1.78, 0.99, 0.25, 1.65, 2.73, 1.59, 2.88, 4.86, -2.89, 0.06, -1.66, 1.96, 2.11, 1.58, 2.45, 1.68, -3.85, -2.08, -5.56, 1.74, 5.83, 1.95, 3.72, -1.53, 1.40, 3.83, -3.13, 3.09, 0.01, 4.43, 2.47, 3.35, 0.12, -18.92, 4.32, 5.89, 6.51, 3.48, 5.89, -0.63, 1.73, 3.95, 4.26, 2.80, 2.49, 0.82, 6.02, 0.76, 1.81, 3.07, 2.19, -0.08, 0.45, 4.74, 0.27, -2.05, -2.90, -0.89, 0.12, -7.87, -3.37, 0.46, 6.45, -7.28, -3.09, 5.29, 0.01, 1.38, 3.15, -2.59, 4.00, 0.60, 4.80, 2.54] | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
Example usage:
python3 sp500_time_machine.py -s20 -p100000 -a0
Answer: lint
minor pep-8 nit:
It would be useful to run
isort on this.
docstrings where appropriate
# Given an initial investment ...
This is a helpful comment, and I thank you for it.
It would be more helpful as a """docstring""".
returning numeric results
def sp500_time_machine(starting_balance, span, annual_contribution):
This is an OK signature.
Consider adding float, int, float type hints to it.
span has units of years,
but that only becomes apparent upon reading the code.
We could introduce it a little more clearly.
If we did add type hinting, the signature would end with
def ... ) -> None:
which makes me sad.
It fits with the verb "show" in the introductory comment.
At fifty-ish lines this function is not too long.
But it does do more than
one thing.
Consider breaking out the initial loop as a helper function,
which returns a list of results.
More generally, consider making the computation of figures
separate from the display of figures.
This aids composition, and allows a
test suite
to verify specific calculations.
globals and testability
current_year = datetime.date.today().year
This is nice enough, but it relies on a global variable (clock).
It would be much nicer if we saw def ... , current_year=None):
in the signature, which defaults to current year:
current_year = current_year or datetime.date.today().year
That way a unit test could specify e.g. 2022
to "freeze" an historic result in time.
And the test would continue pass in 2024, 2025, and following years.
units, & parallel structure to names
The meaning of this manifest constant is very clear:
FIRST_YEAR = 1928
This seems to be a similar quantity, but it is zero-origin:
for base_year in range(total_spans): | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
This seems to be a similar quantity, but it is zero-origin:
for base_year in range(total_spans):
Ultimately it combines with
for month in range(span * MONTHS_PER_YEAR)
to form an anonymous month + base_year index.
Going back and forth on the units is a bit jarring.
Consider incrementing a datetime.date
(or datetime.datetime) in the loop.
Consider breaking out that growth[]
de-reference so a helper function "knows"
how to turn a point-in-time into
the correct array index.
# Store each realized gain over the requested span in a list for later processing
Elide the obvious comment -- the code eloquently said that already.
realized_gain_list.append(realized_gains)
Consider switching to a dict so the year is apparent:
realized_gain[FIRST_YEAR + base_year] = realized_gains.
The idea is to produce a results datastructure
which a maintenance engineer could not possibly misinterpret.
... starting balance = %s" % ...
Outputting an explicit $ dollar sign wouldn't hurt.
Consider using an
f-string
rather than the % percent operator.
extract helper
# Display the average, ...
To keep computation and display separate,
consider breaking out this section into a helper function.
Thank you for the Klement citation
and the reminder of Gaussian facts,
so the magic numbers are well-explained.
wrangling inputs
Nice arg parser.
Aha! "--span", help="The number of consecutive years (span) ... --
that's what I'd been looking for, perfect.
... int(args.principle), int(args.span), int(args.annual)
Consider asking
argparse
to call int() for you,
by specifying type=int. | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
python, performance
Consider asking
argparse
to call int() for you,
by specifying type=int.
docstrings on data
In sp500_data.py,
thank you for the pair of URL citations,
and for the "not in constant dollars!" warning.
These comments would work nicely as a """docstring"""
on the growth vector.
Then a maintenance engineer could import it and use
help(growth) to better understand how to correctly
interpret those figures.
The list of pasted numbers is straightforward,
and it's fine that we wind up with a very long line.
It's too bad that we don't see code or comments
explaining how that list was downloaded / cleaned / computed,
in case we want to reproduce results or incorporate
recent data a few years from now.
This function achieves its design goals.
It would benefit from unit tests,
and from pushing print() statements
into separate helpers.
I would be willing to delegate or accept
maintenance tasks on this codebase. | {
"domain": "codereview.stackexchange",
"id": 44954,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance",
"url": null
} |
rust, file-system, cryptography
Title: Idiomatic and performant file hashing
Question: I've written a small program that will accept a directory path and recursively calculate the MD5 hash of each file.
use std::{env, fs};
use md5::Digest;
fn main() {
let args: Vec<String> = env::args().collect();
let mut entries = get_files(&args[1]);
}
#[derive(Debug)]
struct FileInfo {
full_path: String,
hash: Option<Digest>,
}
fn get_file_info(file_path: &str) -> FileInfo {
FileInfo {
full_path: file_path.to_owned(),
hash: match fs::read(file_path) {
Ok(d) => Some(md5::compute(d)),
Err(_) => None,
},
}
}
fn get_files(dir_path: &str) -> Vec<FileInfo> {
fs::read_dir(dir_path)
.expect("Couldnt read path")
.filter(|path| path.is_ok())
.flat_map(|path| {
let path_buf = path
.as_ref()
.and_then(|p| Ok(p.path().to_owned()))
.expect("Unable to read path");
let file_path = path_buf.to_str().expect("msg");
let is_file = path
.and_then(|p| p.file_type())
.and_then(|ft| Ok(ft.is_file()))
.expect("Unable to read path");
if is_file {
vec![get_file_info(file_path)]
} else {
get_files(file_path)
}
})
.collect()
}
I'm mainly concerned about writing more idiomatic rust and performance. I think most improvements could be made to get_files( dir_path: &str ) -> Vec<FileInfo> but I'm not sure what to change. | {
"domain": "codereview.stackexchange",
"id": 44955,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, file-system, cryptography",
"url": null
} |
rust, file-system, cryptography
Answer: This is some good code for a (presumably) beginner.
Use (more) libraries
You can make your life easier, by using additional libraries like walkdir to traverse the directories.
Additionally, you can use clap to let it parse your command line arguments.
In your current code, further arguments to your program would be silently swallowed, which is not what a user may expect.
Implement useful traits
You can implement the instatiation of the FileInfo, which really constitutes a HashedFile by implementing TryFrom.
Avoid panics
Panicking is not a good way to handle errors, especially in an iterator.
If you're not interested in paths that failed to traverse, you can just filter them out or map them to respective errors.
Panicking would result in unwinding the stack and terminating the thread, thus ending your program, with zero chances for the user to process further, possibly valid items of the iterator.
Use generic types
Currently you limit the user to pass a &str as path to the base directory. Consider using impl AsRef<Path> intead, which will still allow to pass &str but also allow users to pass specialized Path objects.
Suggested change
Cargo.toml
[package]
name = "file_hashes"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
clap = { version = "4.3.19", features = ["derive"] }
md5 = "0.7.0"
walkdir = "2.3.3"
src/lib.rs
use md5::{compute, Digest};
use std::fmt::{Display, Formatter, LowerHex};
use std::fs::read;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
pub struct HashedFile {
path_buf: PathBuf,
hash: Digest,
}
impl Display for HashedFile {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.path_buf
.to_str()
.ok_or_else(std::fmt::Error::default)
.and_then(|path| write!(f, "{path}: "))?;
LowerHex::fmt(&self.hash, f)
}
} | {
"domain": "codereview.stackexchange",
"id": 44955,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, file-system, cryptography",
"url": null
} |
rust, file-system, cryptography
impl TryFrom<PathBuf> for HashedFile {
type Error = std::io::Error;
fn try_from(path_buf: PathBuf) -> Result<Self, Self::Error> {
Ok(Self {
hash: compute(read(path_buf.as_path())?),
path_buf,
})
}
}
pub fn hash_dir(dir: impl AsRef<Path>) -> impl Iterator<Item = std::io::Result<HashedFile>> {
WalkDir::new(dir.as_ref())
.into_iter()
.filter_map(Result::ok)
.filter(|entry| entry.file_type().is_file())
.map(|entry| HashedFile::try_from(entry.into_path()))
}
src/main.rs
use clap::Parser;
use file_hashes::hash_dir;
#[derive(Debug, Parser)]
struct Args {
directory: String,
}
fn main() {
hash_dir(Args::parse().directory).for_each(|result| match result {
Ok(file_hash) => println!("{file_hash}"),
Err(error) => eprintln!("{error}"),
});
} | {
"domain": "codereview.stackexchange",
"id": 44955,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, file-system, cryptography",
"url": null
} |
python, performance, algorithm, time-limit-exceeded
Title: Repeatedly remove a substring quickly
Question: I'm trying to solve the USACO problem Censoring (Bronze), which was the first problem for the 2015 February contest. My solution works for some test cases, but then times out for test cases 7-15. I expected it to run with O(n) time complexity because of the while loop, which should work, but it didn't.
Problem:
Farmer John has purchased a subscription to Good Hooveskeeping
magazine for his cows, so they have plenty of material to read while
waiting around in the barn during milking sessions. Unfortunately, the
latest issue contains a rather inappropriate article on how to cook
the perfect steak, which FJ would rather his cows not see (clearly,
the magazine is in need of better editorial oversight).
FJ has taken all of the text from the magazine to create the string S
of length at most 10^6 characters. From this, he would like to remove
occurrences of a substring T of length <= 100 characters to censor the
inappropriate content. To do this, Farmer John finds the first
occurrence of T in S and deletes it. He then repeats the process
again, deleting the first occurrence of T again, continuing until
there are no more occurrences of T in S. Note that the deletion of one
occurrence might create a new occurrence of T that didn't exist
before.
Please help FJ determine the final contents of S after censoring is
complete.
INPUT FORMAT: (file censor.in) The first line will contain S. The
second line will contain T. The length of T will be at most that of S,
and all characters of S and T will be lower-case alphabet characters
(in the range a..z).
OUTPUT FORMAT: (file censor.out) The string S after all deletions are
complete. It is guaranteed that S will not become empty during the
deletion process. | {
"domain": "codereview.stackexchange",
"id": 44956,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm, time-limit-exceeded",
"url": null
} |
python, performance, algorithm, time-limit-exceeded
# Censoring (Bronze)
input = open('censor.in', 'r').read().split('\n')
s = input[0]
c = input[1]
l = len(c)
while True:
try:
i = s.index(c)
s = s[:i] + s[i + l:]
except:
break
output = open('censor.out', 'w')
output.write(s)
output.close()
How do I speed up the code? I tried to use Numba, but Numba doesn't work in USACO IDE.
This was supposed to solve all the test cases under the time limit, which is 5 seconds.
Answer: Assumption: len(c) << len(s).
For example, when censoring "moo".
You asked if one can
speed up python
but really this is a matter of "speeding up an algorithm".
That is, you have accidentally fallen into a higher
time complexity than necessary.
I expected it to run with O(n) time complexity
Certainly the while loop is linear in size of article string s.
But you're restarting that linear .index() search
from the beginning each time, leading to
nested loop \$O(N × M)\$ behavior
if the censored c appears \$M\$ times within the article.
Given \$M << N\$ an efficient algorithm should see
article size dominate the cost,
with negligible contribution from the censoring operations.
In addition to .index() being linear in len(s),
notice that producing a new immutable str with string catenation
is also \$O(len(s))\$.
input = open('censor.in', 'r').read().split('\n')
A more natural method to call here would have been
.readlines().
Rather than leaving an open file descriptor resource
lying around until end-of-scope,
prefer to use a with context handler
so it closes when you're done with it.
Shadowing the builtin input() is definitely not Best Practice.
s = input[0]
c = input[1]
Usually we give 0 and 1 a pass when it comes to calling out
magic numbers.
But here it obscures Author's Intent, there's no need for such cryptic indexes.
Prefer a tuple unpack:
s, c = input
Also, even though these are local variables in
a very short piece of code,
please consider using more informative names
such as article and censored. | {
"domain": "codereview.stackexchange",
"id": 44956,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm, time-limit-exceeded",
"url": null
} |
python, performance, algorithm, time-limit-exceeded
except:
No.
Do not use "bare" except,
as it will sometimes swallow exceptions such as KeyboardInterrupt
which we really want to be propagated.
Prefer to habitually write except Exception:
But here we know perfectly well what we're hoping to trap,
so spell it out for the Gentle Reader:
except ValueError: # substring not found
i = s.index(c)
Suppose we have a million-character article,
and we've already deleted a thousand instances of "moo".
This .index() call is super expensive -- it's trolling
through roughly a megabyte of article text that we've
already repeatedly scanned before.
We know there's a giant prefix which is entirely "moo"-free.
.index()
offers an optional start parameter.
Use it.
You'll have to maintain another temp variable.
Since deleting "moo" from "momooo" can expose another instance,
you should conservatively use j = s.index(c, j) - len(c).
This will still yield \$O(len(s))\$ complexity,
given our assumption.
s = s[:i] + s[i + l:]
As noted above, this is linear in len(s).
Rather than reading a pair of giant immutable strings
and writing a new giant immutable string, prefer a
tombstone
approach.
Start with this import:
from array import array
Spend \$O(n)\$ time copying article text into an array.
If articles are guaranteed ASCII text then we can
get away with a byte array, else we need an array of ints.
Implement your own version of .index() which
compares against article text in the array, and
knows that it must skip over (ignore) any tombstone entries
Now "deleting" a censored string from the article
is a matter of overwriting each character with a
sentinel
tombstone value such as 0.
Finally at the end you'll need to do linear work with "".join( ... )
to copy out non-sentinel Unicode code points,
producing the final sanitized article that is safe for cows to read. | {
"domain": "codereview.stackexchange",
"id": 44956,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, algorithm, time-limit-exceeded",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, mathematics
Title: Python function to find the count of digits of numerals in base n up to a given limit
Question: This is a simple exercise to find the count of digits of all numerals in a given base up to a given limit (not including the limit), I wrote it to determine the ratio of bytes saved when the numbers are stored as integers rather than strings.
The logic is simple, in base-10, there are 10 natural numbers that can be expressed with only one digit: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9. To express ten, you need two decimal digits. To express one hundred, three digits are needed. There are exactly 90 two-digit numerals.
So the sequence of count of numerals with n decimal digits is 10, 90, 900, 9000 and so on.
In binary, the count of one-bit numerals is 2, the count of two-bit numerals is also 2, and the count of three-bit numerals is 4.
In general, the count of n digit numerals in base b is Sn - Sn - 1, where Si = bi for all i > 0, and S0 = 0, i must be a natural number.
So I just calculated the count of numerals of each length category below the limit, and summed their product with their one-based index.
def digits_total(limit: int, base: int = 10) -> int:
counts = []
power = 1
last = 0
while (power := power * base) < limit:
counts.append(power - last)
last = power
limit -= last
counts.append(limit)
return sum(i * e for i, e in enumerate(counts, start=1))
def bytes_over_digits(limit: int) -> float:
n = 1 << (8 * limit)
return digits_total(n, 256) / digits_total(n)
I calculated the ratio of count of bytes of natural numbers up to 280000 when they are stored as integers (255 -> 1 byte, 65535 -> 2 bytes, 16777215 -> 3 bytes...) to the count of bytes when they are stored as decimal strings ('256' -> 3 bytes), and the result is somewhat close to what I obtained using math:
In [289]: bytes_over_digits(10000)
Out[289]: 0.4152381307217551
In [290]: math.log(10, 256)
Out[290]: 0.41524101186092033
How can this be improved? | {
"domain": "codereview.stackexchange",
"id": 44957,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, algorithm, programming-challenge, mathematics",
"url": null
} |
python, python-3.x, algorithm, programming-challenge, mathematics
In [290]: math.log(10, 256)
Out[290]: 0.41524101186092033
How can this be improved?
Answer: To make the first function run faster, you can sum as you go instead of doing it all at the end:
def digits_total2(limit: int, base: int = 10) -> int:
total_sum = 0
last = 0
power = base
i = 1
while power < limit:
total_sum += (power - last) * i
last = power
power *= base
i += 1
return total_sum + (limit - last) * i
This converts the space complexity from O(log(limit, base = base)) to O(1). Over all limits in range(100000) and all bases in range(2, 1000), here is the difference:
original: 123.10s
revised: 52.56s
Also, your code is very clear (which is why I couldn’t think of any other improvements). There is likely a closed form with geometric series, but I expect exponentiation is computationally expensive unless you make your own just for this purpose. So more math wouldn’t necessarily speed this up! | {
"domain": "codereview.stackexchange",
"id": 44957,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, algorithm, programming-challenge, mathematics",
"url": null
} |
javascript, react.js, axios
Title: Idomatic way to ignore `finally` block after cancelling network request
Question: In React, it is quite common for me to have something similar to the following.
async componentDidMount() {
try {
this.setState({ isLoading: true })
const { data } = await axios.get('...')
this.setState({ data })
} catch(error) {
handleError(error)
} finally {
this.setState({ isLoading: false })
}
}
This is great because the cleanup code (isLoading: false) is DRY. That is, until I try to cancel network requests on unmount. That code would look like this:
async componentDidMount() {
try {
this.axiosCancelTokenSource = axios.CancelToken.source()
this.setState({ isLoading: true })
const { data } = await axios.get('...', {
cancelToken: this.axiosCancelTokenSource.token,
})
this.setState({ data })
} catch(error) {
if (axios.isCancel(error)) return
handleError(error)
} finally {
this.setState({ isLoading: false })
}
}
componentWillUnmount() {
if (this.axiosCancelTokenSource) this.axiosCancelTokenSource.cancel()
}
The problem with this is that it will setState after the component unmounts, which React will warn againts.
As far as I see it, these are my options for dealing with this: | {
"domain": "codereview.stackexchange",
"id": 44958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, react.js, axios",
"url": null
} |
javascript, react.js, axios
Ignore the warning.
React gives a warning when you setState after unmount because it indicates a memory leak (in this case, the lingering network request, if not cancelled). If the network request is cancelled, there is still a setState after unmount, but just to set a flag. There is no more lingering network request. It should be safe to ignore the warning in this case, but it doesn't feel right.
Check what error was thrown in the finally block and add the same if statement as the catch block. This seems incredibly hacky and would require extra code to save the error from the catch block.
Check if the component is mounted in the finally block. This is also hacky and requires boilerplate code to update a this.isMounted flag.
Put the cleanup code at the end of try and after the condition in catch. This is not DRY. Humans are also very forgetful; I cannot count how many times I have forgotten to set isLoading = false in catch.
Define a cleanup() function before the try and call it in try and catch. This is a decent option, but requires extra function calls, making it harder to follow.
So far, it looks like the first or fifth options are best, depending on how much you care about seeing warning messages. Am I missing any good options?
Answer: Finally only for unconditional execution
I am not a React user, and as such I may be missing something unique to the React way.
It seams very strange that you use a finally block to execute code you don't want to guarantee execution.
As far as I see it, these are my options for dealing with this:
You list 5 options... Why not a 6th?
Remove the finally { ... } block setting the is loading state after the try catch and having the catch return if unmounted. | {
"domain": "codereview.stackexchange",
"id": 44958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, react.js, axios",
"url": null
} |
javascript, react.js, axios
If I ignore React the "Idomatic way to ignore finally block..." is to remove it.
eg
async componentDidMount() {
try {
this.axiosCancelTokenSource = axios.CancelToken.source()
this.setState({ isLoading: true })
const { data } = await axios.get('...', {
cancelToken: this.axiosCancelTokenSource.token,
})
this.setState({ data })
} catch(error) {
if (axios.isCancel(error)) return
handleError(error)
}
this.setState({ isLoading: false })
}
Catch only known exceptions
try ... catch should only be used to wrap code that is known to throw a known set of exceptions (in this case network, data, or forced exceptions related to axios.get).
Wrapping all code automatically in a try catch means that it is possible to catch unknown exceptions (AKA BUGS) effectively hiding/obscuring the erroneous behavior during the development cycle.
Example
Removing the try from around known safe code, catching only exceptions related to the functions role.
// pseudo code as example only
async mount() {
loading = (isLoading = true) => this.setState({isLoading});
cancelToken = axios.CancelToken.source();
loading();
try {
this.setState({data: (await axios.get("...", {cancelToken})).data});
} catch (e) {
if (axios.isCancel(e)) { return }
handleError(e);
}
loading(false);
} | {
"domain": "codereview.stackexchange",
"id": 44958,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, react.js, axios",
"url": null
} |
c#, .net, hash-map, mathematics
Title: C# console app that computes the Jaccard Index
Question: So I wrote a basic C# console application that computes the Jaccard Index. This has its applications in cybersecurity and machine learning. Given two sets X and Y, the basic formula is:
$$ J(X, Y) = \frac{|X \cap Y|}{|X \cup Y|} $$
where the bars in this context refers to the number of items in the set or the result of its intersection or union, not the absolute value. The jaccard(HashSet<int>, HashSet<int>) function takes in two HashSet<int> types and then implements this formula, and the Main(string[]) give the jaccard an example. The following code is my implementation of it:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class Jaccard {
public static void Main(string[] args) {
HashSet<int> testSet1 = new HashSet<int>() {1, 2, 3};
HashSet<int> testSet2 = new HashSet<int>() {1, 2, 3};
Console.WriteLine("Test Jaccard is: {0}", jaccard(testSet1, testSet2));
}
public static double jaccard(HashSet<int> set1, HashSet<int> set2) {
set1.IntersectWith(set2);
set2.UnionWith(set2);
// length of set intersection ÷ length of set union
return set1.Count / set2.Count;
}
}
Questions:
Is there a way to implement HashSet<???> to take in a object of any type? Or do I have to just overload the jaccard with different types?
From an aesthetic and style perspective, how is my code?
From a security perspective, how is my code? Do you see any significant code injection or memory corruption vulnerabilities (I know that C# protects against memory corruption, but you never know ;-)?
If I should refactor my code, what do you recommend?
You may view my GitHub repo where the source code is stored here: https://github.com/Alekseyyy/InfoSec/blob/master/reversing/jaccard.cs | {
"domain": "codereview.stackexchange",
"id": 44959,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map, mathematics",
"url": null
} |
c#, .net, hash-map, mathematics
Answer: Bug
Your logic is flawed when computing the union of the sets: it doesn't include data from set1 in the union of sets. This leads to incorrect results in many cases.
Style
C# conventions recommend using PascalCase for method names. This makes the code easier to read for anyone who has some C# experience.
Method names should have a verb describing the action they perform. Again, this improves readability.
Remove unused using statements. These just add useless noise to the code.
Side effects
Glossing over the bugged logic, your method mutates its inputs, which means it isn't possible to do any further work with your sets after computing their Jaccard index, which will most likely cause issues.
Prefer using LINQ methods Union and Intersect over HashSet's UnionWith and IntersectWith, as the former return a new IEnumerable instead of mutating the calling instance.
Make your method static
Your method doesn't require any class members, and should be made static in order to use it without instantiating a class.
Make it generic
There is no reason to limit your method to work with HashSet<int>, as the logic doesn't rely on the underlying data type.
Fewer operations
Set operations are the most expensive operations in your code. You can save computing the set union and just work with the counts of inputs and intersection.
Document your code
This makes the code easier to reuse by other people, or yourself in the future.
Include tests
If your code was properly tested, you would have caught your bug.
Sample code:
JaccardIndex.cs
namespace JaccardIndex
{
public static class JaccardIndex
{
/// <summary>
/// Compute the Jaccard index between two sets.
/// The Jaccard index gauges the similarity between two sets, and ranges from 0.0 (disjoint sets) to 1.0 (identical sets).
/// </summary>
/// <typeparam name="T">Underlying data types of input sets</typeparam>
/// <param name="set1">1st input set</param> | {
"domain": "codereview.stackexchange",
"id": 44959,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map, mathematics",
"url": null
} |
c#, .net, hash-map, mathematics
/// <param name="set1">1st input set</param>
/// <param name="set2">2nd imput set</param>
/// <returns>Jaccard index</returns>
public static double ComputeJaccardIndex<T>(HashSet<T> set1, HashSet<T> set2)
{
var intesectionCount = (double)set1.Intersect(set2).Count();
return intesectionCount / (set1.Count() + set2.Count() - intesectionCount);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44959,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map, mathematics",
"url": null
} |
c#, .net, hash-map, mathematics
JaccardIndexTests.cs
using Xunit;
using static JaccardIndex.JaccardIndex; | {
"domain": "codereview.stackexchange",
"id": 44959,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map, mathematics",
"url": null
} |
c#, .net, hash-map, mathematics
namespace JaccardIndexTests
{
public class JaccardIndexTests
{
/// <summary>
/// Verify that some knwon values are computed correctly
/// </summary>
[Theory]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1 }, 1.0 / 3.0)]
[InlineData(new int[] { 1 }, new int[] { 1 }, 1.0 )]
[InlineData(new int[] { 1 }, new int[] { 2 }, 0.0)]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 4 }, 2.0 / 4.0)]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 }, 0.0)]
public void Samples(int[] data1, int[] data2, double expected)
{
var set1 = new HashSet<int>(data1);
var set2 = new HashSet<int>(data2);
Assert.Equal(expected, ComputeJaccardIndex(set1, set2));
}
/// <summary>
/// Jaccard index of a should be commutative
/// </summary>
[Theory]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 1 })]
[InlineData(new int[] { 1 }, new int[] { 2 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 1, 2, 4 })]
[InlineData(new int[] { 1, 2, 3 }, new int[] { 4, 5, 6 })]
public void Symmetry(int[] data1, int[] data2)
{
var set1 = new HashSet<int>(data1);
var set2 = new HashSet<int>(data2);
Assert.Equal(ComputeJaccardIndex(set1, set2), ComputeJaccardIndex(set2, set1));
}
/// <summary>
/// Jaccard index of a set with itelf should be 1
/// </summary>
[Theory]
[InlineData(new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 4, 5, 6 })]
public void WithSelf(int[] data)
{
var set = new HashSet<int>(data);
Assert.Equal(1, ComputeJaccardIndex(set, set));
}
/// <summary>
/// Jaccard index of a set with empty set should be 0 | {
"domain": "codereview.stackexchange",
"id": 44959,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map, mathematics",
"url": null
} |
c#, .net, hash-map, mathematics
}
/// <summary>
/// Jaccard index of a set with empty set should be 0
/// </summary>
[Theory]
[InlineData(new int[] { 1 })]
[InlineData(new int[] { 1, 2, 3 })]
[InlineData(new int[] { 1, 2, 3, 4, 5, 6 })]
public void WithEmpty(int[] data)
{
var set = new HashSet<int>(data);
Assert.Equal(0, ComputeJaccardIndex(set, new HashSet<int>()));
Assert.Equal(0, ComputeJaccardIndex(new HashSet<int>(), set));
}
/// <summary>
/// Jaccard index of two empty sets is undefined, should return NaN
/// </summary>
[Fact]
public void BothEmpty()
{
Assert.True(double.IsNaN(ComputeJaccardIndex(new HashSet<int>(), new HashSet<int>())));
}
/// <summary>
/// Jaccard index computation should not mutate the input data
/// </summary>
[Fact]
public void NoDataMutation()
{
var set1 = new HashSet<int>() { 1, 2, 3 };
var set2 = new HashSet<int>() { 1, 2, 4, 5 }; | {
"domain": "codereview.stackexchange",
"id": 44959,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map, mathematics",
"url": null
} |
c#, .net, hash-map, mathematics
var set1Copy = new HashSet<int>(set1);
var set2Copy = new HashSet<int>(set2);
ComputeJaccardIndex(set1, set2);
Assert.Equal(set1Copy, set1);
Assert.Equal(set2Copy, set2);
}
}
}
Note that test coverage could probably be improved, by testing operations with other data types or large sets, but this is a good start IMO. | {
"domain": "codereview.stackexchange",
"id": 44959,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, hash-map, mathematics",
"url": null
} |
c#, logging, helper, httpclient
Title: Replacement for EnsureSuccessStatusCode
Question: I like the simplicity of EnsureSuccessStatusCode for HttpResponseMessage after a call using HttpClient. But it does not really provide great information. This is my replacement for it.
I am looking to see if I have missed useful information that is in the HttpResponseMessage, if there is a better exception type to throw or if I could generally improve it.
Some of the tricky parts was constructing a viable logging message and an exception message when logging needs it in its component parts and logging wants it all together (and some parts are optional).
public static class HttpResponseHelper
{
public static async Task CheckResponseAndThrowIfIsError(this HttpResponseMessage response,
string? errorMessage = null, ILogger? logger = null, bool includeResponseContent = true)
{
if (response.IsSuccessStatusCode == false)
{
var statusCode = response.StatusCode.ToString();
string fullErrorMessage = "";
if (!string.IsNullOrEmpty(errorMessage))
{
fullErrorMessage = $"{errorMessage}\r\n";
}
else
{
// Put in something generic so that the log as a value instead of a blank line.
errorMessage = "Call Failed";
}
fullErrorMessage += $"Call Failed with Status Code: {statusCode}";
var errorMessageFromCall = "";
if (includeResponseContent)
{
errorMessageFromCall = await response.Content.ReadAsStringAsync();
fullErrorMessage += $"\r\n{errorMessageFromCall}";
}
logger?.LogError("{errorMessage}\r\nCall Failed with Status Code: {statusCode}\r\n{errorMessageFromCall}",
errorMessage, statusCode, errorMessageFromCall);
throw new ApplicationException(fullErrorMessage);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, logging, helper, httpclient",
"url": null
} |
c#, logging, helper, httpclient
throw new ApplicationException(fullErrorMessage);
}
}
}
Its use would look like this:
var response = await httpClient.SendAsync(message);
await response.CheckResponseAndThrowIfIsError("My Error Message Here", _logger);
Answer: Here are my observations:
if (response.IsSuccessStatusCode == false)
I would rather suggest to have an early exit by inverting the if condition
Having a single giant guard condition is less expressive and maintainable IMHO
string fullErrorMessage = "";
if (!string.IsNullOrEmpty(errorMessage))
{
fullErrorMessage = $"{errorMessage}\r\n";
}
else
{
// Put in something generic so that the log as a value instead of a blank line.
errorMessage = "Call Failed";
}
The fullErrorMessage can be constructed in a single step whenever you throw the exception so, I would advice against build it incrementally
The else block is basically a fallback value if the errorMessage parameter is blank
I would suggest a simple ?: structure instead
var errorMessageFromCall = "";
if (includeResponseContent)
{
errorMessageFromCall = await response.Content.ReadAsStringAsync();
fullErrorMessage += $"\r\n{errorMessageFromCall}";
}
Yet again the errorMessageFromCall is either a blank string or the full response body
So, a simple ?: structure would be enough here as well
I would suggest to truncate the string to avoid logging failure due to too large content
logger?.LogError("{errorMessage}\r\nCall Failed with Status Code: {statusCode}\r\n{errorMessageFromCall}",
errorMessage, statusCode, errorMessageFromCall);
I would suggest to use constant instead of hard coding \r\n many times
By using the line break constant you would rely on string interpolation
In that case you would need to escape the { and } characters by doubling them
throw new ApplicationException(fullErrorMessage) | {
"domain": "codereview.stackexchange",
"id": 44960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, logging, helper, httpclient",
"url": null
} |
c#, logging, helper, httpclient
throw new ApplicationException(fullErrorMessage)
As I stated earlier I would rather construct here the fullErrorMessage in a single step
As it was mentioned by others as well using an HttpRequestException would fill more natural here
So, here is my revised version of your method:
private const string LineBreak = "\r\n";
private const int MaxBodyLength = 5_000;
...
if (response.IsSuccessStatusCode)
return;
errorMessage = !string.IsNullOrEmpty(errorMessage) ? errorMessage : "Call Failed";
string errorMessageFromCall = includeResponseContent ? await response.Content.ReadAsStringAsync() : string.Empty;
errorMessageFromCall = errorMessageFromCall.Length >= MaxBodyLength
? errorMessageFromCall[..(MaxBodyLength - 3)] + "..."
: errorMessageFromCall;
logger?.LogError($"{{errorMessage}}{LineBreak}Call Failed with Status Code: {{statusCode}}{LineBreak}{{errorMessageFromCall}}",
errorMessage, response.StatusCode, errorMessageFromCall);
throw new HttpRequestException($"{errorMessage}{LineBreak}Call Failed with Status Code: {response.StatusCode}{LineBreak}{errorMessageFromCall}"); | {
"domain": "codereview.stackexchange",
"id": 44960,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, logging, helper, httpclient",
"url": null
} |
c#, api, rest, asp.net-core-webapi
Title: Action argument supporting multiple units as string
Question: I've got a controller with two actions that need to support two units: hours & times. The url should read like this:
api/workflows/active/next/hour
api/workflows/active/next/time
api/workflows/active/next/3/hours
api/workflows/active/next/3/times
In order to not write any extra validation for the unit parameter I have defined the last route segment as regex:
[HttpGet("active/next/{unit:regex(^(hour|time))}")]
public async Task<IActionResult> GetNextSingle(string unit)
{
return await GetNextMany(1, $"{unit}s");
}
[HttpGet("active/next/{value:int:min(1):max(10)}/{unit:regex(^(hours|times))}")]
public async Task<IActionResult> GetNextMany(int value, string unit)
{
return Ok(new { value, unit });
}
Would say this is how it's usually done or are there other smarter ways?
Answer:
Action argument supporting multiple units
There is "hour" and "everythingElse". "times" is not a unit really, merely counting. For that matter "hour" fits in that category too. The differentiation of hour|times seems incongruent.
The conceptual inconsistency has led to a lack of extensibility; fine if there are no multiple units; then I'm agreeing with @PeterCsala it's filtering, not routing comment | {
"domain": "codereview.stackexchange",
"id": 44961,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, api, rest, asp.net-core-webapi",
"url": null
} |
c++, performance
Title: Object pooling class BubbleList
Question: Please review C++ class BubbleList design with performance in mind.
Named BubbleList as pooled (unused) objects bubble to the high end of the vector, providing a continuouse set of active objects, delimited by BubbleList.count
It is designed to reduce memory allocation / free overheads of many short lived objects in game like environments (eg bullets, smoke FX, etc). Objects are pooled rather than deleted.
BubbleList maintains ownership of pooled objects, though this is not enforced.
Note there is no guard for the specialization calls bool BubbleList.Update() and bool BubbleList.Update(const bool updateFrame, Box2 *bounds) {
/**
* MSVS: Microsoft Visual Studio V17.6.5
* Relevant compile / link flags:
* /std:c17 /std:c++20 /WX /W4 /sdl- /Ob2 /Oi /Ot /GS-
* /permissive- /Zc:rvalueCast- /OPT:REF /OPT:ICF
**/
/**
* Use C style casts to reduce code noise.
* Compiler converts C Style `(target)expression` to C++ style `static_cast<target>(expression)`
* See https://en.cppreference.com/w/cpp/language/explicit_cast#Explanation for detailed conversion rules
**/
/*
From global.h
#define BM67__FORCE_32_BIT_SIZE
From shorthandTypes.h
#ifdef BM67__FORCE_32_BIT_SIZE
typedef uint32_t sZ;
#else
typedef size_t sZ;
#endif
typedef uint32_t u32;
typedef int32_t i32;
typedef const uint32_t cu32;
*/
#pragma once
#include "global.h"
#include "shorthandTypes.h"
#include <vector>
#include "Box2.h" | {
"domain": "codereview.stackexchange",
"id": 44962,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c++, performance
template <typename Item>
class BubbleList {
public:
BubbleList() = default;
~BubbleList() noexcept { Clear(); }
void Clear() noexcept {
for (Item* item : items) { delete item; }
items.clear();
items.shrink_to_fit();
dirty = true;
count = 0;
idx = 0;
}
void Trim() noexcept {
sZ size = (sZ)items.size();
while (size-- > count) {
delete items[size];
items.pop_back();
}
}
Item* Spawn() noexcept {
Item* item = nullptr;
if ((sZ)items.size() > count) { item = items[count]; }
else { items.push_back(item = new Item); }
dirty = true;
count++;
return item;
}
void Start() noexcept { idx = 0; }
Item* Next() noexcept {
if (idx < count) { return items[idx++]; }
idx = 0;
return nullptr;
}
Item* Next(cu32 type) noexcept {
while (idx < count) {
Item* item = items[idx++];
if (type == (u32)it->type) { return item; }
}
idx = 0;
return nP;
}
void Update(const bool updateFrame, Box2* bounds) noexcept {
sZ head = 0, tail = 0;
while (head < count) {
Item* item = items[head];
if (item->Update(updateFrame, bounds)) {
if (tail != head) {
items[head] = items[tail];
items[tail] = item;
}
tail++;
}
head++;
}
idx = 0;
count = tail;
}
void Update() noexcept {
sZ head = 0, tail = 0;
while (head < count) {
Item* item = items[head];
if (item->Update()) {
if (tail != head) {
items[head] = items[tail];
items[tail] = item;
}
tail++;
}
head++;
}
idx = 0; | {
"domain": "codereview.stackexchange",
"id": 44962,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c++, performance
tail++;
}
head++;
}
idx = 0;
count = tail;
}
private:
sZ idx{0};
public:
std::vector<Item *>items;
sZ count{0};
bool dirty{false};
}; | {
"domain": "codereview.stackexchange",
"id": 44962,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c++, performance
Basic usage example.
/*
FXParticle lives for 10 - 100 frames
With odds 1 in 10 of creating a new particle each frame.
UpdateAndRender creates, updates, and draws particles.
*/
SpriteBuffer<spriteRenderer, spriteSheet> spriteBuf;
struct FXParticle {
Vec2 position{0, 0};
Vec2 delta{0, 0};
u32 idx{0};
i32 life{100};
FXParticle* Init() noexcept {
position.Set(Vec2::Rnd(200.0f, 200.0f)).Sub(100.0f, 100.0f);
delta.Polar(Rnd(TAU), Rnd(1.0f, 2.0f));
life = RndU(10, 100);
return this;
}
bool Update() noexcept {
position += delta;
return life-- > 0;
}
void Render(SpriteBuffer<spriteRenderer, spriteSheet>* sB) noexcept {
sB->DrawSprite(position, idx);
}
};
BubbleList<FXParticle> fx;
void AddParticle(cu32 idx) noexcept {
FXParticle* p = fx.Spawn().Init();
p->idx = idx % 10;
}
void UpdateAndRender() { /* Would normally be two functions to handle many types of objects */
if (ROdds(10)) { AddParticle(RndU(10)); }
fx.Update();
spriteBuf.Use();
FXParticle* p = fx.Next();
while (p) {
p->Render(&spriteBuf);
p = fx.Next();
}
// Or as most often used
// sZ i = 0;
// while (i < fx.count) {
// fx.items[i++]->Render(&spriteBuf);
// }
spriteBuf.Flush();
spriteBuf.Close();
}
As would be used to update and render particle FX via a main loop. | {
"domain": "codereview.stackexchange",
"id": 44962,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c++, performance
As would be used to update and render particle FX via a main loop.
Answer: Simplify your code
There are various issues with your class. It's not truly generic; it depends on Box2 for example, just to be able to pass some parameter to an item's Update() function. You can avoid this by having the caller pass an arbitrary function to BubbleList::update().
You also could have avoided writing a lot of code by making use of the standard library; in particular, use std::unique_ptr to avoid the manual memory management, and use std::partition() to loop over the items in the list and partition the list into active and inactive items.
Consider this rewritten version of your class:
#include <algorithm>
#include <memory>
#include <functional>
#include <vector>
template <typename Item>
class BubbleList {
public:
void Clear() {
items.clear();
count = 0;
}
void Trim() {
items.resize(count);
}
Item* Spawn() {
if (count == items.size()) {
items.push_back(std::make_unique<Item>());
}
return items[count++].get();
}
template<typename Function>
void Update(Function visitor) {
auto end = std::partition(items.begin(), items.begin() + count, [&](auto& item) {
return std::invoke(visitor, *item);
});
count = end - items.begin();
}
private:
std::vector<std::unique_ptr<Item>> items;
std::size_t count;
};
Update() looks a bit complicated, but by writing it this way and using std::invoke() to call the visitor you give it, it can now take all kinds of invocable objects, including pointers to member functions. That allows you to use it like so:
BubbleList<FXParticle> fx;
…
fx.Update(&FXParticle::Update);
Now BubbList's Update() function doesn't need to know about FXParticle's Update(). You can also pass it a lambda function:
fx.Update([](FXParticle& particle){ particle.Update(); }); | {
"domain": "codereview.stackexchange",
"id": 44962,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
c++, performance
This is a bit longer to write, but it allows you to call any function you want, and maybe pass extra parameters as well, without BubbleList having to know about them.
All of the above shouldn't change the performance; it's doing the same thing as your code was doing. Since the class is a template, calls to its member functions can always be inlined, so even though it seems like passing a visitor function to BubbleList::Update() might be slow, the compiler will be able to optimize that away.
Performance
Depending on the size of the Items and how many items are made inactive in calls to Update(), you might want to consider storing the items in the vector by value. This avoids the overhead of all the invididual memory allocations, and the indirection when accessing them. If swapping deactived items to the tail is very expensive, you can also consider just keeping track of which items are active and which are not in a separate data structure (maybe a std::vector<bool>?), so you never have to move items around. | {
"domain": "codereview.stackexchange",
"id": 44962,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance",
"url": null
} |
python, validation
Title: Validate that the console input contains positive integers only
Question: The function validates whether the input is an int, is there a way to make this more concise and is it best practise to use the try/except or just if/else? I then want to create a similar function for checking whether the input contains letters only using isalpha()
def int_validation(prompt):
"""
Validate the given input is a positive number
"""
while True:
answer = input(prompt)
if not answer:
print(blank_input)
else:
try:
answer = int(answer)
except ValueError:
print(positive_int_only)
continue
if answer < 1:
print(positive_int_only)
break
return answer
Answer: First, I would suggest that when posting code for review that it be a complete. For example, variables blank_input and positive_int_only are undefined. Moving on:
Your while True loops suggests that you want to repeatedly prompt the user for a positive number until a valid positive number is entered and then return its value. You do repeatedly loop when the user enters an empty string or a string that cannot be parsed as a number (but not necessarily an integer) but not if a non-positive number is entered. In this case you return the invalid non-positive input. That is an inconsistency and I will assume that this was an oversight on your part. But right now your docstring states that the purpose of the function is to validate that an input is a positive integer. What the function is actually doing is accepting input from a user until a valid positive integer is entered and returning that value.
def int_validation(prompt):
"""
Prompt the user for input until a positive integer
is entered.
""" | {
"domain": "codereview.stackexchange",
"id": 44963,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, validation",
"url": null
} |
python, validation
while True:
answer = input(prompt)
# No need to distinguish between blank input vs,
# an invalid number:
try:
int_answer = int(answer)
except ValueError:
pass
else:
if int_answer >= 1:
return int_answer
print('You must enter a positive integer.')
print(int_validation('Enter a positive integer: '))
This will accept input such as 1e2 as valid. If you want to reject this as valid input then you need to ensure the input string contains only numeric digits.
So if you require that the input be strictly composed of only digits, my preference would be to use a regular expression for validation:
import re
def int_validation(prompt):
"""
Prompt the user for input until a positive integer
is entered.
"""
while True:
answer = input(prompt).strip()
# Allow leading zeroes, but they must be followed by a non-zero:
if re.fullmatch(r'0*[1-9][0-9]*', answer):
return int(answer)
print('You must enter a positive integer.')
print(int_validation('Enter a positive integer: '))
You might consider defining a default value form the prompt argument if it is not supplied. | {
"domain": "codereview.stackexchange",
"id": 44963,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, validation",
"url": null
} |
beginner, assembly, number-guessing-game
Title: Number guessing game for x86
Question: I'm new to assembly and I've just finished this guessing game that I wanted to make to improve my skills in this language. It runs in a Unix environment and does the following:
generates a random number between 0 and 255,
the user inputs a guess belonging to that range,
the program converts it into an integer,
the program then emits a feedback based on whether the input is too low, high or right,
the program gets back to the first step if it's not the right number else it's the end.
I haven't noticed any bugs yet; it seems to work properly. There's a few things I would like to address in the future; tell me what I should add to this list after you've taken a look at the code below:
the code is not made to be robust: it is very error-prone if the user puts in the wrong type of data and/or too many chars,
the switch or match part, no matter what you call it, of the guess function feels a bit weird to me; there's a lot of unnecessary assignment to the registers and I do the same things multiple times (like doing the comparison)
the range 0-255 is a bit weird, often it's 1-100 but it's not unplayable: the worst case scenario is 1+log_2(256) = 9 moves in worst case dichotomic search; also it avoids further manipulation of the random number which could easily cause errors during development.
It's written using AT&T syntax.
main.s
.section .data
.equ SUCCESS, 0
.equ EXIT, 1
.equ SYS_CALL, 0x80
.section .text
.globl _start
_start:
call random
pushl %eax # Save random on the stack as arg
call guess
addl $4, %esp
movl $SUCCESS, %ebx
movl $EXIT, %eax
int $SYS_CALL
random.s
.section .data
.equ GET_RAND, 355
.equ GET_RAND_FLAGS, 0
.equ SYS_CALL, 0x80
.section .bss
.equ RAND_SIZE, 1
.lcomm RAND, RAND_SIZE
.section .text
# Output between 0 and 255
.globl random
.type random, @function
random:
pushl %ebp
movl %esp, %ebp | {
"domain": "codereview.stackexchange",
"id": 44964,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, assembly, number-guessing-game",
"url": null
} |
beginner, assembly, number-guessing-game
movl $GET_RAND, %eax
movl $RAND, %ebx
movl $RAND_SIZE, %ecx
movl $GET_RAND_FLAGS, %edx
int $SYS_CALL
movl RAND, %eax
movl $0, RAND # clear buffer
movl %ebp, %esp
popl %ebp
ret
guess.s
.section .data
MSG_RIGHT: .ascii "That's the right number!\n"
MSG_LOWER: .ascii "Lower!\n"
MSG_HIGHER: .ascii "Higher!\n"
.equ LEN_RIGHT, 25
.equ LEN_LOWER, 7
.equ LEN_HIGHER, 8
.equ READ, 3
.equ WRITE, 4
.equ STDIN, 0
.equ STDOUT, 1
.equ SYS_CALL, 0x80
.equ CHAR_NEW_LINE, 10
.equ CHAR_ZERO, 48
.section .bss
.equ BUFFER_SIZE, 4 # not much size needed, just 4 bytes would suffice
# (from "0" to "255" + '\n')
.lcomm BUFFER_DATA, BUFFER_SIZE
.section .text
# INPUT: the secret number
#
# iteratively guess the number and get a feedback
# until win
#
# -4(%ebp) -> user integer input
# -8(%ebp) -> winning flag ($1 = win)
.globl guess
.type guess, @function
guess:
pushl %ebp
movl %esp, %ebp
movl $0, -8(%ebp) # clear flag
get_input:
# clear input
movl $0, -4(%ebp)
movl $READ, %eax
movl $STDIN, %ebx
movl $BUFFER_DATA, %ecx
movl $BUFFER_SIZE, %edx
int $SYS_CALL
# convert string into number
atoi:
movl $0, %ecx # current digit
movl $0, %edx # current result
movl $BUFFER_DATA, %ebx # pointer into %ebx
atoi_next:
cmpb $CHAR_NEW_LINE, (%ebx) # is the char '\n'?
je atoi_end
# update the current result
imull $10, %edx # %edx *= 10
movb (%ebx), %cl # %ecx = char (putting in %ecx before hand to prevent overflow)
subb $CHAR_ZERO, %cl # %ecx -= '0'
addl %ecx, %edx
movb $0, (%ebx) # clear behind myself
incl %ebx # move the pointer
jmp atoi_next
atoi_end:
movl $0, (%ebx) # clear again
movl %edx, -4(%ebp) # save int input as loc var
movl 8(%ebp), %ebx # put random into %ebx | {
"domain": "codereview.stackexchange",
"id": 44964,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, assembly, number-guessing-game",
"url": null
} |
beginner, assembly, number-guessing-game
# case input == random
movl $1, -8(%ebp) # right flag
movl $MSG_RIGHT, %ecx
movl $LEN_RIGHT, %edx
cmpl %ebx, -4(%ebp)
je write
# case input < random
movl $0, -8(%ebp) # wrong flag
movl $MSG_HIGHER, %ecx
movl $LEN_HIGHER, %edx
cmpl %ebx, -4(%ebp)
jl write
# case input > random
movl $0, -8(%ebp) # wrong flag
movl $MSG_LOWER, %ecx
movl $LEN_LOWER, %edx
cmpl %ebx, -4(%ebp)
jg write
write:
movl $WRITE, %eax
movl $STDOUT, %ebx
int $SYS_CALL
cmpl $0, -8(%ebp) # is the flag false?
je get_input
movl %ebp, %esp
popl %ebp
ret
and to compile:
build.sh (execute it in the same directory as main.s, random.s and guess.s)
#build set of assembly files together
#MODIFY BEGIN - /!\ filenames without extensions
main="main" # entry-point
out="out" # output executable
dependencies=("guess" "random") # dependencies of the project
#MODIFY STOP
as --32 $main.s -o $main.o
obj_files="$main.o"
for dep in ${dependencies[@]}; do
as --32 $dep.s -o $dep.o
obj_files+=" $dep.o"
done
ld -m elf_i386 $obj_files -o $out
rm $main.o
for dep in ${dependencies[@]}; do
rm $dep.o
done
Then you can just run ./out
Answer:
movl RAND, %eax
movl $0, RAND # clear buffer
In the context of this program it's probably fine, but RAND has a size of 1 so generally you should be treating it as being one byte, to avoid loading unrelated data or overwriting some adjacent buffer.
Clearing the buffer seems unnecessary.
the switch or match part, no matter what you call it, of the guess function feels a bit weird to me, there's a lot of unnecessary assigning to the registers and I do the same things multiple times (like doing the comparison) | {
"domain": "codereview.stackexchange",
"id": 44964,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, assembly, number-guessing-game",
"url": null
} |
beginner, assembly, number-guessing-game
Yes, and you can remove some of it. You can do one comparison, and branch several times, even with the stores to the "continue flag" and the loads of ecx and edx in between, since none of that affects the flags. You only need to do movl $0, -8(%ebp) for the "higher" case, for the "lower" case it is already zero at that point.
jg write
write:
movl $WRITE, %eax
That jg doesn't do anything useful. Regardless of whether it is taken or not, the same code is executed next: the movl.
Other stuff
Reading from 8-bit registers is safe as far as I know, writing to 8-bit registers is subject to various quirks. I recommend avoiding it if reasonably possible, which it usually is by using movzx to avoid having to load a byte from memory into a byte register, and by doing most operations in 32-bit registers. Truncating the result to a byte is usually free since storing the value from a byte register to memory is fine. Losing a little bit of performance is not really important in this program specifically but in general you may as well avoid the pitfalls.
The best way to zero a (32-bit or 64-bit) register is xor same, same.
You can make the assembler find the size of a string constant. That works with .equ too.
Speaking of .equ, these don't have to go in the data section, though there is no harm to organizing your files that way. There is no data, they're assemble-time constants. But if you use the . - label trick to calculate a string length (. means "current address") then that must be located directly after the string itself. | {
"domain": "codereview.stackexchange",
"id": 44964,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, assembly, number-guessing-game",
"url": null
} |
python-3.x, pygame
Title: Very simple Flappy 'Bird' game - First project in Python
Question: I am a beginner in Python. This is my first project in Python (that I tried to complete).
There is a grey square that acts as the Flappy 'Bird' with green obstacles spawning with random gap sizes. The difficulty of the game stays the same for now. If an obstacle is hit, the game closes (I haven't implemented any menu thing yet). Pressing Esc pauses/unpauses the game.
How does the code look like and what improvements can I make to it in terms of organization, scalability, best practices, etc?
pygame 2.5.0 (SDL 2.28.0, Python 3.11.4)
game_objects.py
class Player:
def __init__(self, position: tuple[float, float], size: tuple[int, int], color: tuple[int, int, int]):
self.x, self.y = position
self.width, self.height = size
self.acc_y = 0.0
self.vel_y = 0.0
self.color = color
class Obstacle:
vel_x = -65.0
def __init__(self, position: tuple[float, float], size: tuple[int, int], color: tuple[int, int, int]):
self.x, self.y = position
self.width, self.height = size
self.color = color
main.py
import pygame, random
from game_objects import *
# Initializing pygame and setting up the screen
pygame.init()
pygame.display.set_caption("Flappy Bird")
SCREEN_WIDTH, SCREEN_HEIGHT = 600, 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT), flags=pygame.SCALED, vsync=1)
# The player
player = Player((85.0, 150.0), (25, 25), (50, 50, 50))
player.acc_y = 500
# Obstacle list
obstacles: list[Obstacle] = []
def spawn_obstacle():
gap_height = random.randint(125, 250)
gap_y = random.randint(0, (SCREEN_HEIGHT - gap_height))
obstacles.append(Obstacle((SCREEN_WIDTH, 0.0), (65, gap_y), (45, 168, 40)))
obstacles.append(Obstacle((SCREEN_WIDTH, (gap_y + gap_height)), (65, (SCREEN_HEIGHT - (gap_y + gap_height))), (45, 168, 40)))
##### The game loop | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
##### The game loop
# For calculating delta_time
last_tick = pygame.time.get_ticks()
# For spawning obstacles at regular intervals
obstacle_interval = 3000
time_since_last_obstacle = obstacle_interval
last_obstacle_tick = (last_tick - time_since_last_obstacle)
paused = False
lost = False | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
running = True
while (running):
# Handling various events
for event in pygame.event.get():
if (event.type == pygame.QUIT):
running = False
elif (event.type == pygame.KEYDOWN):
if ((event.key == pygame.K_w) or (event.key == pygame.K_UP)):
player.vel_y = -250.
elif (event.key == pygame.K_ESCAPE):
if (paused):
paused = False
last_tick = pygame.time.get_ticks()
last_obstacle_tick = (last_tick - time_since_last_obstacle)
else:
paused = True
if (not paused):
# Check if the player lost the previous iteration
if (lost):
print("You lost!")
running = False
continue
# Calculate delta_time
current_tick = pygame.time.get_ticks()
delta_time = (current_tick - last_tick) / 1000.0
last_tick = current_tick
# Clear the screen for fresh drawing
screen.fill((156, 204, 255))
# Spawning obstacles every obstacle_interval milliseconds
time_since_last_obstacle = (current_tick - last_obstacle_tick)
if (time_since_last_obstacle > obstacle_interval):
last_obstacle_tick = current_tick
spawn_obstacle()
# Updating the player's movement and position
player.vel_y += (player.acc_y * delta_time)
player.y += (player.vel_y * delta_time)
# Check whether the player is colliding with the horizontal edges
if ((player.y < 0.0) or (player.y > (SCREEN_HEIGHT - player.height))):
lost = True
# Obstacle logic
for obstacle in obstacles:
obstacle.x += (Obstacle.vel_x * delta_time)
# Check whether the obstacle is no longer visible
if (obstacle.x < -obstacle.width):
obstacles.remove(obstacle) | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
if (obstacle.x < -obstacle.width):
obstacles.remove(obstacle)
continue
# Check whether the player is colliding with the obstacle
if ((player.x > (obstacle.x - player.width)) and (player.x < (obstacle.x + obstacle.width))):
if ((player.y > (obstacle.y - player.height)) and (player.y < (obstacle.y + obstacle.height))):
lost = True
# Drawing the obstacle
pygame.draw.rect(screen, obstacle.color, pygame.Rect(int(obstacle.x), int(obstacle.y), obstacle.width, obstacle.height))
# Drawing the player
pygame.draw.rect(screen, player.color, pygame.Rect(int(player.x), int(player.y), player.width, player.height))
# Update the entire window
pygame.display.flip() | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
Answer:
The game is too hard for me. As for the code, I appreciate the comments. The main point I want to insist on is to separate things into classes/functions/files where they belong.
Constants
Separate all the constants/settings/parameters to another file. This way if you need to adjust the parameters or maybe add dificulty levels later on, everything is in the same place.
constants.py
## Graphics options
SCREEN_WIDTH, SCREEN_HEIGHT = 600, 600
## Gameplay options
OBSTACLE_SPEED = 65
OBSTACLE_WIDTH = 65
OBSTACLE_GAP_RANGE = (125,250)
OBSTACLE_SPAWN_SPACE_INTERVAL = 200
PLAYER_SPAWN_POS = (85.0, 150.0)
PLAYER_SIZE = (25, 25)
PLAYER_INITIAL_DECEL = 500
As for the colors, you've coded them in instance declarations. I suggest using an Enum to define every color you'll need and separate variables to pick object colors. This way you can play around with colors and objects independantly in the future. In constants.py or another file.
from enum import Enum
## Colors
class Color(Enum):
GREEN = (45, 168, 40)
GREY = (50, 50, 50)
LIGHT_BLUE = (156, 204, 255)
PLAYER_COLOR = Color.GREY
OBSTACLE_COLOR = Color.GREEN
BACKGROUND_COLOR = Color.LIGHT_BLUE
Game objects
You've defined classes for players, which is good. Consider using dataclasses. They let you skip all the boilerplate init code and add useful methods for printing and equality checks.
Your objects also share a few attributes such as position, size and color. These are common to any game object and if you were to add any new type of game object they woud have it too. Maybe its a good idea to define an abstract UI object class:
@dataclass
class UI_object:
# Also possible to go with tuples instead of x, y eg:
# size: Tuple[int,int] and position Tuple[float,float]
x: float
y: float
width: int
height: int
color: cst.Color
@dataclass()
class Obstacle(UI_object):
...
@dataclass
class Player(UI_object):
... | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
@dataclass()
class Obstacle(UI_object):
...
@dataclass
class Player(UI_object):
...
Your code logic is all over the place in your main file. I suggest you separate logic related to each class into its own methods. Spawning players or obstacles should be class methods. Checking if the player is out of bounds shoud be a Player instance method. Checking if the player hit an obstacle could be a Player or Obstacle instance method. Also you update object positions for players and obstacles separately. I would group the logic together into the abstract class.
game_objects.py
from dataclasses import dataclass
from typing import Optional
import constants as cst
import random
@dataclass
class UI_object:
x: float
y: float
width: int
height: int
color: cst.Color
vel_x: Optional[float] = 0
vel_y: Optional[float] = 0
acc_x: Optional[float] = 0
acc_y: Optional[float] = 0
def update_pos(self, time_delta: float):
self.vel_x += self.acc_x * time_delta
self.x += self.vel_x * time_delta
self.vel_y += self.acc_y * time_delta
self.y += self.vel_y * time_delta
@dataclass()
class Obstacle(UI_object):
vel_x: float = -cst.OBSTACLE_SPEED
@classmethod
def spawn_obstacle(cls):
gap_height = random.randint(
cst.OBSTACLE_GAP_INTERVAL[0], cst.OBSTACLE_GAP_INTERVAL[1]
)
gap_y = random.randint(0, (cst.SCREEN_HEIGHT - gap_height))
lower_obstacle = cls(
x=cst.SCREEN_HEIGHT,
y=0,
width=cst.OBSTACLE_WIDTH,
height=gap_y,
color=cst.OBSTACLE_COLOR,
)
upper_obstacle = cls(
x=cst.SCREEN_HEIGHT,
y=gap_y + gap_height,
width=cst.OBSTACLE_WIDTH,
height=cst.SCREEN_HEIGHT - gap_y - gap_height,
color=cst.OBSTACLE_COLOR,
)
return lower_obstacle, upper_obstacle | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
@dataclass
class Player(UI_object):
acc_y: float = cst.PLAYER_INITIAL_DECEL
def is_out_of_bounds(self):
return (self.y < 0.0) or (self.y > (cst.SCREEN_HEIGHT - self.height))
def is_touching_obstacle(self, obstacle: Obstacle):
return (
(obstacle.x - self.width) < self.x < (obstacle.x + obstacle.width)
) and ((obstacle.y - self.height) < self.y < (obstacle.y + obstacle.height))
@classmethod
def spawn(cls):
return cls(
x=cst.PLAYER_SPAWN_POS[0],
y=cst.PLAYER_SPAWN_POS[1],
width=cst.PLAYER_SIZE[0],
height=cst.PLAYER_SIZE[1],
color = cst.PLAYER_COLOR
)
Main file
It's recommended to use a __main__ == "__name__" check in your python scripts mainly to prevent accidental execution of the script.
I created a Game Class to organise the code but you could just as easily achieve the same with functions only.
class Flappy_bird:
def __init__(self) -> None:
pygame.init()
pygame.display.set_caption("Flappy Bird")
self.screen = pygame.display.set_mode((cst.SCREEN_WIDTH, cst.SCREEN_HEIGHT), flags=pygame.SCALED, vsync=1)
self.player : Player = Player.spawn()
self.obstacles : List[Obstacle] = []
self.paused = False
self.last_tick:int = 0
self.last_obstacle_tick: int = 0 | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
You render the background, the obstacles and the player separataly at differents times and places in your code. Say you decided to render you game differently, you would have to change code in all these different places. Put code that does the same or similar things together.
I grouped up everything so as to end up with a simple looking game loop.
while True:
for event in pygame.event.get():
self.handle_event(event)
time_delta = self.update_tick()
if not self.paused:
self.add_or_remove_obstacles()
self.update_object_positions(time_delta)
self.check_if_player_lost()
self.render()
Nitpicking
Instead of (B > A) and (B < C) you can use A < B < C
Don't go too deep into if-elses, usually there are ways of simplyfiying
Too many flags! You don't need the lost and running flags. You can always return or quit().
In general avoid import *
I also changed they way you handle new obstacles from a time interval to a space interval.
It is both simpler to handle pauses and it allows you to change the obstacle speed without having to also adjust the interval.
All in all really good code for a first project. You could add score keeping, didiculty levels, and maybe saving and reloading a game to learn different concepts.
Final script:
main.py
from typing import Any, List
import pygame, random
from game_objects import Player, Obstacle
import constants as cst
class Flappy_bird:
def __init__(self) -> None:
pygame.init()
pygame.display.set_caption("Flappy Bird")
self.screen = pygame.display.set_mode(
(cst.SCREEN_WIDTH, cst.SCREEN_HEIGHT), flags=pygame.SCALED, vsync=1
)
self.player: Player = Player.spawn()
self.obstacles: List[Obstacle] = []
self.paused = False
self.last_tick: int = 0 | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
def handle_event(self, event: pygame.event.EventType):
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_w) or (event.key == pygame.K_UP):
self.player.vel_y = -250.0
elif event.key == pygame.K_ESCAPE:
self.paused = not self.paused
def check_if_player_lost(self):
if self.player.is_out_of_bounds() or any(
self.player.is_touching_obstacle(obstacle) for obstacle in self.obstacles
):
print("You lost!")
exit()
def render(self):
# Clear the screen for fresh drawing
self.screen.fill(cst.BACKGROUND_COLOR.value)
# Drawing the player
pygame.draw.rect(
self.screen,
self.player.color.value,
pygame.Rect(
int(self.player.x),
int(self.player.y),
self.player.width,
self.player.height,
),
)
# Drawing the obstacles
for obstacle in self.obstacles:
pygame.draw.rect(
self.screen,
obstacle.color.value,
pygame.Rect(
int(obstacle.x), int(obstacle.y), obstacle.width, obstacle.height
),
)
# Update the entire window
pygame.display.flip()
def update_object_positions(self, time_delta_ms: int):
time_delta_s = time_delta_ms / 1000
self.player.update_pos(time_delta_s)
for obstacle in self.obstacles:
obstacle.update_pos(time_delta_s) | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
python-3.x, pygame
def add_or_remove_obstacles(self):
self.obstacles = [
obstacle for obstacle in self.obstacles if (obstacle.x >= -obstacle.width)
]
if (
not self.obstacles
or cst.SCREEN_WIDTH - self.obstacles[-1].x
> cst.OBSTACLE_SPAWN_SPACE_INTERVAL
):
self.obstacles.extend(Obstacle.spawn_obstacle())
def update_tick(self) -> int:
current_tick = pygame.time.get_ticks()
time_delta = current_tick - self.last_tick
self.last_tick = current_tick
return time_delta
def run(self):
# initial ticks
self.last_tick = pygame.time.get_ticks()
while True:
for event in pygame.event.get():
self.handle_event(event)
time_delta = self.update_tick()
if not self.paused:
self.add_or_remove_obstacles()
self.update_object_positions(time_delta)
self.check_if_player_lost()
self.render()
if __name__ == "__main__":
game = Flappy_bird()
game.run()
``` | {
"domain": "codereview.stackexchange",
"id": 44965,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python-3.x, pygame",
"url": null
} |
kotlin
Title: Kotlin call API and store JSON files locally
Question: I'm new to Kotlin and wanted to give this mini project a try. Please let me know if you have any improvements in mind. I'm thinking error handling, structuring the module, is there too much going on in the main function that I should handle elsewhere, is the logging handled correctly (it works, but it's a bit odd to put it into the constructor, no?).
The project:
calls an API
iterates over the json data
saves each map in a separate json file and assigns a unique name
Main.kt
import ApiCall.ApiCall
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import ApiCall.MonsterData
import ApiCall.Utils
import java.io.IOException
fun main() {
val api = ApiCall()
val utils = Utils()
try {
val result = api.callApi("https://botw-compendium.herokuapp.com/api/v3/compendium/category/monsters")
if (api.handleResponse(result)) {
val monsters: String = result.body()
val mapper = ObjectMapper()
val monsterData: MonsterData = mapper.readValue(monsters)
val path = "/Users/me"
utils.createDirectory(path)
for (monster in monsterData.data) {
val monsterName = monster.name
.replace(" ", "_")
// Convert the monster object to JSON string
val monsterJson = mapper.writeValueAsString(monster)
// Write the JSON data to a file named after the monster
val fileName = "$path/$monsterName.json"
utils.writeFiles(fileName, monsterJson)
}
}
} catch (e: IOException) {
api.logger.error("$e")
}
}
ApiCall.kt
package ApiCall | {
"domain": "codereview.stackexchange",
"id": 44966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin",
"url": null
} |
kotlin
ApiCall.kt
package ApiCall
import org.slf4j.Logger
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.net.http.HttpResponse.BodyHandlers
import org.slf4j.LoggerFactory
class ApiCall(private val client: HttpClient = HttpClient.newHttpClient(),
val logger: Logger = LoggerFactory.getLogger(ApiCall::class.java)) {
fun callApi(url: String): HttpResponse<String> {
val request = HttpRequest.newBuilder(URI.create(url))
.header("accept", "application/json")
.build()
return client.send(request, BodyHandlers.ofString())
}
fun handleResponse(response: HttpResponse<String>): Boolean {
val statusCode = response.statusCode()
return when (statusCode) {
200 -> {
logger.info("Status 200. API is available")
true
}
in 400..499 -> {
logger.warn("Status $statusCode. Client Error – client sent an invalid request")
false
}
in 500..599 -> {
logger.error("Status $statusCode. Protocol Error – a generic error occurred on the server")
false
}
else -> {
logger.warn("Unknown status code: $statusCode")
false
}
}
}
}
Monsters.kt
package ApiCall
data class Monster(
val category: String = "",
val common_locations: List<String>? = emptyList(),
val description: String = "",
val dlc: Boolean = false,
val drops: List<String>? = emptyList(),
val id: Int = 0,
val image: String = "",
val name: String = ""
)
data class MonsterData(
val data: List<Monster> = emptyList()
)
Utils.kt (those are just wrappers for existing functions -> maybe a bit of an overkill?)
package ApiCall | {
"domain": "codereview.stackexchange",
"id": 44966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin",
"url": null
} |
kotlin
import java.io.FileWriter
import java.io.PrintWriter
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Paths
class Utils {
fun createDirectory(path: String) {
Files.createDirectories(Paths.get(path));
}
fun writeFiles(fileName: String, jsonString: String) {
PrintWriter(FileWriter(fileName, Charset.defaultCharset()))
.use { it.write(jsonString) }
}
}
Answer:
I'm new to Kotlin ...
Well, you know more about Kotlin than I do,
so I'll approach this strictly from a software engineering perspective.
import ApiCall.ApiCall
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import ApiCall.MonsterData
import ApiCall.Utils
If your editor supports M-x sort-lines then recommend you
do that or similar. Or use an IDE or other tool that manages
such administrivia for you. Similarly on the slf4j imports.
We do this to make it easier to read,
and to minimize merge conflicts
when one feature branch added an import
and another added a different import.
If everyone agrees on the "obvious" sequence
for such statements, then they slot in seemlessly.
Similarly when defining manifest constants,
members of a set, or any other repetitive source code
where the ordering is arbitrary so you may as
well pick a convenient ordering.
handle errors, or don't
What is this all about?
try {
...
} catch (e: IOException) {
api.logger.error("$e")
}
Only java has the "checked exceptions" anti-feature,
so it couldn't be that.
Am I to understand that failure to catch an IOException
would silently take down this whole client process?
Without logging anything?
I have trouble believing that.
No idea why you are "handling" an error with this logging boilerplate,
as it doesn't seem to be your problem.
Let the next layer up handle it.
if (api.handleResponse(result)) { | {
"domain": "codereview.stackexchange",
"id": 44966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin",
"url": null
} |
kotlin
OTOH I see no else clause here.
Consider logging that an unexpected thing ("bad result!") happened.
Consider eliding the if altogether --
if we throw, we throw, c'est la vie.
As long as a diagnostic message is displayed
which makes sense to the user, then we're good.
specifying types
val monsters: String = result.body()
val mapper = ObjectMapper()
val monsterData: MonsterData = mapper.readValue(monsters)
Am I to understand that ObjectMapper offers good enough
type hinting that your tool chain was able to infer it,
but result.body() has a bunch of overloads or is
otherwise vague on what it returns?
IDK, maybe the third one is idiomatic kotlin,
better than an explicit as cast?
Not sure which form would be best for the Gentle Reader
in this situation.
trusted inputs
val fileName = "$path/$monsterName.json"
I will just point out that $monsterName
is a string that came from the internet,
in other words it is "attacker controlled data".
Now result comes from a hard-coded URL,
whose contents you have reviewed and which doesn't
(currently) contain crazy names that have .. or / in them.
You have a trust relationship with that web publisher.
If the names change in future, this code snippet
could be used to overwrite /etc/passwd or other important files.
In handleResponse the when is nice enough;
you can certainly leave it as-is.
But it seems like a "200" vs "not 200", true vs false if
would suffice.
a non-null empty list
data class Monster(
...
val common_locations: List<String>? = emptyList(),
...
val drops: List<String>? = emptyList(),
Maybe this is perfect as-is.
But consider insisting that there always be
a (possibly zero length) string list for these.
Even if the web publisher sometimes omits mentioning them.
Imposing such a class invariant
can make code that calls you simpler, so a whole category of
NPE
bugs disappears. | {
"domain": "codereview.stackexchange",
"id": 44966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin",
"url": null
} |
kotlin
This code appears to achieve its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 44966,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "kotlin",
"url": null
} |
python, logging
Title: Generic logging setup that enables context information
Question: I use the below code to include context specific information in logging record (see obj).
import logging
def setup_logging():
logger = logging.getLogger('sample')
logger.setLevel(logging.INFO)
f = logging.Formatter(
"%(asctime)s | %(levelname)-7s | %(funcName)-10s | %(obj)-20s | %(message)s")
s = logging.StreamHandler()
s.setFormatter(f)
logger.addHandler(s)
logger.addFilter(ContextFilter())
return logger
class ContextFilter(logging.Filter):
def filter(self, record):
record.obj = getattr(record, "obj", "")
return True
class ContextLogger:
def __init__(self, logger, obj):
self.logger = logger
self.obj = obj
def log(self, msg, level=logging.INFO):
log_func = {
logging.INFO: self.logger.info,
logging.WARN: self.logger.warn,
logging.ERROR: self.logger.error,
logging.DEBUG: self.logger.debug,
}
log_func[level](msg, extra={"obj": self.obj})
def info(self, msg):
self.log(msg, logging.INFO)
def error(self, msg):
self.log(msg, logging.ERROR)
def warn(self, msg):
self.log(msg, logging.WARN)
def debug(self, msg):
self.log(msg, logging.DEBUG)
The information is recorded in each class via __repr__ dunder method.
Example
class B:
def __init__(self, a, b, logger):
self.a = a
self.b = b
self.logger = logger
self.logger_ = ContextLogger(logger, self)
self.logger.info('plain info')
self.logger_.info('context info')
def __repr__(self):
return f"a: {self.a}"
def method(self):
try:
return float('a')
except Exception as e:
self.logger_.error(e)
def f(logger):
b1 = B('Joe', 48, logger)
b1.method()
def start():
logger = setup_logging()
logger.info('here')
f(logger) | {
"domain": "codereview.stackexchange",
"id": 44967,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, logging",
"url": null
} |
python, logging
def start():
logger = setup_logging()
logger.info('here')
f(logger)
start()
Output
2023-08-08 13:13:02,494 | INFO | start | | here
2023-08-08 13:13:02,499 | INFO | __init__ | | plain info
2023-08-08 13:13:02,500 | INFO | log | a: Joe | context info
2023-08-08 13:13:02,503 | ERROR | log | a: Joe | could not convert string to float: 'a'
I am not particularly convinced about
need for logging level methods inside ContextLogger
need for separate classes for ContextLogger and ContextFilter
cost of initializing ContextLogger with each class instance
occupying __repr__ for the purpose of context
no support for ad hoc context value (e.g. logging.info('msg', 'alternative value'))
Answer: import logging
Yay! You use a familiar interface.
So we already know how to use it.
def setup_logging():
A typical initial call would be to logging.basicConfig()
(which of course uses old-style / inconsistent camelCase
for historic reasons).
Consider naming this def basic_config, or setup_config,
as a hint to the Gentle Reader that they should start here.
logger.setLevel(logging.INFO)
Consider making INFO a keyword default parameter in the signature.
So folks can easily call the function without giving it much thought,
but then can adjust the level to taste when they're grappling
with a debugging session.
def filter(self, record):
The constant True return value is just fine, of course, though slightly surprising.
Consider adding a # comment or """docstring"""
that mentions we "evaluate this for side effects".
... not particularly convinced about ... need for separate class for ... ContextFilter | {
"domain": "codereview.stackexchange",
"id": 44967,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, logging",
"url": null
} |
python, logging
... not particularly convinced about ... need for separate class for ... ContextFilter
Well, you kind of have to code it as you did,
since you're conforming to a public API that you can't change.
But let's take a step back.
The whole "filter nothing while imposing side effects" aspect
seems a bit strained, not a natural way to express Author's Intent.
The .obj attribute is used later on:
log_func[level](msg, extra={"obj": self.obj})
Why not do the getattr() at that point?
With side effects, or without, on the .obj attribute.
The four {debug, info, warn, error} helpers seem a bit tedious.
I'm not sure they're pulling their weight.
Couldn't we have a single helper,
which we pass the log level into?
def __init__(self, a, b, logger):
No, passing in a logger is just weird.
Please reconsider that decision.
Typically a logger is part of the global (or module-level) environment.
self.logger = logger
self.logger_ = ContextLogger(logger, self)
Those are distinct names.
But we really need a better name, perhaps .ctx_logger
In __repr__(), it's unclear why we ignore b.
It's a pretty generic identifier,
so we're missing some review context.
Surely the original source code describes more interesting objects.
OIC, from f() it appears that (a, b) denotes (name, age).
def method(self):
try:
return float('a')
except Exception as e:
self.logger_.error(e) | {
"domain": "codereview.stackexchange",
"id": 44967,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, logging",
"url": null
} |
python, logging
Maybe that's a typo, and author intended float(self.a) ?
Or self.b if we're interested in "age".
Without type hints in the signatures, it's hard to say.
This unconditionally errors, but I'll pretend
that it sometimes returns a float.
Let's just gloss over method being the wrong name for this method;
I assume that with more review context we would see the actual intent.
The return type for method is Union[float|None].
This seems Bad.
Rather than offering a total function on all inputs,
it would probably be better to offer a partial function
which either raises or returns a float.
To "handle" errors, via logging, seems ill advised.
To fall off the bottom with implicit return None seems worse.
Minimally, make the return value explicit,
for the benefit of the Gentle Reader.
It's unclear how one should reason about the
contract
offered to the caller, and that seems to impact the overall design.
It's usually better for higher layers to catch
such errors, optionally log the event,
and worry about remediation or simply do a re-raise.
Notice that exceptions carry lots of metadata.
The inspect
module can help you traverse the call stack
to learn about the signature of the method which blew up.
This code base does not appear to achieve its design goals
in a maintainable way,
largely due to an odd design which favors low-level error handling.
Better to catch errors further up the stack,
and then inspect exception attributes to obtain
the identical logging output which the current code produces. | {
"domain": "codereview.stackexchange",
"id": 44967,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, logging",
"url": null
} |
c++, c++20
Title: C++ System data transfer design
Question: I'm designing a data transferring that supports an IoT framework I'm developing, which targets embedded systems.
A unified communication core is built, wherein each entity of the code can hook its requests sources (name and callback function) into a core (called SystemInterface), which is an entity that's responsible for interfacing requests. Thus interface requests for any new communication medium goes already supported.
The current design is limited in transferring std::string payloads, however, I want to upgrade this part to support transferring raw data also, and being generic.
The current callback function signature is:
std::function<std::pair<ERROR_CODE,std::string>(const std::string& resourceLink, const std::string& payload)>;
Which I'm designing to upgrade to:
std::function<std::pair<ERROR_CODE,std::vector<Data>>(const std::string& resourceLink, const std::vector<Data>& payload)>;
For the Data class, the proposed design goes to utilize std::span<uint8_t> as a "pointer" to the data payload.
And for the std::vector<Data> part, I'm thinking of making it generic, with any number of Data inputs that might be useful for some parts of the system.
I'm seeking feedback for the Data design, as follows:
#include <iostream>
#include <span>
#include <vector>
#include <string_view>
#include <string>
#include <cstdint>
#include <cstring>
#define INITIALIZE_COPY 0
using namespace std;
void print(string context)
{
cout << context << endl;
}
void print(span<uint8_t const> data)
{
cout << "span s:" << data.size() << "=[";
for (auto it = data.begin(); it != data.end(); ++it)
{
cout << (int)*it;
if (it != data.end() - 1)
cout << ", ";
}
cout << "]." << endl;
}
enum Type
{
BINARY, // Raw
STRING
};
class Data
{
Type _type;
vector<uint8_t> _copy;
span<uint8_t> _span; | {
"domain": "codereview.stackexchange",
"id": 44968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c++, c++20
void reset()
{
_copy.clear();
_span = span<uint8_t>();
}
public:
size_t size() { return _span.size(); }
uint8_t* data() { return &_span[0]; }
span<uint8_t> as_span() { return _span; }
string_view as_string_view() { return string_view(reinterpret_cast<char *>(_span.data()), _span.size()); }
string as_string() { return string{_span.begin(), _span.end()}; }
vector<uint8_t> as_vector()
{
cout << "as_vector() _copy.size()=" << _copy.size() << endl;
return _copy.size() ? _copy : vector<uint8_t>{_span.begin(), _span.end()};
}
void set_type(Type type) { _type = type; }
/* Constructors */
Data(const std::string &str) : _type(STRING), _span(str.length() ? (span<uint8_t>(reinterpret_cast<uint8_t *>(const_cast<char *>(str.data())), str.length() + 1)) : span<uint8_t>{})
{
print("std::string constructor");
}
Data(const std::string &&str) : _type(STRING), _copy(vector<uint8_t>{str.begin(), str.end()}), _span(_copy.data(), _copy.size())
{
print("std::string constructor");
}
Data(string_view sv) : _type(STRING), _span(span<uint8_t>{reinterpret_cast<uint8_t *>(const_cast<char *>(&sv.front())), sv.size()})
{
print("std::string_view constructor");
} | {
"domain": "codereview.stackexchange",
"id": 44968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c++, c++20
Data(const char *str, size_t length = 0, bool copy = false) : _type(STRING)
#if INITIALIZE_COPY
,
_copy(copy ? vector<uint8_t>{reinterpret_cast<uint8_t *>(const_cast<char *>(str)), reinterpret_cast<uint8_t *>(const_cast<char *>(str)) + (length ? length : strlen(str))}
: vector<uint8_t>()),
_span(copy ? &_copy.front()
: reinterpret_cast<uint8_t *>(const_cast<char *>(str))
, length ? length : strlen(str))
#endif
{
print("const char* constructor");
#if !INITIALIZE_COPY
if (copy)
{
// _copy=vector<uint8_t>{reinterpret_cast<uint8_t*>(const_cast<char*>(str)), (uint8_t*) str+(length?length:strlen(str))};
std::copy_n(reinterpret_cast<uint8_t *>(const_cast<char *>(str)), length, back_inserter(_copy));
_span = span<uint8_t>(&_copy.front(), length);
}
else
{
// Rely on the implicit constructor of _copy.
_span = span<uint8_t>(reinterpret_cast<uint8_t *>(const_cast<char *>(str)), length ? length : strlen(str));
}
#endif
}
Data(const uint8_t *data, size_t length, bool copy = false) : _type(BINARY), _copy(copy ? vector<uint8_t>{data, data + length} : vector<uint8_t>()), _span((copy ? &_copy.front() : const_cast<uint8_t *>(data)), length)
{
print("const uint8_t* constructor");
}
Data(vector<uint8_t> &data) : _type(BINARY), _span(data.data(), data.size())
{
print("const vector<uint8_t>& constructor");
} | {
"domain": "codereview.stackexchange",
"id": 44968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c++, c++20
Data(vector<uint8_t> &&data) : _type(BINARY), _copy(data), _span(_copy.data(), _copy.size())
{
print("const vector<uint8_t>&& constructor");
}
Data(const Data &rhs) : _type(rhs._type)
{
print("Copy constructor");
cout << "\trhs._copy.size()=" << rhs._copy.size() << endl;
if (rhs._copy.size())
{
_copy = rhs._copy;
}
else
{
std::copy(rhs._span.begin(), rhs._span.end(), back_inserter(_copy));
}
_span = span<uint8_t>{_copy.begin(), _copy.end()};
}
Data &operator=(const Data &rhs)
{
print("Copy assignment operator");
if (this != &rhs)
{
_type = rhs._type;
_copy.clear(); // Ensure no current copied memory.
if (rhs._copy.size())
{
_copy = rhs._copy;
}
else
{
std::copy(rhs._span.begin(), rhs._span.end(), back_inserter(_copy));
}
_span = span<uint8_t>{_copy.begin(), _copy.end()};
}
return *this;
}
Data(Data &&source) : _type(source._type)
#if INITIALIZE_COPY
,
_copy(source._copy.size() ? std::move(_copy)
: vector<uint8_t>{source._span.begin(), source._span.end()})
#endif
{
print("Move constructor");
#if !INITIALIZE_COPY
if (source._copy.size())
{
std::move(source._copy.begin(), source._copy.end(), back_inserter(_copy));
}
else
{
std::copy(source._span.begin(), source._span.end(), back_inserter(_copy));
}
#endif
_span = span<uint8_t>{_copy.begin(), _copy.end()};
source.reset();
} | {
"domain": "codereview.stackexchange",
"id": 44968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c++, c++20
source.reset();
}
Data &operator=(Data &&source)
{
print("Move assignment operator");
_type = source._type;
if (this != &source)
{
if (source._copy.size())
{
std::move(source._copy.begin(), source._copy.end(), back_inserter(_copy));
}
else
{
std::copy(source._span.begin(), source._span.end(), back_inserter(_copy));
}
_span = span<uint8_t>{_copy.begin(), _copy.end()};
source.reset();
}
return *this;
}
~Data() = default;
};
Here's a link for compiling an example.
Any kind of feedback is welcomed.
Answer: Minor issues
Code formatting: the code is very dense and hard to read. Sometimes it is hard to see where a function ends. Avoid multiple statements per line. I suggest you use a code formatting tool to automate this.
Avoid using namespace std, especially in header files. As for one of the problems it has: note that C++23 will introduce std::print(), so suddenly your print() will start shadowing C++23's version of it.
Prefer using '\n' instead of std::endl.
Consider using std::byte instead of std::uint8_t.
Span or copy, pick one.
Your class stores both a std::span to some data that might live outside of the class, and a std::vector to hold some data inside the class. This is very confusing: does Data own the data or not? It seems that it depends on whether you want to store a string in it or binary data; in the former case it will leave _copy empty and just use _span. But it's a bit unsafe: what if I write:
Data foo(std::string("The quick brown fox jumps over the lazy dog.\n"));
std::cout << foo.as_string(); // Oops! | {
"domain": "codereview.stackexchange",
"id": 44968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c++, c++20
When foo() gets constructed, it creates a span of the temporary string object. That string object is gone after the first line has been executed. The second line which tries to print the contents will thus reference data which no longer exists. A tool like Valgrind will find the error in the above code.
It's safer to always make a copy, and to remove _span altogether. If you really want to be able to hold a reference to external data, I would make a separate class for that named DataReference, so it's made explicit what this is doing.
Don't cast away constness
Your class also has a problem because you are using const_cast. Consider this:
Data foo("The quick brown fox jumps over the lazy dog.\n");
foo.data()[0] = 0; // Oops!
This will compile, but since the actual string lives in read-only memory, the second line will cause a segmentation fault. In general, avoid casting away constness, it is there for a reason. This is another reason to always store a copy.
Consider using std::variant
Your class either stores a (reference to a) string or some binary data. It's very similar to what you can do with std::variant. Consider:
using Data = std::variant<std::string, std::vector<std::uint8_t>>;
Or if you really wanted to store strings by reference but store data by value:
using Data = std::variant<std::string_view, std::vector<std::uint8_t>>;
Working with std::variants directly is perhaps not as easy as with your class, but you can make freestanding functions out of the member functions you had:
std::string as_string(const Data& data) {
return std::visit([](auto& data) {
// This works for std::string, std::string_view and std::vector.
return std::string(reinterpret_cast<const char*>(data.data()), data.size());
}, data);
}
And use it like:
Data foo("The quick brown fox jumps over the lazy dog.\n");
std::cout << as_string(foo);
Generic hooks | {
"domain": "codereview.stackexchange",
"id": 44968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c++, c++20
Generic hooks
std::function<std::pair<ERROR_CODE,std::vector<Data>>(const std::string& resourceLink, const std::vector<Data>& payload)>;
So you want to be able to register a function that takes any number of arguments and returns any number of values? Sure that will work, but now you have to check in the functions that you register that payload.size() has the expected length, and the caller has to check that the return values' second.size() has the expected size, and they have to check for each item in those vectors whether it is the expected string or binary data type.
It would be better if the compiler could do the checking for you. You might want to post another question here with more of the code so we can see how it is actually used, and maybe then we can see if there is a better solution. | {
"domain": "codereview.stackexchange",
"id": 44968,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++20",
"url": null
} |
c++, binary-search
Title: C++ Binary Search
Question: Could you advise on this binary search implementation?
template<typename Iterator, typename T>
Iterator binarySearch(Iterator begin, Iterator end, const T& v) {
Iterator low = begin;
Iterator high = end - 1;
while (low <= high)
{
Iterator mid = low + (high - low) / 2;
if (*mid == v) {
return mid;
}
else if (*mid < v) {
low = mid + 1;
} else {
if (mid == begin) {
return end;
}
high = mid-1;
}
}
return end;
}
The mid==begin line is unfortunate but cannot think of a more elegant approach here, welcoming ideas.
Answer: Your implementation follows a c bsearch interface, and has the same problems.
First, if a target is not found, the entire work is thrown away. You essentially return one bit of information.
Second, if there are duplicates, you return an arbitrary one.
c++ solves these problems with the std::lower_bound, which always returns a meaningful iterator - a partition point. All elements to the left are less than target, all the rest are greater or equal.
The mid == begin is indeed unfortunate, and stems from high being inside the search range. If you initialize it as high = end, and modify it as high = mid instead, high would always be beyond the current search range. Of course, a loop condition should be low < high. If it happens that low == high, the search range is exhausted, and the loop naturally breaks.
Notice that working with semi-open ranges is much simpler, and c++ algorithms always follow this pattern.
You assume a random access iterator. The standard search algorithms only require forward iterators. | {
"domain": "codereview.stackexchange",
"id": 44969,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, binary-search",
"url": null
} |
datetime, typescript
Title: List consecutive days
Question: I created this method for consecutive days to be listed with a dash, non-consecutive are separated by “and”. In my UI control I am only getting back a selectedDays: string[],. In this sample I am getting Mon,Tue,Wed,Fri. I am mapping then to the number 1 - 7 and then looping that list and removing consecutive numbers. I am also interested in hearing any other criticisms or thoughts.
Input array []
let arr = ['Mon', 'Tue, 'Wed ', 'Fri'];
Output
Mon-Wed and Fri
public static selectedDaysOfWeekToString(selectedDays: string[], isHtml: boolean): string {
var daysJoinedString: string = "";
var currentRange: number[] = [];
var definitionParts: string[] = [];
let selectedDayData = new Map<string, number>();
for (const day of selectedDays) {
let WeekNumber = ScheduleCalendarHelper.GetDayOfWeekNumber(day);
selectedDayData.set(day, WeekNumber);
}
var selectedDayNumbers: number[];
selectedDayNumbers = Array.from(selectedDayData.values());
var collapseRange = (selectedDayNumbers: number[]): string => {
console.log('collapseRange');
if (selectedDayNumbers.length === 1) {
return selectedDayNumbers[0].toString();
}
var dash = isHtml ? "–" : " – ";
return `${Array.from(selectedDayData.keys())[0]}${dash}${Array.from(selectedDayData.keys())[selectedDayNumbers.length - 1]}`;
}; | {
"domain": "codereview.stackexchange",
"id": 44970,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "datetime, typescript",
"url": null
} |
datetime, typescript
for (var i = 0; i < selectedDayData.size; i++) {
let dayNumber = Array.from(selectedDayData.values())[i];
if (currentRange.length === 0) {
console.log(Array.from(selectedDayData.keys())[i]);
currentRange.push(dayNumber)
} else {
if (dayNumber - currentRange[currentRange.length - 1] > 1) {
definitionParts.push(collapseRange(currentRange));
currentRange = [selectedDayData[i]];
} else {
currentRange.push(dayNumber);
}
}
};
if (currentRange.length > 0) {
definitionParts.push(collapseRange(currentRange));
};
if (definitionParts.length > 0) {
daysJoinedString =
StringHelper.joinStringsWithSpecialLastSeparator(definitionParts.map(x => isHtml ? `<span class="selected-day-in-string">${x}</span>` : x),
", ", definitionParts.length === 2 ? " and " : ", and ");
}
var pluralModifier: string = (selectedDays.length > 1 ? "s" : "");
return `day${pluralModifier} ${daysJoinedString}`;
}
public static GetDayOfWeekNumber(day){
switch (day) {
case "Sun": {
return 1;
}
case "Mon": {
return 2;
}
case "Tues": {
return 3;
}
case "Wed": {
return 4;
}
case "Thu": {
return 5;
}
case "Fri": {
return 6;
}
case "Sat": {
return 7;
}
}
}
working sample
https://stackblitz.com/edit/typescript-zmfzlw?file=index.ts
Answer: Here are my suggestions: | {
"domain": "codereview.stackexchange",
"id": 44970,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "datetime, typescript",
"url": null
} |
datetime, typescript
Answer: Here are my suggestions:
the sample code does not initially yield the correct output because range collapsing is not performed when you reach the end of selectedDayData (thus omitting Friday)
it may be useful to check for edge cases like ['Wed', 'Mon', 'Tue', 'Wed', 'Fri'] which yields Wed–Tue currently (likely not what you intended)
use let for variables with limited scope
use const when you do not intend to reassign (improves performance)
try to modularize into small, focused functions with the minimum necessary parameters
abstractions (like a Map from days to numbers) can be hard-coded for MVPs or when the concrete details are unlikely to change
prefer "const functions before use" over "var functions after use"
whenever reasonable, set useful defaults for parameters
if an expression occurs repeatedly, hoist it into a variable to avoid repeating work
I applied these principles to the sample code:
// Import stylesheets
import './style.css';
// dayToNum[day] gives num
const dayToNum = {
Sun: 0,
Mon: 1,
Tue: 2,
Wed: 3,
Thu: 4,
Fri: 5,
Sat: 6,
};
// numToDay[num] gives day
const numToDay = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
// return the range [n1, n2] as a string
const rangeToString = (n1: number, n2: number, dash: string = '-'): string => {
return `${numToDay[n1]}${dash}${numToDay[n2]}`;
};
console.log('rangeToString(1, 4)');
console.log(rangeToString(1, 4));
// if nums is an array of integers (ideally nondecreasing), collapse
const collapseSeq = (nums: number[], dash: string = '-'): string => {
const n = nums.length;
if (n === 1) return numToDay[nums[0]];
return rangeToString(nums[0], nums[n - 1], dash);
};
console.log('collapseSeq([1, 2, 5])');
console.log(collapseSeq([1, 2, 5])); | {
"domain": "codereview.stackexchange",
"id": 44970,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "datetime, typescript",
"url": null
} |
datetime, typescript
// if nums is an array of increasing integers, collapse sequentially
const collapseNums = (nums: number[], dash: string = '-'): string[] => {
const n = nums.length;
const strings: string[] = [];
let sequence = []; // current run of consecutive integers
for (const num of nums) {
let m = sequence.length;
// if not consecutive, collapse and reset sequence
if (m > 0 && num > sequence[m - 1] + 1) {
strings.push(collapseSeq(sequence, dash));
sequence = [num];
} else sequence.push(num);
}
// if the end of nums is reached, collapse sequence
if (sequence.length > 0) {
strings.push(collapseSeq(sequence, dash));
}
return strings;
};
console.log('collapseNums([1, 2, 5])');
console.log(collapseNums([1, 2, 5]));
// collapses x by separator 'sep', using 'fin' for the last separator
const collapseStrings = (x: string[], sep: string, fin: string): string => {
const n = x.length;
if (n <= 0) return '';
if (n === 1) return x[0];
let result = x[0];
for (let i = 1; i < n - 1; i++) {
result += sep + x[i];
}
return result + fin + x[n - 1];
};
console.log("collapseStrings(['A', 'B', 'C'], ', ', ', and ')");
console.log(collapseStrings(['A', 'B', 'C'], ', ', ', and '));
// converts days to numbers, removing duplicates and sorting
const daysToNums = (days: string[]): number[] => {
const nums: number[] = [];
for (let i = 0; i < numToDay.length; i++) {
if (days.indexOf(numToDay[i]) != -1) {
nums.push(i);
}
}
return nums;
};
console.log("daysToNums(['Mon', 'Fri', 'Fri', 'Wed'])");
console.log(daysToNums(['Mon', 'Fri', 'Fri', 'Wed']));
// minimum working example
let selectedDays = ['Mon', 'Tue', 'Wed', 'Fri'];
console.log('selectedDays');
console.log(selectedDays);
let selectedNums = daysToNums(selectedDays);
console.log('selectedNums');
console.log(selectedNums);
let isHtml = true;
let dash = isHtml ? '–' : ' – ';
let stringParts = collapseNums(selectedNums, dash); | {
"domain": "codereview.stackexchange",
"id": 44970,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "datetime, typescript",
"url": null
} |
datetime, typescript
console.log('stringParts');
console.log(stringParts);
let displayParts = stringParts.map((x) =>
isHtml ? `<span class="selected-day-in-string">${x}</span>` : x
);
let fin_sep = stringParts.length === 2 ? ' and ' : ', and ';
let daysJoinedString = collapseStrings(displayParts, ', ', fin_sep);
let pluralModifier: string = selectedDays.length > 1 ? 's' : '';
let appDiv: HTMLElement = document.getElementById('app');
appDiv.innerHTML = `day${pluralModifier}: ${daysJoinedString}`;
Hope that helps! Great work on making a really straightforward-to-edit MVP.
Edit:
We can further improve daysToNums. In general, suppose you have N day strings mapped to integer values in [0, K). Currently, we call indexOf, an O(N) operation, K times. (For us, N = 4 and K = 7). Thus, the function takes O(N * K) time. We can change this to O(N + K):
const daysToNums = (days: string[]): number[] => {
const k = numToDay.length;
const present: boolean[] = new Array(k);
for (const day of days) {
present[dayToNum[day]] = true;
}
const nums: number[] = [];
for (let i = 0; i < k; i++) {
if (present[i]) {
nums.push(i);
}
}
return nums;
};
Note that this version may be more difficult to understand. | {
"domain": "codereview.stackexchange",
"id": 44970,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "datetime, typescript",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.