text stringlengths 1 2.12k | source dict |
|---|---|
python, tkinter, user-interface, turtle-graphics
Title: Clock time validation app, cognitive exercise, minimal viable product
Question: How to improve this code, how to make it accessible to get user feedback?
This is a minimal clock time validation app. There is a clock face and the user is asked to validate the time the clock hands show. It is written in Python with Turtle and Tkinter. This is the first app I made. I tried to compose the code so that it is minimal and clean. I tried to keep functions and the operations of the app separate. I created a config dictionary for default setups with constants, and a state for variables that change during the running of the program. I tried to create functions that do one thing. I installed a linter and formatted the code. I formatted the import statements so that only specific functions are imported.
I understand that it can be valuable to create a minimal viable product with only one feature, and then find an audience and get feedback. I don't know if there is a need for such an app, I find it very useful and fun. Among other things, apart from learning to read the time easier, I find that this app helps me with number sense, visualising proportions and understanding mathematical connections. It is also fun and motivating to develop an app that I enjoy using. Developing it also brought ideas for other minimal viable products, like fraction validation with different patterns.
It is inspired by Barbara Arrowsmith Young's work. She devised a cognitive clock reading exercise, with many clock hands, to improve the connectivity and functioning of her brain. I don't have access to the actual clock she made and don't know if it is very similar.
from math import radians, sin, cos
from random import randint
from datetime import datetime
from tkinter import Tk, END, Canvas, Frame, Entry, Button, Label
from turtle import TurtleScreen, RawTurtle | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
config = {
"screen": {
"title": "Clock Validation",
"canvas_width": 600,
"canvas_height": 600,
},
"navigation": {
"title": "Navigation Window",
"label_text": "Validate time value (HH:MM:SS)",
},
"theme": {
"light_bg": "white",
"dark_bg": "black",
},
"hands": {
"hour": {
"shape": "arrow",
"color": "blue",
"size": (1, 10),
},
"minute": {
"shape": "arrow",
"color": "red",
"size": (1, 15),
},
"second": {
"shape": "arrow",
"color": "orange",
"size": (1, 20),
},
},
"markings": {
"radius": 220,
"number_of_markings": 60,
"hours": {
"color": "blue",
"size": 10,
},
"minutes": {
"color": "green",
"size": 5,
},
},
"buttons": {
"validate": {
"text": "Validate Time",
},
"next": {
"text": "Next Clock",
},
"theme": {
"dark_text": "",
"light_text": "☀️",
},
},
}
state = {
"theme": {
"light_mode": False,
"theme_bg": config["theme"]["dark_bg"],
},
"current_time": {
"hours": datetime.now().hour,
"minute": datetime.now().minute,
"seconds": datetime.now().second,
},
}
# VALIDATION LOGIC
# Validation handler
def handle_validation():
user_time = input_field.get()
valid_time, message = validate_time(user_time, state["current_time"])
validation_label.config(text=message)
# Function to validate the user's input
def validate_time(user_time, state):
current_hour, current_minute, current_second = state.values()
try:
user_hour, user_minute, user_second = map(int, user_time.split(":"))
except ValueError:
return False, "Invalid format (HH:MM:SS)" | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
if not (0 <= user_hour <= 24 and 0 <= user_minute <= 59 and 0 <= user_second <= 59):
return False, "Invalid time values"
elif (
# User input hours are correct
(
user_hour == current_hour
or user_hour - 12 == current_hour
or user_hour == current_hour - 12
or (user_hour in [0, 24, 12] and current_hour == 0)
)
and
# User input minutes and seconds are correct
user_minute == current_minute
and user_second == current_second
):
return True, "Awesomeness, keep up the good work!"
else:
return False, "Oops, try again!"
# FUNCTIONS FOR DRAWING THE CLOCK
# Functions to create angles from clock values
def hours_angle(hours, minutes):
return (hours % 12) * 360 / 12 + minutes * 360 / (12 * 60)
def minutes_angle(minutes):
return minutes * 360 / 60
def seconds_angle(seconds):
return seconds * 360 / 60
# Loads current time values
def load_current_time():
hours, minutes, seconds = state["current_time"].values()
return [hours, minutes, seconds]
# Calculates hands angles
def calculate_angles(current_time):
hours, minutes, seconds = current_time
hour_angle = hours_angle(hours, minutes)
minute_angle = minutes_angle(minutes)
second_angle = seconds_angle(seconds)
hands_angles = [hour_angle, minute_angle, second_angle]
return hands_angles
# Function for drawing the hands
def draw_hands():
current_time = load_current_time()
hands_angles = calculate_angles(current_time)
for hand, angle in zip(reversed(clock_hands), reversed(hands_angles)):
# Set the hands' angles
hand.setheading(90 - angle)
# Generates random hours, minutes, and seconds
def generate_random_time_values():
random_hours = randint(0, 11)
random_minutes = randint(0, 59)
random_seconds = randint(0, 59)
return [random_hours, random_minutes, random_seconds] | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
# Refreshing state with new time values
def refresh_time(state):
refreshed_state = state
random_time = generate_random_time_values()
refreshed_state = {
"hours": random_time[0],
"minutes": random_time[1],
"seconds": random_time[2],
}
return refreshed_state
# Next clock drawing handler
def load_next_clock():
# Clear the input field and validation message
input_field.delete(0, END)
validation_label.config(text="")
# Refresh state with new time values
state["current_time"] = refresh_time(state["current_time"])
# Change direction of the hand turtles
draw_hands()
# GUI SETUP
def toggle_theme():
# If it is dark mode at the moment, make light
if state["theme"]["light_mode"] is False:
state["theme"]["light_mode"] = True
state["theme"]["theme_bg"] = config["theme"]["light_bg"]
screen.bgcolor(config["theme"]["light_bg"])
theme_button.config(text=config["buttons"]["theme"]["dark_text"])
# If it is light mode, make dark
else:
state["theme"]["light_mode"] = False
state["theme"]["theme_bg"] = config["theme"]["dark_bg"]
screen.bgcolor(config["theme"]["dark_bg"])
theme_button.config(text=config["buttons"]["theme"]["light_text"])
# Create tkinter GUI for interaction
root = Tk()
root.title(config["screen"]["title"])
# Create a Canvas to hold the Turtle screen
canvas = Canvas(
root,
width=config["screen"]["canvas_width"],
height=config["screen"]["canvas_height"],
)
canvas.pack()
# Create a Frame to hold the button
button_frame = Frame(root)
button_frame.pack(side="bottom", fill="both", expand=True)
# Create a Turtle screen within the canvas
screen = TurtleScreen(canvas)
screen.bgcolor(state["theme"]["theme_bg"])
# Create the input field and buttons
input_field = Entry(button_frame)
input_field.pack() | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
# Create the input field and buttons
input_field = Entry(button_frame)
input_field.pack()
# Create validate button
validate_button = Button(
button_frame, text=config["buttons"]["validate"]["text"], command=handle_validation
)
validate_button.pack()
# Create validation label
validation_label = Label(button_frame, text=config["navigation"]["label_text"])
validation_label.pack()
# Create next button
next_clock_button = Button(
button_frame, text=config["buttons"]["next"]["text"], command=load_next_clock
)
next_clock_button.pack()
# Create theme toggle:
theme_button = Button(
button_frame, text=config["buttons"]["theme"]["light_text"], command=toggle_theme
)
theme_button.pack()
# DRAWING THE MARKINGS AND THE HANDS
# Create a turtle to draw the clock face
clock = RawTurtle(screen)
clock.speed(100)
# Make turtles for clock hands
clock_hands = []
for hand_name, hand_config in config["hands"].items():
hand = RawTurtle(screen)
hand.shape(hand_config["shape"])
hand.color(hand_config["color"])
hand.shapesize(
stretch_wid=hand_config["size"][0], stretch_len=hand_config["size"][1]
)
clock_hands.append(hand)
# Load values for the markings
clock_radius = config["markings"]["radius"]
number_of_markings = config["markings"]["number_of_markings"]
hours_dot_size = config["markings"]["hours"]["size"]
hours_dot_color = config["markings"]["hours"]["color"]
minutes_dot_size = config["markings"]["minutes"]["size"]
minutes_dot_color = config["markings"]["minutes"]["color"]
# Draw markings
for i in range(number_of_markings):
angle = radians(i * 360 / number_of_markings)
x = clock_radius * sin(angle)
y = -clock_radius * cos(angle) | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
if i % 5 == 0:
# Larger dot for hours
clock.penup()
clock.goto(x, y)
clock.dot(hours_dot_size, hours_dot_color)
elif i % 1 == 0:
# Smaller dot for minutes
clock.penup()
clock.goto(x, y)
clock.dot(minutes_dot_size, minutes_dot_color)
# Draw hands
draw_hands()
# Start the tkinter main loop to manage the GUI
root.mainloop()
```
Answer: Thank you for the obvious effort put into readability.
isort
Your imports are nice enough as is.
But you're working too hard.
Run "$ isort *.py"
and be done with it, don't give it a second thought.
The package's motto is "I sort ... so you don't have to."
config
Gosh, that's a lot of config details!
Reading this for the first time,
I'm wondering if maybe it's not the most
convenient way to achieve your goal.
There's lots of key names that appear here as str
and will wind up being bound to identifiers down in the code.
Feel free to keep it as-is, but I will toss out
a pair of alternatives to consider.
And the three Hands makes me wonder if we'd like a class or a
named tuple
to represent them.
This dict may look like data but really it's code, within a source file.
Consider using json.dump(), or better,
yaml.dump(),
to serialize it out to a config file.
Use the same git source control edit / commit practices
on the config file that you use on your *.py source files.
Consider using keyword arguments (kwargs) in a function's
signature to adjust some of these parameters.
And then typer
gives you CLI --help "for free".
def main(
nav_title="Navigation Window",
nav_label_text="Validate time value (HH:MM:SS)",
theme_light_bg="white",
theme_dark_bg="black", # and so on...
):
...
if __name__ == "__main__":
typer.run(main) | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
if __name__ == "__main__":
typer.run(main)
comments
There's nothing wrong with writing comments -- feel free to do so.
But sometimes, if you feel a need to explain code which isn't sufficiently clear,
the comment is a code smell that is helping you to identify a refactor.
# VALIDATION LOGIC
# Validation handler
def handle_validation():
...
# Function to validate the user's input
def validate_time(user_time, ...
All of those identifiers are great.
The "validation logic" comment is maybe helpful for grouping things,
maybe not too redundant with the "valid"s we see in function names.
Or maybe it would be helpful to banish these functions
to a new validation.py module, and import them.
Similarly for a draw_clock.py module.
The next two comments are on the redundant side,
enough that I'd probably delete one or both of them.
If you do wish to retain descriptions
of those (well named, self explanatory!) functions,
then use a """docstring""" rather than a # comment.
A single English sentence would likely suffice.
It would be very nice if you explain we're expecting str input rather than a
datetime.time:
def validate_time(user_time: str, ...
Now, about that second argument, the state dict.
Consider creating a class so you can turn this function into a method.
def validate_time(self, user_time: str): | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
Then we might access self.state.
Or we might break out its values
to store each one directly as an object attribute.
I confess that referencing state.values() confuses me a bit.
I was expecting to see state.current_time.values().
Your H,M,S tuple unpack makes me slightly nervous,
as it's reading from a dict rather than a tuple.
Yes, in cPython since 3.5 we've had stable iterator order
which matches the key insertion order.
But the python language is bigger than cPython,
there are other interpreters.
It just seems slightly jarring that we don't have three dict de-refs there.
Feel free to keep it, anyway.
Consider turning H,M,S into a namedtuple or
dataclass.
Or better, prefer to use a
time.
BTW, kudos on that map(int, user_time.split(":")) tuple unpack expression.
It's a very clear, natural way to express your intent.
Give the signature a type annotation, please, so caller knows to expect a
tuple[bool, str].
diagnostic message
return False, "Invalid format (HH:MM:SS)"
This is nice as-is.
Consider tacking on the bad user_time value,
to help some future maintenance engineer diagnose bugs quicker.
Rather than returning a boolean, you possibly would like to
raise ValueError(...), so caller can't accidentally ignore the False value.
half-open interval
Kudos for the very clear math notation in this expression:
if not (... and 0 <= user_second <= 59):
You might want to habitually prefer a half-open over a closed interval:
0 <= user_second < 60
There are several advantages.
They compose nicely, e.g. Mon .. Wed combined with Wed .. Sat gives all weekdays.
They match the builtin range semantics.
Magic numbers appear in their more obvious form, e.g. 59 vs 60.
Continuous and discrete work the same (float and int, also datetime and date). | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
nit: Here's a fun fact. The <= 59 expression isn't exactly correct.
Twice a year (start of January & July) a leap second may be inserted.
Which lets 23:59:59 tick over to 23:59:60 before advancing to 00:00:00.
Many people (well, non-astronomer people) ignore this, and you should, too.
The takeaway is "timekeeping is complex", and you'd be better off
modeling instants of time with a mature library such as datetime.
modulo
elif ( ...
(
user_hour == current_hour
or user_hour - 12 == current_hour
or user_hour == current_hour - 12
or (user_hour in [0, 24, 12] and current_hour == 0)
)
Yikes! Such a simple concept, so much complexity.
It looks like you had trouble with edge cases and
just kept piling one fix on top of another.
Step back a moment. The math concept you're looking for is %
modulo,
which grade school math teachers often introduce in terms of clock hands.
Compare both quantities mod 12 and we're done.
If datetime times were involved we wouldn't be jumping through hoops like this.
Maybe we're sad that we lost the AM/PM indicator bit?
Better, maybe we should have immediately
trimmed twelve hours off any PM input values,
before it could even get here.
@property
The FOO_angle functions are very nice, keep them as-is.
Perhaps mark them as _private helpers with a leading _ underscore.
In general, your Public API is pretty big, exporting a great many identifiers.
I will just point out that if you create your own class (maybe a dataclass)
to represent an instant in time, there is an opportunity to turn those
functions into three @property decorated methods.
negation
def toggle_theme could toggle by assigning not state["theme"]["light_mode"].
Notice that we could construct the relevant key name with an expression like:
>>> ['dark', 'light'][False]
'dark'
>>> ['dark', 'light'][True]
'light'
main guard
root = Tk() | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
python, tkinter, user-interface, turtle-graphics
main guard
root = Tk()
This is bog standard, it's nice as-is.
Please bury it within def main(): or another function.
That way other modules, such as a
test suite,
can import this one and exercise the various helper functions.
It is usual that import should not print, create a new window,
or have other annoying side effects, beyond defining functions and constants.
You have a bunch of helpers.
They would benefit from an automated
unit test
suite.
unyt
There's no need to adopt this library.
But I will note in passing that
unyt
lets you annotate your variables with degree or radian.
This can promote type safety and reduce confusion.
This well-engineered application achieves its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 45186,
"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, tkinter, user-interface, turtle-graphics",
"url": null
} |
performance, haskell
Title: Haskell code optimization for short Pi approximator
Question: Very new in Haskell, as a first easy program I went for an old algorithm of mine to approximate pi by counting points within a circle. The snippet below is what I could get working. I had quite an issue with types (you will notice very extensive use of fromIntegral) and would also like to know about performance, since I read that Haskell can be quite fast (the same algorithm I test in C++ and it is a lot faster).
So to sum up:
How could this code be written better/shorter in Haskell?
How would this code be written for better performance?
module PiCalc (approximatePi) where
type Point = (Int,Int)
pointInCircle :: Point -> Int -> Bool
pointInCircle (x,y) r =
let xd = fromIntegral x
yd = fromIntegral y in
sqrt (xd*xd + yd*yd) <= fromIntegral r
countPoinstInDistance :: Int -> Int
countPoinstInDistance n = sum [1 | x <- [0..n], y <- [0..n], pointInCircle(x,y) n]
approximatePi :: Int -> Double
approximatePi n = 4 * fromIntegral (countPoinstInDistance n) / fromIntegral (n*n)
The algorithm works by passing in a large number like 10000 for example and checking the distance of all points (x,y) from the center.
Answer: Incorrect results
There's a bug in your code. It produces incorrect results. The line
[1 | x <- [0..n], y <- [0..n], pointInCircle(x,y) n]
should be
[1 | x <- [0..n], y <- [1..n], pointInCircle(x,y) n] | {
"domain": "codereview.stackexchange",
"id": 45187,
"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": "performance, haskell",
"url": null
} |
performance, haskell
should be
[1 | x <- [0..n], y <- [1..n], pointInCircle(x,y) n]
so that the x=0 column is included in the count but the y=0 row is not, because it's the same pixels as the x=0 column of the adjacent quarter circle. If you include both in the tally, you effectively count the border pixels twice. Your code returns 3.14199056 for approximatePi 10000 and with the bug fixed, it returns 3.14159052.
Style and Performance
Instead of clobbering the namespace with top level functions and types, define functions in where clauses. I removed the Point type in favor of taking separate x and y arguments and I put the pointInCircle function into a where clause in countPointsInDistance. Note how pointInCircle now captures n from the parent scope so that you only have to pass x and y as arguments. I also squared the right side of the comparison instead of taking the square root on the left side, which removes floating point calculations (and fromIntegral conversions) altogether.
countPointsInDistance :: Int -> Int
countPointsInDistance n = sum [1 | x <- [0..n], y <- [1..n], pointInCircle x y]
where pointInCircle x y = x*x + y*y <= n*n
approximatePi :: Int -> Double
approximatePi n = 4 * fromIntegral (countPointsInDistance n) / fromIntegral (n*n)
You can take this one step further by removing countPointsInDistance as a top-level function as well, but you probably wanted to keep that one accessible for testing. If you want to remove it, your entire code simplifies down to:
approximatePi :: Int -> Double
approximatePi n = 4 * fromIntegral pointsInDistance / fromIntegral (n*n)
where pointsInDistance = sum [1 | x <- [0..n], y <- [1..n], pointInCircle x y]
pointInCircle x y = x*x + y*y <= n*n | {
"domain": "codereview.stackexchange",
"id": 45187,
"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": "performance, haskell",
"url": null
} |
performance, haskell
Haskell can be rather fast, but you have to compile your program into an executable with optimizations turned on. Running code in GHCi is slow as hell. Also keep in mind that Int are 64 bit integers (fast, but can overflow) whereas Integer are unbounded, but slower. Using Integer by default is highly recommended, although it makes performance comparisons harder when the other language, often C++, uses overflowing integers.
Algorithm improvements
As usual, the biggest improvement comes from a better algorithm. Instead of running the inner loop over all possible values of y, take y from the previous iteration of the outer loop and adjust it slightly because x has been incremented. My code starts with x=0, y=n and increments x as part of the outer loop. After incrementing x, it decrements y until the condition x*x + y*y <= n*n is valid again. The remaining decrements of y down to zero are omitted. I just add that number to the counter instead of actually iterating down to zero and adding 1 on each iteration.
countPointsInDistance :: Int -> Int
countPointsInDistance n = go 0 n 0
where go x y count
| y == 0 = count
| x*x + y*y <= n*n = go (x+1) y (count+y)
| otherwise = go x (y-1) count
This code can be improved further by not squaring the numbers, which prevents overflow issues for native integers, or performance issues for arbitrary precision integers. We can do this by introducing a variable z = x*x + y*y - n*n and updating z whenever we increment x or decrement y. We never recalculate z from scratch. We initialize with x=0, y=n, z=0
countPointsInDistance :: Int -> Int
countPointsInDistance n = go 0 n 0 0
where go x y z count
| y == 0 = count
| z <= 0 = go (x+1) y (z+2*x+1) (count+y)
| otherwise = go x (y-1) (z-2*y+1) count | {
"domain": "codereview.stackexchange",
"id": 45187,
"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": "performance, haskell",
"url": null
} |
performance, haskell
If you want to compare the performance of Haskell vs. C++, the equivalent C++ implementation of the last code sample would be:
int countPointsInDistance(int n) {
int x = 0, y = n, z = 0, count = 0;
while (y != 0) {
if (z <= 0) {
z += 2*x+1;
x += 1;
count += y;
} else {
z += -2*y+1;
y -= 1;
}
}
return count;
} | {
"domain": "codereview.stackexchange",
"id": 45187,
"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": "performance, haskell",
"url": null
} |
sql, sql-server, t-sql
Title: Is there a more concise way to write this Procedure
Question: I have this stored Procedure that is passed in the data below that will building the SQL select that will get EXEC. The data that can be passed in can me null so I have three IF ISNULL checking and then adding to the @SqlWhereCommand object. Any help would be great.
parameter
@StartDate AS DATE = NULL,
@EndDate AS DATE = NULL,
@Ids As Varchar(500) = NULL,
@SubCategories As Varchar(300) = NULL,
@LanguageIds As Varchar(300) = NULL,
@RegionIds As Varchar(300) = NULL,
DECLARE
DECLARE @SqlCommand nvarchar(4000)
DECLARE @SQLColumnList varchar(2000)
DECLARE @SqlSelectCommand nvarchar(4000)
DECLARE @SqlFromCommand varchar(200)
DECLARE @SqlWhereCommand nvarchar(2000)
DECLARE @SqlGroupCommand nvarchar(4000)
Buildings the Selects
SET @SQLColumnList =' Id, [Name] as ''gl.Name'', type = ''PDF'', CONCAT([Description],''Data Stats'') as Description,
SUM (WebsiteDownloads) As Downloads,[Language],
Region = ''Asia'''
Set @SqlFromCommand =' from [report].[Downloads]'
Set @SqlGroupCommand =' GROUP BY Id, [Name],[Description],[Language]'
Set @SqlWhereCommand = ' where cast(LogDate as date) >= + ''' + CONVERT(VARCHAR(25), @StartDate, 120) + ''' and cast(LogDate as date) <= ''' + CONVERT(VARCHAR(25), @EndDate, 120) + ''''
IF ((ISNULL(@Ids,'')) <> '')
BEGIN
SET @SqlWhereCommand = @SqlWhereCommand + ' AND Id IN (SELECT val AS linkType FROM dbo.Split(''' + @Ids + ''','',''))'
END
IF ((ISNULL(@SubCategories,'')) <> '')
BEGIN
SET @SqlWhereCommand = @SqlWhereCommand + ' AND LinkTypeId IN (SELECT val As subCategorys FROM dbo.Split(''' + @SubCategories + ''', '',''))'
END
IF ((ISNULL(@LanguageIds,'')) <> '')
BEGIN
SET @SqlWhereCommand = @SqlWhereCommand + ' AND LanguageId IN (SELECT val As subCategorys FROM dbo.Split(''' + @LanguageIds + ''', '',''))'
END | {
"domain": "codereview.stackexchange",
"id": 45188,
"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": "sql, sql-server, t-sql",
"url": null
} |
sql, sql-server, t-sql
SET @SqlCommand = 'SELECT ' + @SQLColumnList + @SqlFromCommand + @SqlWhereCommand + @SqlGroupCommand
Answer: Not anything groundbreaking, but I use the template replicate(myString,aFlag) to decide to include a string or not. Also, you don't really need the isnull() here, because if your variable is indeed null, all checks fail, including <>''.
Here:
SET @SqlWhereCommand = @SqlWhereCommand
+replicate(' AND Id IN (SELECT val AS linkType FROM dbo.Split(''' + @Ids + ''','',''))' , case when @Ids <> '' then 1 else 0 end)
+replicate(' AND LinkTypeId IN (SELECT val As subCategorys FROM dbo.Split(''' + @SubCategories + ''', '',''))' , case when @SubCategories <> '' then 1 else 0 end)
+replicate(' AND LanguageId IN (SELECT val As subCategorys FROM dbo.Split(''' + @LanguageIds + ''', '',''))' , case when @LanguageIds <> '' then 1 else 0 end) | {
"domain": "codereview.stackexchange",
"id": 45188,
"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": "sql, sql-server, t-sql",
"url": null
} |
java, algorithm, array, dynamic-programming
Title: Another ATMs cash-out (denomination) algorithm in Java
Question: Related to this question and this answer, I would like to have a second review from you on a modified version.
The problem I tried to solve
Some kind of "Minimum count of numbers required from given array to represent S" (see here).
Algorithms that I used
Some kind of dynamic programming array (see here), but I don't know the exact name.
Java Code
import java.util.Arrays;
public class CashMachineWithDynamicProgrammingArray {
private final int[] billValues;
private final int[] billAmounts;
private final int maxBillAmount;
private int currentBillAmountIndex = 0;
public CashMachineWithDynamicProgrammingArray(final int[] billValues, final int maxDepth) {
this.billValues = billValues;
billAmounts = new int[billValues.length];
maxBillAmount = maxDepth;
}
private boolean next() {
billAmounts[currentBillAmountIndex]++;
if (billAmounts[currentBillAmountIndex] >= maxBillAmount) {
do {
billAmounts[currentBillAmountIndex] = 0;
currentBillAmountIndex++;
if (currentBillAmountIndex >= billAmounts.length) {
currentBillAmountIndex = 0;
return false;
}
} while (billAmounts[currentBillAmountIndex] >= maxBillAmount);
billAmounts[currentBillAmountIndex]++;
currentBillAmountIndex = 0;
}
return true;
}
private void skipCurrentBillIndexIncrementation() {
billAmounts[currentBillAmountIndex] = maxBillAmount;
}
private int calculateBillsAmount() {
int amount = 0;
for (int i = 0; i < billValues.length; i++) {
amount += billValues[i] * billAmounts[i];
}
return amount;
} | {
"domain": "codereview.stackexchange",
"id": 45189,
"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, algorithm, array, dynamic-programming",
"url": null
} |
java, algorithm, array, dynamic-programming
private int calculateBillsSum() {
int sum = 0;
for (final int billAmount : billAmounts) {
sum += billAmount;
}
return sum;
}
public int[] calculateBillAmountsWithLowestSum(final int amountToLookFor) {
int lowestSum = 0;
int[] billAmountsWithLowestSum = new int[billValues.length];
do {
int amount = calculateBillsAmount();
if (amount >= amountToLookFor) {
if (amount == amountToLookFor) {
int sum = calculateBillsSum();
if (lowestSum == 0 || sum < lowestSum) {
lowestSum = sum;
System.arraycopy(billAmounts, 0, billAmountsWithLowestSum, 0, billAmounts.length);
}
}
skipCurrentBillIndexIncrementation();
}
} while (next());
return billAmountsWithLowestSum;
}
public static void main(final String[] args) {
int[] billValues = {1, 29, 59, 109, 209, 509, 1000, 2000, 5000};
int maxDepth = 5;
CashMachineWithDynamicProgrammingArray cashMachine = new CashMachineWithDynamicProgrammingArray(billValues, maxDepth);
System.out.println(Arrays.toString(cashMachine.calculateBillAmountsWithLowestSum(1)));
System.out.println(Arrays.toString(cashMachine.calculateBillAmountsWithLowestSum(30)));
System.out.println(Arrays.toString(cashMachine.calculateBillAmountsWithLowestSum(5000)));
System.out.println(Arrays.toString(cashMachine.calculateBillAmountsWithLowestSum(25114)));
}
}
Answer: Use banknote for name of physical currency and withdrawl for the target/requested amount. I think this solves most of the program's understandability problem.
Name things for what they are, not how they are implemented.
CashMachineWithDynamicProgrammingArray ---> CashMachine
skipCurrentBillIndexIncrementation
Do not make a method out of that one code line. | {
"domain": "codereview.stackexchange",
"id": 45189,
"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, algorithm, array, dynamic-programming",
"url": null
} |
java, algorithm, array, dynamic-programming
skipCurrentBillIndexIncrementation
Do not make a method out of that one code line.
"skip" means to pass over or ignore, so why is there a method that does nothing?
The method does not do what it says. It is setting a default value, it is not skipping.
The surrounding code logic is doing the skipping. This method is only the processing of that condition.
Even with an accurate name the method hurts understanding. After all the details of working with array indexes, buried 3 "if"s deep you hide the detail of an "else" fall-through branch. A very simple detail it turns out. Ouch.
calculateBillSum - "calculate" is superfluous. "Sum" is a verb (in this use) and very specific - add a list of numbers. "calculate" can mean anything.
It is OK to name methods as if they are properties because it is a given that properties return values.
calculateBillAmountsWithLowestSum ---> BillLowestSum or LowestBillSum
for-each makes code shorter, cleaner, and easier on the eyes.
Physically order the algorithm methods with cashMachine.calculateBillAmountsWithLowestSum at the top and the rest in depth/call order.
Return immediately on terminating conditions.
Nested redundant evaluation is bad. It hides simpler logic that must stand out.
if (amount >= amountToLookFor) {
if (amount == amountToLookFor) {
Much Better:
if (amount > amountToLookFor) { addLargestBanknote(); }
if (amount == amountToLookFor) {
int sum = calculateBillsSum();
if (lowestSum == 0 || sum < lowestSum) {
lowestSum = sum;
System.arraycopy(billAmounts, 0, billAmountsWithLowestSum, 0, billAmounts.length);
}
}
} while (next());
return billAmountsWithLowestSum;
}
Blank space around conditional code blocks really, totally, for sure, helps comprehension speed and readability.
NOTE: After this refactoring - and "skip..." method name change - I take back almost everything I said about that method earlier. | {
"domain": "codereview.stackexchange",
"id": 45189,
"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, algorithm, array, dynamic-programming",
"url": null
} |
java, algorithm, array, dynamic-programming
Cover all conditions.
The refactor above made me realize there is no 'less than' condition. Never say it will never happen.
If the oversight is intentional, add a comment. Alternatively add a line of code that "skips" for that condition.
However if higher level / caller code explicitly takes care of the possibility then ignoring it is ok. The Object constructor is the best place to set complete, valid execution state. | {
"domain": "codereview.stackexchange",
"id": 45189,
"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, algorithm, array, dynamic-programming",
"url": null
} |
c++, template-meta-programming
Title: Template for making distinct numeric type aliases
Question: I've tried to make a small template for the creation of distinct (incompatible) numerical types. For example both row and column indices are usually represented as the same underlying type. However it is rare that you would want to mix the two.
Code
template< typename Base, std::size_t Id>
struct Alias
{
explicit( true ) Alias( Base const & inBase ): mValue( inBase ) {};
explicit( false ) Alias( Alias const & inOther ): mValue( inOther.mValue ) {};
~Alias() = default;
explicit( false ) operator Base() { return mValue; }
Alias & operator=( Alias const & inOther ){ mValue = inOther.mValue; return *this; }
Base mValue;
};
Usage
using Rows = Alias< std::size_t, 'rows' >;
using Cols = Alias< std::size_t, 'cols' >;
Rows row( 5 );
Cols col( 7 );
// row = col; // not allowed
auto area = row * col; // implicitly both casted to std::size, the underlying type.
// row = 5; // not allowed
row = Rows( 5 );
Goals
No overhead, I would assume that the compiler can treat code using this template the same as the underlying type
Allow for implicit down casting ( Alias -> Base )
explicit upcasting ( Base -> Alias )
Two distinct aliases cannot be assigned to each other without the involvement of some explicit cast
So, I am wondering is my implementation enough for this. Or am I missing subtle details about c++ that would cause this to fail?
Answer: This is a good idea, and it’s something similar to what I’ve been toying around with for a while (though, I’ve been focused on creating strong aliases for strings, not numbers). However, this implementation has a number of problems.
Let’s start with the obvious ones: you say it’s for numeric type aliases, but:
using alias = Alias<std::string, 'foo'>; // works just fine! | {
"domain": "codereview.stackexchange",
"id": 45190,
"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++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
If you really want it to be for numeric types only, you should constrain it:
template <typename T>
concept number = (
std::integral<T>
or std::floating_point<T> // assuming you want *all* numbers
)
and (not std::same_as<T, bool>);
template <number Base, std::size_t Id>
struct Alias
But there doesn’t really seem to be a sensible reason to constrain this to only numeric type aliases.
The bigger problem is that you are using std::size_t as the discriminator. That means it’s trivial to do this:
using type_1 = Alias<int, 12345>; // I think 12345 is a unique enough number
// elsewhere in a very large code base:
using type_2 = Alias<int, 12345>; // no one else would use 12345!
// it's the combination i use on my luggage!
You seem to think that this will be less likely if you use multi-character literals… but that actually makes things worse.
Multi-character literals are not portable. And where they do work, they may not work the way you expect.
(In case it isn’t clear what is happening there: On that platform, multi-character constants are 4 bytes wide… so they only accept 4 characters. The rest are just dropped. Only the last 4 characters are accepted. So x_vals and y_vals both get crunched down to vals. Thus the two types end up with the same ID, and the assertion fires.)
Using a std::size_t as the discriminator is not a great idea. Using multi-character literals takes it from a bad idea to a terrible one.
You have two options.
You could use types as the discriminator. For example:
template <typename Base, typename Id>
struct Alias
{
// ...
};
struct row_tag {};
struct col_tag {};
using row_t = Alias<std::size_t, row_tag>;
using col_t = Alias<std::size_t, col_tag>; | {
"domain": "codereview.stackexchange",
"id": 45190,
"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++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
using row_t = Alias<std::size_t, row_tag>;
using col_t = Alias<std::size_t, col_tag>;
If you go this route, there is an additional benefit: the discriminator type could also be a policy class:
template <typename Base, typename Policy>
struct Alias
{
constexpr auto operator++() -> Alias&
requires Policy::supports_increment
{ ++mValue; return *this; }
// ... etc. ...
};
struct row_policy
{
static inline constexpr bool supports_increment = true;
// ... and so on ...
};
using row_t = Alias<std::size_t, row_policy>;
// Now this will work (well, once you also support operator<)
for (auto row = row_t{0}; row < number_of_rows; ++row)
That’s just a very simple example, but you could make it so that:
If the policy class has no static member named increment, the alias does not support incrementing.
If the policy class has a static member named increment:
If that static member is a bool constant:
If it is false, the alias does not support incrementing.
If it is true, the alias supports incrementing, with a default implementation.
If that static member is a function that takes a Base value and returns a Base value:
The alias supports incrementing, implemented by calling that function.
(That’s actually similar to what I’ve been working on, for strings.)
The other option, if you still want to keep things simple and use a non-type template parameter as the discriminator, is to use a string constant type. Here’s a very quick-and-dirty example:
class tag
{
public:
static inline constexpr std::size_t max_size = 127; // should be enough for tags!
constexpr auto operator==(tag const&) const noexcept -> bool = default;
std::array<char, max_size + 1> chars;
friend consteval auto operator""_tag(char const*, std::size_t) -> tag;
private:
consteval tag(char const* p, std::size_t n)
{
if (n > max_size)
throw std::invalid_argument{"tag is too long"}; | {
"domain": "codereview.stackexchange",
"id": 45190,
"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++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
std::ranges::copy_n(p, n, chars.begin());
chars.back() = '\0';
}
};
consteval auto operator""_tag(char const* p, std::size_t n) -> tag
{
return tag{p, n};
}
template <typename Base, tag Tag>
struct Alias
{
// ...
};
using row_t = Alias<std::size_t, "rows"_tag>;
using col_t = Alias<std::size_t, "cols"_tag>;
Now you can use strings to discriminate between aliases, which should effectively reduce collisions to close to zero in practice. (And if 127 characters isn’t long enough to disambiguate all your aliases, you could make it longer.)
So now let’s look at the actual code:
explicit( true ) Alias( Base const & inBase ): mValue( inBase ) {};
This is… okay. But it could be much better. It requires copying the argument. That’s probably fine if you really only mean to alias integral types. But otherwise, you should allow moving. For example:
constexpr explicit Alias(Base const& b) noexcept(std::is_nothrow_copy_constructible_v<Base>)
: mValue{b}
{}
constexpr explicit Alias(Base&& b) noexcept(std::is_nothrow_move_constructible_v<Base>)
: mValue{std::move(b)}
{}
Note also the added constexpr, and noexcept.
Also, as a style note, putting a space between the const and the & makes the & look like the binary AND operator. When & is being used as a reference modifier, C++ coders usually attach it to the type (same for &&; when used as rvalue reference modifier it attaches to the type, and when used as logical AND it has spaces on both sides). In other words, the C++ style is Base const& (or const Base& if you prefer west-const).
explicit( false ) Alias( Alias const & inOther ): mValue( inOther.mValue ) {};
This is completely unnecessary. It’s basically just a bog-standard copy constructor, although writing it out like this will disable a number of optimizations. If you don’t need to explicitly specify a standard operation, don’t.
~Alias() = default; | {
"domain": "codereview.stackexchange",
"id": 45190,
"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++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
This is only necessary because you have spelled out the copy constructor and copy assignment operator. Both are unnecessary (and unwise), and if removed, this line also becomes superfluous.
explicit( false ) operator Base() { return mValue; }
I know that implicit “down-casting” is one of your design goals, but I’m not sure I’m keen on having a value that I have carefully wrapped up in a secure and safe alias suddenly and silently unwrapped.
Let’s look at your own example code to illustrate what I mean:
using Rows = Alias<std::size_t, 'rows'>;
using Cols = Alias<std::size_t, 'cols'>;
auto row = Rows{5};
auto col = Cols{7};
auto area = row * col;
So what happens if I typo:
auto area = row * row;
Suddenly all that strong aliasing is no longer worth a damn. I might as well be using naked ints.
On the other hand, if implicit unwrapping wasn’t allowed, I could write:
using Area = Alias<std::size_t, 'area'>;
constexpr auto operator*(Rows const& r, Cols const& c)
{
return Area{r.value * c.value};
}
constexpr auto operator*(Cols const& c, Rows const& r)
{
return r * c;
}
And now the original code would work (and give a strong type as result!), but the typo would not compile.
I also get more control, because I can choose to copy (x = y.value;) or move (x = std::move(y.value);) as I please.
Having to write .value or .get() or whatever might seem like a burden, but given the potential for silent errors and bugs with implicit unwrapping, it’s not that big a deal. And with well-written aliases that are given all the proper conversions, in my experience you only need to unwrap when you are passing values to other libraries. The rest of the time, you just use the types directly, and everything works fine, with the type system keeping you safe.
Alias & operator=( Alias const & inOther ){ mValue = inOther.mValue; return *this; }
Explicitly writing the copy assignment operator is unnecessary, and unwise.
Base mValue; | {
"domain": "codereview.stackexchange",
"id": 45190,
"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++, template-meta-programming",
"url": null
} |
c++, template-meta-programming
Explicitly writing the copy assignment operator is unnecessary, and unwise.
Base mValue;
Making the wrapped value publicly available isn’t a terrible idea, if there are no other constraints or invariants. But in that case, you might as well give it a better name.
However, you might also consider playing it safe, and making the wrapped value private. You can provide a full set of accessors, similar to std::optional’s .value() functions.
Personally, I’d just call it value and make it public.
That’s it! Hope it helps! | {
"domain": "codereview.stackexchange",
"id": 45190,
"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++, template-meta-programming",
"url": null
} |
python, performance, array, functional-programming
Title: Merging sorted integer arrays (without duplicates)
Question: I have written a Python function called merge_arrays which takes two lists and returns the new list merge without duplicate.
The function works as expected, but my code very complicated, and I'm looking for ways to optimize it.
Below is my current implementation:
def update_if_new(d, results, element):
if element not in d:
results.append(element)
d[element] = True
def merge_arrays(first, second):
seen = dict()
results = []
i, j, m, n = 0, 0, len(first), len(second)
while i < m and j < n:
x, y = first[i], second[j]
if x < y:
update_if_new(seen, results, x)
i += 1
else:
update_if_new(seen, results, y)
j += 1
for residual in first[i:] + second[j:]:
update_if_new(seen, results, residual)
return results
print(merge_arrays([1,2,3],[5,7,1]))
#[1, 2, 3, 5, 7]
I'm seeking suggestions for improvements in the code to make it more efficient and reduce the execution time.
Any tips or alternative solutions would be greatly appreciated.
Answer: This is a two-way merge.
preconditions
merge_arrays([1, 2, 3],
[5, 7, 1])
I was a little surprised to see that non-monotonic 1 tacked on at the end.
Recommend that you insist the caller presents only sorted( ... ) arrays,
or that you call timsort yourself, perhaps before calling a private helper.
unique
Itertools
is happy to help you discard repeated entries from sorted input.
It costs O(N) linear time and no additional storage.
Or perhaps you'd rather spend O(N) storage to construct e.g. set(first),
at similar cost to the seen dict you've been maintaining.
Consider writing a two-way merge generator
which will yield monotonic array entries.
use builtins
The simplest solution would look like this.
def merge_arrays(first: list[int], second: list[int]) -> list[int]:
return sorted(set(first + second)) | {
"domain": "codereview.stackexchange",
"id": 45191,
"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, array, functional-programming",
"url": null
} |
python, performance, array, functional-programming
Depending on details of your data and required performance,
you might want a few tweaks.
For example, initially de-dup'ing two separate sets and
then combining those smaller results,
destructively running .sort() on caller's list in-place,
that sort of thing. | {
"domain": "codereview.stackexchange",
"id": 45191,
"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, array, functional-programming",
"url": null
} |
c, interpreter, brainfuck, c99
Title: 200 line Brainfuck Interpreter
Question: I wrote a simple brainfuck interpreter in C99. Coming from a background of C++ made the task easier, but still there is some stuff I had to get used too. The program accepts a path to a brainfuck file as a command line argument, and also an optional tape size. Tape size is defaulted to 30000 bytes. It also features some program validation and error messages.
I'm looking for feedback of any kind on how a more experienced c programmer would improve my code. Thank you!
I have been compiling with gcc:
gcc main.c -o brainfuck
main.c:
// So we can use fopen on windows platforms
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include <errno.h>
#ifdef __unix__
#include <sysexits.h>
#define IO_ERR EX_IOERR
#define USAGE_ERR EX_USAGE
#define DATA_ERR EX_DATAERR
#else
#define IO_ERR EXIT_FAILURE
#define USAGE_ERR EXIT_FAILURE
#define DATA_ERR EXIT_FAILURE
#endif
#define DEFAULT_TAPE_SIZE 30000
typedef struct {
char* contents;
size_t size;
} SourceFile;
// load file from filepath into SourceFile struct
const SourceFile readSourceFile(const char* filePath) {
FILE* fp;
size_t lSize;
char *buffer;
fp = fopen (filePath , "rb");
if(!fp) {
perror(filePath);
exit(IO_ERR);
}
fseek(fp,0L,SEEK_END);
lSize = ftell(fp);
rewind(fp);
buffer = calloc(1, lSize+1);
if(!buffer) {
fclose(fp);
fputs("memory alloc fails",stderr);
exit(IO_ERR);
}
if(fread( buffer , lSize, 1 , fp) != 1) {
fclose(fp);
free(buffer);
fputs("entire read fails",stderr);
exit(IO_ERR);
}
fclose(fp);
SourceFile sourceFile = {
buffer,
lSize
};
return sourceFile;
} | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
c, interpreter, brainfuck, c99
SourceFile sourceFile = {
buffer,
lSize
};
return sourceFile;
}
// check validity of a brainfuck program
bool checkSourceFileValidity(const SourceFile* sourceFile){
/*
Keep track of how many lines we have scanned and the amount of chars in those lines
*/
size_t newlines = 0;
size_t lineCharsScanned = 0;
// Using an integer to simulate a stack popping and emplacing brackets when we find them
size_t stack = 0;
for (size_t i = 0; i < sourceFile->size; i++){
uint8_t symbol = sourceFile->contents[i];
if (symbol == '[') {
stack++;
}
else if (symbol == ']'){
// if stack is already empty, can't have a closing bracket
if (stack == 0) {
fprintf(stderr, "Line %zu: Character %zu :: Closing bracket found with no opening bracket!", newlines + 1, i - lineCharsScanned + 1);
return false;
}
stack--;
}
else if (symbol == '\n'){
newlines++;
lineCharsScanned = i;
}
}
bool valid = stack == 0;
if (!valid) {
fprintf(stderr, "Found %zu opening brackets without closing brackets!", stack);
}
return valid;
}
int main(int argc, char *argv[]) {
// Get source file from command line args
if (argc < 2) {
puts("Error! Expected path to source file as command line argument.");
return USAGE_ERR;
} | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
c, interpreter, brainfuck, c99
/*
if we have 3 arguments, 3rd argument will be the tape size in bytes
we will try and parse it as a size_t
*/
size_t tapeSize;
if (argc == 3) {
char* str = argv[2];
char* end;
tapeSize = (size_t)strtoumax(str, &end, 10);
if (errno == ERANGE || tapeSize == 0) {
fprintf(stderr, "Tape size out of range. Tape size must be greater than 0 and less than or equal to %zu", SIZE_MAX);
return USAGE_ERR;
}
} else {
tapeSize = DEFAULT_TAPE_SIZE;
}
const char* pathToSource = argv[1];
// Initial tape of memory and zero it all
uint8_t* tape = (uint8_t*)malloc(tapeSize * sizeof(uint8_t));
memset(tape, 0, tapeSize * sizeof(uint8_t));
// Index of current memory cell
size_t tapePosition = 0;
// Keeps track of nested braces
size_t braceCount = 0;
// Load source file into a char array
SourceFile sourceFile = readSourceFile(pathToSource);
// Check the source file is valid brainfuck code
if (!checkSourceFileValidity(&sourceFile)) {
return DATA_ERR;
} | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
c, interpreter, brainfuck, c99
// iterate over source file symbols, performing different operations for each
size_t i = 0;
while(i < sourceFile.size) {
uint8_t symbol = sourceFile.contents[i];
switch (symbol) {
case '>': {
tapePosition++;
break;
}
case '<': {
tapePosition--;
break;
}
case '+': {
tape[tapePosition]++;
break;
}
case '-': {
tape[tapePosition]--;
break;
}
case ',': {
tape[tapePosition] = getchar();
break;
}
case '.': {
putchar(tape[tapePosition]);
break;
}
case '[': {
if (tape[tapePosition] == 0) {
++braceCount;
while (sourceFile.contents[i] != ']' || braceCount != 0) {
++i;
if (sourceFile.contents[i] == '[') {
++braceCount;
}
else if (sourceFile.contents[i] == ']') {
--braceCount;
}
}
}
break;
}
case ']': {
if (tape[tapePosition] != 0) {
++braceCount;
while (sourceFile.contents[i] != '[' || braceCount != 0) {
--i;
if (sourceFile.contents[i] == ']') {
++braceCount;
}
else if (sourceFile.contents[i] == '[') {
--braceCount;
}
}
}
break;
}
}
++i;
} | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
c, interpreter, brainfuck, c99
// Free resources used
free(sourceFile.contents);
free(tape);
return EXIT_SUCCESS;
}
Answer: Enable more compiler warnings:
gcc -std=c99 -fPIC -gdwarf-4 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes -fanalyzer brainfuck.c -o brainfuck
brainfuck.c:31:1: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
31 | const SourceFile readSourceFile(const char* filePath) {
| ^~~~~
brainfuck.c: In function ‘readSourceFile’:
brainfuck.c:44:13: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘long int’ may change the sign of the result [-Wsign-conversion]
44 | lSize = ftell(fp);
| ^~~~~
brainfuck.c: In function ‘checkSourceFileValidity’:
brainfuck.c:81:26: warning: conversion to ‘uint8_t’ {aka ‘unsigned char’} from ‘char’ may change the sign of the result [-Wsign-conversion]
81 | uint8_t symbol = sourceFile->contents[i];
| ^~~~~~~~~~
brainfuck.c: In function ‘main’:
brainfuck.c:153:26: warning: conversion to ‘uint8_t’ {aka ‘unsigned char’} from ‘char’ may change the sign of the result [-Wsign-conversion]
153 | uint8_t symbol = sourceFile.contents[i];
| ^~~~~~~~~~
brainfuck.c:172:38: warning: conversion from ‘int’ to ‘uint8_t’ {aka ‘unsigned char’} may change value [-Wconversion]
172 | tape[tapePosition] = getchar();
| ^~~~~~~
brainfuck.c:134:5: warning: use of possibly-NULL ‘tape’ where non-null expected [CWE-690] [-Wanalyzer-possible-null-argument]
134 | memset(tape, 0, tapeSize * sizeof(uint8_t));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
‘main’: events 1-4
|
| 108 | if (argc < 2) {
| | ^
| | |
| | (1) following ‘false’ branch (when ‘argc > 1’)...
|...... | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
c, interpreter, brainfuck, c99
| | (1) following ‘false’ branch (when ‘argc > 1’)...
|......
| 118 | if (argc == 3) {
| | ~
| | |
| | (2) ...to here
|......
| 133 | uint8_t* tape = (uint8_t*)malloc(tapeSize * sizeof(uint8_t));
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (3) this call could return NULL
| 134 | memset(tape, 0, tapeSize * sizeof(uint8_t));
| | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
| | |
| | (4) argument 1 (‘tape’) from (3) could be NULL where non-null expected
|
In file included from brainfuck.c:7:
/usr/include/string.h:61:14: note: argument 1 of ‘memset’ must be non-null
61 | extern void *memset (void *__s, int __c, size_t __n) __THROW __nonnull ((1));
| ^~~~~~
These are all avoidable.
Undefined behavior:
From the C Standard: (footnote 234 on p. 267 of the linked Standard)
Setting the file position indicator to end-of-file, as with fseek(file,
0, SEEK_END),has undefined behavior for a binary stream (because of
possible trailing null characters) or for anystream with
state-dependent encoding that does not assuredly end in the initial
shift state.
The call to fseek() in readSourceFile() invokes undefined behavior.
Bugs:
$ ./brainfuck in.bf 490cakac
The interpreter doesn't detect trailing junk.
$ ./brainfuck in.bf acksnca
Tape size out of range. Tape size must be greater than 0 and less than or equal to 18446744073709551615
The error message claims that third argument can be equal to 18446744073709551615, but it is rejected as invalid input:
./brainfuck in.txt 18446744073709551615
Tape size out of range. Tape size must be greater than 0 and less than or equal to 18446744073709551615 | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
c, interpreter, brainfuck, c99
And when it is one less than 18446744073709551615, a segmentation fault occurs. (Because the result of malloc() goes unchecked)
/brainfuck in.txt 18446744073709551614
Segmentation fault (core dumped)
If the converted value falls out of range of corresponding return
type, a range error occurs (setting errno to ERANGE) and INTMAX_MAX,
INTMAX_MIN, UINTMAX_MAX or 0 is returned, as appropriate.
We are not handling the return value of strtoumax()
correctly. Consider:
#if 0
/*
if we have 3 arguments, 3rd argument will be the tape size in bytes
we will try and parse it as a size_t
*/
size_t tapeSize;
if (argc == 3) {
char* str = argv[2];
char* end;
tapeSize = (size_t)strtoumax(str, &end, 10);
if (errno == ERANGE || tapeSize == 0) {
fprintf(stderr, "Tape size out of range. Tape size must be greater than 0 and less than or equal to %zu", SIZE_MAX);
return USAGE_ERR;
}
} else {
tapeSize = DEFAULT_TAPE_SIZE;
}
#else
uintmax_t tapeSize;
if (argc == 3) {
errno = 0; /* strto* functions don't set it to 0 for us. */
const char *const str = argv[2];
char* end;
tapeSize = strtoumax(str, &end, 10);
if (end == str || *end != '\0' ||
(errno == ERANGE && (tapeSize == 0 || tapeSize == UINTMAX_MAX))) {
fprintf(stderr, "Tape size out of range. Tape size must be greater than 0 and less than or equal to %zu", SIZE_MAX);
return USAGE_ERR;
}
} else {
tapeSize = DEFAULT_TAPE_SIZE;
}
#endif
In the switch statement, there are no checks for overflow. What happens when the size of the file exceeds tapeSize? For instance, if I try to input a file containing 31000 bytes of < followed by 500 bytes of +, all I get is a segmentation fault:
$ printf "%0.s<" {1..31000} > in.bf
$ printf "%0.s+" {1..500} >> in.bf
$ ./bf in.bf
Segmentation fault (core dumped) | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
c, interpreter, brainfuck, c99
Segmentation fault (core dumped)
Declare variables where they are needed:
Starting from C99, variables do not have to be declared at the beginning of a function (or block); instead, you can declare them at the point where they are needed within the function's body.
fopen() is not required to set errno:
The error-handling is inconsistent. At times, we are using perror(), and at times we're calling fputs() with an error message. Consider:
#if 0
fp = fopen (filePath , "rb");
if(!fp) {
perror(filePath);
exit(IO_ERR);
}
#else
errno = 0;
fp = fopen(filePath, "rb");
/* The cast void is required as ISO C forbids conditional expr with only one
* void side.
*/
if (!fp) {
errno ? perror(filePath) : (void) fputs("Error - failed to open file.", stderr);
exit(IO_ERR);
}
#endif
Use a compound literal for simplification:
As we're using C99, this:
SourceFile sourceFile = {
buffer,
lSize
};
return sourceFile;
can be simplified to just:
return (SourceFile) {buffer, lSize};
Noise:
const serves no purpose with const SourceFile readSourceFile in the declaration const SourceFile readSourceFile(const char* filePath). It is ignored.
Send error messages to stderr:
if (argc < 2) {
// puts("Error! Expected path to source file as command line argument.");
fputs("Error! Expected path to source file as command line argument.\n", stderr);
return USAGE_ERR;
}
Note that fputs() doesn't automatically append a newline like puts().
Minor:
/*
if we have 3 arguments, 3rd argument will be the tape size in bytes
we will try and parse it as a size_t
*/
Does it matter if there are more than 3 arguments? Currently, the interpreter is ignoring them.
Use more const:
In main():
// char* str = argv[2];
const char *const str = argv[2]; | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
c, interpreter, brainfuck, c99
Ignoring the return of malloc() and family risks invoking undefined behavior:
// Initial tape of memory and zero it all
uint8_t* tape = (uint8_t*)malloc(tapeSize * sizeof(uint8_t));
memset(tape, 0, tapeSize * sizeof(uint8_t));
malloc() and family returns NULL to indicate failure. The returned void * need not be casted as there is an implicit conversion to and from a void * to any other pointer type in C.
/* Allocate to the referenced object, not the type.
* It is easier to maintain.
*/
uint8_t *const tape = malloc(tapesize * sizeof *tape);
if (!tape) {
complain();
..
}
As suggested in the comments, malloc() + memset() can be replaced with calloc().
The return values of fseek() and ftell() are also ignored.
getchar() returns an int, not a uint8_t:
// ??
case ',': {
tape[tapePosition] = getchar();
break;
}
Formatting:
The code seems manually formatted. Consider using an automatic formatter (perhaps GNU indent) and limiting the line length to 80.
Aside:
We are missing a \n in all the calls to fprintf() and fputs().
I'd expect the exit status to be EX_NOINPUT if the input file did not exist or was not readable.
Question:
How will the user ever learn about the optional third argument? The usage message doesn't say anything about it. | {
"domain": "codereview.stackexchange",
"id": 45192,
"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, interpreter, brainfuck, c99",
"url": null
} |
python, number-guessing-game
Title: RNG Minigame In Python - Best Practices & Possible Improvements?
Question: Recently, I got into programming with Python as a fun little side hobby. After watching a bunch of YouTube tutorials (to learn about IDE's, variables, etc.), I finally got to the point where I was able to make this really simple game where the player tries to guess the number that the computer generated. So, today I was hoping to get some feedback on the code I wrote.
I'm mostly interested in learning about the best practices for this language, but any criticism is welcome:
player.py
class Player:
def __init__(self):
"""Initializes the player object's attributes."""
self.username = "Player_1"
self.guess = None
self.wins = 0
def create_username(self):
"""Prompts the player to enter their username."""
self.username = input("What is your name?: ")
def get_username(self):
"""Returns the player's username as a string."""
return self.username
def get_guess(self):
"""Returns the player's guess as an integer."""
is_valid_input = False
while not is_valid_input:
try:
self.guess = int(input("Can you guess what it is?: "))
is_valid_input = True
return self.guess
except ValueError:
print()
print("Please enter a whole number.")
def add_win(self):
"""Adds a win to the player's win count."""
self.wins += 1
def get_wins(self):
"""Returns the player's win count as a string."""
return str(self.wins)
random_number_guesser.py
from player import Player
import random
class Random_Number_Guesser:
def __init__(self):
"""Initializes the game object's attributes."""
self.player = None
self.winning_number = None | {
"domain": "codereview.stackexchange",
"id": 45193,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
def create_player(self):
"""Creates a new player object."""
self.player = Player()
self.player.create_username()
def greet_player(self):
"""Greets the player."""
print("Welcome, " + self.player.get_username() + "!")
def generate_random_number(self):
"""Generates a winning number."""
self.winning_number = random.randint(1, 10)
print()
print("The winning number is: " + str(self.winning_number) + ".")
print("I'm thinking of a number between 1 & 10.")
def guess_and_check(self):
"""Compares the player's guess to the winning number."""
# Checks if the player's guess is correct.
if self.player.get_guess() == self.winning_number:
print()
print(self.player.get_username() + " Won!")
self.player.add_win()
else:
print()
print(self.player.get_username() + " Lost!")
def play_again(self):
"""Determines whether or not the player wants to play again."""
is_finished_playing = False
while not is_finished_playing:
play_again = input("Would you like to play again? (y/n): ")
# Checks if the player wants to play again & handles invalid inputs.
if play_again == "y":
self.generate_random_number()
self.guess_and_check()
elif play_again == "n":
print()
# Checks the player's win count and determines if 'time' or 'times' should be used.
if int(self.player.get_wins()) > 1 or int(self.player.get_wins()) == 0:
print(self.player.get_username() + " won " + self.player.get_wins() + " times!")
else:
print(self.player.get_username() + " won " + self.player.get_wins() + " time!")
break | {
"domain": "codereview.stackexchange",
"id": 45193,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
else:
print()
print("Please enter either 'y' or 'n'.")
def play_random_number_guesser():
print("Welcome To Random Number Guesser!")
print("=================================")
game = Random_Number_Guesser()
game.create_player()
game.greet_player()
game.generate_random_number()
game.guess_and_check()
game.play_again()
game.py
from random_number_guesser import *
if __name__ == "__main__":
play_random_number_guesser() | {
"domain": "codereview.stackexchange",
"id": 45193,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
if __name__ == "__main__":
play_random_number_guesser()
Answer: It's a good start.
The good
You've avoided global variables.
You've written properly-formatted docstrings.
You have multiple modules (fancy!)
You have some input validation.
You have a correctly-defined __main__ guard and top-level method.
Broadly, the code does seem to function as intended.
The bad
username mutates, when it shouldn't need to - it can be passed into the constructor and then never changed. Decreasing member mutation will create more provably-correct and more easily-testable code.
Do not store self.guess as a member.
Add type hints. In this case, since you have very few functions that accept arguments or return values, almost everything is None.
It's conventional for Python class members to be accessed directly instead of through getters, so delete get_username etc.
get_username in particular is better represented as a __str__ method so that you can write the likes of print(player) and it will do the right thing.
You need to get out of the habit of writing unnecessary loop variables such as is_valid_input. Many such variables can be replaced with a simple break when the time comes.
Since this is in theory a game, you should delete your The winning number is: debug statement.
generate_random_number only needs to be called from one place in this program - in the middle of the play_again loop.
In that play_again method, you actually need two loops - an outer loop for the game, and an inner loop for input validation.
Your plural check can be simplified by checking for equality with 1.
1 and 10 should not be hard-coded; move them to class member variables or statics.
The ugly
Don't add underscores to your class names; PEP8 asks for UpperCamelCase.
Suggested
Certainly other things to improve, but this is a start:
import random
class Player:
def __init__(self) -> None:
"""Initializes the player object's attributes."""
self.username = "Player_1"
self.wins = 0 | {
"domain": "codereview.stackexchange",
"id": 45193,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
def create_username(self) -> None:
"""Prompts the player to enter their username."""
self.username = input("What is your name?: ")
def get_guess(self) -> int:
"""Gets the player's guess as an integer."""
while True:
try:
return int(input("Can you guess what it is?: "))
except ValueError:
print("Please enter a whole number.")
def add_win(self) -> None:
"""Adds a win to the player's win count."""
self.wins += 1
def __str__(self) -> str:
return self.username
class RandomNumberGuesser:
MIN = 1
MAX = 10
def __init__(self) -> None:
"""Initializes the game object's attributes."""
self.player: Player | None = None
self.winning_number: int | None = None
def create_player(self) -> None:
"""Creates a new player object."""
self.player = Player()
self.player.create_username()
def greet_player(self) -> None:
"""Greets the player."""
print(f"Welcome, {self.player}!")
def generate_random_number(self) -> None:
"""Generates a winning number."""
self.winning_number = random.randint(self.MIN, self.MAX)
# Debug only
# print(f"The winning number is: {self.winning_number}.")
print(f"I'm thinking of a number between {self.MIN} & {self.MAX}.")
def guess_and_check(self) -> None:
"""Compares the player's guess to the winning number."""
# Checks if the player's guess is correct.
if self.player.get_guess() == self.winning_number:
print(f'{self.player} Won!')
self.player.add_win()
else:
print(f'{self.player} Lost!')
def play_loop(self) -> None:
"""Determines whether the player wants to play again."""
while True:
print()
self.generate_random_number()
self.guess_and_check() | {
"domain": "codereview.stackexchange",
"id": 45193,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
while True:
play_again = input("Would you like to play again? (y|n): ")
# Checks if the player wants to play again & handles invalid inputs.
if play_again == "y":
break
elif play_again == "n":
print()
# Checks the player's win count and determines if 'time' or 'times' should be used.
if self.player.wins == 1:
print(f'{self.player} won one time!')
else:
print(f'{self.player} won {self.player.wins} times!')
return
else:
print("Please enter either 'y' or 'n'.")
def play_random_number_guesser() -> None:
print("Welcome To Random Number Guesser!")
print("=================================")
game = RandomNumberGuesser()
game.create_player()
game.greet_player()
game.play_loop()
if __name__ == "__main__":
play_random_number_guesser()
Welcome To Random Number Guesser!
=================================
What is your name?: me
Welcome, me!
I'm thinking of a number between 1 & 10.
Can you guess what it is?: 2
me Lost!
Would you like to play again? (y|n): y
I'm thinking of a number between 1 & 10.
Can you guess what it is?: 3
me Lost!
Would you like to play again? (y|n): n
me won 0 times! | {
"domain": "codereview.stackexchange",
"id": 45193,
"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, number-guessing-game",
"url": null
} |
c++, beginner, linked-list
Title: Printing the elements of a forward linked list
Question: I'm a sophomore in computer science who's working on a linked list class for his DSA class. I believe this code can be improved, but I'm not sure how because everything got really messy really fast. Thanks.
List.hpp:
// This is a blueprint for all list-like data structures.
// It won't specify how the operations are carried out.
#ifndef LIST_HPP
#define LIST_HPP
#include <cassert>
#include <initializer_list>
template <typename T>
class List
{
public:
List()
{}
virtual ~List()
{}
List(const List&)
{}
virtual void insert(int pos, const T& item) = 0;
virtual void append(const T& item) = 0;
virtual T remove(const int pos) = 0;
virtual int size() const = 0;
virtual T& operator[](const int pos) = 0;
// The const overload is called only when used on const object.
virtual const T& operator[](const int pos) const = 0;
};
#endif // LIST_HPP
LinkedList.hpp:
#ifndef LINKEDLIST_HPP
#define LINKEDLIST_HPP
#include "List.hpp"
#include "Node.hpp"
#include <iostream>
template <typename T>
class LinkedList: public List<T>
{
private:
Node<T>* m_head{nullptr};
Node<T>* m_tail{nullptr};
int m_size{};
public:
LinkedList() = default;
LinkedList(std::initializer_list<T> i_list)
{
for (const auto& item : i_list)
{
append(item);
}
}
~LinkedList()
{
// Start from the beginning.
Node<T>* temp = m_head;
// Traverse the list while deleting previous elements.
while (temp != nullptr)
{
temp = temp->next; // Move forward.
delete m_head; // Delete the previous element.
m_head = temp; // m_head moved one forward.
}
}
auto head() const
{
return m_head;
}
auto tail() const
{
return m_tail;
}
bool empty() const
{
return m_size == 0;
} | {
"domain": "codereview.stackexchange",
"id": 45194,
"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++, beginner, linked-list",
"url": null
} |
c++, beginner, linked-list
bool empty() const
{
return m_size == 0;
}
int size() const
{
return m_size;
}
void prepend(const T& item)
{
// Create a node holding our item and pointing to the head.
auto new_item = new Node<T>{item, m_head};
// If the head is the last element
// (meaning it is the only element),
// it'll be the tail.
if (m_head == nullptr)
{
m_tail = m_head;
}
m_head = new_item;
m_size++;
}
void append(const T& item)
{
// Create a node with no pointer.
auto new_item = new Node<T>{item};
if (m_tail == nullptr)
{
// If the list is empty, set the new item as the head as well.
m_head = new_item;
m_tail = new_item;
}
else
{
// Otherwise, update the current tail's next pointer to the new item and move the tail.
m_tail->next = new_item;
m_tail = new_item;
}
m_size++;
}
void insert(const int pos, const T& item)
{
// If the position is the beginning of the list, prepend the new node.
if (pos == 0)
{
prepend(item);
}
// If the position is beyond the end of the list, append the new node.
else if (pos >= m_size)
{
append(item);
}
else
{
// Create a new node.
auto new_item = new Node<T>{item};
// Starting from the head, go to the one previous position.
auto temp = m_head;
int i{};
for (; i < pos - 1; ++i)
{
temp = temp->next;
}
new_item = temp->next;
temp->next->next = new_item->next;
m_size++;
}
}
void remove_front()
{
Node<T>* temp = m_head; | {
"domain": "codereview.stackexchange",
"id": 45194,
"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++, beginner, linked-list",
"url": null
} |
c++, beginner, linked-list
m_size++;
}
}
void remove_front()
{
Node<T>* temp = m_head;
if (temp != nullptr)
{
return;
}
m_head = m_head->next; // Move m_head one element forward.
delete temp; // Get rid of the previous element.
--m_size;
}
void remove_back()
{
Node<T>* temp = m_head;
if (temp == nullptr)
{
return;
}
// If the list's size is 1.
if (temp == m_tail)
{
delete temp;
m_head = m_tail = nullptr;
--m_size;
return;
}
// Traverse to one past the end.
while (temp->next != m_tail)
{
temp = temp->next;
}
m_tail = temp;
temp = temp->next;
delete temp;
m_tail->next = nullptr;
--m_size;
}
T remove(const int pos)
{
Node<T>* temp = m_head;
int i{};
for (; i < pos - 1; ++i)
{
temp = temp->next;
}
auto to_removed = temp->next;
temp->next = temp->next->next;
T removed_data = to_removed->data; // Retrieve the data before deleting the node.
delete to_removed;
return removed_data;
}
T& operator[](const int pos)
{
Node<T>* temp = m_head;
int i{};
for (; i != pos; ++i)
{
temp = temp->next;
}
return temp->data;
}
const T& operator[](const int pos) const
{
Node<T>* temp = m_head;
int i{};
for (; i != pos; ++i)
{
temp = temp->next;
}
return temp->data;
}
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const LinkedList<T>& list)
{
for (auto begin = list.head(); begin != nullptr; begin = begin->next)
{
os << begin->data << ' ';
}
return os;
}
#endif // LINKEDLIST_HPP | {
"domain": "codereview.stackexchange",
"id": 45194,
"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++, beginner, linked-list",
"url": null
} |
c++, beginner, linked-list
#endif // LINKEDLIST_HPP
main.cpp:
#include "LinkedList.hpp"
#include <iostream>
int main()
{
LinkedList<int> l{1,2,4};
for (int i{}; i < 10; ++i)
{
l.append(i * i);
}
std::cout << l << "\n";
}
```
Answer: The code is not too bad, so I think you're well on your way to mastering C++. Here are a few things to consider.
Be wary of signed versus unsigned
What happens if you specify a negative number for the position? For example, l.remove(-9);? I think you'll find that nothing good will happen there. The two options you have are to check for and reject negative numbers or to declare it as unsigned to avoid the issue entirely.
Use only necessary #includes
The #include <cassert> line in list.hpp is not necessary and can be safely removed.
Consider returning std::size_t for size()
The standard containers tend to use std::size_t for the return type for size() and that is probably a good choice for your code, too.
Consider range checking
Both of your operator[] return a reference and do no range checking, so that if one asks for l[99] the code will invoke undefined behavior. This isn't necessarily a problem (the standard containers to the same thing) but you might consider documenting this fact and/or implementing an at() function that does bounds checking, as the standard containers do.
Minimize the scope of variables
In a few places, you have something like this:
int i{};
for (; i != pos; ++i)
{
temp = temp->next;
}
That's not wrong, but I think I would write it like this instead:
for (int i{0}; i != pos; ++i) {
temp = temp->next;
}
In that version, the scope of i is solely within the for loop. Another idiomatic option is this:
for ( ; pos; --pos) {
temp = temp->next;
} | {
"domain": "codereview.stackexchange",
"id": 45194,
"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++, beginner, linked-list",
"url": null
} |
c++, beginner, linked-list
Make sure your comments don't mislead
There is a comment in remove_back() that seems misleading to me.
// Traverse to one past the end.
while (temp->next != m_tail)
{
temp = temp->next;
}
In fact, it's traversing to one before the end.
Consider slightly streamlining the code
In a few places, there are extra assignments that aren't needed. For example, in remove_back we have this:
m_tail = temp;
temp = temp->next;
delete temp;
m_tail->next = nullptr;
A slightly simpler version is this:
m_tail = temp;
delete m_tail->next;
m_tail->next = nullptr;
Reconsider the use of const arguments
The arguments for operator[] and remove() take const int arguments for the pos argument, but there's really no need for restricting the caller in this way since we're passing by value anyway.
Use override or final on overridden functions
Explicitly using either final or override can help detect errors, and so you should use these where appropriate. See C.128 for details.
Fix the bug
The prepend() function contains this code:
// If the head is the last element
// (meaning it is the only element),
// it'll be the tail.
if (m_head == nullptr)
{
m_tail = m_head;
}
I think that if you think about this, you'll see that it's a bug. | {
"domain": "codereview.stackexchange",
"id": 45194,
"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++, beginner, linked-list",
"url": null
} |
c++
Title: Cumulative grade-point-average calculator in C++
Question: I wrote a simple Cumulative grade-point-average calculator in C++, and would like to ask for advices to improve the code in terms of best practices (efficiency, reliability) in the language. Here's my code:
#include <stdio.h>
#include <iostream>
#include <string>
#include <vector>
class Subject
{
public:
std::string name;
unsigned creditHour, mark;
Subject(const std::string& name, unsigned creditHour, unsigned mark)
: name(name), creditHour(creditHour), mark(mark)
{}
};
class CGPACalculator
{
public:
unsigned getGradePointWith(unsigned mark)
{
if (mark <= 100 && mark > 90) return 10;
if (mark <= 90 && mark > 80) return 9;
if (mark <= 80 && mark > 70) return 8;
if (mark <= 70 && mark > 60) return 7;
if (mark <= 60 && mark > 50) return 6;
if (mark <= 50 && mark > 40) return 5;
if (mark <= 40 && mark > 30) return 4;
return 0;
}
double calculateCGPAWith(double gradePointsSum, unsigned numOfSubjects)
{
return gradePointsSum / numOfSubjects;
}
};
class CGPAPrinter
{
public:
void printSubjectsSummary(std::vector<Subject*> subjects)
{
for(Subject* s : subjects)
{
std::cout << "Subject:\t" << s->name << "\t\t";
std::cout << "Credit Hours:\t" << s->creditHour << "\t\t";
std::cout << "Mark:\t" << s->mark << std::endl;
}
}
void printCGPA(double cgpa)
{
std::cout << "Your CGPA is: " << cgpa << std::endl;
}
};
int main()
{
std::string subjectName;
unsigned creditHour, mark, numOfSubjects;
double gradePointsSum = 0;
std::vector<Subject*> subjects;
CGPACalculator calculator;
CGPAPrinter printer; | {
"domain": "codereview.stackexchange",
"id": 45195,
"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++",
"url": null
} |
c++
// Get input from user
std::cout << "Enter number of subjects: \t";
std::cin >> numOfSubjects;
for(int i = 0; i < numOfSubjects; i++)
{
std::cout << "Enter subject name: \t";
std::cin >> subjectName;
std::cout << "Enter credit hours: \t";
std::cin >> creditHour;
std::cout << "Enter mark: \t";
std::cin >> mark;
gradePointsSum += calculator.getGradePointWith(mark);
Subject *s = new Subject(subjectName, creditHour, mark);
subjects.push_back(s);
}
printer.printSubjectsSummary(subjects);
printer.printCGPA(calculator.calculateCGPAWith(gradePointsSum, numOfSubjects));
return 0;
}
Appreciate your valuable feedbacks.
Answer: C vs C++ headers
#include <stdio.h>
This is a C header. For C++ we'd want #include <cstdio> instead (which puts the contents in the std:: namespace). Though it looks like we're not using anything from this header anyway.
Aggregate initialization
class Subject
{
public:
std::string name;
unsigned creditHour, mark;
Subject(const std::string &name, unsigned creditHour, unsigned mark)
: name(name), creditHour(creditHour), mark(mark)
{
}
};
In modern C++ we don't need to add a constructor just to initialize member variables like this. We can write this as a simple struct, and use aggregate initialization:
struct Subject
{
std::string name;
unsigned creditHour, mark;
};
...
Subject *s = new Subject{ subjectName, creditHour, mark };
Classes vs free functions | {
"domain": "codereview.stackexchange",
"id": 45195,
"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++",
"url": null
} |
c++
...
Subject *s = new Subject{ subjectName, creditHour, mark };
Classes vs free functions
class CGPACalculator
{
public:
unsigned getGradePointWith(unsigned mark)
{
if (mark <= 100 && mark > 90)
return 10;
if (mark <= 90 && mark > 80)
return 9;
if (mark <= 80 && mark > 70)
return 8;
if (mark <= 70 && mark > 60)
return 7;
if (mark <= 60 && mark > 50)
return 6;
if (mark <= 50 && mark > 40)
return 5;
if (mark <= 40 && mark > 30)
return 4;
return 0;
}
double calculateCGPAWith(double gradePointsSum, unsigned numOfSubjects)
{
return gradePointsSum / numOfSubjects;
}
};
This class has no state (i.e. contains no member variables), so it should not be a class. This also applies to the CGPAPrinter class. We can use a namespace to group related functions instead of a class:
namespace GPA
{
struct Subject
{
std::string name;
unsigned creditHour, mark;
};
unsigned getGradePointWith(unsigned mark) { ... }
double calculateCGPAWith(double gradePointsSum, unsigned numOfSubjects) { ... }
void printSubjectsSummary(std::vector<Subject *> subjects) { ... }
void printCGPA(double cgpa) { ... }
} // GPA
Now we don't need to create any unnecessary objects. We can just call the functions we need.
Variable declaration
int main()
{
std::string subjectName;
unsigned creditHour, mark, numOfSubjects;
double gradePointsSum = 0;
std::vector<Subject *> subjects; | {
"domain": "codereview.stackexchange",
"id": 45195,
"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++",
"url": null
} |
c++
Declaring all variables at the top of a scope is an obsolete and unnecessary habit from ancient C. We should instead declare variables where they are first needed, initialize them to useful values, and avoid reusing them where practical. Something like:
int main()
{
std::cout << "Enter number of subjects: \t";
unsigned numOfSubjects;
std::cin >> numOfSubjects;
std::vector<Subject *> subjects;
double gradePointsSum = 0.0;
for (unsigned i = 0; i < numOfSubjects; i++)
{
std::cout << "Enter subject name: \t";
std::string subjectName;
std::cin >> subjectName;
std::cout << "Enter credit hours: \t";
unsigned creditHour;
std::cin >> creditHour;
std::cout << "Enter mark: \t";
unsigned mark;
std::cin >> mark;
gradePointsSum += GPA::getGradePointWith(mark);
Subject *s = new Subject{ subjectName, creditHour, mark };
subjects.push_back(s);
}
GPA::printSubjectsSummary(subjects);
GPA::printCGPA(GPA::calculateCGPAWith(gradePointsSum, numOfSubjects));
return 0;
}
Memory management
std::vector<Subject *> subjects;
...
Subject *s = new Subject{ subjectName, creditHour, mark };
If we use new to allocate memory we must ensure we clean it up again by calling delete (to avoid leaking memory). We should generally avoid manual memory management and use a smart pointer (e.g. std::unique_ptr) instead.
However, in this case it's unnecessary. We can simply store the subjects by value:
std::vector<Subject> subjects;
...
subjects.emplace_back(subjectName, creditHour, mark);
User input
std::cout << "Enter number of subjects: \t";
unsigned numOfSubjects;
std::cin >> numOfSubjects;
We should add some error checking to ensure that the user actually entered a number, and that we successfully read it.
Aside
Contrary to the other answer, I actually don't mind the series of if statements in: | {
"domain": "codereview.stackexchange",
"id": 45195,
"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++",
"url": null
} |
c++
Aside
Contrary to the other answer, I actually don't mind the series of if statements in:
unsigned getGradePointWith(unsigned mark)
{
if (mark <= 100 && mark > 90) return 10;
if (mark <= 90 && mark > 80) return 9;
if (mark <= 80 && mark > 70) return 8;
if (mark <= 70 && mark > 60) return 7;
if (mark <= 60 && mark > 50) return 6;
if (mark <= 50 && mark > 40) return 5;
if (mark <= 40 && mark > 30) return 4;
return 0;
}
But, we could make it simpler by only checking one bound (since we're checking in descending order):
unsigned getGradePointWith(unsigned mark)
{
if (mark > 100) return 0; // todo: output an error!??
if (mark >= 91) return 10;
if (mark >= 81) return 9;
if (mark >= 71) return 8;
if (mark >= 61) return 7;
if (mark >= 51) return 6;
if (mark >= 41) return 5;
if (mark >= 31) return 4;
return 0;
}
It's much easier to glance at this and understand the grade boundaries than it is to understand the nuances of a math equation. | {
"domain": "codereview.stackexchange",
"id": 45195,
"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++",
"url": null
} |
c, datetime, converting, winapi, visual-foxpro
Title: Convert FoxPro/dBase DATETIME field to Win32 SYSTEMTIME struct
Question: I'm trying to write a complete driver for Visual FoxPro's DBF format for Win32. I found that the way that fields of the DATETIME type are stored in dBase files is a bit strange: it's an 8 byte string where the first four bytes represent the date as the number of days since January 1, 4713 BC, and the last four bytes represent the time as:
(Hours * 3600000) + (Minutes * 60000) + (Seconds * 1000)
The DATE type is much simpler as it represents a YYYYMMDD date as an ASCII string.
Here is my function for converting this date format into a SYSTEMTIME struct:
#include <Windows.h>
#include <sal.h>
_Success_(return == TRUE)
_Ret_range_(FALSE, TRUE)
_Check_return_
BOOL WINAPI FoxProDateTimeToSystemTime(
_In_reads_(cbFxpTime) BYTE *bFoxProDateTime,
_In_ SIZE_T cbFxpTime,
_Out_writes_(1) LPSYSTEMTIME lpSystemTime
)
{
LONG lDate, lTime;
CONST DOUBLE dConvert = 2440587.5;
DOUBLE dTemp;
LONGLONG uxTime;
LONGLONG llTime;
FILETIME ft;
if (NULL == bFoxProDateTime || NULL == lpSystemTime)
{
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
ZeroMemory(lpSystemTime, sizeof(SYSTEMTIME));
if (cbFxpTime < 8)
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return FALSE;
}
CopyMemory(&lDate, bFoxProDateTime, 4);
CopyMemory(&lTime, bFoxProDateTime + 4, 4);
dTemp = (lDate - dConvert) * 86400;
uxTime = (LONGLONG)dTemp;
llTime = Int32x32To64(uxTime, 10000000) + 116444736000000000;
ft.dwLowDateTime = (DWORD)llTime;
ft.dwHighDateTime = llTime >> 32;
FileTimeToSystemTime(&ft, lpSystemTime);
lpSystemTime->wHour = (WORD) (lTime / 3600000);
lpSystemTime->wMinute = (WORD) ((lTime % 3600000) / 60000);
lpSystemTime->wSecond = (WORD) (((lTime % 3600000) % 60000) / 1000);
SetLastError(ERROR_SUCCESS);
return TRUE;
} | {
"domain": "codereview.stackexchange",
"id": 45196,
"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, datetime, converting, winapi, visual-foxpro",
"url": null
} |
c, datetime, converting, winapi, visual-foxpro
SetLastError(ERROR_SUCCESS);
return TRUE;
}
The way the algorithm works right now is a bit clunky since it basically does three conversions in a row to end up with a SYSTEMTIME - first to a UNIX timestamp, then to a FILETIME struct, and finally to a SYSTEMTIME struct. This function works; I've tested it, but I'm wondering if I can get some feedback on how to improve the efficiency of this conversion.
Answer: meaningful identifier
CONST DOUBLE dConvert = 2440587.5;
Simonyi and
Spolsky
would tell you that this is not the original Apps Hungarian Notation.
It does not help the Gentle Reader, 'nuff said on that topic,
let's ignore the redundant d prefix.
"Convert" is not super helpful.
This could be an OK identifier if accompanied by
a comment describing which epoch this denotes,
or by the URL of some cited calendar reference.
Absent such text, prefer something more descriptive
like dJulian1Jan1970, or dJd1Jan1970.
The "noon --> midnight" aspect of 0.5
still suggests that a brief comment is needed.
You might find it more convenient to bury this constant
in a brief convertJulianDayToUnixTime() helper function.
DOUBLE dTemp;
Ok, we weren't even trying to name this quantity.
The code eventually makes it clear that
it is the dUnixTime of some UTC midnight instant.
It's very short lived -- not sure why we chose to name it.
LONGLONG uxTime;
Aha! Finally, a good name, this is a "unix time".
LONGLONG llTime;
Yes, it is a time, but that doesn't make it a good name.
It appears to be an llTicks in units of 100-nanosecond ticks since 1970.
llTime = Int32x32To64(uxTime, 10000000) + 116444736000000000; | {
"domain": "codereview.stackexchange",
"id": 45196,
"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, datetime, converting, winapi, visual-foxpro",
"url": null
} |
c, datetime, converting, winapi, visual-foxpro
Ten million tick/sec isn't the easiest number to visually scan
when it's not 1e7.
Isn't there some convenient 10_000_000 notation available?
Maybe not.
Consider creating a MANIFEST_CONSTANT for this magic number.
And that other figure is just out of control.
We seem to be talking about IDK 1-Jan-1601 or something? In terms of ticks.
A software artifact containing such an expression is not maintainable
and should never be merged down to main.
Doesn't matter if it happens to compute the correct quantity.
It's not obvious that it does,
and it does not invite us to trace details from source code
back to a requirements document or a standards document.
Choosing essentially the same name twice, lTime and llTime,
does not help the Gentle Reader to understand Author's Intent.
type punning
CopyMemory(&lDate, bFoxProDateTime, 4);
CopyMemory(&lTime, bFoxProDateTime + 4, 4);
The OP introductory prose was very clear and helpful,
outlining that we have a Julian Day followed
by UTC milliseconds since midnight.
Which suggests a two-element struct.
Consider using a struct pointer to bFoxProDateTime
to accomplish what these two lines are doing.
word width
llTime = Int32x32To64(uxTime, 10000000) + 116444736000000000;
ft.dwLowDateTime = (DWORD)llTime;
Even when running on a 64-bit host, this
appears
to be a uint32 we just cast the sum to.
Notice that there have been significantly more
than four billion ticks since 1601.
I imagine this line does the right thing,
but it's not obvious that it does.
Consider adopting types like uint64.
OIC, you meant this:
LONGLONG mask32 = 0xFfffFfff;
ft.dwLowDateTime = (DWORD)(llTime & mask); | {
"domain": "codereview.stackexchange",
"id": 45196,
"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, datetime, converting, winapi, visual-foxpro",
"url": null
} |
c, datetime, converting, winapi, visual-foxpro
Consider adding an explicit mask.
Not for the machine.
For the reader.
Generated machine code won't change at all.
Though I wouldn't be surprised if original line was
UB.
It's unclear why pointer type-punning or a memcpy()
couldn't accomplish this in a single line,
but maybe the two fields are in incoveniently
backward order or something.
define conversion factors
lpSystemTime->wMinute = (WORD) ((lTime % 3600000) / 60000);
Again, this is more tedious to read than 3600_000,
so give it a name like HOUR_TO_MILLISECOND.
We compute these in H,M,S order, but starting with seconds
might have been more convenient.
Because then we can subtract out a nicely named seconds or minutes
that we just computed.
Generated machine code likely wouldn't change, though readability would.
test suite
OP includes no unit tests.
This code does timestamp conversion for DBF v1 input files.
Suppose another version comes out and a maintainer needs to refactor
this code to also parse v2 input files.
How would we know if we broke anything in the process?
Adding automated unit tests would be an essential first step
for such a maintenance activity.
This code appears to achieve its design goals.
I would not be willing to delegate or accept maintenance tasks on it
in its current form. | {
"domain": "codereview.stackexchange",
"id": 45196,
"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, datetime, converting, winapi, visual-foxpro",
"url": null
} |
matrix, common-lisp
Title: Determinant calculation of a matrix of any degree
Question: My program calculates the determinant of a matrix of any degree. If you really can't understand my comments or indentifiers please let me know.
//;;MakeShift make element number 'ind' the head of list:
(defun MakeShift (ind L buf)
(if (= ind 1) (cons (car L) (append buf (cdr L)))
(makeReplace (- ind 1) (cdr L) (append buf (list (car L))))
)
)
//;;Shift call MakeShift:
(defun Shift (ind L) (MakeShift ind L nil))
//;;makeTransp make transposition of two elements list:
(defun makeTransp (L) (cons (cadr L) (cons (car L) nil)))
//;;PushForEach put element elem into a heads of all lists of L:
(defun PushForEach (elem L)
(if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))
)
)
//;;MakeTranspositions create a list of all transpositions
//;;using first transposition like '(1 2 3 ...).
//;;transpNum is transpositions number and numOfElem
//;;is amount of elements in transposition:
(defun MakeTranspositions (transp transpNum numOfElem)
(cond ((> transpNum numOfElem) nil)
((= numOfElem 2) (cons transp (cons (makeTransp transp) nil)))
(T (append (PushForEach (car transp) (MakeTranspositions (cdr transp) 1 (- numOfElem 1)))
(MakeTranspositions (Shift (+ transpNum 1) transp) (+ transpNum 1) numOfElem)))
)
)
//;;MakeFirstTransp make a first transpositiion like '(1 2 3 ... )
//;;which has number of element equal matrix degree:
(defun MakeFirstTransp (matrixDegree transp)
(if (= matrixDegree 0) transp
(MakeFirstTransp (- matrixDegree 1) (cons matrixDegree transp))
)
)
//;;Transpositions make all transpositions of matrix using MakeTranspositions:
(defun Transpositions (matrixDegree)
(MakeTranspositions (MakeFirstTransp matrixDegree nil) 1 matrixDegree)
) | {
"domain": "codereview.stackexchange",
"id": 45197,
"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": "matrix, common-lisp",
"url": null
} |
matrix, common-lisp
//;;GetCol return elemnt number col in row (row belong to matrix):
(defun GetCol (col rowVector)
(if (= col 1) (car rowVector)
(GetCol (- col 1) (cdr rowVector))
)
)
//;;GetElem return element a[row][col] which belong to matrix:
(defun GetElem (row col matrix)
(if (= row 1) (GetCol col (car matrix))
(GetElem (- row 1) col (cdr matrix))
)
)
//;;CheckFirst check first element in transposition (cons first transp) for even:
(defun CheckFirst (first transp)
(cond ((null transp) 1)
((< first (car transp)) (CheckFirst first (cdr transp)))
(T (* -1 (CheckFirst first (cdr transp))))
)
)
//;;Sign return sign of transposition (1 or -1):
(defun Sign (transp)
(if (null (cdr transp)) 1
(* (CheckFirst (car transp) (cdr transp)) (Sign (cdr transp)))
)
)
//;;Product return product of elements of matrix by transposition transp:
(defun Product (matrix transp) (GetProduct matrix 1 transp))
//;;GetProduct are called by Product:
(defun GetProduct (matrix ind transp)
(if (null transp) 1
(* (GetElem ind (car transp) matrix)
(GetProduct matrix (+ ind 1) (cdr transp))
)
)
)
//;;GetSumm return summ of all products by transpositions whith their signs:
(defun GetSumm (matrix transps)
(if (null transps) 0
(+ (* (Sign (car transps)) (Product matrix (car transps)))
(GetSumm matrix (cdr transps))
)
)
)
//;;Determinant call GetSumm:
(defun Determinant (matrix matrixDegree)
(GetSumm matrix (Transpositions matrixDegree))
)
//;;So, programm work fast.
Answer: The first thing is to learn proper indentation.
//;;PushForEach put element elem into a heads of all lists of L:
(defun PushForEach (elem L)
(if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))
)
)
What's wrong with the code layout? | {
"domain": "codereview.stackexchange",
"id": 45197,
"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": "matrix, common-lisp",
"url": null
} |
matrix, common-lisp
What's wrong with the code layout?
Common Lisp has built-in documentation features. A documentation string can be placed inside the function and can be retrieved with the DOCUMENTATIONfunction.
trailing parentheses are a big DON'T DO THAT. It just wastes space without adding much information. Your editor will count parentheses or will show the corresponding parentheses.
put constructs, when they are too long on a line, over several lines.
don't use CamelCase, use hyphens
Let's do the editing step by step:
(defun PushForEach (elem L)
"put element elem into a heads of all lists of L"
(if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))
)
)
(defun PushForEach (elem L)
"put element elem into a heads of all lists of L"
(if (null L) nil (cons (cons elem (car L)) (PushForEach elem (cdr L)))))
Now we get the version which is best readable:
(defun push-for-each (elem L)
"put element elem into a heads of all lists of L"
(if (null L)
nil
(cons (cons elem (car L))
(push-for-each elem (cdr L)))))
Above function has a documentation string and useful code layout.
Next: can we write it better? You can bet that basic recursion in Lisp has been provided as a higher-order function. Applying a function over all items in a list is called mapping. The basic mapping function is MAPCAR.
(defun push-for-each (element list)
"adds element as head of all sublists of list"
(mapcar #'(lambda (item)
(cons element item))
list)) | {
"domain": "codereview.stackexchange",
"id": 45197,
"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": "matrix, common-lisp",
"url": null
} |
javascript, html
Title: Simple JS Password System
Question: I created a simple password system using HTML, CSS, and JS to quiz myself on my variable, localstorage, and if and else statement knowledge. I don't know how to make the create/login password input fields required though. Any other improvement suggestions/feedback would be appreciated!
<!DOCTYPE html>
<html>
<head>
<style>
#loginPassword {
display: none;
}
</style>
</head>
<body>
<form id="createPassword">
<input type="password" id="createdPassword" required>
<button type="password" onclick="storepassword()">Submit</button>
</form>
<form id="loginPassword">
<input type="password" id="loggedinPassword" required>
<button type="submit" onclick="checkpassword()">Login</button>
</form>
<div id="content" style="display:none">
<h1>this is super secret content</h1>
</div>
<script>
//convenient variable
var createdPassword = document.getElementById('createdPassword').value;
function storepassword() {
//creates password
event.preventDefault();
//variables for convenience
var createdPassword = document.getElementById('createdPassword').value;
localStorage.setItem('createdPasswordstorage', createdPassword);
document.getElementById('loginPassword').style.display = "block";
document.getElementById('createPassword').style.display = "none";
} | {
"domain": "codereview.stackexchange",
"id": 45198,
"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, html",
"url": null
} |
javascript, html
function checkpassword() {
//convenient variables
let storedPassword = localStorage.getItem('createdPasswordstorage');
let loginPassword = document.getElementById('loggedinPassword').value;
let content = document.getElementById('content');
event.preventDefault();
//checks if password is correct
if (loginPassword == storedPassword) {
alert('Logged in');
content.style.display = "block";
//add functions for displaying content, etc. here:
} else {
alert('Incorrect Password');
}
}
function loadforms() {
//checks if password exists in storage
let storedPassword = localStorage.getItem('createdPasswordstorage');
//if it doesn't exist, create password form displayed
if (storedPassword === null) {
document.getElementById('loginPassword').style.display = "none";
document.getElementById('createPassword').style.display = "block";
} else {
//if it exists, login for displayed
document.getElementById('loginPassword').style.display = "block";
document.getElementById('createPassword').style.display = "none";
}
}
loadforms();
</script>
</body>
</html>
Answer: lint
With no indent, your code starts to become illegible. Find a
pretty-printer
and use it.
The machine doesn't care.
But people do.
security
// checks if password is correct
if (loginPassword == storedPassword) { | {
"domain": "codereview.stackexchange",
"id": 45198,
"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, html",
"url": null
} |
javascript, html
security
// checks if password is correct
if (loginPassword == storedPassword) {
This is the essence of your stated goal to create a password system.
It is needlessly weak.
The CTF
goal of Mallory is to trick the system into reporting boolean true,
and you've reduced that to the simple goal of retrieving (or guessing)
storedPassword. Much better that you never store a password at all,
preferring to store the hash of a password.
Npm
would be happy to obtain (PHC-winner) argon2 for you.
Ask it to produce a hash,
and store that rather than the cleartext password.
Sometimes users will choose same password on another website as on your site.
Now if that website is compromised, revealed knowledge of that site's credentials
will have much less impact on your site.
Conversely if your list of hashes suffers a compromise, that has minimal impact on other websites frequented by your users. | {
"domain": "codereview.stackexchange",
"id": 45198,
"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, html",
"url": null
} |
javascript, floating-point
Title: Solving round number in JS by using String
Question: Whatever language you choose, you may encounter a rounding problem. In fact, this is due to the limit of the required number of bits needed to get the right number after a calculation.
Simple example:
In javascript (like any other language), you may want to use a function to round the result after even a simple sum (with decimals) :
Unfortunately it's not always working as we expect.
That's why I created my own function which is based on a string version.
I read every char and make the round by myself so I'm not limited by the number of bits.
round(number, decimalsLength) {
// If the number does contains a scientific notation, we use a more traditionnal calculation method
if(number.toString().includes("e"))
number = parseFloat(number.toFixed(4));
// Split the integer part and the decimal part
var number = (typeof number === "number") ? number : (number != null) ? parseFloat(number) : 0; // Return NaN for [null; {}]
var decimalsLength = decimalsLength || 0;
var array = (number+"").split(".");
var left = array[0];
var right = "1"+(array[1] || 0); // We add 1 to keep the left 0
// Round only if we have more decimal than needed
if(right.length-1 >= decimalsLength) {
// Round up
if(parseInt(right.substr(decimalsLength+1, 1)) >= 5)
right = parseInt(right.substr(0, decimalsLength+1))+1;
// If we moved to the upper integer
if(right.toString().substr(0, 1) == 2) { // If the added 1 has became a 2
var noDecimal = parseInt(right.toString().substr(1, decimalsLength)) == 0; // Return an integer if we no longer have any decimal
left = (parseInt(left) + (number > 0 ? 1 : -1)).toString();
return parseFloat(left + (noDecimal ?"":".") + (noDecimal?"":right.toString().substr(1, decimalsLength)));
}
} | {
"domain": "codereview.stackexchange",
"id": 45199,
"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, floating-point",
"url": null
} |
javascript, floating-point
// Else, we don't need to round
var noDecimal = parseInt(right.toString().substr(1, decimalsLength)) == 0;
return parseFloat(left + (noDecimal?"":".") + (noDecimal?"":right.toString().substr(1, decimalsLength)));
}
I wanted to share this with you in case it can help, but also to have a feedback and improve the function if you find it useful.
Answer: document the return value
round(number, decimalsLength) {
The name suggests something similar to
this
documented function:
Math.round()
The Math.round() static method returns the value of a number rounded to the nearest integer.
That's a crystal clear
guarantee
about the return value.
Your function offers no assurances at all about what's returned.
document the input value
var number = (typeof number === "number") ? number : (number != null) ? parseFloat(number) : 0; // Return NaN for [null; {}]
Your round() is a
total function.
Silently accepting any and all types for
what ostensibly should be a number,
and mapping a subset of them to 0,
sounds disastrous for the caller.
Much better to insist on one-or-more input types, perhaps FP and string,
and throw a fatal error if caller messed up by passing in some random object.
be direct
var right = "1"+(array[1] || 0); // We add 1 to keep the left 0
Hacks such as this do not lead to maintainable code.
Say what you mean and mean what you say.
Starting with "234.567" and then assigning right = "1567"
tells the reader that right does not mean "the digits
to the right of the decimal point".
We're left with the identifier not having a clear meaning.
Break this out as a well-named helper if there's a transform you need.
solve a general problem
if(right.length-1 >= decimalsLength) {
...
if(parseInt(right.substr(decimalsLength+1, 1)) >= 5)
right = ... [an integer expression, definitely not a string] ...
if(right.toString().substr(0, 1) == 2) {
...
return ...
}
}
...
return ... [expression which involves 'right'] ... | {
"domain": "codereview.stackexchange",
"id": 45199,
"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, floating-point",
"url": null
} |
javascript, floating-point
Wow, that's a lot of special cases.
First, extract helper, which would give you an opportunity
to name and to document that you're transforming from this to that.
Plus you could separately unit test the helpers.
Second, consider using FP arithmetic to solve this problem.
Your chief complaint seems to be that FP quantities describe
intervals on the real number line, and some are "a bit off",
a bit negative. You give the example of 10.395,
which encodes an interval that contains 10.395,
but which starts at 10.394999...99905, leading to
unfortunate truncated string results.
For restricted input ranges, which you'd need to document,
you might be able to get away with always adding epsilon = 1e-12
to the input number, and then rounding, obviating the need for many ifs.
Obtaining 100% code coverage via unit tests would pose some slight challenge,
given the current code.
scaled integer
No app-level motivating use case was offered in the original submission.
It is possible that an app which cares about rounding
details of a very large set of FPs which includes 10.395
may want a different approach.
Let's focus on the "two decimal places" case.
Consider advising app developers to work with integer number of cents,
rather than FP decimal number of dollars.
Format with two decimal places upon display.
For FP operations on a restricted range of integers,
conservatively the natural numbers less than a trillion,
FP calculations are always exact.
Fifty-three bits of significand is a lot of bits to
represent exact integer quantities. | {
"domain": "codereview.stackexchange",
"id": 45199,
"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, floating-point",
"url": null
} |
javascript, floating-point
As a consumer of this code,
I would not want to call into it,
as it is unclear what value it might return.
As a QA tester, I would not want
to be tasked with obtaining 100% code coverage.
(The OP, alas, did not include any automated testing.)
As a maintenance engineer on the team responsible for this library routine,
I would not be able to confidently add features or fix bugs, as the current
contract
is unclear.
Recommend revising this code before attempting to merge it down to main. | {
"domain": "codereview.stackexchange",
"id": 45199,
"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, floating-point",
"url": null
} |
python, comparative-review
Title: Leap Year Calculator Using If Elif and Else Only
Question: I'm taking the 100 Days of Code (Python) taught by Angela Yu on Udemy. There have been a few other questions revolving around this lesson but I can't find one who came up with my specific question so I do apologize if it's out there somewhere.
The course is asking us to check whether or not a year is a leap year using the below flow chart:
If not cleanly divisible by 4 - Not a leap year.
If is cleanly divisible by 4 but not cleanly divisible by 100 - A leap year
If is cleanly divisible by 4, and by 100, but not cleanly divisible by 400 - Not a leap year
If is cleanly divisible by 4, is cleanly divisible by 100 and if is cleanly divisible by 400 - Leap year
The code I came up with does generate the desired outputs and passes the checks required to finish the lesson. I've tested it against a good two dozen years and it's correctly identified whether or not the year was a leap year each time. I'm not getting any syntax errors either. Most of my solutions to the lessons so far have had small variations but this one feels moreso than any of the rest and it's making me question its validity.
The point of the lesson is to get acclimated with if/elif and else statements, so I'm not trying to optimize it or use any more advanced/efficient/shorter keywords. The instructor provides their own solution but does specify there are other ways to go about it.
Is mine just structured poorly? Is there a scenario where it wouldn't work? Again, limiting it to only if/elif and else keywords is very much intentional.
My code:
year = int(input())
if year % 4 != 0:
print ("Not leap year")
elif year % 100 != 0:
print ("Leap year")
elif year % 400 !=0:
print ("Not leap year")
else:
print ("Leap year")
Instructor:
year = int(input()) | {
"domain": "codereview.stackexchange",
"id": 45200,
"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, comparative-review",
"url": null
} |
python, comparative-review
Instructor:
year = int(input())
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
print("Leap year")
else:
print("Not leap year")
else:
print("Leap year")
else:
print("Not leap year")
Answer: Your code is nice. Contrasting to the instructor's solution, you have cleanly inverted the arrow anti-pattern to be as 'flat' as possible. I like your code more.
Some possibly uninteresting feedback:
Using 2 spaces for indentation is abnormal with Python. Python users typically use 4 spaces for indentation.
I can understand a JavaScript developer, amoungst some other languages, using 2 spaces for indentation. Or if you're working in a cross language project.
Putting a space between the function name print and the opening bracket ( is abnormal. I may be wrong, but I think the convention is abnormal in most programming languages.
By changing your code to a function we can easily test if your code is correct. "I've tested it against a good two dozen years" must have been a bit of a pain. We can use calendar.isleap() to test.
Personally I try to keep the left side of lines as small as possible and keep the right larger. When reading the following code the small != 0 can easily be skimmed over.
if really_long_function_name(really_long_variable_name, another_variable) != 0:
I like the consistancy of your if statements, always using !=.
import calendar
def is_leap_year(year: int) -> bool:
if 0 != year % 4:
return False
elif 0 != year % 100:
return True
elif 0 != year % 400:
return False
else:
return True
if __name__ == "__main__":
for year in range(1, 10_000):
assert is_leap_year(year) == calendar.isleap(year), f"{year} is mismatched"
print("All the results are correct!") | {
"domain": "codereview.stackexchange",
"id": 45200,
"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, comparative-review",
"url": null
} |
python, comparative-review
One thing to note is we don't actually need to use if statements. If we change to using == then we know %4 is a leep year, %100 cancels out some leap years, and %400 cancels out some cancels out. So we can instead use - to cancel the 100s and + to readd the 400s.
def is_leap_year__ray(year: int) -> bool:
return bool(
(0 == year % 4)
- (0 == year % 100)
+ (0 == year % 400)
)
if __name__ == "__main__":
for year in range(1, 10_000):
assert is_leap_year__ray(year) == calendar.isleap(year), f"{year} is mismatched"
print("All the results are correct!")
Note: Python's calendars.isleap() source actually uses and and or to perform the canceling which allows for better performance than my code. | {
"domain": "codereview.stackexchange",
"id": 45200,
"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, comparative-review",
"url": null
} |
python, performance, python-3.x
Title: Brute force password cracker in Python
Question: I made a brute force password cracker with Python, but it's extremely slow. How can I make it faster?
import itertools
import string
import time
def guess_password(real):
chars = string.ascii_uppercase + string.digits
password_length = 23
start = time.perf_counter()
for guess in itertools.product(chars, repeat=password_length):
guess = ''.join(guess)
t = list(guess)
t[5] = '-'
t[11] = '-'
t[17] = '-'
tg = ''.join(t)
if tg == real:
return 'Scan complete. Code: \'{}\'. Time elapsed: {}'.format(tg, (time.perf_counter() - start))
print(guess_password('E45E7-BYXJM-7STEY-K5H7L'))
As I said, it's extremely slow. It takes at least 9 days to find a single password.
Answer: You should exploit the structure of the password, if it has any. Here you have a 20 character password separated into four blocks of five characters each, joined with a -. So don't go on generating all combinations of length 23, only to throw most of them away.
You also str.join the guess, then convert it to a list, then replace the values and str.join it again. You could have saved yourself the first str.join entirely by directly converting to list.
You know the length of the password, so no need to hardcode it. Just get it from the real password (or, in a more realistic cracker, pass the length as a parameter).
With these small changes your code would become:
def guess_password(real):
chars = string.ascii_uppercase + string.digits
password_format = "-".join(["{}"*5] * 4)
password_length = len(real) - 3
for guess in itertools.product(chars, repeat=password_length):
guess = password_format.format(*guess)
if guess == real:
return guess | {
"domain": "codereview.stackexchange",
"id": 45201,
"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, python-3.x",
"url": null
} |
python, performance, python-3.x
Here I used some string formatting to get the right format.
Note also that the timing and output string are not in there. Instead make the former a decorator and the latter part of the calling code, which should be protected by a if __name__ == "__main__": guard to allow you to import from this script without running the brute force cracker:
from time import perf_counter
from functools import wraps
def timeit(func):
@wraps(func)
def wrapper(*args, **kwargs):
start = perf_counter()
ret = func(*args, **kwargs)
print(f"Time elapsed: {perf_counter() - start}")
return ret
return wrapper
@timeit
def guess_password(real):
...
if __name__ == "__main__":
real_password = 'E45E7-BYXJM-7STEY-K5H7L'
if guess_password(real_password):
print(f"Scan completed: {real_password}")
On my machine this takes 9.96 s ± 250 ms, whereas your code takes 12.3 s ± 2.87 s for the input string "AAAAA-AAAAA-AAAAA-FORTN".
But in the end you will always be limited by the fact that there are a lot of twenty character strings consisting of upper case letters and digits. Namely, there are \$36^{20} = 13,367,494,538,843,734,067,838,845,976,576\$ different passwords that need to be checked (well, statistically you only need to check half of them, on average, until you find your real password, but you might get unlucky). Not even writing your loop in Assembler is this going to run in less than days. | {
"domain": "codereview.stackexchange",
"id": 45201,
"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, python-3.x",
"url": null
} |
python, python-3.x, csv, pandas
Title: Concatenate several CSV files in a single dataframe
Question: I have currently 600 CSV files (and this number will grow) of 50K lines each i would like to put in one single dataframe.
I did this, it works well and it takes 3 minutes :
colNames = ['COLUMN_A', 'COLUMN_B',...,'COLUMN_Z']
folder = 'PATH_TO_FOLDER'
# Dictionnary of type for each column of the csv which is not string
dictTypes = {'COLUMN_B' : bool,'COLUMN_D' :int, ... ,'COLUMN_Y':float}
try:
# Get all the column names, if it's not in the dict of type, it's a string and we add it to the dict
dictTypes.update({col: str for col in colNames if col not in dictTypes})
except:
print('Problem with the column names.')
# Function allowing to parse the dates from string to date, we put in the read_csv method
cache = {}
def cached_date_parser(s):
if s in cache:
return cache[s]
dt = pd.to_datetime(s, format='%Y-%m-%d', errors="coerce")
cache[s] = dt
return dt
# Concatenate each df in finalData
allFiles = glob.glob(os.path.join(folder, "*.csv"))
finalData = pd.DataFrame()
finalData = pd.concat([pd.read_csv(file, index_col=False, dtype=dictTypes, parse_dates=[6,14],
date_parser=cached_date_parser) for file in allFiles ], ignore_index=True)
It takes one minute less without the parsing date thing. So i was wondering if i could improve the speed or it was a standard amount of time regarding the number of files. Thanks !
Answer: Here is my untested feedback on your code. Some remarks:
Encapsulate the functionality as a named function. I assumed folder_path as the main "variant" your calling code might want to vary, but your use case might "call" for a different first argument.
Use PEP8 recommendations for variable names.
Comb/separate the different concerns within the function:
gather input files
handle column types
read CSVs and parse dates | {
"domain": "codereview.stackexchange",
"id": 45202,
"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, csv, pandas",
"url": null
} |
python, python-3.x, csv, pandas
gather input files
handle column types
read CSVs and parse dates
Depending on how much each of those concerns grows in size over time, multiple separate functions could organically grow out of these separate paragraphs, ultimately leading to a whole utility package or class (depending on how much "instance" configuration you would need to preserve, moving the column_names and dtypes parameters to object attributes of a class XyzCsvReader's __init__ method.)
Concerning the date parsing: probably the bottleneck is not caused by caching or not, but how often you invoke the heavy machinery behind pd.to_datetime. My guess is that only calling it once in the end, but with infer_datetime_format enabled will be much faster than calling it once per row (even with your manual cache).
import glob
import os
import pandas as pd
def read_xyz_csv_folder(
folder_path,
column_names=None,
dtypes=None):
all_files = glob.glob(os.path.join(folder_path, "*.csv"))
if column_names is None:
column_names = [
'COLUMN_A',
'COLUMN_B', # ...
'COLUMN_Z']
if dtypes is None:
dtypes = {
'COLUMN_B': bool,
'COLUMN_D': int,
'COLUMN_Y': float}
dtypes.update({col: str for col in column_names
if col not in dtypes})
result = pd.concat((
pd.read_csv(file, index_col=False, dtype=dtypes)
for file in all_files),
ignore_index=True)
# untested pseudo-code, but idea: call to_datetime only once
result['date'] = pd.to_datetime(
result[[6, 14]],
infer_datetime_format=True,
errors='coerce')
return result
# use as
read_xyz_csv_folder('PATH_TO_FOLDER')
Edit: as suggested by user FMc in their comment, switch from a list comprehension to a generator expression within pd.concat to not create an unneeded list. | {
"domain": "codereview.stackexchange",
"id": 45202,
"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, csv, pandas",
"url": null
} |
javascript
Title: Listener for property value changes in a Javascript object
Question: The purpose of this code is add proxy on nested object for log changes on property. This is a debug utility!
// check if value is object or array
function isObject(value) {
return value !== null && typeof value === "object" && ["Array", "Object"].includes(value.constructor.name);
}
// add nested proxy
function buildProxy(poj, callback = console.log, tree = []) {
const getPath = (prop) => tree.concat(prop).join(".");
return new Proxy(poj, {
get(target, prop) {
const value = Reflect.get(target, prop);
if (isObject(value)) {
return buildProxy(value, callback, tree.concat(prop));
}
return value;
},
set(target, prop, value) {
callback({
action: "set",
path: getPath(prop),
newValue: value,
preValue: Reflect.get(target, prop, value),
stack: new Error().stack.split("\n")[1].trim()
});
return Reflect.set(target, prop, value);
},
deleteProperty(target, prop) {
callback({ action: "delete", path: getPath(prop), stack: new Error().stack.split("\n")[1].trim() });
return Reflect.deleteProperty(target, prop);
},
});
}
// remove nested proxy
const unbuildProxy = (value) => {
if (isObject(value)) {
if (Array.isArray(value)) {
value = [...value];
} else {
value = { ...value };
}
for (const key in value) {
value[key] = unbuildProxy(value[key]);
}
}
return value;
}
// set nested proxy on data
let data = buildProxy(
{
name: "David",
occupation: "freelancer",
children: [{ name: "oliver" }, { name: "ruby" }],
nested: { a: { b: true } }
}
); | {
"domain": "codereview.stackexchange",
"id": 45203,
"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",
"url": null
} |
javascript
// test console.log on changes
data.name = "Mike";
data.children.push({ name: "baby" });
data.children[1].name = "fred";
delete data.occupation;
data.nested.a.b = { c: true };
data.nested.a.b.c = "Mike2";
// remove nested proxy
data = unbuildProxy(data)
// structuredClone raise exception if object is proxy
console.log(structuredClone(data))
there are improvements?
Answer: Serious BUG!
Normally this would make the question "off topic", but unless you are experienced with JS this type of bug is very often overlooked or even considered in normal testing regimes.
The bug is very dangerous, that will either throw a call stack overflow or timeout the page.
You do not check created proxy objects for cyclic references.
As proxies are slow and depending on the structure of the proxy the page will often timeout before the call stack overflows.
Demo the bug
For example your testing code can be changed to
data.a.b = {c: true}; // adds new proxy
data.a.b.c = data.a; // cyclic proxy reference
data = unbuildProxy(data); // call stack overflow (or page timeout)
The call chain is not straight forward as its the unbuildProxy call that starts the infinite call chain.
See snippet below for example.
Fix
Most common solution is to use a WeakSet (only keeps the hash of objects) to track objects you create a proxy for. If the object exists in the map don't build a new proxy for it.
Another solution is to count the cycle depth and throw an error if it gets too deep. (Note at all ideal)
Example of bug
The snippet shows the bug by throwing an error when the call depth to buildProxy is > 50.
Open the console [hit F12] to see the trace when the snippet throws the error.
Note I made some minor mods (before I noticed the bug). Changes do not change codes behaviour (Apart from (fixed) unguarded for in loop in original code). | {
"domain": "codereview.stackexchange",
"id": 45203,
"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",
"url": null
} |
javascript
function isObject(value) {
return value !== null && typeof value === "object" && ["Array", "Object"].includes(value.constructor.name);
}
function buildProxy(poj, callback = console.log, tree = [], count = 0) {
if (count > 50) { throw new Error("Cycle depth too deep: " + count) }
const getPath = (prop) => tree.concat(prop).join(".");
return new Proxy(poj, {
get(target, prop) {
const value = Reflect.get(target, prop);
if (isObject(value)) { return buildProxy(value, callback, tree.concat(prop), count + 1); }
return value;
},
set(target, prop, value) {
callback({
action: "set",
path: getPath(prop),
newValue: value,
preValue: Reflect.get(target, prop, value),
stack: new Error().stack.split("\n")[1].trim()
});
return Reflect.set(target, prop, value);
},
deleteProperty(target, prop) {
callback({
action: "delete",
path: getPath(prop),
stack: new Error().stack.split("\n")[1].trim()
});
return Reflect.deleteProperty(target, prop);
},
});
}
const unbuildProxy = (value) => {
if (isObject(value)) {
value = Array.isArray(value)? [...value] : {...value};
// Do not use unguarded for in loops. BM67 Replaced with for of loop
for (const key of Object.keys(value)) { value[key] = unbuildProxy(value[key]) }
}
return value;
}
var data = buildProxy({a: {b: true}});
data.a.b = {c: true};
data.a.b.c = data.a;
data = unbuildProxy(data); | {
"domain": "codereview.stackexchange",
"id": 45203,
"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",
"url": null
} |
python, number-guessing-game
Title: Identifying unnecessary attributes in a Python class?
Question: I have commented out two attributes (in random_number_guesser.py) which I believe are unnecessary.
Am I correct in assuming that, because the code runs correctly without their implementation, they should not be included in my program?
player.py
class Player:
def __init__(self) -> None:
"""Initializes the player object's attributes."""
self.wins = 0
def create_username(self) -> None:
"""Prompts the player to enter their username."""
attempts = 1
MAX_ATTEMPTS = 3
while attempts <= MAX_ATTEMPTS:
self.username = input("What is your name?: ")
# Checks if the username contains only whitespace.
if not self.username.strip():
if attempts == MAX_ATTEMPTS:
self.username = "Player_1"
else:
print()
print("Your username must contain at least one character.")
else:
self.username = self.username.strip()
break
attempts += 1
def __str__(self) -> str:
"""Returns the player's username as a string."""
return self.username
def get_guess(self) -> int:
"""Returns the player's guess as an integer."""
while True:
try:
self.guess = int(input("Can you guess what it is?: "))
return self.guess
except ValueError:
print()
print("Please enter a whole number.")
def add_win(self) -> None:
"""Adds a win to the player's win count."""
self.wins += 1
random_number_guesser.py
from player import Player
import random
class RandomNumberGuesser: | {
"domain": "codereview.stackexchange",
"id": 45204,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
random_number_guesser.py
from player import Player
import random
class RandomNumberGuesser:
def __init__(self) -> None:
"""Initializes the game object's attributes."""
#self.player: Player | None = None
#self.winning_number: int | None = None
def create_player(self) -> None:
"""Creates a new player object."""
self.player = Player()
self.player.create_username()
def greet_player(self) -> None:
"""Greets the player."""
print(f"Welcome, {self.player}!")
def generate_random_number(self) -> None:
"""Generates a winning number."""
MIN = 1
MAX = 10
self.winning_number = random.randint(MIN, MAX)
print()
#DEBUG - Displays the winning number:
#print(f"The winning number is: {self.winning_number}.")
print("I'm thinking of a number between 1 & 10.")
def guess_and_check(self) -> None:
"""Compares the player's guess to the winning number."""
# Checks if the player's guess is correct.
if self.player.get_guess() == self.winning_number:
print()
print(f"{self.player} Won!")
self.player.add_win()
else:
print()
print(f"{self.player} Lost!")
def play_again(self) -> None:
"""Determines whether or not the player wants to play again."""
while True:
play_again = input("Would you like to play again? (y/n): ")
# Checks if the player wants to play again & handles invalid inputs.
if play_again == "y":
self.generate_random_number()
self.guess_and_check() | {
"domain": "codereview.stackexchange",
"id": 45204,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
elif play_again == "n":
print()
# Checks the player's win count and determines if 'time' or 'times' should be used.
if self.player.wins == 1:
print(f"{self.player} won {self.player.wins} time!")
else:
print(f"{self.player} won {self.player.wins} times!")
break
else:
print()
print("Please enter either 'y' or 'n'.")
def play_random_number_guesser() -> None:
print("Welcome To Random Number Guesser!")
print("=================================")
game = RandomNumberGuesser()
game.create_player()
game.greet_player()
game.generate_random_number()
game.guess_and_check()
game.play_again()
game.py
from random_number_guesser import *
if __name__ == "__main__":
play_random_number_guesser()
Answer:
Am I correct [that] ... they are unnecessary to include in my program?
Good question.
Incorrect. You should continue to include them.
class RandomNumberGuesser:
def __init__(self) -> None:
"""Initializes the game object's attributes."""
#self.player: Player | None = None
#self.winning_number: int | None = None
def create_player(self) -> None: ...
self.player = Player() ...
def generate_random_number(self) -> None:
...
self.winning_number = random.randint(MIN, MAX)
Now, I see where you're coming from,
it is totally sensible that you might
conclude "bah, useless!" and rip it out.
The machine doesn't care.
But people do.
programs must be written for people to read, and only incidentally for machines to execute.
-- SICP | {
"domain": "codereview.stackexchange",
"id": 45204,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
programs must be written for people to read, and only incidentally for machines to execute.
-- SICP
In many OO
languages an object constructor is responsible for
declaring / allocating storage for all attributes
which the object might use over its lifetime.
Python is a dynamic language where strictly speaking
this is not necessary -- attributes can be tacked onto
an object, and even destroyed, any time the object is accessible.
But declarations are helpful to humans.
Good manners dictates that we conventionally introduce
every attribute we will ever use, right up front in the constructor.
If we do not yet have some sensible value we just assign None and move on.
This is a kindness to the Gentle Reader.
Seeing each attribute reminds us to perhaps describe it
in the __init__ constructor """docstring""",
or to write a # comment for it.
Each class is responsible for maintaining its
class invariants
over the attributes, and that responsibility starts
the moment the constructor returns.
They can be weak or strong invariants.
The stronger the guarantees, usually the easier
it is for a maintenance engineer to reason about object behavior.
So yes, please retain that "catalog" of attributes,
even if we're not yet ready to fill them in at object init time.
Here is a possible refactor you might consider:
MIN = 1
MAX = 10
def __init__(self) -> None:
"""Initializes the game object's attributes."""
self.player: Player = self._create_player()
self.winning_number: int = random.randint(self.MIN, self.MAX)
def _create_player(self) -> Player:
"""Creates a new player object."""
player = Player()
player.create_username()
return player | {
"domain": "codereview.stackexchange",
"id": 45204,
"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, number-guessing-game",
"url": null
} |
python, number-guessing-game
Notice that we're making a stronger guarantee.
Can self.player be "None or a Player" ?
No, now it can only be a Player.
And similarly we promise to always have an int.
Now a maintenance engineer has one less case to consider.
No need to worry about potential None,
as the class promises that that won't happen.
And we can use
mypy
to verify it stays that way, even after weeks of code edits. | {
"domain": "codereview.stackexchange",
"id": 45204,
"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, number-guessing-game",
"url": null
} |
python, beginner, pandas, matplotlib
Title: Extending die roll simulations for complex data science tasks
Question: I've developed a Python script that simulates die rolls and analyses the results. I'm now looking to extend and modify this code for more complex data science tasks and simulations.
Is this code simple and readable?
Are there more insightful statistics or visualisations that can be generated from the die roll data?
How could this code be extended or modified for more complex data science tasks or simulations?
import unittest
from random import randint
import matplotlib.pyplot as plt
import pandas as pd
def roll_die() -> int:
"""Simulate rolling a fair six-sided die and return the result"""
return randint(1, 6)
num_rolls = 1000
die_rolls = [roll_die() for _ in range(num_rolls)]
df = pd.DataFrame({"Rolls": die_rolls})
roll_counts = df["Rolls"].value_counts().sort_index()
print(df)
print(roll_counts)
plt.bar(roll_counts.index, roll_counts.values)
plt.xlabel("Die Face")
plt.ylabel("Frequency")
plt.title("Die Roll Distribution")
plt.show()
class TestRollDie(unittest.TestCase):
def test_roll_die(self):
result = roll_die()
self.assertTrue(1 <= result <= 6)
if __name__ == "__main__":
unittest.main()
Answer: Pandas should not be used for this purpose. Just use bare Numpy.
Do not generate random numbers one at a time. Use the vectorised Numpy random number generator.
Rather than value_counts on a dataframe, use bincount on an ndarray.
Prefer the Matplotlib OOP interface over the non-reentrant interface.
It's good that you've started writing unit tests, but... the unit test you've written isn't very useful - it's just testing randint itself (something that should already be working, and is tested in this case by the Python test suite).
For reproducible results, set a seed before calling random routines within a simulation.
Suggested
import matplotlib.pyplot as plt
import numpy as np | {
"domain": "codereview.stackexchange",
"id": 45205,
"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, beginner, pandas, matplotlib",
"url": null
} |
python, beginner, pandas, matplotlib
n_rolls = 10_000
n_sides = 6
rand = np.random.default_rng(seed=0)
die_rolls = rand.integers(low=1, high=1 + n_sides, size=n_rolls)
roll_counts = np.bincount(die_rolls)[1:]
fig, ax = plt.subplots()
ax.bar(np.arange(1, 1 + n_sides), roll_counts)
ax.set_xlabel('Die Face')
ax.set_ylabel('Frequency')
ax.set_title('Die Roll Distribution')
plt.show()
Questions
Is this code simple and readable?
Basically, yes
Are there more insightful statistics or visualisations that can be generated from the die roll data?
That's impossible to answer, because it's a trivially simple simulation and (as the kids say) "there isn't a lot of there there". You could plot a kernel density estimate, or an empirical cumulative PDF; but these would not be interesting since the distribution is so simple.
How could this code be extended or modified for more complex data science tasks or simulations?
Impossible to answer. Different things are different. | {
"domain": "codereview.stackexchange",
"id": 45205,
"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, beginner, pandas, matplotlib",
"url": null
} |
python, performance, python-3.x, bitwise, memoization
Title: Convert 64-bit Gray code to integer
Question: This algorithm encodes a 64 bit integer.
As input I have a 64 bit integer a, for example:
(a is a single 64 bit number,which I split in 8 bytes for readability) a=11110110,10101110,00010000,01100110,11101011,11000001,11001011,01100011
To calculate b=f(a), I begin with the rightmost digit (the less significant digit) and write '0'. Then, I work my way leftward. Each time I encounter a '1' in a, I switch between writing '0' and '1'. For example, if a=1011, then b=0010.
Here is an example of 64 bit a and b=f(a)
a=11110110,10101110,00010000,01100110,11101011,11000001,11001011,01100011
b=10100100,11001011,11100000,01000100,10110010,10000001,01110010,01000010
This is dumb code that calculates it for a list of bytes:
# Slow function to memoize f(numbers_to_memoize) up to 8 bits
# Returns the encoded list
def encode_reversed_gray_code(numbers: list) -> list:
# Convert to binary
numbers_bin = np.vectorize(np.binary_repr)(numbers, width=bit_length)
# Convert each string to a list of digits
numbers_bin_list = [list(x) for x in numbers_bin]
# encode reversed gray code
gray_code = []
for _list in numbers_bin_list:
reversed_number = _list[::-1]
next_digit_is_1 = False
encoded_list_reversed = ["0"]
for x in reversed_number:
if x == "1":
next_digit_is_1 = not next_digit_is_1
encoded_list_reversed.append(["0", "1"][next_digit_is_1])
gray_code.append(int("".join(encoded_list_reversed[-2::-1]), 2))
# print("".join(new_list[::-1]))
return np.asarray(gray_code).astype(np.uint8) | {
"domain": "codereview.stackexchange",
"id": 45206,
"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, python-3.x, bitwise, memoization",
"url": null
} |
python, performance, python-3.x, bitwise, memoization
# print("".join(new_list[::-1]))
return np.asarray(gray_code).astype(np.uint8)
That code is slow, but runs only once. I use it to accelerate the calculation for 64 bit.
I need a lot more speed, so I thought to memoize the result in a table, but the table would have 2⁶⁴ uint64, which is too much memory.
So, I thought to memoize only up to 8 bits, which only requires 256 bytes of memory. And build the 64 bit code as a paste of 8 bytes encoded.
This will allow me to use the memoization tables for 8-bit integers to encode larger integers.
With the above code, I made an 8-bit table named gray_code_starting_in_0
The 8-bit table is a convenient approach, because most calculations will involve much smaller numbers than 64 bit. So, the small table will likely be useful on its own, requiring only one or two lookups, and I guess will fit easily into the cpu cache, meanwhile an 16 bit will probably not.
The caveat is that although the encoding of the entire 64-bit uint starts with 0, the individual bytes may not. A new byte encoding does not necessarily start with 0, but with the most significant bit of the last byte XORed. If the last byte was byte_a, and its encoding was code(byte_a), the next byte starts with (byte_a ^ code(byte_a)) >> 7.
So I made a second table memoizing the same encoding, but starting with "1" instead of "0":
gray_code_starting_in_0 = not gray_code_starting_in_0
this is the complete code:
import numpy as np
bit_length = 8
numbers_to_memoize = np.arange(0, 2**bit_length).astype(np.uint8)
# Slow function to memoize f(numbers_to_memoize) up to 8 bits
# Returns the encoded list
def encode_reversed_gray_code(numbers: list) -> (list, list):
# Convert to binary
numbers_bin = np.vectorize(np.binary_repr)(numbers, width=bit_length)
# Convert each string to a list of digits
numbers_bin_list = [list(x) for x in numbers_bin] | {
"domain": "codereview.stackexchange",
"id": 45206,
"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, python-3.x, bitwise, memoization",
"url": null
} |
python, performance, python-3.x, bitwise, memoization
# Convert each string to a list of digits
numbers_bin_list = [list(x) for x in numbers_bin]
# encode reversed gray code
gray_code = []
for _list in numbers_bin_list:
reversed_number = _list[::-1]
next_digit_is_1 = False
encoded_list_reversed = ["0"]
for x in reversed_number:
if x == "1":
next_digit_is_1 = not next_digit_is_1
encoded_list_reversed.append(["0", "1"][next_digit_is_1])
gray_code.append(int("".join(encoded_list_reversed[-2::-1]), 2))
# print("".join(new_list[::-1]))
return np.asarray(gray_code).astype(np.uint8)
gray_code_starting_in_0 = encode_reversed_gray_code(numbers_to_memoize)
# the bitwise_not, calculates the code as if it started with 1 instead of 0
gray_code_starting_in_1 = np.vectorize(np.bitwise_not)(gray_code_starting_in_0).astype(
np.uint8
)
# Dummy variable to be overwritten, to avoid creating a new one each time a code is caculated
chunks_encoded = np.asarray([0] * 8, dtype=np.uint8)
# Weights to reconvert the array of bytes into a 64 bit uint
chunk_weights = 2 ** np.arange(0, 8**2, 8, dtype=np.uint64)
FF = 0xFF
# code to split a 64-bit integer into bytes
import struct
pack = struct.pack
unpack = struct.unpack
# Usage:
# 8_byte_chunks_of_n = unpack("8B", pack("Q", n))
from math import ceil
def fast_64_bit_encoding(n: int) -> int:
# split n in byte sized chunks
n = int(n)
# split 64 bit integer into 8 bit chunks
number_of_chunks = ceil(n.bit_length() / 8)
chunks = unpack("8B", pack("Q", n))[:number_of_chunks] | {
"domain": "codereview.stackexchange",
"id": 45206,
"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, python-3.x, bitwise, memoization",
"url": null
} |
python, performance, python-3.x, bitwise, memoization
next_starting_bit_is_1 = False
for index, chunk in enumerate(chunks):
# print(",".join(np.vectorize(np.binary_repr)(chunks[::-1], width=bit_length)))
# print(
# ",".join(
# np.vectorize(np.binary_repr)(chunks_encoded[::-1], width=bit_length)
# )
# )
# print()
if next_starting_bit_is_1:
chunks_encoded[index] = gray_code_starting_in_1[chunk]
else:
chunks_encoded[index] = gray_code_starting_in_0[chunk]
next_starting_bit_is_1 = (chunk ^ chunks_encoded[index]) >> 7 == 1
# # assert that next starting bit is correct
# assert (
# ((chunk ^ chunks_encoded[index]) & int("10000000", 2)) > 0
# ) == next_starting_bit_is_1, "".join(
# [
# f""" chunk {np.binary_repr(chunk, width=bit_length)}\n""",
# f"""code: {np.binary_repr(chunks_encoded[index], width=bit_length)}\n""",
# f"""next bit: { next_starting_bit_is_1}""",
# ]
# )
return np.dot(chunks_encoded, chunk_weights)
# Random uint64 to test the encoding
a = int("1" + "".join(np.random.choice(["0", "1"], size=63)), 2)
answer = f"{np.binary_repr(fast_64_bit_encoding(a))}"
# split "a" and "answer" in bytes
bin_a = bin(a)[2:]
a_split = [bin_a[i : i + 8] for i in range(0, len(bin_a), 8)]
answer = [answer[i : i + 8] for i in range(0, len(answer), 8)]
print("a=" + ",".join(a_split))
print("b=" + ",".join(answer))
Note: the OEIS sequence A006068 calculates the same thing, but from left to right.
That webpage has slow code (but simpler) for that calculation:
def oeis_A006068(n: np.uint64):
s = 1
while True:
ns = n >> s
if ns == 0:
break
n = n ^ ns
s <<= 1
return n | {
"domain": "codereview.stackexchange",
"id": 45206,
"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, python-3.x, bitwise, memoization",
"url": null
} |
python, performance, python-3.x, bitwise, memoization
Answer: While it's not your code, I'll point out that the routine from OEIS can be significantly shortened by using an assignment expression, available since Python 3.8:
def oeis_A006068(n: int):
s = 1
while ns := n >> s:
n ^= ns
s <<= 1
return n
Here's an unrolled version of it for 64-bit arguments:
def oeis_A006068_64bit(n: np.uint64):
n ^= n >> 1
n ^= n >> 2
n ^= n >> 4
n ^= n >> 8
n ^= n >> 16
n ^= n >> 32
return n
Either of these will probably be significantly faster than your approach, since they involve relatively few basic operations (bytecode instructions).
Converting to the Gray-code representation is simpler than converting back. In your code, you do in effect
for g in range(256):
table[g] = from_gray(g)
you could simplify the construction of the table by instead doing this:
for i in range(256):
table[to_gray(i)] = i
or more precisely
def make_lookup_table():
table = np.empty(1 << bit_length, dtype=np.uint8)
for i in range(1 << bit_length):
table[i ^ (i >> 1)] = i
return table
gray_code_starting_in_0 = make_lookup_table()
(That doesn't produce the same output as your code, but I think your code is buggy: for one thing, it only produces even numbers.)
numbers_bin_list = [list(x) for x in numbers_bin]
It's unnecessary to convert the strings to lists. Iterating over the strings directly will return the same characters.
for _list in numbers_bin_list:
Leading underscores in Python are usually reserved for variables that are private in some sense. I would call the variable list_ or lst or (probably better) a descriptive name like number_bin, or even a short loop-variable name like n.
# Dummy variable to be overwritten, to avoid creating a new one each time a code is caculated
chunks_encoded = np.asarray([0] * 8, dtype=np.uint8)
Using a global variable as scratch space is generally a bad idea since it makes the code not thread safe.
FF = 0xFF | {
"domain": "codereview.stackexchange",
"id": 45206,
"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, python-3.x, bitwise, memoization",
"url": null
} |
python, performance, python-3.x, bitwise, memoization
I don't think this is a good idea. Either use 0xFF directly or give the constant a descriptive name like BYTE_MASK. (In any case, it isn't used.)
import struct
pack = struct.pack
unpack = struct.unpack
You can just say from struct import pack, unpack instead. Also, imports should generally be at the top of the file.
chunks = unpack("8B", pack("Q", n))[:number_of_chunks]
The unpack isn't necessary; you can slice and iterate over the return value of pack.
The byte order of pack("Q", ...) is platform-dependent. If you want little-endian output you should say pack("<Q", ...).
There's a built-in method of int that would work better here: n.to_bytes(number_of_chunks, 'little'). That way you needn't import the struct module at all, and it will work if number_of_chunks > 8.
return np.dot(chunks_encoded, chunk_weights)
Similarly, this could be return int.from_bytes(chunks_encoded, 'little'). | {
"domain": "codereview.stackexchange",
"id": 45206,
"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, python-3.x, bitwise, memoization",
"url": null
} |
javascript, strings, array, vue.js
Title: JS animated string builder
Question: Today, I tried to write a simple function that would display the characters of my string one by one by iterating over a string containing the letters of the alphabet and showing the steps on the screen.
Just out of personal curiosity and fun: how would you write it? Is there something you would optimize, both in terms of readability and complexity?
I'll provide both the sandbox of the desired behavior and the code for the function.
Sandbox
const buildString = (finalString) => {
let i = 0;
let j = 0;
const tempStringArray = [];
const cycleLength = finalString.length;
const interval = setInterval(() => {
const temp = finalString[i];
const char = alphabet[j];
tempStringArray.push(undefined);
tempStringArray[i] = char;
name.value = tempStringArray.join('');
if (temp === char) {
j = 0;
i++;
} else {
j++;
}
if (i >= cycleLength) clearInterval(interval);
}, 50);
}
Answer: Most of the variable names are badly chosen.
buildString doesn't really express what it does.
name doesn't match its use (unless you happen to output a name, but it's hard-coded into the function and you'll hardly be outputing a name each time. See also below.)
I don't see the meaning of final in finalString.
i and j don't have a connection to the variables they index.
temp is always a bad name/prefix, because all variables are temporary.
etc. | {
"domain": "codereview.stackexchange",
"id": 45207,
"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, strings, array, vue.js",
"url": null
} |
javascript, strings, array, vue.js
The arrow function syntax should only be used when in-lining a function. For "top level" functions the function keyword clearly shows what is being defined.
tempStringArray.push(undefined) is pointless. In JavaScript array items don't need to exist in order to write to them. Also you are creating far too many items. If, then you'd only need it when i is incremented.
tempStringArray itself isn't really needed. It would be easier just to output the first i - 1 characters of the original string plus alphabet[j].
Hard-coding name into the function is a bad idea.
For one, as general rule in programming, functions should never access outside variables (alphabet is okay, because it's an actual constant).
The function is unnecessarily bound to Vue.
You only can use the function only once in the same component.
Here's my solution:
const alphabet = " abcdefghijklmnopqrstuwyz";
const waterfallOutput = ref("");
function waterfall(string, output, speed = 50) {
let stringIndex = 0;
let alphabetIndex = 0;
const interval = setInterval(() => {
const stringChar = string[stringIndex];
const alphabetChar = alphabet[alphabetIndex];
// TODO Add escape clause if `alphabetIndex` is too large, because the character is missing in `alphabet`
output(string.substr(0, stringIndex - 1) + alphabetChar);
if (stringChar === alphabetChar) {
alphabetIndex = 0;
stringIndex++;
} else {
alphabetIndex++;
}
if (stringIndex >= string.length) clearInterval(interval);
}, speed);
};
onMounted(() => {
waterfall("hello world", s => waterfallOutput.value = s);
}); | {
"domain": "codereview.stackexchange",
"id": 45207,
"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, strings, array, vue.js",
"url": null
} |
c#, performance, unity3d
Title: How to optimize the player movement code like in Tomb Of The Musk game?
Question: I've written some code that performs movement similar to the Tomb Of The Musk game. The idea is that the objet should move in a certain direction until it encounters an obstacle. After that, the player can choose which way the object should move.
The code I wrote seems to me to be rather unoptimized. I think it could have been done quite a bit more rationally than I did.
Object movement code:
[SerializeField]
float speed = .9f;
[SerializeField]
LayerMask obstacleMask;
Vector3 targetPosition;
Vector3 moving_direction;
bool movingHorizontally;
bool canCheck;
void Start()
{
targetPosition = transform.position;
}
void Update()
{
if (movingHorizontally)
canCheck = Physics.Raycast(transform.position, Vector3.left, .6f, obstacleMask) || Physics.Raycast(transform.position, Vector3.right, .6f, obstacleMask);
else
canCheck = Physics.Raycast(transform.position, Vector3.forward, .6f, obstacleMask) || Physics.Raycast(transform.position, Vector3.back, .6f, obstacleMask);
if (canCheck)
{
if (Input.GetAxisRaw("Horizontal") != 0)
{
if (Input.GetAxisRaw("Horizontal") > 0)
{
moving_direction = Vector3.right;
}
else
{
moving_direction = Vector3.left;
}
targetPosition = GetTargetPosition();
movingHorizontally = true;
}
else if (Input.GetAxisRaw("Vertical") != 0)
{
if (Input.GetAxisRaw("Vertical") > 0)
{
moving_direction = Vector3.forward;
}
else
{
moving_direction = Vector3.back;
}
targetPosition = GetTargetPosition();
movingHorizontally = false;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 45208,
"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, unity3d",
"url": null
} |
c#, performance, unity3d
void FixedUpdate()
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed);
}
Vector3 GetTargetPosition()
{
float ray_lenght = 1;
while(true)
{
if (Physics.Raycast(transform.position, moving_direction, ray_lenght, obstacleMask))
break;
ray_lenght += 1;
}
return transform.position + moving_direction * (ray_lenght-1);
}
Do you have any ideas regarding the improvement of my code?
Answer: In terms of performance what I have done is removed unnecessary method calls and helped out your branch predictor by removing if/else statements.
What I have mainly done though is to enhance code readability which will make it much easier to find performance bottlenecks. I have left your logic intact as I don't have enough information to change it.
Also I noticed you have a call to Vector3.left. Have you implemented your own Vector3 class?
[SerializeField]
float speed = .9f;
[SerializeField]
LayerMask obstacleMask;
Vector3 targetPosition;
Vector3 moving_direction;
bool movingHorizontally;
bool canCheck;
void Start()
{
targetPosition = transform.position;
}
void Update()
{
if (!CanMove()) return;
var horizontalRawAxis = Input.GetAxisRaw("Horizontal");
var verticalRawAxis = Input.GetAxisRaw("Vertical");
(moving_direction, movingHorizontally) = horzontalRawAxis > 0? (Vector3.right, true)
: horizontalRawAxis < 0 ? (Vector3.left, true)
: verticalRawAxis > 0 ? (Vector3.forward, false)
: (Vector3.back, false);
targetPosition = GetTargetPosition();
}
void FixedUpdate()
{
transform.position = Vector3.MoveTowards(transform.position, targetPosition, speed);
}
Vector3 GetTargetPosition()
{
float ray_lenght = 1;
while(!PhysicsRaycast(moving_direction, ray_lenght)) ray_lenght += 1;
return transform.position + moving_direction * (ray_lenght-1);
} | {
"domain": "codereview.stackexchange",
"id": 45208,
"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, unity3d",
"url": null
} |
c#, performance, unity3d
return transform.position + moving_direction * (ray_lenght-1);
}
bool CanMove(MovementType movementType) => movementType switch
{
MovementType.Left => PhysicsRaycast(Vector3.left, .6f);
MovementType.Right => PhysicsRaycast(Vector3.right, .6f);
MovementType.Forward => PhysicsRaycast(Vector3.forward, .6f);
MovementType.BackWard => PhysicsRaycast(Vector3.back, .6f);
_ => throw new Exception("Unrecognised movement type");
};
bool CanMove(){
return movingHorizontally? CanMove(MovementType.Left) || CanMove(MovementType.Right)
: CanMove(MovementType.Forward) || CanMove(MovementType.BackWard);
}
bool PhysicsRaycast(Vector3 moving_direction, float ray_length) =>
Physics.Raycast(transform.position, moving_direction, ray_length, obstacleMask);
enum MovementType{
Left,
Right,
Forward,
BackWard,
} | {
"domain": "codereview.stackexchange",
"id": 45208,
"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, unity3d",
"url": null
} |
c++, c
Title: Calling fgets() twice
Question: I am a beginner. I have really struggled with fgets() when using the function twice. I am on Windows with VS Code and C++ extension. My test program is working, but it is IMHO lengthy and complicated for such a simple task. Furthermore, the use of goto is bad practice, I have read. Is there a simpler solution?
#include <iostream>
#include <string.h>
using namespace std;
#define max 5
void killNL(char *str) {
int i = 0;
while (*(str+i) != EOF){
if (*(str+i) == '\n'){
*(str+i) = '\0';
*(str+i+1) = EOF;
}
i++;
}
}
int main()
{
size_t len = 0;
char string[5] = {0};
int c = 0;
begin:
printf("Enter string: ");
fgets(string, max, stdin);
killNL(string); //Is used only for the len count when length is 1 less
//than max. It depends on the space that is left for
//'\n' AND '\0' which raises the count to when the
//(getchar()) != gets activated. Which needs a leftover
//'\n' in the buffer to not go into endless loop.
len = strlen(string);
for (int i = 0 ; i <= len ; i++) {
if (string[i] == '\n'){ printf("\\n \n");}
else if (string[i] == '\0'){ printf("\\0 \n");}
else { printf("%c \n", string[i]);}
}
askAgain:
if (len >= max - 1) {
while (c = (getchar()) != '\n' && c != EOF) {}
}
printf("Continue? 'y'/'n' :");
fgets(string , 3, stdin);
if (*(string) == 'y'){
goto begin;
} else if (*(string) == 'n') {
goto end;
} else {
printf("\nWrong answer!\n");
goto askAgain;
}
end:
printf("END!\n");
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 45209,
"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",
"url": null
} |
c++, c
return 0;
}
I have been searching here, on Youtube and then in a book where I found the killNL function, which finally did make it work.
This question has many variants on Stack Overflow, with a combination with sscanf, with reading a file and more. But not this variant, which is why I am posting it despite the fact that it is an old subject.
Answer: Well, for starters, you really want to decide whether you are coding in C or C++. You #include <iostream>, but make no use of any iostream functions (presumably you thought about using std::cout or the like). You also specify using namespace std;, but that is not valid in C. Rule: only include necessary headers for the functions used in your code.
We will presume you are wanting to write code in C given your choice of input and output functions. If not, drop a comment and I'm happy to help with C++ as well. Working though your code: | {
"domain": "codereview.stackexchange",
"id": 45209,
"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",
"url": null
} |
c++, c
max 5 -- Don't SKIMP on buffer size. While you would use std::string if writing in C++, when declaring an array to hold input in C, don't skimp. While fgets() will only attempt to write size number of characters (minus 1 to provide room for the nul-terminating character) your purpose in using fgets(), among others, is to read a complete line of input at a time without leaving extraneous characters in the input stream. You do that by providing a sufficiently sized buffer.
When taking input, you generally loop-continually and then break your read-loop if the input fails stream error or manual EOF (generated by the user pressing Ctrl + d (or Ctrl + z on Windows)), or successful input is received, or one of your exit conditions is satisfied (e.g. the user pressing Enter alone for the string indicating they are done with input)
In C, to trim the '\n' from the end of the string read by fgets() (e.g. fgets (string, MAXC, stdin)), then you simply call string[strcspn (string, "\n")] = 0; effectively overwriting the '\n' with the nul-terminating character '\0' (which is just ASCII 0)
Declare your variables in the scope where they are needed, and
There is absolutely nothing wrong with goto used properly. It is the only way to break nested loops in a single expression, etc..
With that as a backdrop, you can simplify and clean up your code similar to the following. Many of the choices are up to you, but this is one general way to approach
reading input,
checking if the input is valid,
checking if the user generated an EOF,
checking if the user is done with input,
checking if the input matches a string you want, and finally
looping again if the input isn't what is needed.
(a rough interpretation of what it looked like you were wanting to do)
The code (with additional comments) can be:
// #include <iostream> /* only include needed headers for functions used */
#include <stdio.h> /* or <cstdio> for modern C++ */
#include <string.h> /* or <cstring> for modern C++ */ | {
"domain": "codereview.stackexchange",
"id": 45209,
"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",
"url": null
} |
c++, c
// using namespace std; /* using nothing from std:: namespace */
#define MAXC 1024 /* don't SKIMP on buffer size, UPPERCASE defines */
#define ANS "guess"
int main()
{
char string[MAXC] = {0}; /* declare string */
/* read-loop continually, break on condition of your choice */
while (1) {
fputs ("\nEnter string: ", stdout); /* no conversion, fputs is fine */
/* validate EVERY input based on return of read function */
if (!fgets (string, MAXC, stdin)) {
puts ("(user generated manual EOF)");
return 0;
}
/* trim '\n' from string */
string[strcspn (string, "\n")] = 0;
/* exit if empty-string (user just pressed [Enter], or any condition) */
if (*string == '\0') {
puts ("(all done)");
break;
}
/* check if correct answer ANS given */
if (strcmp (string, ANS) == 0) {
puts ("(correct!)");
break;
}
puts ("(answer didn't match)"); /* otherwise, loop again */
}
puts ("(That's All Folks!)");
}
Example Use/Output
$ ./bin/read-loop
Enter string: my dog has fleas
(answer didn't match)
Enter string: why?
(answer didn't match)
Enter string: what if I guess?
(answer didn't match)
Enter string: guess
(correct!)
(That's All Folks!)
Or canceling with a Ctrl + d:
$ ./bin/read-loop
Enter string: (user generated manual EOF)
Or using the exit-condition of the user just pressing Enter alone at the prompt indicating they are done guessing:
$ ./bin/read-loop
Enter string: next we will just press Enter when prompted, to quit input
(answer didn't match)
Enter string:
(all done)
(That's All Folks!)
You can add (or remove) as many of the exit conditions for the read-loop as you like. The key take-aways are: | {
"domain": "codereview.stackexchange",
"id": 45209,
"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",
"url": null
} |
c++, c
loop continually until the user provides the required input,
always condition exiting your read-loop on the return of your read-function,
validate EVERY user-input,
provide the needed exit conditions to control exit from your read-loop, and
handle any errors that occur as needed.
Let me know if this is what you needed. If not, I'm happy to help further. | {
"domain": "codereview.stackexchange",
"id": 45209,
"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",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.