text stringlengths 1 2.12k | source dict |
|---|---|
python, performance, beginner, python-3.x
Title: Custom-made spellchecker with Wiktionary
Question: I have been coding on Python for two weeks.
All I want the code to do is this:
Check if each word in sentence has an English category Wiktionary article
Ignore all words inside quotations and proper-nouns
If the word doesn't have an English category Wiktionary article, add it to a list of misspellings
For each misspelling, replace the misspelling with an auto-corrected version (if it doesn't auto-correct, blame the user for messing up so badly and leave it alone) | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, performance, beginner, python-3.x
This is only one part of three in the python file that I want to use to correct the grammar of sentences (I plan to do punctuation-check next then grammar-check, the hardest one, last)
This is my current code:
import requests
from autocorrect import Speller
original_input = input("Input: ")
#Spelling
misspellings = []
quotation_parameters = []
quotation_indices = []
spelling_input = original_input
spelling_output = original_input
for i in "?.!,":
spelling_input = spelling_input.replace(i, "")
words = spelling_input.split()
for index, i in enumerate(words):
website1 = requests.get('https://en.wiktionary.org/wiki/' + i)
website2 = requests.get('https://en.wiktionary.org/wiki/' + i.casefold())
if (website1.status_code == 200 or website2.status_code == 200) and ("<span class=\"mw-headline\" id=\"English\">English</span>" in website1.text or "<span class=\"mw-headline\" id=\"English\">English</span>" in website2.text):
print("\"" + i + "\"" + " is spelled right! :D")
else:
if (i[0] == '\'' or i[-1] == '\'') or (i[0] == '\"' or i[-1] == '\"'):
quotation_parameters.append(index)
for indexx, item in enumerate(quotation_parameters):
if indexx % 2 == 0:
try:
quotation_indices.append(list(range(item, quotation_parameters[indexx + 1])))
except IndexError:
pass
try:
for j in quotation_indices:
for k in j:
if words[k] in misspellings:
misspellings.remove(words[k])
except IndexError:
pass
else:
print("\"" + i + "\"" + " is spelled wrong... :(")
misspellings.append(i)
for word in misspellings:
try:
if (i[0] == '\'' or i[-1] == '\'') or (i[0] == '\"' or i[-1] == '\"'):
misspellings.remove(i)
except ValueError:
pass | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, performance, beginner, python-3.x
misspellings.remove(i)
except ValueError:
pass
spell = Speller(lang='en')
if (word == spell(word) or word[0].isupper() == True):
pass
else:
words = [spell(word) if x == word else x for x in words]
spelling_output = spelling_output.replace(word, spell(word))
print(misspellings)
print(words)
print(spelling_output) | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, performance, beginner, python-3.x
The code works, I guess (to an accuracy limited by the spellchecker module's library of words) - hence this wasn't posted on StackOverflow - but the problem is that it is really slow (around 20-60 seconds for new average-length sentence) and on top of that it looks really unneat and "unpythonic", I'm sure there is plenty of unnecessary try-excepts in there - this is the result of two days of trial and error - finding this and that on StackOverflow to debug the code. How can I improve the code's appearance and make the code's performance resemble closer to that of an average spell-checker like Grammarly?
Answer: First off, I would say you're quite ambitious with your choice of project. This isn't necessarily a bad thing and you can learn a lot along the way, but spelling and grammar checking of English beyond the simple sentences may not be easy. Consider the following weird, but valid sentence
'Tis naïve for Guinea-Bissau to serve hors d'oeuvre at the France-Côte d'Ivoire all-american BBQ; the grocers' response was unfavourable. | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, performance, beginner, python-3.x
We have valid words in here, archaic words, ones that start end and with apostrophes, words which require particular capitalisation to be found, words with special characters, hypenated words, words which are only valid as multiple words, abbreviations, etc.
Regardless, it's an interesting project idea and I wish you the best of luck. Particularly with English grammar.
Format
First off, you have no comments in your code, this makes it quite difficult to work out what this is doing. I'm not sure what quotation_parameters is supposed to do.
Also, you have no white-space in your code making it harder to visually parse.
Your variable names are also sometimes not helpful why i, not word, why indexx?
You also seem to have taken the odd choice of deliberately forcing yourself to escape quotes. In Python " and ' are semantically identical, you can either be consistent throughout, or make the choice which makes your work easier. Instead of "\"" we can use '"'; instead of '\'' we can use "'", if we're using them frequently enough we can do:
SINGLE_QUOTE = "'"
DOUBLE_QUOTE = '"'
And use constants to make it more obvious and readable.
In Python, we don't need parentheses around if statements and checking if True is a default operation (as well as numerous others such as is zero, is empty, etc.). Also, we tend to test against the value we want to check rather than pass .. else, so:
if (word == spell(word) or word[0].isupper() == True):
pass
else:
words = [spell(word) if x == word else x for x in words]
spelling_output = spelling_output.replace(word, spell(word))
becomes
if word != spell(word) and not word[0].isupper(): ## Could also do `and word[0].islower()`
words = [spell(word) if x == word else x for x in words]
spelling_output = spelling_output.replace(word, spell(word))
Probable logic errors
if (i[0] == '\'' or i[-1] == '\'') or (i[0] == '\"' or i[-1] == '\"'): | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, performance, beginner, python-3.x
Probable logic errors
if (i[0] == '\'' or i[-1] == '\'') or (i[0] == '\"' or i[-1] == '\"'):
This just checks if the first or last letters are " or ', i.e. "the", 'tis, 'so", a", Julius' are all caught. The inner checks probably want to be and not or.
More helpfully, since we use this multiple times, we could also make this a function:
def isquoted(inp: str) -> bool:
"""Checks if a string is quoted
:param inp: String to be checked
:returns: true if quoted, else false
"""
return ((inp.startswith("'") and inp.endswith("'")) or
(inp.startswith('"') and inp.endswith('"')))
Also in this block
if (i[0] == '\'' or i[-1] == '\'') or (i[0] == '\"' or i[-1] == '\"'):
[...]
try:
[...]
except IndexError:
[...]
else: # <-- This else is attached to the `try` not the `if`, which probably isn't what you want
[...]
Efficiency
Every word of your sentence you are looping through every misspelling multiple times and removing duplicates. This function is built into Python in the set object. A set is a type which stores one copy of each of the elements. This means that instead of having to check if word in misspellings and filter duplicates, we just do:
misspellings = set()
misspellings.add(word)
It will never store duplicate copies.
Standard Libraries
You are attempting to strip out the punctuation from your string, but there is much more possible punctuation in English; ;, &, (), etc.
One advantage of Python is that it comes with a plethora of pre-written code you can use in the stdlib (including requests which you've used), one such library is string, which contains the useful constant punctuation.
string.punctuation
String of ASCII characters which are considered punctuation characters in the C locale: !"#$%&'()*+,-./:;<=>?@[\]^_\{|}~.`
If we want to keep ', we can filter that our on your loop.
i.e.
for i in "?.!,":
spelling_input = spelling_input.replace(i, "") | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, performance, beginner, python-3.x
becomes
for i in (j for j in string.punctuation if j not in ("'", '"')):
spelling_input = spelling_input.replace(i, "")
(N.B. this isn't the most efficient way to strip punctuation, but given it happens once, that's not too much of a concern)
Simplifying logic
You are doing the same check against multiple cases when you download the websites. In order to avoid repeating ourselves (and not having a line that stretches into next week), we could replace:
website1 = requests.get('https://en.wiktionary.org/wiki/' + i)
website2 = requests.get('https://en.wiktionary.org/wiki/' + i.casefold())
if (website1.status_code == 200 or website2.status_code == 200) and ("<span class=\"mw-headline\" id=\"English\">English</span>" in website1.text or "<span class=\"mw-headline\" id=\"English\">English</span>" in website2.text):
print("\"" + i + "\"" + " is spelled right! :D")
else: # An `else .. if` should usually be an `elif`
if (i[0] == '\'' or i[-1] == '\'') or (i[0] == '\"' or i[-1] == '\"'):
[...]
with
for case in (i, i.casefold()):
website = requests.get('https://en.wiktionary.org/wiki/' + case)
if website.status_code == 200 and "<span class=\"mw-headline\" id=\"English\">English</span>" in website.text: # Should probably make the string here a constant
print("\"" + i + "\"" + " is spelled right! :D")
break
else: # Python lets us do an `else` on a loop, which means `if exited naturally and not by break, etc.`
if (i[0] == '\'' or i[-1] == '\'') or (i[0] == '\"' or i[-1] == '\"'):
[...] | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, performance, beginner, python-3.x
Putting it all together
So when we add docstrings, main guard, split some things into functions we might end up with (untested as I don't have autocorrect installed)
N.B. Most of the comments here are for you to understand what I've changed and aren't good code documentation, make sure your code blocks are informatively, but not excessively, commented if they do more than a small thing.
"""
My spell checker using wiktionary
"""
import string
import requests
from autocorrect import Speller
WIKI_ADDRESS = 'https://en.wiktionary.org/wiki/'
ENGLISH_HEADER = "<span class=\"mw-headline\" id=\"English\">English</span>"
SUCCESS_RESPONSE = 200
SPELL_CHECKER = Speller(lang='en')
def isquoted(inp: str) -> bool:
"""Checks if a string is quoted
:param inp: String to be checked
:returns: true if quoted, else false
"""
return ((inp.startswith("'") and inp.endswith("'")) or
(inp.startswith('"') and inp.endswith('"')))
def check_spelling(inp: str) -> tuple[str, list[str], list[str]]:
"""
Checks the spelling of the input word-by-word
:param inp: String to be checked
:returns: Tuple of a corrected version, a list of misspellings and list of the new words
"""
misspellings = set()
spelling_input = inp
spelling_output = inp
for i in (j for j in string.punctuation if j not in ("'", '"')):
spelling_input = spelling_input.replace(i, "")
words = spelling_input.split() | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, performance, beginner, python-3.x
words = spelling_input.split()
for word in words:
for case in (word, word.casefold()):
website = requests.get(WIKI_ADDRESS + case)
if website.status_code == SUCCESS_RESPONSE and ENGLISH_HEADER in website.text:
print(f'"{word}" is spelled right! :D')
break
# I honestly have very little idea what this next block was supposed
# to be doing without comments
# But I'm going to try to do what it says in your spec
else:
if isquoted(word): # Ignore quoted words here
continue
print(f'"{word}" may be spelled wrong... :(')
# Set takes care of duplicates
misspellings.add(word)
# Unindent this so it's done after we've got all the misspellings not each iteration
for word in misspellings:
if word[0].isupper(): # Skip Proper Nouns
continue
if word != SPELL_CHECKER(word): # Spell checker found correction
words = [SPELL_CHECKER(word) if x == word else x for x in words]
spelling_output = spelling_output.replace(word, SPELL_CHECKER(word))
else:
# Here we inform the user their word was not fixed
print(f'Your word "{word}" could not be fixed by spell checker')
return spelling_output, misspellings, words
if __name__ == "__main__": # Main guard allows us to import module functions and use them elsewhere
# Loop until no input received from user
while user_input := input("Input: "):
corrected, misspellings, words = check_spelling(user_input)
print(f"Corrected: {corrected}")
print(f"Misspellings: {misspellings}")
print(f"Words: {words}") | {
"domain": "codereview.stackexchange",
"id": 44475,
"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, beginner, python-3.x",
"url": null
} |
python, python-3.x, api, rest
Title: Python script to get and save data from a web API
Question: I'm working as a system administrator (sort of), but learning Python on the side.
Life gave me a chance to apply that knowledge, since our organization is being provided cloud email service, and it has a pretty terrible GUI (without even an option to download a list of user accounts), so the only option to do some things is by using their API (which is also not very advanced). I happily jumped on the chance to actually write something useful in Python and wrote the following script, that makes a request to their "users" endpoint, parses JSON for relevant fields and writes it all to a csv.
It's a very simple script that does one thing, it works, and I'm the only person that has to use it, so I'm my only critic, still, I tried to make it as self-describing as possible. But I couldn't help but wondering what would my colleagues say if I were a software developer working in a team and they had to use it, and if the result bears any resemblance to "production-worthy" code and what could be improved in terms of its performance, security, readability or extensibility.
So, I'd very much appreciate it if someone could glance over it and maybe give any advice.
Thanks!
import csv
import os
import sys
from collections import namedtuple
from typing import Iterable, List, Optional
from requests_cache import CachedSession
from prettytable import PrettyTable
from constants import (
SAVE_DIR, USERS_INPUT_FIELDS, USERS_OUTPUT_FIELDS,
CACHE_EXPIRATION, USERS_URL, USER_STR_TEMPLATE,
USERS_PER_PAGE, TOKEN)
OUTPUT_FILE_NAME = 'user.csv'
OUTPUT_FILE_PATH = os.path.join(SAVE_DIR, 'users.csv')
class User(namedtuple('User', USERS_INPUT_FIELDS)):
def __new__(cls, *args, **kwargs) -> 'User':
kwargs = { k: v for k, v in kwargs.items() if k in cls._fields }
return super().__new__(cls, *args, **kwargs) | {
"domain": "codereview.stackexchange",
"id": 44476,
"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, api, rest",
"url": null
} |
python, python-3.x, api, rest
@property
def first_name(self) -> Optional[str]:
if self.name:
return self.name.get('first')
return None
@property
def last_name(self) -> Optional[str]:
if self.name:
return self.name.get('last')
return None
def __repr__(self) -> str:
return str(self._asdict())
def __str__(self) -> str:
return USER_STR_TEMPLATE.format(
class_name=self.__class__.__name__,
fields=(self.id, self.nickname))
def get_users(session: CachedSession) -> Iterable[User]:
headers = {
'Authorization': f'OAuth {TOKEN}',
'Content-Type': 'text/plain; charset=utf-8'
}
params = {
'perPage': USERS_PER_PAGE
}
response = session.get(
url=USERS_URL,
headers=headers,
params=params)
response.raise_for_status()
if 'users' not in response.json():
raise KeyError('Couldn\'t extract users from server response')
for json_object in response.json()['users']:
yield User(**json_object)
def user_to_row(user: User) -> Iterable[List[str]]:
yield [getattr(user, field) for field in USERS_OUTPUT_FIELDS]
def get_user_rows(session: CachedSession) -> Iterable[List[str]]:
for user in get_users(session):
yield from user_to_row(user)
def write_to_csv(rows) -> None:
with open(OUTPUT_FILE_PATH, 'wt', encoding='utf8') as file:
writer = csv.writer(
file,
dialect=csv.unix_dialect,
quoting=csv.QUOTE_MINIMAL)
writer.writerows(
[USERS_OUTPUT_FIELDS, *rows])
def print_users_table(rows) -> None:
users_table = PrettyTable()
users_table.field_names = USERS_OUTPUT_FIELDS
users_table.add_rows(rows)
print(users_table) | {
"domain": "codereview.stackexchange",
"id": 44476,
"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, api, rest",
"url": null
} |
python, python-3.x, api, rest
if __name__ == '__main__':
with CachedSession(expire_after=CACHE_EXPIRATION) as session:
rows = list(get_user_rows(session))
write_to_csv(rows)
if '-v' in sys.argv:
print_users_table(rows)
Answer: This is pretty good!
For the purpose of your job, I would suggest leaving this alone unless or until you decide it's broken in some way. It's certainly "good enough".
As a learning experience, there are some things I might raise in code review, but I have to preface this by saying that I'm not experienced with CachedSessions or PrettyTable. | {
"domain": "codereview.stackexchange",
"id": 44476,
"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, api, rest",
"url": null
} |
python, python-3.x, api, rest
The indirection of importing the structure of the User class from constants is neat, but it's not good. I assume that flexibility is an important feature of the script, in which case any solution will be as ugly as what you're doing with namedtuple.
There are still some issues with the User class though. What guarantee do you have that id name or nickname will have been included in USERS_INPUT_FIELDS? Why are you comfortable leaving name as a dictionary (or, conversely, why bother making User a convoluted class if a dictionary is ok)?
I'm assuming constants is a file full of settings you expect to change often, and may maintain different copies of for different clients. (If not, then just pull all those constants into this same file.) I'm not fond of implementing config settings as importable code; I've had co-workers start adding complex (or even side-effect-ful!) code in settings files, and other solutions are actually more flexible. I think my suggestion would have been to implement all the settings as CLI arguments, set up parsing/validation/defaults with argparse, and then finally allow loading of settings from a file using fromfile_prefix_chars. This would probably also require that these values get passed around as function arguments instead of file-level globals, which is good.
OUTPUT_FILE_NAME isn't used, you just hard-coded the same string on the next line. At the same time, why isn't this configurable like the other constants?
For typing: A return type is a promise, so don't promise more than you need to. Specifically, annotating something as a List is an invitation for the consumer to mutate it. (In the case of an argument annotation, it would mean the function was insisting on the right to mutate its arg.) Use Sequence to denote an indexable re-usable iterable, or Iterable if you want to be really conservative. Same logic applies for Mapping vs dict, and usually applies for AbstractSet vs Set. | {
"domain": "codereview.stackexchange",
"id": 44476,
"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, api, rest",
"url": null
} |
python, python-3.x, api, rest
Consider using csv.DictWriter. You can judge from the doc and example if it's a good fit; I think it usually is.
You've written parts of this in "streaming" style (using iterators/generators instead of just lists). That's usually good! But then you break it when you get to main, I assume because you want to use rows twice. I suggest thinking about it in terms of failure. | {
"domain": "codereview.stackexchange",
"id": 44476,
"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, api, rest",
"url": null
} |
python, python-3.x, api, rest
Right now there doesn't seem to be a strategy for what should happen if something goes wrong, but you're pretty close to one sensible strategy: If something goes wrong nothing happens and an error is thrown. In that paradigm I think the only things I would change would be moving the print_users_table before write_to_csv, and possibly adding a "Success!" message. It would also be possible to build the entire CSV as a str and write it to the file at the very end, but that might be more trouble than it's worth.
Two other strategies would be: Records are written to the file streaming-style until an error occurs,
or records are written streaming-style with an effort to log errors and keep going if an error occurs. In a lot of contexts that last option is best; it'd just require refactoring most of your functions! | {
"domain": "codereview.stackexchange",
"id": 44476,
"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, api, rest",
"url": null
} |
c++, beginner, game-of-life, sfml
Title: John Conway's Game of Life in C++
Question: I have created Game of Life in C++ SFML. The code works just fine. However since I am not used to working with C++, I implemented a lot of stuff the way I would in python (for example I have not used pointers). So I would appreciate any feedback (even if it is really nitpicky) on my project. My goal with this project is the build good fundamentals before I work on bigger projects.
Main:
#include "Grid.hpp"
void handle_mouse(Grid &grid, sf::RenderWindow &window )
{
sf::Vector2i position = sf::Mouse::getPosition(window);
int x = position.x;
int y = position.y;
int i = int(y/TILE_SIZE);
int j = int(x/TILE_SIZE);
grid.change_tile(i,j);
}
Grid grid;
int main()
{
sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "SFML works!");
grid.reset();
bool draw_mode = true;
window.setFramerateLimit(60);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (draw_mode)
{
if (event.type == sf::Event::MouseButtonPressed)
{
handle_mouse(grid, window);
}
if (event.key.code == sf::Keyboard::Space)
{
draw_mode = false;
window.setFramerateLimit(4);
}
}
if (not draw_mode and event.key.code == sf::Keyboard::LControl)
{
grid.reset();
draw_mode = true;
}
}
window.clear();
grid.draw(window);
window.display();
if (not draw_mode) {grid.update();}
}
return 0;
}
Grid.hpp:
#pragma once
#include "settings.hpp"
#include <SFML/Graphics.hpp>
class Grid{
public: | {
"domain": "codereview.stackexchange",
"id": 44477,
"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, game-of-life, sfml",
"url": null
} |
c++, beginner, game-of-life, sfml
Grid.hpp:
#pragma once
#include "settings.hpp"
#include <SFML/Graphics.hpp>
class Grid{
public:
void reset();
void update();
void draw(sf::RenderWindow &window);
int check_nearby_cells(int i, int j);
void change_tile(int i, int j){Grid::array[i][j] = !Grid::array[i][j];}
bool array[NUM_VERTICAL_TILES][NUM_HORIZONTAL_TILES];
};
Grid.cpp
#include "Grid.hpp"
#include <iostream>
sf::RectangleShape get_rectangle(int i, int j, bool filled);
void Grid::reset()
{
for (int i=0; i<NUM_VERTICAL_TILES; i++)
{
for (int j=0; j<NUM_HORIZONTAL_TILES; j++)
{
Grid::array[i][j] = false;
}
}
}
void Grid::draw(sf::RenderWindow &window)
{
for (int i=0; i<NUM_VERTICAL_TILES; i++)
{
for (int j=0; j<NUM_HORIZONTAL_TILES; j++)
{
bool filled = Grid::array[i][j];
sf::RectangleShape rectangle = get_rectangle(i, j, filled);
window.draw(rectangle);
}
}
}
void Grid::update()
{
bool new_array[NUM_VERTICAL_TILES][NUM_HORIZONTAL_TILES];
for (int i=0; i<NUM_VERTICAL_TILES; i++)
{
for (int j=0; j<NUM_HORIZONTAL_TILES; j++)
{
int num_adjacent_cells = check_nearby_cells(i, j);
if (Grid::array[i][j])
{
if (num_adjacent_cells <2 or num_adjacent_cells>3) {new_array[i][j] = false;}
else {new_array[i][j] = true;}
}
else
{
if (num_adjacent_cells == 3) {new_array[i][j] = true;}
else {new_array[i][j] = false;}
}
}
}
for (int i=0; i<NUM_VERTICAL_TILES; i++)
{
for (int j=0; j<NUM_HORIZONTAL_TILES; j++)
{
Grid::array[i][j] = new_array[i][j];
}
}
}
bool is_valid(int i, int j)
{
return (i>=0 and j>=0 and i < NUM_VERTICAL_TILES and j < NUM_HORIZONTAL_TILES);
} | {
"domain": "codereview.stackexchange",
"id": 44477,
"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, game-of-life, sfml",
"url": null
} |
c++, beginner, game-of-life, sfml
int Grid::check_nearby_cells(int i, int j)
{
int count = 0;
for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
// Skip the (i, j) tile itself
if (x == 0 and y == 0) {
continue;
}
if (is_valid(i + x, j + y) and Grid::array[i + x][j + y]) {
count++;
}
}
}
return count;
}
sf::RectangleShape get_rectangle(int i, int j, bool filled)
{
sf::RectangleShape rectangle;
rectangle.setPosition(j*TILE_SIZE, i*TILE_SIZE);
rectangle.setSize(sf::Vector2f(TILE_SIZE, TILE_SIZE));
if (filled)
{
rectangle.setFillColor(sf::Color::White);
}else{
rectangle.setFillColor(sf::Color::Black);
}
rectangle.setOutlineColor(sf::Color::Red);
rectangle.setOutlineThickness(1);
return rectangle;
}
settings.hpp
#pragma once
constexpr int WIDTH = 1200;
constexpr int HEIGHT = 800;
constexpr int TILE_SIZE = 50;
constexpr int NUM_HORIZONTAL_TILES = WIDTH/TILE_SIZE;
constexpr int NUM_VERTICAL_TILES = HEIGHT/TILE_SIZE; | {
"domain": "codereview.stackexchange",
"id": 44477,
"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, game-of-life, sfml",
"url": null
} |
c++, beginner, game-of-life, sfml
Answer: General Observations
Not too bad if this is your very first C++ program.
You need to become aware of the Standard Template Library which provides data structures such as std::array and std::vector. The way the arrays are currently implemented is a lot more like the C Programming language than C++. Naming the array array may also have caused some problems.
Generally header files in C++ use the .h notation, there are libraries where there are .hpp but these are generally header files that contain executable code and not just header information. I would suggest changing settings.hpp to settings.h.
Separate the game logic from the input and output. The Grid class should only contain information about the game and not about input or output. You may not have encountered design patterns yet, but there are several design patterns that deal with separating the I/O from the logic of the program. Some of these are Model View Controller (MVC), and Model View View Model (MVVM).
In modern C++ we avoid pointers as much as possible.
Avoid Global Variables
It is very difficult to read, write, debug and maintain programs that use global variables. Global variables can be modified by any function within the program and therefore require each function to be examined before making changes in the code. In C and C++ global variables impact the namespace and they can cause linking errors if they are defined in multiple files. The answers in this stackoverflow question provide a fuller explanation.
Not only is grid a global variable, all of the constants defined in settings.hpp are global variables.
It might be better in settings.hpp if each constant was declared as static so that it is local to the file including settings.hpp
static constexpr int WIDTH = 1200;
static constexpr int HEIGHT = 800;
static constexpr int TILE_SIZE = 50;
static constexpr int NUM_HORIZONTAL_TILES = WIDTH / TILE_SIZE;
static constexpr int NUM_VERTICAL_TILES = HEIGHT / TILE_SIZE; | {
"domain": "codereview.stackexchange",
"id": 44477,
"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, game-of-life, sfml",
"url": null
} |
c++, beginner, game-of-life, sfml
Currently if settings.hpp is included by multiple files there may be link time errors about the constants being declared in multiple files.
Magic Numbers
The frame rates in the main() are magic numbers, there are a number of symbolic constants already defined in settings.hpp, why aren't the frame rates defined there as well? | {
"domain": "codereview.stackexchange",
"id": 44477,
"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, game-of-life, sfml",
"url": null
} |
rust, simulation
Title: Smoothed Particle Hydrodynamics in Rust
Question: So I'm simultaneously learning both Rust and Smoothed Particle Hydrodynamics.
I've been using this video from AMD as a reference and the provided smoothing kernels.
At this stage, I've not optimised the simulation with voxelisation, nor have I added hardware acceleration, so it is very slow. I've also not added a visualisation step to check if it actually works.
At this point, it compiles, and it runs. So what I'm interested in is whether this code looks reasonably understandable from a purely rust code point of view. Although if you feel like reviewing the actual SPH implementation, I wouldn't say no...
//use std::collections::HashMap;
use std::f32::consts::PI;
use cgmath::{InnerSpace, Vector3, Vector4, Zero};
use rand::Rng;
const NUM_PARTICLES: u32 = 1000; // 1.2 Litres
const BUFFER_LEN: usize = NUM_PARTICLES as usize;
const BOX_DIMENSIONS_M: Vector3<f32> = Vector3::new(0.30, 0.10, 0.10);
const SMOOTHING_RADIUS: f32 = NUM_PARTICLES as f32 / (0.3 * 0.1 * 0.1 * 60.0);
const TIME_STEP_SECONDS: f32 = 0.01;
const GRAVITY: Vector4<f32> = Vector4::new(0.0, -9.8, 0.0, 0.0);
const SIM_LENGTH_SECONDS: f32 = 10.0;
const PARTICLE_MASS_KG: f32 = 0.001; //1mL of water
const FLUID_CONST: f32 = 2.2; // Possibly needs a x10^9
const VISCOUS_CONST: f32 = 0.0001;
const RHO_ZERO: f32 = 1000.0;
//TODO - Voxelise
fn main() {
let mut sim_data: SimulationData = setup();
let mut current_time: f32 = 0.0;
while current_time < SIM_LENGTH_SECONDS {
sim_step(&mut sim_data);
current_time += TIME_STEP_SECONDS;
println!("Time: {}s", current_time);
}
}
fn sim_step(sim_data: &mut SimulationData) {
let densities = sim_data.simulation_space.positions.iter().enumerate()
.map(|(i, _)| calculate_density_at_point(&sim_data.simulation_space, i))
.collect::<Vec<f32>>(); | {
"domain": "codereview.stackexchange",
"id": 44478,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, simulation",
"url": null
} |
rust, simulation
let pressures = sim_data.simulation_space.positions.iter().enumerate()
.map(|(i, _)| calculate_pressure_at_point(densities[i]))
.collect::<Vec<f32>>();
let pressure_grad_terms = sim_data.simulation_space.positions.iter().enumerate()
.map(|(i, _)| calculate_pressure_grad_term_at_point(&sim_data.simulation_space, &pressures, &densities, i))
.collect::<Vec<Vector4<f32>>>();
let viscosity_terms = sim_data.simulation_space.positions.iter().enumerate()
.map(|(i, _)| calculate_viscosity_term_at_point(&sim_data.simulation_space, &densities, i))
.collect::<Vec<Vector4<f32>>>();
let accelerations = sim_data.simulation_space.positions.iter().enumerate()
.map(|(i, _)| calculate_acceleration_at_point(&pressure_grad_terms, &viscosity_terms, i))
.collect::<Vec<Vector4<f32>>>();
let new_velocities = sim_data.simulation_space.velocities.iter().enumerate()
.map(|(i, v)| v + accelerations[i] * TIME_STEP_SECONDS)
.collect::<Vec<Vector4<f32>>>();
let new_positions = sim_data.simulation_space.positions.iter().enumerate()
.map(|(i, p)| p + new_velocities[i] * TIME_STEP_SECONDS)
.collect::<Vec<Vector4<f32>>>();
//TODO - Check for collisions with walls and floor
// This will make rustaceans cry
sim_data.simulation_space.velocities = new_velocities.try_into().unwrap();
sim_data.simulation_space.positions = new_positions.try_into().unwrap();
}
fn calculate_acceleration_at_point(pressure_terms: &Vec<Vector4<f32>>, viscosity_terms: &Vec<Vector4<f32>>, i: usize) -> Vector4<f32> {
let acceleration: Vector4<f32> = GRAVITY + pressure_terms[i] + viscosity_terms[i];
return acceleration;
} | {
"domain": "codereview.stackexchange",
"id": 44478,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, simulation",
"url": null
} |
rust, simulation
fn calculate_viscosity_term_at_point(sim_space: &SimulationSpace, densities: &Vec<f32>, i: usize) -> Vector4<f32> {
let viscosity_term: Vector4<f32> = sim_space.positions.iter()
.filter(|&x| is_in_interaction_radius_and_not_self(x, sim_space.positions[i]))
.enumerate()// exclude self
.fold(Vector4::zero(), |acc: Vector4<f32>, (j, _)| {
acc + (VISCOUS_CONST / densities[j]) * PARTICLE_MASS_KG * (sim_space.velocities[j] - sim_space.velocities[i]) / densities[j] * laplacian_smooth(sim_space.positions[i], sim_space.positions[j])
});
return viscosity_term;
}
fn calculate_pressure_at_point(density: f32) -> f32 {
let pressure_at_point: f32 = FLUID_CONST * (density - RHO_ZERO);
return pressure_at_point;
}
fn calculate_pressure_grad_term_at_point(sim_space: &SimulationSpace, pressures: &Vec<f32>, densities: &Vec<f32>, i: usize) -> Vector4<f32> {
let pressure_grad_term: Vector4<f32> = sim_space.positions.iter()
.filter(|&x| is_in_interaction_radius_and_not_self(x, sim_space.positions[i]))
.enumerate()// exclude self
.fold(Vector4::zero(), |acc: Vector4<f32>, (j, _)| {
acc + PARTICLE_MASS_KG * (pressures[i] / (densities[i].powi(2)) + pressures[j] / (densities[j].powi(2))) * grad_smooth(sim_space.positions[i], sim_space.positions[j])
});
return pressure_grad_term;
}
fn calculate_density_at_point(sim_space: &SimulationSpace, i: usize) -> f32 {
let density = sim_space.positions.iter()
.filter(|&x| is_in_interaction_radius_and_not_self(x, sim_space.positions[i]))
.enumerate()// exclude self
.fold(0.0, |acc: f32, (j, _)| acc + PARTICLE_MASS_KG * smooth(sim_space.positions[i], sim_space.positions[j]));
return density;
}
fn is_in_interaction_radius_and_not_self(current: &Vector4<f32>, other: Vector4<f32>) -> bool {
return *current != other && (current - other).magnitude() < SMOOTHING_RADIUS;
} | {
"domain": "codereview.stackexchange",
"id": 44478,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, simulation",
"url": null
} |
rust, simulation
// There are some terms reused between smooth, grad_smooth and laplacian_smooth, this could be optimised
// Not to mention, some of these terms are constants...
fn smooth(current_position: Vector4<f32>, other_position: Vector4<f32>) -> f32
{
return (315.0/(64.0*PI*(SMOOTHING_RADIUS.powi(9)))) * (SMOOTHING_RADIUS.powi(2) - (current_position - other_position).magnitude2()).powi(3);
}
fn grad_smooth(current_position: Vector4<f32>, other_position: Vector4<f32>) -> Vector4<f32>
{
return (-45.0/(PI*(SMOOTHING_RADIUS.powi(6)))) * (SMOOTHING_RADIUS - (current_position - other_position).magnitude2()).powi(2) * ((current_position - other_position) / (current_position - other_position).magnitude2());
}
fn laplacian_smooth(current_position: Vector4<f32>, other_position: Vector4<f32>) -> f32
{
return (45.0/(PI*(SMOOTHING_RADIUS.powi(6)))) * (SMOOTHING_RADIUS - (current_position - other_position).magnitude());
}
fn setup() -> SimulationData {
let sim_space = SimulationSpace{
positions: get_initial_positions(),
velocities: get_initial_velocities(),
accelerations: get_initial_accelerations()
};
let sim_data = SimulationData {
simulation_space: sim_space,
//voxel_pixel_map: HashMap::new()
};
return sim_data;
}
fn get_initial_positions() -> [Vector4<f32>; BUFFER_LEN] {
let mut rng = rand::thread_rng();
let mut positions: [Vector4<f32>; BUFFER_LEN] = [Vector4::zero(); BUFFER_LEN];
for i in 0..BUFFER_LEN {
positions[i] = Vector4::new(
rng.gen_range(0.0..0.1),
rng.gen_range(0.0..0.01),
rng.gen_range(4.9..5.0),
0.0
);
}
return positions;
}
fn get_initial_velocities() -> [Vector4<f32>; BUFFER_LEN] {
return [ Vector4::zero(); BUFFER_LEN];
}
fn get_initial_accelerations() -> [Vector4<f32>; BUFFER_LEN] {
return [ Vector4::zero(); BUFFER_LEN];
} | {
"domain": "codereview.stackexchange",
"id": 44478,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, simulation",
"url": null
} |
rust, simulation
struct SimulationData {
simulation_space: SimulationSpace,
//voxel_pixel_map: HashMap<u16, Vec<u32>>
}
struct SimulationSpace {
positions: [Vector4<f32>; BUFFER_LEN as usize],
velocities: [Vector4<f32>; BUFFER_LEN as usize],
accelerations: [Vector4<f32>; BUFFER_LEN as usize]
}
Answer: One big item: compile and run in --release mode. You mention it being slow, but it takes only a few second to run for me in release mode, mostly because of all the printing it does.
Typically, in Rust, we'd make the setup function a constructor method on SimulationData
impl SimulationData {
fn new() -> SimulationData {
...
}
}
We'd also typically make sim_step a method on SimulationData
impl SimulationData {
fn step(&mut self) {
...
}
}
This comment seem inscrutable and probably wrong
const NUM_PARTICLES: u32 = 1000; // 1.2 Litres
This constant could use a comment explaining something about the mysterious numbers being multiplied:
const SMOOTHING_RADIUS: f32 = NUM_PARTICLES as f32 / (0.3 * 0.1 * 0.1 * 60.0);
You've got a number of blocks that have this sort of pattern
let pressure_grad_term: Vector4<f32> = sim_space.positions.iter()
.filter(|&x| is_in_interaction_radius_and_not_self(x, sim_space.positions[i]))
.enumerate()// exclude self
.fold(Vector4::zero(), |acc: Vector4<f32>, (j, _)| {
acc + PARTICLE_MASS_KG * (pressures[i] / (densities[i].powi(2)) + pressures[j] / (densities[j].powi(2))) * grad_smooth(sim_space.positions[i], sim_space.positions[j])
}); | {
"domain": "codereview.stackexchange",
"id": 44478,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, simulation",
"url": null
} |
rust, simulation
Firstly, it's wrong because you filter before you enumerate. This means that all of your indexes are off because the indexes are generated after the filter. If you want the indexes to match your arrays, you need to enumerate() before filtering items out.
Secondly, rust has a sum method you can use instead of the generic fold.
let pressure_grad_term: Vector4<f32> = sim_space.positions.iter()
.filter(|&x| is_in_interaction_radius_and_not_self(x, sim_space.positions[i]))
.enumerate()// exclude self
.map(|(j, _)| {
PARTICLE_MASS_KG * (pressures[i] / (densities[i].powi(2)) + pressures[j] / (densities[j].powi(2))) * grad_smooth(sim_space.positions[i], sim_space.positions[j])
})
.sum()
However, for the type of coding you are doing here, you probably want to look at using the ndarray crate. It provides an Array type with useful functions that operate on arrays. In your case, this seems a better fit than converting to iterators and back. So, for example, here is a rewritten version of calculate_density_at_point
fn calculate_density_at_point(sim_space: &SimulationSpace, i: usize) -> f32 {
sim_space.positions.fold(0.0, |acc, x| {
if is_in_interaction_radius_and_not_self(x, sim_space.positions[i]) {
acc + PARTICLE_MASS_KG * smooth(sim_space.positions[i], *x)
} else {
acc
}
})
}
You'll notice that its much simpler then the iterator version. We can go a step further and define a function that builds the entire density array.
fn calculate_density_at_point(sim_space: &SimulationSpace) -> Array1<f32> {
sim_space.positions.map(|&position| {
sim_space.positions.fold(0.0, |acc, x| {
if is_in_interaction_radius_and_not_self(x, position) {
acc + PARTICLE_MASS_KG * smooth(position, *x)
} else {
acc
}
})
})
} | {
"domain": "codereview.stackexchange",
"id": 44478,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, simulation",
"url": null
} |
rust, simulation
Going one step further, if you turn on the parallel features, you can easily parallelize the calculations:
fn calculate_density_at_point(sim_space: &SimulationSpace) -> Array1<f32> {
ndarray::Zip::from(&sim_space.positions).par_map_collect(|&position| {
sim_space.positions.fold(0.0, |acc, x| {
if is_in_interaction_radius_and_not_self(x, position) {
acc + PARTICLE_MASS_KG * smooth(position, *x)
} else {
acc
}
})
})
} | {
"domain": "codereview.stackexchange",
"id": 44478,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, simulation",
"url": null
} |
c++, design-patterns, c++20
Title: Modern chain of responsibility design pattern
Question: Based on this question, I tried to simplify the use case with simpler model,
Let me know if you have other suggests on optimizations potentially algorithmic.
#include <iostream>
#include <tuple>
#include <iostream>
class AtmHandler
{
static inline auto chain = std::make_tuple(
[](auto &amt)
{
if (amt % 50 == 0)
{
std::cout << "Number of 50 Dollar:" << amt / 50 << std::endl;
std::cout << "Request is completed so no need to forward it" << std::endl;
return true;
}
int numberOf50Dollar = amt / 50;
std::cout << "Number of 50 Dollar:" << numberOf50Dollar << std::endl;
amt %= 50;
return !amt;
},
[](auto &amt)
{
if (amt % 20 == 0)
{
std::cout << "Number of 20 Dollar:" << amt / 20 << std::endl;
std::cout << "Request is completed so no need to forward it" << std::endl;
return true;
}
int numberOf20Dollar = amt / 20;
std::cout << "Number of 20 Dollar:" << numberOf20Dollar << std::endl;
amt %= 20;
return !amt;
},
[](auto &amt)
{
if (amt % 10 == 0)
{
std::cout << "Number of 10 Dollar:" << amt / 10 << std::endl;
std::cout << "Request is completed so no need to forward it" << std::endl;
return true;
}
std::cout << "!!!!!!!!!!!!!!!!!!!Can Not with draw this amout please enter correct amount" << std::endl;
return false;
}); | {
"domain": "codereview.stackexchange",
"id": 44479,
"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++, design-patterns, c++20",
"url": null
} |
c++, design-patterns, c++20
public:
bool parse(int value)
{
bool result;
auto handle = [&](auto &h)
{
return result = h(value);
};
std::apply([&](auto &&...xs)
{ (handle(xs) || ...); },
chain);
return result;
}
};
int main()
{
AtmHandler handler;
std::cout << handler.parse(530) << std::endl;
}
Answer: You wouldn't use the chain of responsibility for converting an amount of money into a number of bills, there are much better ways to solve that problem. But let's forget that for now. There are still some other improvements possible:
Use '\n' instead of std::endl
Prefer to use '\n' instead of std::endl; the latter is equivalent to the former, but also forces the output to be flushed, which is usually unnecessary and might impact performance.
Avoid code duplication
You already duplicated a lot of code by using the chain-of-responsibility pattern for this problem, as the three handlers look very much alike. However, even within one handler you have duplication. Here's one way to address all that duplication:
template<std::size_t Denomination>
static inline auto billHandler = [](auto &amount) {
std::size_t numberOfBills = amount / Denomination;
std::cout << "Number of " << Denomination << " Dollar bills: "
<< numberOfBills << '\n';
amount -= numberOfBills * Denomination;
if (!amount) {
std::cout << "Request is completed so no need to forward it.\n"
}
return !amount;
};
static inline auto chain = std::make_tuple(
billHandler<50>,
billHandler<20>,
billHandler<10>,
[](auto &amount) {
std::cout << "Cannot handle the change!\n";
return false;
}
); | {
"domain": "codereview.stackexchange",
"id": 44479,
"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++, design-patterns, c++20",
"url": null
} |
c++, design-patterns, c++20
Simplify parse()
Your parse() function is unnecessarily complex. There is no need for the lambda handle, and since std::apply() will return the return value of the function it calls, you can use that to directly generate the return value of parse():
bool parse(auto value)
{
return std::apply([&](const auto&... handler) {
return (handler(value) || ...);
}, chain);
}
There is no need to make a class
If there is only one member function, and no state is stored in an object of class AtmHandler, the class is unnecessary. Instead, you could write a free function parse(). | {
"domain": "codereview.stackexchange",
"id": 44479,
"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++, design-patterns, c++20",
"url": null
} |
performance, c, linked-list, unit-testing
Title: A singly linked list implementation
Question: Here's yet another implementation of a singly linked list. You may base your review on the following questions:
Review goals:
Is the API well thought of?
Does this design include undefined behavior, allow unnecessary flexibility, or make unnecessary assumptions? Are there arbitrary details in the design?
Does the design handle special cases, such as an empty list?
Does any function do more than one task? Do all functions follow the Single Responsibility Principle?
Can any of the expressions in my code overflow / underflow?
Have I used any C idioms in a questionable way?
Am I referencing memory that I have no right to touch? Do you see any memory leaks in the code?
Do you approve of my doxygen-styled comments? I was introduced to it in my last post.
What features is my list missing?
Was I able to successfully abstract away the implementation?
Are the tests well thought of? I believed the process of testing one's code must be complicated, and never did it. But it turned out to be quite rewarding and uncomplicated.
How can I make the list more generic?
How can I improve my code?
Code:
list.h:
#ifndef LIST_H
#define LISH_H 1
/* The header is meant for users of the code. So in there I document the interface:
* how to use it, preconditions and postconditions, etcetera.
*
* The .c file is for maintainers. In there, I document the implementation:
* how things work internally, and why they work that way.
*/
struct ll_node;
/**
* @brief ll_tally() shall count the number of elements in the list.
* @param head - A pointer to the head of the list.
* @return Upon successful return, ll_tally() returns number
* of elements present.
*/
extern intmax_t ll_tally (const struct ll_node *head); | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
/**
* @brief ll_push_node() shall push a new node to the front of the list.
* @param head - A pointer to a pointer to the head of the list.
* @param data - The value of the element to initialize the node with.
* @return Upon successful return, ll_push node returns true. Otherwise it
* returns false to indicate an allocation failure.
* @warning The caller is responsible for ensuring that the head pointer is
* not NULL. Failing to comply could result in unexpected program
* termination and potential loss of data.
*/
extern bool ll_push_node (struct ll_node **head, intmax_t data);
/**
* @brief ll_delete() shall free all the elements in the list. Allows head to be NULL
* to mimic free (NULL), in which case no operation is performed.
* @param head - A pointer to the head of the list.
* @return This function returns nothing.
*/
extern void ll_delete (struct ll_node *head);
/**
* @brief ll_build_head() shall build a linked list by inserting nodes at the
* head of the list.
* @param size - The initial number of nodes in the list.
* @param data[size] - An optional array to initialize the values of the elements
* of the nodes with. If data is NULL pointer, the elements
* of all nodes are initialized to 0.
* @return Upon successful return, ll_build_head() shall return a pointer to the
* head of the list. Otherwise, it shall return a NULL pointer to indicate
* a memory allocation failure.
*/
extern struct ll_node *ll_build_head (size_t size,
const intmax_t data[size]); | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
/**
* @brief ll_build_tail() shall build a linked list by inserting the first
* node at the head, and henceforth at the tail.
* @param size - the initial number of nodes in the list.
* @param data[size] - an optional array to initialize the values of the
* elements of the nodes with. If data is a NULL pointer,
* the elements of the nodes are initialized to 0.
* @return Upon successful return, ll_build_tail() shall return a pointer
* to the head of the list. Otherwise, it shall return a NULL pointer
* to indicate a memory allocation failure.
*/
extern struct ll_node *ll_build_tail (size_t size,
const intmax_t data[size]);
/**
* @brief ll_print() prints the value of all the elements associated with a node.
* @param head - A pointer to the head of the linked list. Allows head
* to be NULL, in which case no operation is performed.
* @return Upon successful return, ll_print return the number of bytes
* written.
*/
extern int ll_print (const struct ll_node *head);
/**
* @brief ll_find_node() shall search the list for the node at index index.
* @param head - a pointer to the head of the list.
* @index index - the index of the node to return.
* @return Upon successful return, ll_find_node() shall return a pointer
* the node. Otherwise, it returns a NULL pointer to indicate failure.
* A NULL pointer would also be returned for an empty list, i.e.
* a NULL head pointer.
*/
extern struct ll_node *ll_find_node (struct ll_node *head, size_t index); | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
/**
* @brief ll_pop_node() pops the first node pointed to by head.
* @param head - a pointer to pointer to the head of the list.
* @return Upon successful return, ll_pop_node() shall free the
* first node and return the value of the element associated
* with the node pointed to by head.
* @warning The caller is responsible for ensuring that the head pointer and
* the pointer pointed to by head is not NULL. Failing to comply
* could result in unexpected program termination and potential loss
* of data.
*/
extern intmax_t ll_pop_node (struct ll_node **head);
/**
* @brief ll_update_node() shall update the value of the element of the first
* node that matches the value of old_data.
* @param head - A pointer to the head of the list.
* @param old_data - The value of the element associated with a node to update.
* @param new_data - THe new value to initialize the element with.
* @return ll_update_node() returns nothing.
* @warning The caller is responsible for ensuring that the head pointer is
* not NULL. Failing to comply could result in unexpected program
* termination and potential loss of data.
*/
extern void ll_update_node (struct ll_node *head, intmax_t old_data,
intmax_t new_data);
/**
* @brief ll_append_node() shall append a new node to the end of the list.
* @param head - A pointer to the head of the node.
* @param data - The value to initialize the element associated with
* the new node.
* @return Upon successful return, ll_append_node() returns the value of head
* that was passed in. ELse, it returns a NULL pointer to indicate
* allocation failure.
*/
extern void *ll_append_node (struct ll_node *head, intmax_t data); | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
/**
* @brief ll_insert_pos() shall insert a new node at position index
* of the list.
* @param head - A pointer to pointer to the head of the list.
* @param index - The index of the node to insert at.
* @param data - The value to initialize the element associated with
* the new node.
* @return Upon successful return, ll_insert_pos() shall return true.
* Otherwise, it returns false to indicate a memory allocation failure.
* @warning The caller is responsible for ensuring that the head pointer is
* not NULL. Failing to comply could result in unexpected program
* termination and potential loss of data.
*/
extern bool ll_insert_pos (struct ll_node **head, size_t index,
intmax_t data);
/**
* @brief ll_search() shall search each node of the list pointed to by head
* for data.
* @param head - A pointer to the head of the list.
* @param data - The value to search for.
* @return Upon successful return, ll_search() returns true. Otherwise it returns
* false to indicate failure.
*/
extern bool ll_search (const struct ll_node *head, intmax_t data);
/**
* @brief ll_pop_end() pops the node at the end of the list.
* @param head - A pointer to a pointer to the head of the list.
* @return Upon successful return, ll_pop_end() frees the node and
* returns the value of the element associated with the node.
* @warning The caller is responsible for ensuring that both head and
* the pointer pointed to by head is not NULL. Failure to comply
* could result in unexpected program termination and potential
* loss of data.
*/
extern intmax_t ll_pop_end (struct ll_node **head); | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
/**
* @brief ll_pop_pos() pops the node at index index of the list.
* @param head - A pointer to a pointer to the head of the node.
* @param index - The index of the node to pop.
* @return Upon successful return, ll_pop_pos() frees the node at
* index index and returns the value associated with that node.
* Otherwise, it returns INTMAX_MIN to indicate failure.
*/
extern intmax_t ll_pop_pos (struct ll_node **head, size_t index);
/**
* @brief ll_get_data() shall obtain the value of the element associated with
* the node pointed to by head.
* @param head - A pointer to a node.
* @return Upon successful return, ll_get_data() returns the value of the
* node's element.
* @warning The caller is responsible for assuring a NULL pointer is not passed
* in. Failure to comply could result in unexpected program termination
* and potential loss of data.
*/
extern intmax_t ll_get_data (const struct ll_node *head);
/**
* @brief ll_set_data() shall update the value of the element associated with
* the node pointed to by head.
* @param head - A pointer to a node.
* @param data - The new value.
* @return ll_set_data() returns nothing.
* @warning The caller is responsible for assuring a NULL pointer is not passed
* in. Failure to comply could result in enexpected program termination
* and potential loss of data.
*/
extern void ll_set_data (struct ll_node *head, intmax_t data);
#endif
list.c:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <assert.h>
#include "list.h"
struct ll_node {
intmax_t data;
struct ll_node *next;
};
extern intmax_t ll_tally (const struct ll_node *head)
{
intmax_t count;
for (count = 0; head; head = head->next) {
count++;
}
return count;
} | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
for (count = 0; head; head = head->next) {
count++;
}
return count;
}
extern void ll_update_node (struct ll_node *head, intmax_t old_data,
intmax_t new_data)
{
assert (head);
while (head) {
if (head->data == old_data) {
head->data = new_data;
return;
}
head = head->next;
}
}
extern bool ll_insert_pos (struct ll_node **head, size_t index,
intmax_t data)
{
assert (head);
if (!(*head) || !index) {
return ll_push_node (head, data);
}
size_t count = 0;
struct ll_node *current = *head;
while (current && (count++ < index)) {
current = current->next;
}
struct ll_node *new_node = realloc (0, sizeof *new_node);
if (!new_node) {
return false;
}
new_node->data = data;
new_node->next = current->next;
current->next = new_node;
return true;
}
extern bool ll_search (const struct ll_node *head, intmax_t data)
{
while (head) {
if (head->data == data) {
return true;
}
head = head->next;
}
return false;
}
extern intmax_t ll_get_data (const struct ll_node *head)
{
assert (head);
return head->data;
}
extern void ll_set_data (struct ll_node *head, intmax_t data)
{
assert (head);
head->data = data;
}
/* Should the return type and the parameter type of struct ll_node be const-qualified? */
extern struct ll_node *ll_find_node (struct ll_node *head, size_t index)
{
size_t count = 0;
while (head) {
if (count++ == index) {
return head;
}
head = head->next;
}
return 0;
}
extern bool ll_push_node (struct ll_node **head, intmax_t data)
{
assert (head);
struct ll_node *new_node = realloc (0, sizeof *new_node); | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
struct ll_node *new_node = realloc (0, sizeof *new_node);
if (!new_node) {
return false;
}
new_node->data = data;
new_node->next = *head;
*head = new_node;
return true;
}
extern struct ll_node *ll_build_tail (size_t size,
const intmax_t data[size])
{
struct ll_node *head = 0;
struct ll_node *tail = 0;
bool ret_val = ll_push_node (&head, data ? data[0] : 0);
if (!ret_val) {
return 0;
}
tail = head;
for (size_t i = 1; i < size; i++) {
bool ret_val = ll_push_node (&(tail->next), data ? data[i] : 0);
if (!ret_val) {
ll_delete (head);
return 0;
}
tail = tail->next;
}
return head;
}
extern intmax_t ll_pop_end (struct ll_node **head)
{
assert (head && *head);
struct ll_node *prev = 0;
struct ll_node *current = *head;
while (current->next) {
prev = current;
current = current->next;
}
prev->next = current->next;
intmax_t result = current->data;
free (current);
return result;
}
/* XXX: Change to_be_popped's name */
extern intmax_t ll_pop_pos (struct ll_node **head, size_t index)
{
assert (head && *head);
if (!index) {
return ll_pop_node (head);
}
struct ll_node *prev = *head;
struct ll_node *current = ll_find_node (prev, index);
/* While this reduces the range of legally usable values in the
* list, it makes positive and negative range equally sized.
*/
if (!current) {
return INTMAX_MIN;
}
while (prev->next != current) {
prev = prev->next;
}
prev->next = current->next;
intmax_t result = current->data;
free (current);
return result;
}
extern void *ll_append_node (struct ll_node *head, intmax_t data)
{
while (head->next) {
head = head->next;
}
struct ll_node *new_node = realloc (0, sizeof *new_node); | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
if (!new_node) {
return 0;
}
new_node->data = data;
new_node->next = 0;
head->next = new_node;
return head;
}
extern struct ll_node *ll_build_head (size_t size,
const intmax_t data[size])
{
struct ll_node *head = 0;
for (size_t i = 0; i < size; i++) {
if (!ll_push_node (&head, data ? data[i] : 0)) {
ll_delete (head);
}
}
return head;
}
extern intmax_t ll_pop_node (struct ll_node **head)
{
assert (head && *head);
struct ll_node *current = *head;
intmax_t data = current->data;
*head = current->next;
free (current);
return data;
}
extern int ll_print (const struct ll_node *head)
{
assert (head);
int ret_val = 0;
for (; head; head = head->next) {
if (ret_val > 0) {
ret_val += fputc ('-', stdout);
}
ret_val += printf (" %jd ", head->data);
}
ret_val += fputc ('\n', stdout);
return ret_val;
}
extern void ll_delete (struct ll_node *head)
{
while (head) {
struct ll_node *current = head;
head = head->next;
free (current);
}
}
Unit tests:
I used the criterion framework for the tests.
tests.c:
#include <criterion/criterion.h>
#include <stdint.h>
#include "../src/list.h"
#define SIZE 10
struct ll_node *head = 0;
void setup (void)
{
intmax_t limits[SIZE];
for (intmax_t i = 0; i < SIZE; i++) {
limits[i] = i;
}
head = ll_build_head (SIZE, limits);
cr_assert (head);
}
void tear_down (void)
{
ll_delete (head);
}
TestSuite (list_tests,.init = setup,.fini = tear_down);
Test (list_tests, ll_push_node)
{
cr_assert (ll_push_node (&head, -18));
cr_assert (ll_push_node (&head, 4929320493214));
cr_assert (ll_push_node (&head, 0));
cr_assert (ll_push_node (&head, -3021302324));
cr_assert (ll_push_node (&head, 450340));
}
Test (list_tests, ll_print)
{
cr_assert (ll_print (head) > 0);
} | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
Test (list_tests, ll_print)
{
cr_assert (ll_print (head) > 0);
}
Test (list_tests, ll_find_node)
{
struct ll_node *current = ll_find_node (head, 0);
cr_assert (current && ll_get_data (current) == 9);
current = ll_find_node (head, 9);
cr_assert (current && !ll_get_data (current));
cr_assert (!ll_find_node (0, 4));
}
Test (list_tests, ll_set_data)
{
struct ll_node *current = ll_find_node (head, 0);
ll_set_data (current, 1);
cr_assert (ll_pop_node (&head) == 1);
}
Test (list_tests, ll_pop_node)
{
cr_assert (ll_pop_node (&head) == 9);
cr_assert (!ll_search (head, 9));
}
Test (list_tests, ll_tally)
{
cr_assert (ll_tally (head) == SIZE);
cr_assert (!ll_tally (0));
}
Test (list_tests, ll_update_node)
{
ll_update_node (head, 9, 90);
}
Test (list_tests, ll_append_node)
{
head = ll_append_node (head, 30);
}
Test (list_tests, ll_insert_pos)
{
cr_assert (ll_insert_pos (&head, 0, 333));
cr_assert (ll_search (head, 333));
cr_assert (ll_insert_pos (&head, 10, 444));
cr_assert (ll_search (head, 444));
}
Test (list_tests, ll_pop_end)
{
cr_assert (ll_pop_end (&head) == 0);
cr_assert (!ll_search (head, 0));
}
Test (list_tests, ll_pop_pos)
{
cr_assert (ll_pop_pos (&head, 0) == 9);
cr_assert (!ll_search (head, 9));
cr_assert (ll_pop_pos (&head, 1) == 7);
cr_assert (!ll_search (head, 7));
cr_assert (ll_pop_pos (&head, 2) == 5);
cr_assert (!ll_search (head, 5));
}
Test (list_tests, ll_search)
{
cr_assert (!ll_search (0, 4));
cr_assert (!ll_search (head, 3912932));
cr_assert (!ll_search (head, -893821));
cr_assert (ll_search (head, 9));
cr_assert (ll_search (head, 4));
cr_assert (!ll_search (0, 0));
cr_assert (!ll_search (head, 3928310888308831190123209));
}
Test (list_tests1, ll_build_tail)
{
intmax_t limits[SIZE] = { 0, 4, 30, 20, 1 };
head = ll_build_tail (SIZE, limits);
cr_assert (head); | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
ll_update_node (head, 30, 35);
cr_assert (ll_search (head, 35));
struct ll_node *current = ll_find_node (head, 2);
cr_assert (current && ll_get_data (current) == 35);
ll_delete (head);
head = ll_build_tail (SIZE, 0);
cr_assert (head && !ll_pop_node (&head));
ll_delete (head);
}
Dynamic testing:
And here is valgrind's dump:
==85== Memcheck, a memory error detector
==85== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==85== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==85== Command: tests/bin/tests
==85==
==85== error calling PR_SET_PTRACER, vgdb might block
9 - 8 - 7 - 6 - 5 - 4 - 3 - 2 - 1 - 0
[====] Synthesis: Tested: 13 | Passing: 13 | Failing: 0 | Crashing: 0
==85==
==85== HEAP SUMMARY:
==85== in use at exit: 0 bytes in 0 blocks
==85== total heap usage: 762 allocs, 762 frees, 115,093 bytes allocated
==85==
==85== All heap blocks were freed -- no leaks are possible
==85==
==85== For lists of detected and suppressed errors, rerun with: -s
==85== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Compilation:
It compiled with zero warnings.
make
mkdir lib
mkdir obj
gcc-10 -std=c17 -no-pie -g3 -ggdb -Wall -Wextra -Warray-bounds -Wconversion -Wmissing-braces -Wno-parentheses -Wpedantic -Wstrict-prototypes -Wwrite-strings -Winline -c src/list.c -o obj/list.o
ar -cvrs lib/list.a obj/list.o
a - obj/list.o | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
Answer: Acknowledging the importance of interface is a valuable idea - I don't find it in the code.
What will be use cases for what's defined in list.h?
I see
- addition of values in a predictable position
- removal of values by position or value
- update by first value
- several administrative functions
- and an ll_find_node() returning a non-const node pointer: this looks a non-minor abstraction leak (would be worse if list.h spelled out struct ll_node).
Another aspect of incomplete abstraction is the mix of parameters passed as the list: struct ll_node ** vs. struct ll_node *. And always passing a const struct ll_node ** isn't a solution. (Or is it, with ll_build_*() returning a suitable value?)
I'd like a type definition llist better, anyway:
Ideally, I don't want to be reminded there is something under the hood, just give me a handy abstract datatype.
While I remember to take ** as an indication of an output parameter with C and to not mind where I think this thing might change, this is not the case here:
I want the list to stay, modified or not, until I ll_delete() it.
I don't see
direct iteration support: return each value in turn or call a function with each value in turn passed in - ll_find_node()&ll_get/set_data() not being that bulky to read.
I think neither of ll_build_head() and ll_build_tail() spelling out its effect (let alone the difference to the other one) a consequence of this.
Having both ll_build_head() and ll_build_tail() looks uncalled for.
There should be a warning against prepending different "prefixes" to any one head/node and considering the results lists: if no sooner, calling ll_delete() for both should cause havoc.
The implementation of ll_build_head() does not follow the specification to return NULL on allocation failure.
ll_build_tail() doesn't check 0 < size. It could be coded without special-casing the first value. | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
ll_build_tail() doesn't check 0 < size. It could be coded without special-casing the first value.
For functions returning data associated with a key, I prefer *find* over *search*: in this regard, I appreciate ll_find_node(). (The current ll_search() is in or contains elsewhere - a convention such as the name of every predicate shall start is_ would result in e.g. is_containing.)
ll_tally() (length or size seem more common) specification names elements, weakly suggesting set. item would avoid this. | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
performance, c, linked-list, unit-testing
The catch-all regarding generic is void * in C. | {
"domain": "codereview.stackexchange",
"id": 44480,
"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, c, linked-list, unit-testing",
"url": null
} |
c++, serialization
Title: Integer endianness types for protocol structures
Question: Motivation
When working with storage or wire protocols, we often read or write structures containing integers with specific byte-ordering (e.g. big-endian for Internet Protocol, or little-endian for USB).
It's common to use functions such as the htons() family to convert values, but it's easy to miss a conversion (particularly if the protocol is the same endianness as the development system). Instead, I prefer to use the type system to distinguish host integers from their representations' protocol byte-order.
Known limitations (non-goals):
I haven't had a need to handle floating-point values, so only integers are handled here.
It's not suitable for protocols such as IIOP or X11 where one of the hosts chooses at run-time which endianness to use.
Implementation
#ifndef ENDIAN_HPP
#define ENDIAN_HPP
#include <array>
#include <concepts>
#include <cstdint>
#include <ranges>
#include <type_traits>
namespace endian
{
template<std::integral T, auto ReadView, auto WriteView>
struct Endian
{
// We use unsigned T for bitwise operations
using U = std::make_unsigned_t<T>;
// The underlying storage
std::array<unsigned char, sizeof (T)> data = {};
// implicit conversion from T
Endian(T value = 0)
{
auto uval = static_cast<U>(value);
for (auto& c: data | WriteView) {
c = static_cast<std::uint8_t>(uval);
uval >>= 8;
}
}
// implicit conversion to T
operator T() const
{
U value = 0;
for (auto c: data | ReadView) {
value <<= 8;
value |= c;
}
return static_cast<T>(value);
}
};
template<std::integral T>
using BigEndian = Endian<T, std::views::all, std::views::reverse>; | {
"domain": "codereview.stackexchange",
"id": 44481,
"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++, serialization",
"url": null
} |
c++, serialization
template<std::integral T>
using BigEndian = Endian<T, std::views::all, std::views::reverse>;
template<std::integral T>
using LittleEndian = Endian<T, std::views::reverse, std::views::all>;
}
#endif // ENDIAN_HPP
Tests
using endian::BigEndian;
using endian::LittleEndian;
#include <gtest/gtest.h>
// Ensure there's no padding
static_assert(sizeof (BigEndian<int>) == sizeof (int));
static_assert(sizeof (LittleEndian<int>) == sizeof (int));
TEST(big_endian, uint8)
{
std::uint8_t x = 2;
auto be = BigEndian{x};
std::array<unsigned char, 1> expected{{2}};
EXPECT_EQ(be.data,expected);
for (auto& c: be.data) { ++c; }
std::uint8_t y = be;
EXPECT_EQ(y, 3);
}
TEST(little_endian, uint8)
{
std::uint8_t x = 2;
auto le = LittleEndian{x};
std::array<unsigned char, 1> expected{{2}};
EXPECT_EQ(le.data,expected);
for (auto& c: le.data) { ++c; }
std::uint8_t y = le;
EXPECT_EQ(y, 3);
}
TEST(big_endian, uint16)
{
std::uint16_t x = 0x1234;
BigEndian be = x;
std::array<unsigned char, 2> expected{{0x12, 0x34}};
EXPECT_EQ(be.data,expected);
for (auto& c: be.data) { ++c; }
std::uint16_t y = be;
EXPECT_EQ(y, 0x1335);
}
TEST(little_endian, uint16)
{
std::uint16_t x = 0x1234;
auto le = LittleEndian{x};
std::array<unsigned char, 2> expected{{0x34, 0x12}};
EXPECT_EQ(le.data,expected);
for (auto& c: le.data) { ++c; }
std::uint16_t y = le;
EXPECT_EQ(y, 0x1335);
}
TEST(big_endian, uint32)
{
std::uint32_t x = 0x12345678;
auto be = BigEndian{x};
std::array<unsigned char, 4> expected{{ 0x12, 0x34, 0x56, 0x78 }};
EXPECT_EQ(be.data,expected);
for (auto& c: be.data) { ++c; }
std::uint32_t y = be;
EXPECT_EQ(y, 0x13355779);
}
TEST(little_endian, uint32)
{
std::uint32_t x = 0x12345678;
auto le = LittleEndian{x};
std::array<unsigned char, 4> expected{{ 0x78, 0x56, 0x34, 0x12 }};
EXPECT_EQ(le.data,expected); | {
"domain": "codereview.stackexchange",
"id": 44481,
"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++, serialization",
"url": null
} |
c++, serialization
for (auto& c: le.data) { ++c; }
std::uint32_t y = le;
EXPECT_EQ(y, 0x13355779);
}
Example usage
I'm currently using this when sending values over the wire. A simplified example, with all the error handling removed, looks something like:
struct Response {
BigEndian<std::uint16_t> seq_no;
BigEndian<std::uint16_t> sample_value;
};
We send by assigning (which implicitly converts our integer to BigEndian) and then writing the structure:
void send_result(std::uint16_t value)
{
Response r;
r.seq_no = counter++;
r.sample_value = value;
write(fd, &r, sizeof r);
}
On the receive side, we read the wire representation into the same structure (so it's bitwise identical to the sending side) and then use the conversion operator to access the data in native form:
std::uint16_t recv_result()
{
Response r;
read(fd, &r, sizeof r);
// ignore seq_no, for now
return r.sample_value;
}
Concerns
I don't like having to pass two different view adapters, but I feel that reverse | reverse would add overhead that I don't want, and I do like the simple arithmetic when we read the most-significant byte first and write the least-significant first.
I'd like optimised compilation to emit a simple load or store when converting to/from the host's native order if possible, but I'm not good enough at assembly languages to check that (I think that the result [on gobolt] implies that writing is well-optimised, but not reading, since the two read functions look so similar). And it may well be impossible, if the data are not aligned correctly for the integer type.
For systems with CHAR_BIT > 8, am I doing the right thing by assuming we pack/unpack 8 bits per char for transmission? Will it even compile, given the likely absence of std::uint8_t, and should I be masking with 0xFF instead of truncating by casting?
Should I declare a separate default constructor (using = default) instead of using the defaulted argument?
Answer: About your concerns | {
"domain": "codereview.stackexchange",
"id": 44481,
"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++, serialization",
"url": null
} |
c++, serialization
Answer: About your concerns
I'd like optimised compilation to emit a simple load or store when converting to/from the host's native order if possible, but I'm not good enough at assembly languages to check that (I think that the result [on gobolt] implies that writing is well-optimised, but not reading, since the two read functions look so similar). And it may well be impossible, if the data are not aligned correctly for the integer type.
If the compiler can see it is well-aligned, then it will most likely result in optimal code (ie, no-op for native endianness, potential use of byte-swapping instructions for non-native endianness). However, if it cannot see this, that might be a problem. You can solve that by adding an alignas specifier to make sure your types have the same alignment as T would have.
You could also make the alignment requirement part of the template parameters, but default it to be the same as alignof(T).
For systems with CHAR_BIT > 8, am I doing the right thing by assuming we pack/unpack 8 bits per char for transmission? Will it even compile, given the likely absence of std::uint8_t, and should I be masking with 0xFF instead of truncating by casting? | {
"domain": "codereview.stackexchange",
"id": 44481,
"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++, serialization",
"url": null
} |
c++, serialization
You have a big problem on such systems if you want to use it to store fixed-with types which are a multiple of 8 bits in size. It might not be possible;
I have never heard of systems where CHAR_BITS != 8 that do support uint8_t.
However, what is guaranteed in C is that you can at least tell the size of a type in the number of chars using sizeof. So you can still swap endianness, but for example on a 36-bit system with CHAR_BITS == 9, you would swap 4 9-bit characters. This might make sense if you have two 36-bit systems that have different endianness that you want to communicate between. To complicate matters even worse, there are some 32-bit systems where CHAR_BITS == 16 or even larger, as they physically cannot address anything smaller.
In any case, make sure you don't mix unsigned char and std::uint8_t like you did in your code: I recommend you stick with unsigned char, shift by CHAR_BITS, and not use any of the fixed-width types in your Endian class. If you do want to swap 8-bits at a time, then the size of the array data is wrong for CHAR_BITS > 8, it should then be (sizeof(T) * CHAR_BITS) / 8.
Should I declare a separate default constructor (using = default)? | {
"domain": "codereview.stackexchange",
"id": 44481,
"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++, serialization",
"url": null
} |
c++, serialization
Should I declare a separate default constructor (using = default)?
You already have an explicit default constructor. You could add a defaulted one if you remove the default value = 0 from the existing constructor. It probably makes sense to do this, to get the same behavior as with the built-in integral types.
More about endianness
There is more to endianness than little-endian and big-endian. There is also middle-endian. There are architectures were some types are in one endianness, others in another endianness (mostly floats vs. ints though). There are architectures where endianness is flexible, and can be changed per process or even per memory page. How are you going to handle that?
At the other extreme I would say that in practice, you nowadays don't need to worry about anything but little-endian systems where integer sizes are multiples of 8. So you only need a BigEndian class to deal with conversions to/from big-endian, nothing more. Anything else falls into the YAGNI category.
Make it constexpr
You can make the constructor and conversion operator constexpr. | {
"domain": "codereview.stackexchange",
"id": 44481,
"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++, serialization",
"url": null
} |
c++, comparative-review, stream, stl
Title: Logger that can be redirected to switch off output
Question: I am evaluating two implementations of a C++ logging mechanism.
The first implementation, below, unconditionally streams (calls the insertion operator) to the std::ostream& returned by a class's various warn()/info()/etc. functions. Those functions conditionalize which std::ostream& is returned: std::cout or a "do-nothing" std::ostream:
// log.h
#ifndef FOO_LOG_H
#define FOO_LOG_H
#include <ostream>
namespace foo {
class Log {
public:
static std::ostream& warn();
static std::ostream& info();
static std::ostream& err();
static std::ostream& debug();
};
#define CERR_ERRNO(x) \
foo::Log::err() << x << "() error " << errno << "(" << strerror(errno) << ")" << std::endl
#define DEBUG(x) \
foo::Log::debug() << "[D] | " << x << std::endl
#define ERR(x) \
foo::Log::err() << "[E] | " << x << std::endl
#define INFO(x) \
foo::Log::info() << "[I] | " << x << std::endl
#define WARN(x) \
foo::Log::warn() << "[W] | " << x << std::endl
void set_log_level(const int& level);
}
#endif // FOO_LOG_H
// log.cpp
#include "log.h"
#include <iostream>
#include <streambuf>
#include <syslog.h>
namespace {
int log_level = LOG_DEBUG;
class NullBuffer : public std::streambuf {
public:
int overflow(int c) { // Discard all output
return traits_type::not_eof(c);
}
int sync() { // Do nothing
return 0;
}
} null_buffer;
std::ostream nout(&null_buffer);
}
namespace foo {
std::ostream& Log::warn() {
return (log_level >= LOG_WARNING) ? std::cout : nout;
}
std::ostream& Log::info() {
return (log_level >= LOG_INFO) ? std::cout : nout;
}
std::ostream& Log::err() {
return (log_level >= LOG_ERR) ? std::cout : nout;
}
std::ostream& Log::debug() {
return (log_level >= LOG_DEBUG) ? std::cout : nout;
}
void set_log_level(const int& level) {
if (level >= LOG_EMERG && level <= LOG_DEBUG) {
log_level = level;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44482,
"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++, comparative-review, stream, stl",
"url": null
} |
c++, comparative-review, stream, stl
}
The second implementation, below, uses a different strategy: the macros are redefined as for-loops that define a Log instance within the loop scope; the loop-condition is initially conditional on the Log instance's log-level versus a separately-set threshold; if the condition is true (the for-loop is entered), content is streamed to to the Log instance's std::ostream while also setting a flag to ensure the for-loop is not entered a second time. I.e. the second implementation conditionalizes whether to perform any streaming at all.
// log.h
#ifndef FOO_LOG_H
#define FOO_LOG_H
#include <ostream>
#include <syslog.h>
namespace foo {
class Log {
private:
int level_; ///< The log-level for this Log instance.
public:
Log(int level);
/** Whether this Log instance should log. */
bool should_log();
/** @return The std::ostream that this Log instance outputs to. */
std::ostream& out();
};
#define CERR_ERRNO(x) \
for (foo::Log log(LOG_ERR); log.should_log(); ) { \
log.out() << x << "() error " << errno << "(" << strerror(errno) << ")" << std::endl; \
}
#define DEBUG(x) \
for (foo::Log log(LOG_DEBUG); log.should_log(); ) { \
log.out() << "[D] | " << x << std::endl; \
}
#define ERR(x) \
for (foo::Log log(LOG_ERR); log.should_log(); ) { \
log.out() << "[E] | " << x << std::endl; \
}
#define INFO(x) \
for (foo::Log log(LOG_INFO); log.should_log(); ) { \
log.out() << "[I] | " << x << std::endl; \
}
#define WARN(x) \
for (foo::Log log(LOG_WARNING); log.should_log(); ) { \
log.out() << "[W] | " << x << std::endl; \
}
void set_log_level(const int& level);
}
#endif // FOO_LOG_H
// log.cpp
#include "log.h"
#include <iostream>
#include <streambuf>
namespace {
int log_level = LOG_INFO;
}
namespace foo {
Log::Log(int level)
: level_(level >= LOG_EMERG && level <= LOG_DEBUG ? level : LOG_DEBUG) {}
bool Log::should_log() {
return level_ <= log_level;
} | {
"domain": "codereview.stackexchange",
"id": 44482,
"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++, comparative-review, stream, stl",
"url": null
} |
c++, comparative-review, stream, stl
bool Log::should_log() {
return level_ <= log_level;
}
std::ostream& Log::out() {
level_ = log_level + 1;
return std::cout;
}
void set_log_level(const int& level) {
if (level >= LOG_EMERG && level <= LOG_DEBUG) {
log_level = level;
}
}
}
I think I can summarize the difference as follows: the first implementation conditionalizes whether to stream to std::cout or a "no-nothing" std::ostream instance, and the second implementation conditionalizes whether to stream, at all, to std::cout.
Both implementations are intended to be used by the DEBUG(x)/ERR(x)/etc. macros, so I think that usability/user-friendliness can be discounted as a criteria for judgement.
Question to the code-reviewing community: is either implementation "better"?
Criteria for "better" might be efficiency, code size, and memory consumption.
I'm open to other criteria I may have overlooked from consideration.
I have a gut feeling that conditionalizing whether or not to call an insertion operator at all is more efficient than unconditionally calling the insertion operator, even if the target std::ostream instance is effectively do-nothing -- but I'm not sure I have anything to back up that gut feeling.
Does any set of criteria make one of these two implementation objectively "better"?
Answer: Both implementations share an obvious flaw: the obvious place to write logs is to the standard log stream (std::clog), not the standard output stream.
namespace foo isn't a great choice - choose a name that's more informative.
The null-object pattern used by the first version is easier to use than the conditional version, which ends up only being usable via macros. It's much easier to eliminate the macros from the first version.
The second should be a little more efficient in the case where significant work is done to retrieve the values to be logged - e.g. if we have:
INFO(some_expensive_function(my_struct)); | {
"domain": "codereview.stackexchange",
"id": 44482,
"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++, comparative-review, stream, stl",
"url": null
} |
c++, comparative-review, stream, stl
then the null-object version will perform the computation and stream it before throwing it away, whereas the conditional version won't evaluate the call at all.
As an enhancement, consider improving the macros so that they can be configured to prepend the file and line number of the call site - that can be very useful when you end up with very similar messages in different places. | {
"domain": "codereview.stackexchange",
"id": 44482,
"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++, comparative-review, stream, stl",
"url": null
} |
python, performance, beginner, formatting
Title: Calculate the price of fruits in a trade (for a game)
Question: I'm making a calculator that is supposed to calculate the price of fruits in a trade (for a game)
omg, my code is so bad and messy that its embarrassing. I'm so sorry for anyone who has to look at this
def add(u, x, y, z):
return u + x + y + z
fruit1 = input("Enter first fruit: " )
fruit2 = input("Enter second fruit: ")
fruit3 = input("Enter third fruit: ")
fruit4 = input("Enter fourth fruit: ")
# fruit 1
if fruit1 == "blank":
fruit1 = 0
elif fruit1 == "kilo":
fruit1 = 7500
elif fruit1 == "spin":
fruit1 = 10000
elif fruit1 == "chop":
fruit1 = 100000
elif fruit1 == "spring":
fruit1 = 20000
elif fruit1 == "bomb":
fruit1 = 30000
elif fruit1 == "smoke":
fruit1 = 200000
elif fruit1 == "spike":
fruit1 = 100000
elif fruit1 == "flame":
fruit1 = 450000
elif fruit1 == "falcon":
fruit1 = 200000
elif fruit1 == "ice":
fruit1 = 800000
elif fruit1 == "sand":
fruit1 = 750000
elif fruit1 == "dark":
fruit1 = 1000000
elif fruit1 == "revive":
fruit1 = 450000
elif fruit1 == "diamond":
fruit1 = 550000
elif fruit1 == "light":
fruit1 = 900000
elif fruit1 == "love":
fruit1 = 350000
elif fruit1 == "rubber":
fruit1 = 400000
elif fruit1 == "barrier":
fruit1 = 400000
elif fruit1 == "magma":
fruit1 = 1100000
elif fruit1 == "quake":
fruit1 = 1100000
elif fruit1 == "buddha":
fruit1 = 2300000
elif fruit1 == "string":
fruit1 = 1600000
elif fruit1 == "phoenix":
fruit1 = 1700000
elif fruit1 == "portal":
fruit1 = 2200000
elif fruit1 == "rumble":
fruit1 = 2450000
elif fruit1 == "paw":
fruit1 = 1750000
elif fruit1 == "blizzard":
fruit1 = 2700000
elif fruit1 == "gravity":
fruit1 = 2600000
elif fruit1 == "dough":
fruit1 = 4400000
elif fruit1 == "shadow":
fruit1 = 3300000
elif fruit1 == "venom":
fruit1 = 4000000
elif fruit1 == "control":
fruit1 = 2600000
elif fruit1 == "spirit":
fruit1 = 2500000 | {
"domain": "codereview.stackexchange",
"id": 44483,
"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, beginner, formatting",
"url": null
} |
python, performance, beginner, formatting
elif fruit1 == "control":
fruit1 = 2600000
elif fruit1 == "spirit":
fruit1 = 2500000
elif fruit1 == "dragon":
fruit1 = 4200000
elif fruit1 == "leopard":
fruit1 = 7800000
# fruit 2
if fruit2 == "blank":
fruit2 = 0
elif fruit2 == "kilo":
fruit2 = 7500
elif fruit2 == "spin":
fruit2 = 10000
elif fruit2 == "chop":
fruit2 = 100000
elif fruit2 == "spring":
fruit2 = 20000
elif fruit2 == "bomb":
fruit2 = 30000
elif fruit2 == "smoke":
fruit2 = 200000
elif fruit2 == "spike":
fruit2 = 100000
elif fruit2 == "flame":
fruit2 = 450000
elif fruit2 == "falcon":
fruit2 = 200000
elif fruit2 == "ice":
fruit2 = 800000
elif fruit2 == "sand":
fruit2 = 750000
elif fruit2 == "dark":
fruit2 = 1000000
elif fruit2 == "revive":
fruit2 = 450000
elif fruit2 == "diamond":
fruit2 = 550000
elif fruit2 == "light":
fruit2 = 900000
elif fruit2 == "love":
fruit2 = 350000
elif fruit2 == "rubber":
fruit2 = 400000
elif fruit2 == "barrier":
fruit2 = 400000
elif fruit2 == "magma":
fruit2 = 1100000
elif fruit2 == "quake":
fruit2 = 1100000
elif fruit2 == "buddha":
fruit2 = 2300000
elif fruit2 == "string":
fruit2 = 1600000
elif fruit2 == "phoenix":
fruit2 = 1700000
elif fruit2 == "portal":
fruit2 = 2200000
elif fruit2 == "rumble":
fruit2 = 2450000
elif fruit2 == "paw":
fruit2 = 1750000
elif fruit2 == "blizzard":
fruit2 = 2700000
elif fruit2 == "gravity":
fruit2 = 2600000
elif fruit2 == "dough":
fruit2 = 4400000
elif fruit2 == "shadow":
fruit2 = 3300000
elif fruit2 == "venom":
fruit2 = 4000000
elif fruit2 == "control":
fruit2 = 2600000
elif fruit2 == "spirit":
fruit2 = 2500000
elif fruit2 == "dragon":
fruit2 = 4200000
elif fruit2 == "leopard":
fruit2 = 7800000
# fruit 3
if fruit3 == "blank":
fruit3 = 0
elif fruit3 == "kilo":
fruit3 = 7500
elif fruit3 == "spin":
fruit3 = 10000
elif fruit3 == "chop":
fruit3 = 100000 | {
"domain": "codereview.stackexchange",
"id": 44483,
"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, beginner, formatting",
"url": null
} |
python, performance, beginner, formatting
elif fruit3 == "spin":
fruit3 = 10000
elif fruit3 == "chop":
fruit3 = 100000
elif fruit3 == "spring":
fruit3 = 20000
elif fruit3 == "bomb":
fruit3 = 30000
elif fruit3 == "smoke":
fruit3 = 200000
elif fruit3 == "spike":
fruit3 = 100000
elif fruit3 == "flame":
fruit3 = 450000
elif fruit3 == "falcon":
fruit3 = 200000
elif fruit3 == "ice":
fruit3 = 800000
elif fruit3 == "sand":
fruit3 = 750000
elif fruit3 == "dark":
fruit3 = 1000000
elif fruit3 == "revive":
fruit3 = 450000
elif fruit3 == "diamond":
fruit3 = 550000
elif fruit3 == "light":
fruit3 = 900000
elif fruit3 == "love":
fruit3 = 350000
elif fruit3 == "rubber":
fruit3 = 400000
elif fruit3 == "barrier":
fruit3 = 400000
elif fruit3 == "magma":
fruit3 = 1100000
elif fruit3 == "quake":
fruit3 = 1100000
elif fruit3 == "buddha":
fruit3 = 2300000
elif fruit3 == "string":
fruit3 = 1600000
elif fruit3 == "phoenix":
fruit3 = 1700000
elif fruit3 == "portal":
fruit3 = 2200000
elif fruit3 == "rumble":
fruit3 = 2450000
elif fruit3 == "paw":
fruit3 = 1750000
elif fruit3 == "blizzard":
fruit3 = 2700000
elif fruit3 == "gravity":
fruit3 = 2600000
elif fruit3 == "dough":
fruit3 = 4400000
elif fruit3 == "shadow":
fruit3 = 3300000
elif fruit3 == "venom":
fruit3 = 4000000
elif fruit3 == "control":
fruit3 = 2600000
elif fruit3 == "spirit":
fruit3 = 2500000
elif fruit3 == "dragon":
fruit3 = 4200000
elif fruit3 == "leopard":
fruit3 = 7800000
# fruit 4
if fruit4 == "blank":
fruit4 = 0
elif fruit4 == "kilo":
fruit4 = 7500
elif fruit4 == "spin":
fruit4 = 10000
elif fruit4 == "chop":
fruit4 = 100000
elif fruit4 == "spring":
fruit4 = 20000
elif fruit4 == "bomb":
fruit4 = 30000
elif fruit4 == "smoke":
fruit4 = 200000
elif fruit4 == "spike":
fruit4 = 100000
elif fruit4 == "flame":
fruit4 = 450000
elif fruit4 == "falcon":
fruit4 = 200000 | {
"domain": "codereview.stackexchange",
"id": 44483,
"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, beginner, formatting",
"url": null
} |
python, performance, beginner, formatting
elif fruit4 == "flame":
fruit4 = 450000
elif fruit4 == "falcon":
fruit4 = 200000
elif fruit4 == "ice":
fruit4 = 800000
elif fruit4 == "sand":
fruit4 = 750000
elif fruit4 == "dark":
fruit4 = 1000000
elif fruit4 == "revive":
fruit4 = 450000
elif fruit4 == "diamond":
fruit4 = 550000
elif fruit4 == "light":
fruit4 = 900000
elif fruit4 == "love":
fruit4 = 350000
elif fruit4 == "rubber":
fruit4 = 400000
elif fruit4 == "barrier":
fruit4 = 400000
elif fruit4 == "magma":
fruit4 = 1100000
elif fruit4 == "quake":
fruit4 = 1100000
elif fruit4 == "buddha":
fruit4 = 2300000
elif fruit4 == "string":
fruit4 = 1600000
elif fruit4 == "phoenix":
fruit4 = 1700000
elif fruit4 == "portal":
fruit4 = 2200000
elif fruit4 == "rumble":
fruit4 = 2450000
elif fruit4 == "paw":
fruit4 = 1750000
elif fruit4 == "blizzard":
fruit4 = 2700000
elif fruit4 == "gravity":
fruit4 = 2600000
elif fruit4 == "dough":
fruit4 = int(4400000)
elif fruit4 == "shadow":
fruit4 = 3300000
elif fruit4 == "venom":
fruit4 = 4000000
elif fruit4 == "control":
fruit4 = 2600000
elif fruit4 == "spirit":
fruit4 = 2500000
elif fruit4 == "dragon":
fruit4 = 4200000
elif fruit4 == "leopard":
fruit4 = 7800000
print(fruit1, "+", fruit2, "+", fruit3, "+", fruit4, "=", fruit1 + fruit2 + fruit3 + fruit4)
Answer: zomg, my eyes are bleeding, it is copy-n-paste, copy-n-paste, make it stop!
Two bits of advice:
define a helper() already
prefer a dict mapping over endless if / elif / elif / elif ...
You require a mapping from string to integer.
Model it along these lines:
def price_of(fruit_name: str) -> int:
...
What goes in the body?
Define a dict like this:
name_to_price = {
"blank": 0,
"kilo": 7500,
"spin": 10000,
...
}
Then your helper can return name_to_price[fruit_name].
You wish to solicit user input several times. Good.
Then call the helper several times, as well.
DRY. | {
"domain": "codereview.stackexchange",
"id": 44483,
"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, beginner, formatting",
"url": null
} |
javascript, beginner, formatting
Title: code to format text input to 2 decimal places before computation
Question: I have this piece of code that checks the input of a text box before I compute for my main logic. This looks like it should be refactored but I'm currently stumped how to do so. The only thing that comes to mind is to make 2 functions "processDecimal" and "processInt" and I just copy the code under their respective if condition but it just feels wrong. Any help?
function inputChanges(element) {
let elm = document.getElementById(element.id);
let val = elm.value;
let isDecimal = elm.hasAttribute("decimal") ? true : false;
if (isDecimal) {
if (parseFloat(val) == 0 || val == "") {
elm.value = "0.00";
} else {
elm.value = isNaN(parseFloat(val)) ? "0.00" : parseFloat(val).toFixed(2);
}
}else {
if (parseInt(val) == 0 || val == "") {
elm.value = "0";
} else {
elm.value = isNaN(parseInt(val)) ? "0" : parseInt(val);
}
}
computeTemperature();
}
Answer: I would say
if (parseFloat(val) == 0 || val == "") {
elm.value = "0.00";
} else {
elm.value = isNaN(parseFloat(val)) ? "0.00" : parseFloat(val).toFixed(2);
}
is redundant. You can simply use elm.value = isNaN(parseFloat(val)) ? "0.00" : parseFloat(val).toFixed(2);.
The same holds true for the integer evaluation. This
if (parseInt(val) == 0 || val == "") {
elm.value = "0";
} else {
elm.value = isNaN(parseInt(val)) ? "0" : parseInt(val);
}
can be reduced to elm.value = isNaN(parseInt(val)) ? "0" : parseInt(val);
From a "Code Smell" perspective, it reduces cognitive complexity by reducing the number of logical paths | {
"domain": "codereview.stackexchange",
"id": 44484,
"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, beginner, formatting",
"url": null
} |
c++, design-patterns
Title: Modern state machine
Question: Based on previous examples and code submitted, I wrote this simple state machine, let me know if you have other suggests on optimizations potentially algorithmic.
#include <iostream>
#include <tuple>
#include <array>
#include <unordered_map>
#include <functional>
#include <string_view>
enum AccountTypes
{
Red,
Silver,
Gold,
AccountTypesNum
};
class Account
{
public:
Account(std::string owner)
: owner_{std::move(owner)},
withDrawFunctrs_{// red
[this](double amount)
{
double newAmount = amount + serviceFee_;
if (balance_ - newAmount < lowerLimit_)
{
std::cout << "No funds available for withdrawal!\n";
}
else
{
balance_ -= newAmount;
}
},
[this](double amount) // silver
{ balance_ -= amount; },
[this](double amount) //gold
{ balance_ -= amount; }},
stateChangeFunctrs_{ | {
"domain": "codereview.stackexchange",
"id": 44485,
"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++, design-patterns",
"url": null
} |
c++, design-patterns
stateChangeFunctrs_{
[this]() //red
{
if (balance_ > upperLimit_)
{
accountType_ = Silver;
unpack();
}
},
[this]() // silver
{
if (balance_ < lowerLimit_)
{
accountType_ = Red;
unpack();
}
else if (balance_ > upperLimit_)
{
accountType_ = Gold;
unpack();
}
},
[this]() //gold
{
if (balance_ < 0.0)
{
accountType_ = Red;
unpack();
}
else if (balance_ < lowerLimit_)
{
accountType_ = Silver;
unpack();
}
else if (balance_ > upperLimit_)
{
std::cout << "Your account is too big now. Please consider using other account types\n";
}
}},
accountType_{Silver}
{
unpack();
}
void deposit(double amount)
{
balance_ += amount;
stateChangeFunctrs_[accountType_]();
print("Deposited", amount);
}
void withdraw(double amount)
{
withDrawFunctrs_[accountType_](amount);
stateChangeFunctrs_[accountType_]();
print("Withdrew", amount);
}
void payInterest()
{
balance_ = balance_ * (interest_ / 100);
stateChangeFunctrs_[accountType_]();
} | {
"domain": "codereview.stackexchange",
"id": 44485,
"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++, design-patterns",
"url": null
} |
c++, design-patterns
private:
void print(std::string_view action, double amount)
{
std::cout << action << " $" << amount << '\n';
std::cout << "Balance $" << balance_ << '\n';
std::cout << "Status " << stateName_ << '\n';
std::cout << "\n";
}
static inline std::unordered_map<AccountTypes, std::tuple<double, double, double, double, std::string_view>> thresholds_ // reference data
{
// intrest, lower, upper, service_fee
{Red, {0.0, -100.0, 0.0, 15.0, "Red"}},
{Silver, {1.0, 0.0, 1000.0, 0, "Silver"}},
{Gold, {5.0, 1000.0, 1000'000.0, 0, "Gold"}}};
void unpack()
{
std::tie(interest_, lowerLimit_, upperLimit_, serviceFee_, stateName_) = thresholds_[accountType_];
}
std::string owner_;
double balance_;
double interest_;
double lowerLimit_;
double upperLimit_;
double serviceFee_;
using ActionCallBack = std::array<std::function<void(double)>, AccountTypesNum>;
using VoidCallBack = std::array<std::function<void()>, AccountTypesNum>;
ActionCallBack withDrawFunctrs_;
VoidCallBack stateChangeFunctrs_;
AccountTypes accountType_;
std::string_view stateName_;
};
int main()
{
Account account("Dr. Who");
account.withdraw(10.00);
account.withdraw(30.00);
account.withdraw(70.00);
account.deposit(234.00);
account.deposit(5000.00);
account.withdraw(5200.00);
account.deposit(1500.00);
account.deposit(1.00);
account.withdraw(1200.00);
account.deposit(10001200.00);
account.deposit(1200.00);
}
Answer: Move AccountType into Account
You can nest namespaces, classes and enums in C++. Consider writing:
class Acount {
enum Type {
Red,
…
};
…
}; | {
"domain": "codereview.stackexchange",
"id": 44485,
"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++, design-patterns",
"url": null
} |
c++, design-patterns
Keep related data together in a struct
thresholds_ is a map from account type to a tuple of stuff. The problem with std::tuple is that it's harder to get data into and out of it, and the elements of the tuple don't have a name, so you have to be very careful and remember the correct order all the time.
Furthermore, given an account type, you also have a withdrawal function and a state change function. It would be nice of those were not in separate arrays, because now you have to ensure all those containers have the same ordering.
Using std::function to store the withdrawal and state change functions is one way to store them into a map or an array, but it makes the code more messy than necessary. I think pointers to member functions are a better choice here.
Consider this instead:
class Account {
…
void withdraw_red(double amount) {
double newAmount = amount + state_[accountType_].serviceFee;
…
}
void withdraw_other(double amount) {
balance_ -= amount;
}
void change_red() {
if (balance_ > state_[accountType_].upperLimit)
accountType_ = Silver;
}
…
struct State {
std::string name;
double interest;
double lowerLimit;
double upperLimit;
double serviceFee;
void (Account::* withdraw)(double);
void (Account::* change)();
};
static inline const State states_[] = {
{"Red", 0.0, -100.0, 0.0, 15.0,
&Account::withdraw_red, &Account::change_red)},
{"Silver", 1.0, 0.0, 1000.0, 0,
&Account::withdraw_other, &Account::change_silver)},
{"Gold", 5.0, 1000.0, 1000'0000.0, 0,
&Account::withdraw_other, &Account::change_gold)},
};
…
public:
…
void withdraw(double amount) {
(this->*states_[accountType_].withdraw)(amount);
(this->*states_[accountType_].change)();
print("Withdrew", amount);
}
}; | {
"domain": "codereview.stackexchange",
"id": 44485,
"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++, design-patterns",
"url": null
} |
c++, design-patterns
Avoid storing data unnecessarily
You have the account limits in a map, but you also copy that into non-static member variables everytime you change the account type. But that is duplicating the data that was already there, so you are using more memory than necessary. And now you had to spend a lot of effort trying to keep things in sync by calling unpack() every time you change the account type. It is easy to forget to do that in one place, and then you'll have a program that seems to be working fine, but actually has a bug.
In the above example I just accessed states_[accountType_] everywhere. If you think that's a lot to type, you could create a helper function for that:
State& state() const {
return states_[accountType_];
}
Do you need a state machine?
This particular program doesn't need to be implemented as a state machine. I would keep the array of properties for each account type, like the interest rate and the limits, but I would just put all the logic into a few functions. Most of it is just checking against the upperLimit and lowerLimit of an account type, and adjusting the type accordingly. Note that you can modify the value of an enum variable programmatically:
// raise type:
accountType_ = Type(int(accountType_) + 1);
// lower type:
accountType_ = Type(int(accountType_) - 1);
Of course, care should be taken that the enum values are consecutive, and that you don't raise or lower it to a non-existing value. You could also consider not using an enum type to hold the account type, just use an integer.
Remove the service fee
This is a terrible practice, especially if you only charge it for accounts with low funds. | {
"domain": "codereview.stackexchange",
"id": 44485,
"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++, design-patterns",
"url": null
} |
javascript, jquery, html, css, html5
Title: Sign Up Page - A mini Frontend Project
Question: I have designed a a small frontend project, a sign-up page. It uses HTML, CSS, JavaScript and jQuery. Being a beginner to frontend development, I want to adapt to all the best practices. I am looking forward to all your feedback.
My website has the following features:
View the optimal layout for the site depending on their device's screen size
See hover states for all interactive elements on the page
Receive an error message when the form is submitted if:
Any input field is empty.
The email address is not formatted correctly (i.e. a correct email address should have this structure: name@host.tld).
CODE :
function isEmail(email) {
var regex = /^([a-zA-Z0-9_.+-])+\@@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
}
$("button").on("click", function(){
if (!$(".box1").val()) {
$(".box1").val(" Name cannot be empty").show();
$(".box1").css("color", "red");
}
if (!$(".box2").val()) {
$(".box2").val(" Name cannot be empty").show();
$(".box2").css("color", "red");
}
if (!$(".box3").val()) {
$(".box3").val(" Email cannot be empty").show();
$(".box3").css("color", "red");
}
var email = $(".box3").val();
if (!isEmail(email)){
$(".box3").val(" Looks like this is not an email").show();
$(".box3").css("color", "red");
}
if (!$(".box4").val()) {
$(".box4").val(" Password cannot be empty").show();
$(".box4").css("color", "red");
$(".box4").get(0).type = 'text';
}
})
body {
background-image: url(images/bg-intro-desktop.png);
background-color: hsl(0, 100%, 74%);
font-family: "Poppins";
}
h1 {
color: white;
font-size: 45px;
line-height: 50px;
}
p {
color: white;
font-family: "Poppins";
}
footer {
bottom: 0%;
width: 100%;
margin-top: 10px;
}
.attribution {
font-size: 11px;
text-align: center;
} | {
"domain": "codereview.stackexchange",
"id": 44486,
"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, jquery, html, css, html5",
"url": null
} |
javascript, jquery, html, css, html5
.attribution {
font-size: 11px;
text-align: center;
}
.attribution a {
color: hsl(228, 45%, 44%);
}
.parent {
margin-top: 8%;
display: flex;
}
.left-div {
padding: 5% 0% 0% 10%;
width: 35%;
text-align: left;
flex: auto;
}
.right-div {
flex: auto;
width: 50%;
}
.offer-div {
color: white;
background-color: hsl(248, 32%, 49%);
text-align: center;
margin: auto;
margin-bottom: 20px;
margin-left: 10%;
padding: 2%;
width: 55%;
box-shadow: 5px 5px rgba(0, 0, 0, 0.5);
border-radius: 4%;
}
.signup-box {
background-color: white;
max-width: 55%;
height: 75%;
box-shadow: 5px 5px rgba(0, 0, 0, 0.5);
border-radius: 4%;
margin: auto;
margin-left: 10%;
padding: 3%;
}
.input-box {
display: block;
width: 90%;
padding: 3%;
margin: auto;
margin-bottom: 20px;
border-radius: 3%;
border-color: rgb(226 211 211);
font-family: "Poppins";
font-weight: bold;
}
input[type=text]:focus {
outline: 1px solid hsl(248, 32%, 49%);
}
.btn {
background-color: hsl(154, 59%, 51%);
color: white;
display: block;
width: 97%;
padding: 3%;
border: none;
border-radius: 3%;
margin: auto;
margin-top: 20px;
margin-bottom: 20px;
font-family: "Poppins";
}
.btn:hover{
background-color: blue;
cursor: pointer;
}
#terms {
font-size: 10px;
text-align: center;
color: gray;
}
@media only screen and (max-width: 500px){
body{
background-image: url(./images/bg-intro-mobile.png);
}
h1{
font-size: 40px;
line-height: 40px;
} | {
"domain": "codereview.stackexchange",
"id": 44486,
"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, jquery, html, css, html5",
"url": null
} |
javascript, jquery, html, css, html5
h1{
font-size: 40px;
line-height: 40px;
}
.parent {
margin-top: 50px;
display: block;
}
.left-div {
display: block;
padding: 0%;
margin: auto;
text-align: justify;
width: 80%;
}
.offer-div {
margin: auto;
margin-bottom: 20px;
margin-left: 25px;
padding: 2%;
width: 75%;
}
.signup-box {
max-width: 75%;
height: 75%;
margin: auto;
margin-left: 25px;
padding: 3%;
}
.right-div {
display: block;
margin: auto;
margin-left: 5%;
width: 100%;
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- displays site properly based on user's device -->
<link rel="icon" type="image/png" sizes="32x32" href="./images/favicon-32x32.png">
<title>Frontend Mentor | Sign Up</title>
<!--CSS Links-->
<link rel="stylesheet" href="styles.css">
<!--Google Fonts-->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
</head>
<body> | {
"domain": "codereview.stackexchange",
"id": 44486,
"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, jquery, html, css, html5",
"url": null
} |
javascript, jquery, html, css, html5
<main>
<div class="parent">
<div class="left-div">
<h1> Learn to code by watching others </h1>
<p> See how experienced developers solve problems in real-time. Watching scripted tutorials is great, but understanding how developers think is invaluable.</p>
</div>
<div class="right-div">
<div class="offer-div">
<b>Try it free 7 days </b> then $20/mo. thereafter
</div>
<div class="signup-box">
<input class="input-box box1" type="text" placeholder="First Name">
<input class="input-box box2" type="text" placeholder="Last Name">
<input class="input-box box3" type="text" placeholder="Email Address">
<input class="input-box box4" type="password" placeholder="Password">
<button class="btn">Claim your free trial</button>
<p id="terms">By clicking the button, you are agreeing to our <span style="color: hsl(0, 100%, 74%) ;">Terms and Services</span></p>
</div>
</div>
</div>
</main>
<footer>
<p class="attribution">
Challenge by <a href="https://www.frontendmentor.io/profile/chayansurana3" target="_blank">Frontend Mentor</a>.
Coded by <a href="https://github.com/chayansurana3" target="_blank">Chayan Surana</a>.
</p>
</footer>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="./index.js"></script>
</body>
</html>
Live Site URL
Problem Statement
Solution Repository
Answer: First, I want to commend you on your organization! Your repo is clean, your code is well organized, and it's nicely documented.
You did a good job overall reproducing the design. Some of the notable deviations from the design files are: | {
"domain": "codereview.stackexchange",
"id": 44486,
"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, jquery, html, css, html5",
"url": null
} |
javascript, jquery, html, css, html5
The border, border-radius, and border-color on the form inputs. The color should change on hover.
The box-shadow, border-radius, text case (should be uppercase), and hover color on the form button.
The font-weight on the terms link.
The form border-radius.
The font-size on the main heading should be smaller on mobile. I can see how you might interpret the images to show the alignment as justified, but justify isn't great for readability. I would set it to left alignment on desktop and center on mobile. There's quite a lot of additional spacing around the heading on mobile.
Ditto on the alignment of the paragraph text.
The form validation styles. While clever to add the error messages to the input, it doesn't produce a good UX. Users have to select the error message and delete it to add the correct input value. Also, your code could overwrite a partially correct value (as you can see with the email value). Most importantly, the error message in the field would result in the "required" validation returning true when the submit button is clicked again!
Generally, I would check the spacing, sizing, and line-height for all of the elements closely and make adjustments as needed.
In response to your question about best practices, here's where I'd focus: | {
"domain": "codereview.stackexchange",
"id": 44486,
"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, jquery, html, css, html5",
"url": null
} |
javascript, jquery, html, css, html5
Revisit your markup and make sure you're using the right element types. For example, make sure that you use a <form> to wrap your inputs instead of a div. Make sure that your markup is valid. Use a validator. And particularly for forms, you want to make sure you're using the right attributes. If you're interviewing, make sure that you can talk effectively about the proper use of each element you chose (e.g., how your choices affect accessibility and SEO, and it's important to be able to explain what is valid according to the specs).
Similarly, accessibility is not just a hot topic for employers (who can be liable for millions in regulatory fines and civil suits if their sites are not accessible), it's also the right thing to do. Even though this project isn't a production app, use it to demonstrate your knowledge and skills in this area. If you don't know or have any experience with accessibility, this is a great and safe way to experiment and learn. Start here and make sure to focus on forms, which require particular care.
Practice mobile-first. A good rule of thumb is that if you're writing your media-queries using max-width in them, you're doing it wrong . Seriously, this is an important concept to learn and practice, but it'll also make your life easier in the end.
They say that naming things is the hardest part about being a developer and I'm sure nothing could be truer. That said, something you could definitely improve is the naming of your classes in your CSS. Don't use names like right-div or left-div. Even in this project, on mobile devices, there is no "right" or "left" column, so your names are rendered meaningless. Also, avoid referring to a class as something "div" (like offer-div) or parent because those too can change as your project evolves. (Oh and by the way, never use a color name in your class names either such as "blue-button"). | {
"domain": "codereview.stackexchange",
"id": 44486,
"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, jquery, html, css, html5",
"url": null
} |
javascript, jquery, html, css, html5
Another way to improve your CSS is to favor classes in your CSS. As a general rule, you should never use an id as a selector (like #terms). If your element has an id for convenience in Javascript or use in accessible design, just add a class for CSS.
I thought you did a great job keeping your CSS streamlined. One way you could streamline it even further is with CSS grid. Once you go grid, you'll never look back .
Learn to use vanilla JavaScript. jQuery isn't useful in modern web application development so it just signals that you're missing a crucial skill if you use it. | {
"domain": "codereview.stackexchange",
"id": 44486,
"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, jquery, html, css, html5",
"url": null
} |
javascript, jquery, html, css, html5
Once again, congrats on your project.
** If you're interested to see how someone else would tackle this challenge, I did one for fun. ** | {
"domain": "codereview.stackexchange",
"id": 44486,
"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, jquery, html, css, html5",
"url": null
} |
c, array, pointers
Title: Dynamic array type using void pointers C
Question: I made my own dynamic array type using void pointers. I'd like to know what you think of my implementation. void pointers are nice but I fear they may be inefficient. The compiler cannot tell what you are doing because it has no size information. Either way i like the flexibility and the fact that i do not have to use macros as much. But what are your thoughts on this? I am still working on it and am still finding some minor bugs here and there. It has been a fun project to work on.
main.c
#include "array.h"
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
void log_int(void *p);
int main(int argc, char const *argv[])
{
/* declare an integer array. */
int *a = array_alloc(sizeof(*a), log_int);
array_reserve(a, 32);
/*
append a list 1 - 9
fixed functions usually take in local arrays
or variadic macro arguments.
*/
array_give_fixed(a, 1, 2, 3, 4, 5, 6, 7, 8, 9);
/*
array_take usually stores the values taken
from an array into a buffer.
Passing NULL causes each elelemnt taken to have
its destructor called.
*/
array_take(a, NULL, 3);
int i[2];
/* array_take returns the number of elements taken. */
for(; array_take_fixed(a, i); )
{
fprintf(stdout, "%d ", i[0]);
fprintf(stdout, "%d\n", i[1]);
}
/*
array_free calls each elements destructor
and frees the array itself.
*/
array_free(a);
return 0;
}
void log_int(void *p)
{
int *i = p;
fprintf(stderr, "integer popped %d\n", *i);
}
array.h
#ifndef ARRAY_H
#define ARRAY_H
#include <assert.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#define COUNT(a) (sizeof(a) / sizeof *a)
typedef struct {
void (*freeElem)(void *);
size_t szElem;
size_t ctElem;
size_t cpElem;
} Array_Header; | {
"domain": "codereview.stackexchange",
"id": 44487,
"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, array, pointers",
"url": null
} |
c, array, pointers
void *array_alloc(size_t szElem, void (*freeElem)(void *));
void array_free_impl(void *a);
void *array_reserve_impl(void *a, size_t capacity);
void *array_push_impl(void *a, const void *elem);
void array_pop(void *a);
void *array_give_impl(void *a, const void *elems, size_t n);
size_t array_take(void *a, void *elems, size_t n);
size_t array_szElem(const void *a);
size_t array_ctElem(const void *a);
size_t array_cpElem(const void *a);
#define array_reserve(a, capacity) do { a = array_reserve_impl(a, capacity); } while(0)
#define array_push(a, elem) do { a = array_push_impl(a, elem); } while(0)
#define array_give(a, elems, n) do { a = array_give_impl(a, elems, n); } while(0)
#define array_give_fixed(p, ...) \
do { \
p = array_give_impl( \
p, &(__typeof__(*p)[]){__VA_ARGS__}, \
sizeof((__typeof__(*p)[]){__VA_ARGS__}) \
/ sizeof(__typeof__(*p))); \
} while(0)
#define array_take_fixed(p, a) \
array_take(p, a, sizeof(a) / sizeof(*a))
#define array_free(a) do { array_free_impl(a); a = NULL; } while(0)
#endif /* ARRAY_H */
array.c
#include "array.h"
void *array_alloc(size_t szElem, void (*freeElem)(void *))
{
void *a = malloc(sizeof(Array_Header));
Array_Header *header = a;
header->freeElem = freeElem;
header->szElem = szElem;
header->ctElem = 0;
header->cpElem = 0;
return header + 1;
}
void array_free_impl(void *a)
{
assert(a);
Array_Header *header = (Array_Header *)a - 1;
if(header->freeElem)
{
unsigned char *begin = a;
unsigned char *end = begin + header->ctElem * header->szElem;
for(; begin != end; begin += header->szElem)
{
header->freeElem(begin);
}
}
free(header);
} | {
"domain": "codereview.stackexchange",
"id": 44487,
"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, array, pointers",
"url": null
} |
c, array, pointers
void *array_reserve_impl(void *a, size_t capacity)
{
assert(a);
Array_Header *header = (Array_Header *)a - 1;
if(capacity > header->cpElem)
{
header->cpElem = capacity;
header = realloc(header, sizeof(*header) + header->cpElem * header->szElem);
a = header + 1;
assert(header);
}
return header + 1;
}
void *array_push_impl(void *a, const void *elem)
{
assert(a);
assert(elem);
Array_Header *header = (Array_Header *)a - 1;
if(header->ctElem + 1 > header->cpElem)
{
header->cpElem = (header->cpElem + 1) * 2;
header = realloc(header, sizeof(*header) + header->cpElem * header->szElem);
a = header + 1;
assert(header);
}
memcpy((unsigned char *)a + header->ctElem * header->szElem, elem, header->szElem);
++header->ctElem;
return header + 1;
}
void array_pop(void *a)
{
assert(a);
Array_Header *header = (Array_Header *)a - 1;
if(header->ctElem > 0)
{
--header->ctElem;
if(header->freeElem)
{
unsigned char *p = (unsigned char *)a + header->ctElem * header->szElem;
header->freeElem(p);
}
}
}
void *array_give_impl(void *a, const void *elems, size_t n)
{
assert(a);
assert(elems);
Array_Header *header = (Array_Header *)a - 1;
if(header->ctElem + n > header->cpElem)
{
header->cpElem = (header->cpElem + n) * 2;
header = realloc(header, sizeof *header + header->cpElem * header->szElem);
a = header + 1;
assert(header);
}
memcpy((unsigned char *)a + header->ctElem * header->szElem, elems, n * header->szElem);
header->ctElem += n;
return header + 1;
} | {
"domain": "codereview.stackexchange",
"id": 44487,
"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, array, pointers",
"url": null
} |
c, array, pointers
size_t array_take(void *a, void *elems, size_t n)
{
assert(a);
Array_Header *header = (Array_Header *)a - 1;
// if(header->ctElem >= n)
n = n > header->ctElem ? header->ctElem : n;
{
header->ctElem -= n;
if(elems)
{
memcpy(elems, (unsigned char *)a + header->ctElem * header->szElem, n * header->szElem);
}
else
{
unsigned char *begin = (unsigned char *)a + header->ctElem * header->szElem;
unsigned char *end = begin + n * header->szElem;
for(; begin != end; begin += header->szElem)
header->freeElem(begin);
}
}
return n;
}
size_t array_ctElem(const void *a)
{
assert(a);
Array_Header *header = (Array_Header *)a - 1;
return header->ctElem;
}
size_t array_cpElem(const void *a)
{
assert(a);
Array_Header *header = (Array_Header *)a - 1;
return header->cpElem;
}
size_t array_szElem(const void *a)
{
assert(a);
Array_Header *header = (Array_Header *)a - 1;
return header->szElem;
}
```
Answer: Much feedback on the recent Array List C implementation applies here too.
() around macro parameters
Good practice to enclose a macro parameters with (), yet a still remain problematic. Example:
// #define array_push(a, elem) do { a = array_push_impl(a, elem); } while(0)
#define array_push(a, elem) do { a = array_push_impl((a), (elem)); } while(0)
Check allocation success
void *a = malloc(sizeof(Array_Header));
if (a == NULL) return NULL; // add
.h file: only code necessary #include for the headers.
#include <assert.h> and perhaps others not needed in the .h file. Remove them.
Unnecessary struct
typedef struct { ... } Array_Header; not needed in the .h file. Move to the .c file.
Even better, re-define functions to use a pointer to Array_Header. | {
"domain": "codereview.stackexchange",
"id": 44487,
"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, array, pointers",
"url": null
} |
c, array, pointers
Array alignment
As OP wants to use header + 1 as the start of an array of any type, additional padding may be needed in Array_Header. Since *alloc() returns a pointer good for all alignments, to make certain header + 1 is also aligned for any type use a FAM of type max_align_t (which is an object type whose alignment is the greatest fundamental alignment).
typedef struct {
void (*freeElem)(void *);
size_t szElem;
size_t ctElem;
size_t cpElem;
max_align_t a[]; // Add
} Array_Header; | {
"domain": "codereview.stackexchange",
"id": 44487,
"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, array, pointers",
"url": null
} |
python, sqlite, decorator-pattern
Title: decorator to execute sqlite statement
Question: I'd like to wrap all my sqlite statement functions with a decorator which collects the statement and the lists of values I will inject in place of placeholders in my statement (to avoid sql injection).
Code looks like this:
#decorator
def dbexecute(func):
def withcon(*args):
conn = sqlite3.connect(sqlite_file_name)
conn.row_factory = sqlite3.Row
with conn:
fa = func(*args)
if isinstance(fa, tuple):
s, v = fa
else:
s, v = fa, ()
out = conn.execute(s, v).fetchall()
conn.close()
return out
return withcon
#statement functions that are decorated
@dbexecute
def create_user(user_settings: dict):
user_settings['id'] = str(uuid.uuid4())
columns = tuple([key for (key,value) in user_settings.items()])
values = tuple([value for (key,value) in user_settings.items()])
qmarks = tuple(['?']*len(values))
statement = f"INSERT INTO users {columns} VALUES {qmarks}".replace("'","")
return statement, values
@dbexecute
def get_all_users():
statement = "SELECT * FROM users"
return statement
First function returns values to replace the question marks with, but the second not. I had to handle this directly in the decorator, but I am not sure this is the good way to do it or maybe there is a more pythonic way than an if...else... block that checks the type of the inputs args.
Thanks for your feedback! | {
"domain": "codereview.stackexchange",
"id": 44488,
"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, sqlite, decorator-pattern",
"url": null
} |
python, sqlite, decorator-pattern
Answer: It's cool that you are experimenting, but from my point of view this is just trying to be fancy for no good reason.
How is this better than just executing the code safely at end of your create_user and get_all_users by calling designated fuction to that similar to what your decorator does?
Imho the result is the same, decomposition is the same, only the code is less confusing.
What I don't like about it the most, is the confusing naming. The method names suggest that they are "getting" or "creating" something, but in fact they are only creating input for the sql query.
If you insist on your decorator, I would say the cleanest solution would be to return empty tuple in get_all_users to be consistent with your interface. | {
"domain": "codereview.stackexchange",
"id": 44488,
"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, sqlite, decorator-pattern",
"url": null
} |
haskell
Title: Mutable IORef-based factorial example in Haskell
Question: Here is my attempt to write the infamous factorial using Data.IORef.
import Data.IORef
xgo accRef nRef = go where
go = do
acc <- readIORef accRef
n <- readIORef nRef
writeIORef accRef (acc * n)
writeIORef nRef (n - 1)
if (n > 2) then go else readIORef accRef
facM n = do
accRef <- newIORef 1
nRef <- newIORef n
xgo accRef nRef
This code is supposed to be an example for dummies on how to use IORefs, so certainly I want to keep it simple -- e.g. no tuples and no lens. But the whole xgo thing seem artificial. Can we have xgo defined within facM? What is the most idiomatic way to write IORef code like this (of course I don't mean avoiding IORef, we all know the fac n = prod [1..n] solution here).
Upd: I got it to:
facM n = do
accRef <- newIORef 1
nRef <- newIORef n
let xgo = go where {
go = do
acc <- readIORef accRef
n <- readIORef nRef
writeIORef accRef (acc * n)
writeIORef nRef (n - 1)
if (n > 2) then go else readIORef accRef
}
xgo
So there are no second accRef/nRef anymore, but there is still this xgo/go separation. Somehow I can't get xgo = do { ... } working without an intermediate go | {
"domain": "codereview.stackexchange",
"id": 44489,
"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": "haskell",
"url": null
} |
haskell
Answer: First off, there a bug, if not a very significant one - 0! is meant to be 1, but the current code returns 0. Checking if n > 1 before you do any multiplication would get around this.
Second, since acc is only ever used for updating accRef, I feel it might be cleaner to use modifyIORef instead of a readIORef followed by a writeIORef. This wouldn't apply to nRef, though, since n is actually used in multiple places
Also, I'd like to see explicit type signatures added to any top-level functions (facM and, in the original code, xgo). I find that knowing the exact type of a value often makes it much easier to understand what it is and why.
Finally, you mention being able to merge the separate xgo function into facM, but ended up having to also have an effectively identical go function to make it work. I think that might've been you running into haskell's notoriously confusing indentation rules. For instance, the following won't work:
import Data.IORef
facM :: (Num a, Ord a) => a -> IO a
facM n = do
accRef <- newIORef 1
nRef <- newIORef n
let go = do
n <- readIORef nRef
if n > 1 then do
modifyIORef accRef (* n)
writeIORef nRef (n - 1)
go
else readIORef accRef
go
because the content of that do block is to the left of the name it is bound to (go). However, either of the following will work, because the block is indented further than the name it is bound to:
import Data.IORef
facM :: (Num a, Ord a) => a -> IO a
facM n = do
accRef <- newIORef 1
nRef <- newIORef n
let
go = do
n <- readIORef nRef
if n > 1 then do
modifyIORef accRef (* n)
writeIORef nRef (n - 1)
go
else readIORef accRef
go
import Data.IORef | {
"domain": "codereview.stackexchange",
"id": 44489,
"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": "haskell",
"url": null
} |
haskell
import Data.IORef
facM :: (Num a, Ord a) => a -> IO a
facM n = do
accRef <- newIORef 1
nRef <- newIORef n
let go = do
n <- readIORef nRef
if n > 1 then do
modifyIORef accRef (* n)
writeIORef nRef (n - 1)
go
else readIORef accRef
go | {
"domain": "codereview.stackexchange",
"id": 44489,
"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": "haskell",
"url": null
} |
java
Title: Java code for generating 16bit DMX values using sine and cosine
Question: This is my try, based on good inputs from different places.
I ended up saving the DMX-values in two arrays (one for sine and one for cosine) as I guess that will make stuff easier later on when I want to add offset (and so on) to the lamps receiving the dmx-values.
This how I declare the two arrays and how the code is saving dmx-values in the two arrays:
int[] sineValues = new int[(360 * 1000) + 1];
int[] coSineValues = new int[(360 * 1000) + 1];
public void generateSineValuesInArray() {
int y = 0;
for (double x = 0; x <= 360; x = x + 0.001) {
double degrees = x;
double radians = Math.toRadians(degrees);
double sine = Math.sin(radians);
sineValues[y] = (int) ((sine * 127) * 255) + (127 * 255);
y++;
}
}
public void generateCosineValuesInArray() {
int y = 0;
for (double x = 0; x <= 360; x = x + 0.001) {
double degrees = x;
double radians = Math.toRadians(degrees);
double sine = Math.cos(radians);
coSineValues[y] = (int) ((sine * 127) * 255) + (127 * 255);
y++;
}
}
Yes, many elements in the two arrays and very small (0.001) increments in the two loops but that is what I found out was working best for getting a resolution that can do the dmx-fine so I can achieve smooth movements even at very low speeds.
This is the code for getting and sending the actual dmx-values:
public void doMovement() {
valFromArrayPan = sineValues[counter];
valFromArrayTilt = coSineValues[counter];
coarsePan = (valFromArrayPan >> 8) & 255;
finePan = valFromArrayPan & 255;
coarseTilt = (valFromArrayTilt >> 8) & 255;
fineTilt = valFromArrayTilt & 255;
//Send dmx-values
counter++;
if (counter == sineValues.length) {
counter = 1; | {
"domain": "codereview.stackexchange",
"id": 44490,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
counter++;
if (counter == sineValues.length) {
counter = 1;
}
}
This is the code and what I do for running the movement:
SineMovement SineMovement = new SineMovement();
SineMovement.generateSineValuesInArray();
SineMovement.generateCosineValuesInArray();
speed = 20000000; //Slow speed
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(SineMovement::doMovement, 0, speed, TimeUnit.NANOSECONDS);
I have tested above with a "real" 16bit moving head and I think, overall, it is working as I want it to.
Answer: Initialization
First about your idea of storing the precalculated values for sine and cosine: this is OK, and done for many different applications. But the way you initialize those arrays seems a bit complicated: | {
"domain": "codereview.stackexchange",
"id": 44490,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
I would use just one loop for sine and cosine
You should never compare a floating point number with an == or similar, as there is a chance that this never will be true due to rounding errors. In your case the <= 360 is not necessary at all and can be replaced by a < 360 without doubt because sin(0°) is the same as sine(360°)
I would not use the angle as loop counter at all - you have a nice index in the array that you want to fill, so instead use the array index as loop counter and calculate your angle from it. This way you also don't have to fiddle with degrees to radian conversion.
You can make the tables and their initialization static because the sine and cosine tables will never change, no matter how often you load that class. And it's good practise to minimize visibility, and you never need to exchange the array, so set it private static final and use a static initializer.
Naming conventions say that you should name static final fields in ALL_UPPER_SNAKE_CASE.
As long as you do double calculations, use only double literals (= add a .0 to numbers if you don't have any other decimal places) to help the compiler in optimizing the code.
Summary: I would do the initialization like this:
private static final int[] SIN_TABLE = new int[(360 * 1000) + 1];
private static final int[] COS_TABLE = new int[(360 * 1000) + 1];
private static final double INDEX_RAD_FACTOR = 2 * Math.PI / sineValues.length;
private static final double STRETCH_SIN = 127.0 * 255.0;
static {
for (int x = 0; x < sineValues.length; x++) {
double radians = x * INDEX_RAD_FACTOR;
double sine = Math.sin(radians);
SIN_TABLE[x] = (int) (Math.sin(radians) * STRETCH_SIN + STRETCH_SIN);
COS_TABLE[x] = (int) (Math.cos(radians) * STRETCH_SIN + STRETCH_SIN);
}
} | {
"domain": "codereview.stackexchange",
"id": 44490,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
Ongoing movement
repeated calculation
You should create a private method for the splitting of the high and low byte as you use it multiple times.
private int[] splitInt(int toSplit) {
int[] result = new byte[2];
result[0] = toSplit & 255;
result[1] = (toSplit >> 8) & 255;
return result;
}
Instead of an int you could also use a short, but don't use a byte because all of that datatypes are signed and byte goes from -128 to +127.
timing relevant code
Also as you are working with stuff that needs exact timing, I would not use an if in that method - the case where the condition is true and where it's not, could take a different amount of time and therefore create a weird pause if your application requires short execution times (when the "speed" is not slow, but fast). Also you should start counter with and reset it to 0 all the time - arrays are 0-based in Java.
private int counter = 0;
public void doMovement() {
int[] overallPan = splitInt(SIN_TABLE[counter]);
int[] overallTilt = splitInt(COS_TABLE[counter]);
int coarsePan = overallPan[1];
int finePan = overallPan[0];
int coarseTilt = overallTilt[1]
int fineTilt = overallTilt[0];
// TODO: Send dmx-values
counter = (counter + 1) % SIN_TABLE.length;
} | {
"domain": "codereview.stackexchange",
"id": 44490,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
// TODO: Send dmx-values
counter = (counter + 1) % SIN_TABLE.length;
}
Starting
The starting of your timed code looks quite good, with the above changes to the initialization you do no longer have to call the initialization of sine and cosine tables manually.
And I would not use nanoseconds as time unit, probably your code wouldn't be fast enough to be called that often, and also with 360000 possible steps in the sine curve, even with a microsecond resolution you would only need one third of a second to have set all possible values. Probably even that is too fast to be visible. I would not go just millisecond resolution, because then all values would need 6 minutes to be shown and thats probably to slow.
Again if speed is a long variable it deserves to be initialized with a long literal to help the compiler in optimization, this is denoted by an L at the end of the number. (And I divided the value you gave by 1000 because I reduced the resolution to microseconds.)
SineMovement SineMovement = new SineMovement();
long speed = 20000L; //Slow speed
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
executorService.scheduleAtFixedRate(SineMovement::doMovement, 0L, speed, TimeUnit.MICROSECONDS);
``` | {
"domain": "codereview.stackexchange",
"id": 44490,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
beginner, python-3.x, tic-tac-toe
Title: "Tic-Tac-Toe" implemented in Python
Question: With the following code I implemented the mini-game "Tic-Tac-Toe" in Python. However, I am still a beginner in programming and I wanted to ask if someone could give me some tips on how to make the code more elegant and better. But please don't be too strict, because as already mentioned I am a beginner.
So the code works but is not so nice/clean.
I would be very happy about answers.
from random import shuffle, seed
seed()
# Winning options are defined
WINNING_OPTIONS = [[0, 1, 2],[3, 4, 5],[6, 7, 8],[0, 3, 6],[1, 4, 7],[2, 5, 8],[0, 4, 8],[2, 4, 6]]
# Game board is created
board_fields = [box for box in range(1,10)]
def game_board():
for line in 0,3,6:
print(f"|{board_fields[line]}|{board_fields[line+1]}|{board_fields[line+2]}|")
# Start player is selected
def player_order():
liste = ["x","o"]
shuffle(liste)
return liste
# Input is checked for correctness
def input_verification():
while (user_input := "placeholder")not in board_fields:
try:
user_input = int(input(f"{xo} is now on the turn: "))
if user_input not in board_fields:
print("The input was invalid. Please try again.")
continue
board_fields[user_input-1] = xo
break
except:
print("The input was invalid. Please try again.")
continue
# Game process
game_end = False
occupied_boxes = 0
suggested_solution = []
sequence_player = player_order()
while not game_end:
for xo in sequence_player:
game_board()
input_verification()
occupied_boxes = occupied_boxes + 1 | {
"domain": "codereview.stackexchange",
"id": 44491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, python-3.x, tic-tac-toe",
"url": null
} |
beginner, python-3.x, tic-tac-toe
startpos = 0
while xo in board_fields[startpos:]:
pos = board_fields.index(xo, startpos)
if xo == "x":
suggested_solution.append(pos)
startpos = pos + 1
# The winner and the loser are recognized
for solution in WINNING_OPTIONS:
if set(solution) <= set(suggested_solution):
print(f"Great! You win, player {xo}")
game_end = True
if occupied_boxes == 9:
game_board()
print("Draw.")
game_end = True
break
Answer: Hi and welcome to the forum! I have a longer post about what I often see when someone asks for improvement, you can check it out here.
What I want to focus on though, is naming, specifically methods. Methods do stuff, so their names should be action like, e.g. print_something, check_if_player_won and so on.
Specifically, let's look at two of your methods:
game_board prints out the board. So let's name it like that: print_game_board, or print_board if it's clear from context that the game board is meant. Props to you btw, otherwise the method is fine. Most importantly, it is short, easy to understand and only does one thing. This is very important to making code easy to comprehend, other than naming.
input_verification This name is a lie. The name suggests (ignoring the naming convention) that this method takes some input and verifies it in some way, and giving back whether the input is valid or not. What it should be is something akin to get_guaranteed_input or read_valid_player_input. Note here, that the name suggests nothing about how the method works, just its intent. And the intent is to get an input that is valid and guaranteed to be so. | {
"domain": "codereview.stackexchange",
"id": 44491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, python-3.x, tic-tac-toe",
"url": null
} |
beginner, python-3.x, tic-tac-toe
Conclusion
Naming is important. Be precise, and name methods after their intent. This enables readers to understand what a method does without having to know how it accomplishes that.
Naming precisely is important, because if something is named one way but does something else, there suddenly is a lot of confusion as to what it actually does and what it should.
All that said though, getting the hang of properly naming things is hard, especially as a beginner. I also regularly rename my methods because I can think of a better name. Just keep trying and if you can't think of a better name, move on. Good thing: Most modern IDEs have a built in refactor to rename methods (and other stuff), which makes it really easy. | {
"domain": "codereview.stackexchange",
"id": 44491,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, python-3.x, tic-tac-toe",
"url": null
} |
javascript, programming-challenge, node.js, json, rest
Title: Using JavaScript to interface with REST APIs
Question: The website TryHackMe came up with a challenge that involves using HTTP requests to interface with REST APIs (here, task #14/day 9). The challenge basically involves querying a basic REST API to reconstruct a string value from the information returned by the service. Specifically, the value key has a piece of the string to be appended to a final string, and the next key has a subdirectory to visit for the next value to be appended to the final string. The solution is supposed to repeat this procedure until the value key has a value of "end".
I published a writeup that discusses this further (if the paywall is giving you problems, just open this link in private browsing ;-):
"Aleksey" (2023). Hacking REST APIs with JavaScript. JavaScript In Plain English. Link: https://javascript.plainenglish.io/hacking-rest-apis-with-javascript-ecf39e38c21f
Here are some things that I am curious about:
What are your initial & overall impressions of the code?
Is there a better way of writing an implementation?
A bit of a rehash of the second one, but what do you not like about my code (assuming that you notice flaws)?
A bit of a meta question: do you think I can present my problem & solution a little better next time?
And of course, my JavaScript solution
/*
* An implementation to the Advent of Cyber's "Requests" task.
* (Partially) ported from Hamdan (2021)'s solution
* Implemented by Aleksey
* - GitHub: https://github.com/Alekseyyy
* - Keybase: https://keybase.io/epsiloncalculus
*/
const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const xhr = new XMLHttpRequest();
const url = "http://requests.thm:3000/";
let currentPath = "";
let flag = "";
let done = false;
while (!done) {
if (currentPath.toLowerCase() === "end") {
done = true;
break;
}
xhr.open("GET", url + currentPath, false);
xhr.send(); | {
"domain": "codereview.stackexchange",
"id": 44492,
"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, programming-challenge, node.js, json, rest",
"url": null
} |
javascript, programming-challenge, node.js, json, rest
xhr.open("GET", url + currentPath, false);
xhr.send();
const myJson = JSON.parse(xhr.responseText);
flag += myJson["value"];
currentPath = myJson["next"];
}
console.log(flag);
/* References
* Hamdan, M. (2021). Python For Web Automation | TryHackMe
* Advent Of Cyber 1 Day 9. YouTube Video. Retrieved on Feb.
* 12, 2023 from: https://youtu.be/zFeLExZNPso
*/
Answer: Your questions
"What are your initial & overall impressions of the code?"
Very old school, then I noticed that this must be Node.js. Is fetch still behind a flag??? Though a synchronous request is old school as well. When possible always use asynchronous API's
Looks like you do not understand what JSON is! JSON is a transport format (file) when loaded and parsed JSON is an object like any other object.
You don't need to use bracket notation when not required. flag += myJson["value"]; is same as flag += myJson.value;
You only use bracket notation if the object property has an illegal JavaScript name eg flag += myJson["1flag"]; is valid but as myJson.1flag is a syntax error.
Prefixing my to names is only for example code and represents a name to replace with your own variables name, you should never prefix my in your own code.
Not catching errors. JSON.parse can throw, server requests can fail, yet there is no error checking in your code?
currentPath too verbose in this context and could just be path
"Is there a better way of writing an implementation?"
Yes use the fetch API and async functions. Node has fetch behind some flags eg node --experimental-fetch myCode.js
See rewrite
Note rather than break out of the while loop, the rewrite tests for path === "end" inside the while clause using a reg expression eg while (!path.match(/^end$/i)) {
"A bit of a meta question: do you think I can present my problem & solution a little better next time?" | {
"domain": "codereview.stackexchange",
"id": 44492,
"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, programming-challenge, node.js, json, rest",
"url": null
} |
javascript, programming-challenge, node.js, json, rest
I edited your question and replaced the html tag with node as it was far more relevant to the question.
Rewrite
Rewrite uses fetch API and async function.
The catch will catch both request errors and JSON parsing errors.
const url = "url";
async function doThing() {
var path = "", flag = "";
while (!path.match(/^end$/i)) {
const data = await fetch(url + path).then(res => res.json());
flag += data.value;
path = data.next;
}
return flag;
}
doThing()
.then(flag => console.log(flag))
.catch(error => console.error(error)); | {
"domain": "codereview.stackexchange",
"id": 44492,
"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, programming-challenge, node.js, json, rest",
"url": null
} |
python, python-2.x, recursion, hash-map
Title: Get value from dictionary given a list of nested keys
Question: I would like to get a deeply-nested value, for example {"a":{"b":{"c":"myValue"}} by providing the keys to traverse. I tried chaining together .get() but that didn't work for cases where some of the keys were missing—in those cases, I want to get None instead.
Could this solution be improved?
#!/usr/bin/env python
# encoding: utf-8
def nestedGet(d,p):
if len(p) > 1:
try:
return nestedGet(d.get(p[0]),p[1:])
except AttributeError:
return None
if len(p) == 1:
try:
return d.get(p[0])
except AttributeError:
return None
print nestedGet({"a":{"b":{"c":1}}},["a","b","c"]) #1
print nestedGet({"a":{"bar":{"c":1}}},["a","b","c"]) #None
Answer: Unless I'm missing something you'd like to implement, I would go for a simple loop instead of using recursion:
def nested_get(input_dict, nested_key):
internal_dict_value = input_dict
for k in nested_key:
internal_dict_value = internal_dict_value.get(k, None)
if internal_dict_value is None:
return None
return internal_dict_value
print(nested_get({"a":{"b":{"c":1}}},["a","b","c"])) #1
print(nested_get({"a":{"bar":{"c":1}}},["a","b","c"])) #None | {
"domain": "codereview.stackexchange",
"id": 44493,
"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-2.x, recursion, hash-map",
"url": null
} |
c#, amazon-web-services
Title: Reading S3 files from two different buckets but adding it to one list variable
Question: I have a below code which reads all the S3 files from a particular S3 bucket and then it adds all those files in a objectList variable.
private static async Task<List<String>> ListObjects()
{
var objectList = new List<String>();
var firstRequest = new ListObjectsV2Request()
{
BucketName = _firstS3BucketName,
MaxKeys = _configurationStateManager.GetState().MaxReferenceDataKeys
};
ListObjectsV2Response getListObjectResponse;
do
{
getListObjectResponse = await GetListObjectResponse(firstRequest);
if (getListObjectResponse != null && getListObjectResponse.S3Objects != null && getListObjectResponse.S3Objects.Count > 0)
{
foreach (var s3Object in getListObjectResponse.S3Objects)
{
// here s3Object.Key has the file name as it's prefix
objectList.Add(s3Object.Key);
}
}
firstRequest.ContinuationToken = getListObjectResponse.NextContinuationToken;
}
while (getListObjectResponse.IsTruncated);
if (getListObjectResponse == null || getListObjectResponse.S3Objects == null ||
getListObjectResponse.S3Objects.Count == 0)
{
return null;
}
return objectList;
}
private static Task<ListObjectsV2Response> GetListObjectResponse(ListObjectsV2Request _request)
{
return _adapter.ReferenceDataAdapter.ListObjectsV2Async(_request);
}
s3Object.Key has the file name in it. Format for the file name is like this - SomeFileName~MM-DD-YYYY.txt
Problem Statement
I am trying to modify the above code in such a way so that it can read some files from one S3 bucket and few other files from second S3 bucket but add all those files in the same objectList variable. Here is what I need to do: | {
"domain": "codereview.stackexchange",
"id": 44494,
"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#, amazon-web-services",
"url": null
} |
c#, amazon-web-services
I don't want to read CustomerOutput~MM-DD-YYYY.txt and AccountManager~MM-DD-YYYY.txt from first S3 bucket but read all other files.
But I only want to read CustomerOutput~MM-DD-YYYY.txt and AccountManager~MM-DD-YYYY.txt from second S3 bucket and avoid all other files.
What is the best and generic way to do above problem? I came up with below code which does the job but it isn't the nice way to do it as I am repeating lot of things which can be made generic.
private static async Task<List<String>> ListObjects()
{
var objectList = new List<String>();
var firstRequest = new ListObjectsV2Request()
{
BucketName = _firstS3BucketName,
MaxKeys = _configurationStateManager.GetState().MaxReferenceDataKeys
};
var secondRequest = new ListObjectsV2Request()
{
BucketName = _secondS3BucketName,
MaxKeys = _configurationStateManager.GetState().MaxReferenceDataKeys
};
ListObjectsV2Response firstResponse;
ListObjectsV2Response secondResponse;
do
{
firstResponse = await GetListObjectResponse(firstRequest);
secondResponse = await GetListObjectResponse(secondRequest);
if (firstResponse != null && firstResponse.S3Objects != null && firstResponse.S3Objects.Count > 0
&& secondResponse != null && secondResponse.S3Objects != null && secondResponse.S3Objects.Count > 0)
{
foreach (var s3Object in firstResponse.S3Objects)
{
var objectDelimiterIndex = s3Object.Key.IndexOf("~");
if (objectDelimiterIndex < 0) continue; | {
"domain": "codereview.stackexchange",
"id": 44494,
"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#, amazon-web-services",
"url": null
} |
c#, amazon-web-services
// do not read CustomerOutput and AccountManager from first s3 bucket but read all other files
if (!s3Object.Key.Substring(0, objectDelimiterIndex).Equals(ReferenceFiles.CustomerOutput.ToString(), StringComparison.OrdinalIgnoreCase)
|| !s3Object.Key.Substring(0, objectDelimiterIndex).Equals(ReferenceFiles.AccountManager.ToString(), StringComparison.OrdinalIgnoreCase))
{
objectList.Add(s3Object.Key);
}
}
foreach (var s3Object in secondResponse.S3Objects)
{
var objectDelimiterIndex = s3Object.Key.IndexOf("~");
if (objectDelimiterIndex < 0) continue;
// Only read CustomerOutput and AccountManager from second s3 bucket and avoid all other files
if (s3Object.Key.Substring(0, objectDelimiterIndex).Equals(ReferenceFiles.CustomerOutput.ToString(), StringComparison.OrdinalIgnoreCase)
|| s3Object.Key.Substring(0, objectDelimiterIndex).Equals(ReferenceFiles.AccountManager.ToString(), StringComparison.OrdinalIgnoreCase))
{
objectList.Add(s3Object.Key);
}
}
}
firstRequest.ContinuationToken = firstResponse.NextContinuationToken;
secondRequest.ContinuationToken = secondResponse.NextContinuationToken;
}
while (firstResponse.IsTruncated && secondResponse.IsTruncated);
if (firstResponse == null || firstResponse.S3Objects == null ||
firstResponse.S3Objects.Count == 0 || secondResponse == null || secondResponse.S3Objects == null ||
secondResponse.S3Objects.Count == 0)
{
return null;
}
return objectList;
}
Answer: According to my understanding you can separate your code like this:
Have an orchestrator which knows
how to retrieve data from which bucket
how to combine the result
Have a worker which knows | {
"domain": "codereview.stackexchange",
"id": 44494,
"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#, amazon-web-services",
"url": null
} |
c#, amazon-web-services
how to retrieve data from which bucket
how to combine the result
Have a worker which knows
how to call paged API
how to verify the response
how to filter objects based on the parameters
Orchestrator
private static async Task<List<string>> ListObjectsFromTwoBucketsAsync()
{
var firstBucketKeys = await ListObjectKeysAsync(_firstS3BucketName, false);
var secondBucketKeys = await ListObjectKeysAsync(_secondS3BucketName, true);
return firstBucketKeys?.Any() && secondBucketKeys?.Any()
? firstBucketKeys.Union(secondBucketKeys)
: null;
}
Notes:
The order of the keys here might be different than in your code
You can issue the two queries concurrently via Task.WhenAll if you need
Worker
private static async Task<List<string>> ListObjectKeysAsync(string bucketName, bool shouldIncludeSpecificOnly)
{
var request = new ListObjectsV2Request()
{
BucketName = bucketName,
MaxKeys = _configurationStateManager.GetState().MaxReferenceDataKeys
};
const string customerOutput = ReferenceFiles.CustomerOutput.ToString();
const string accountManager = ReferenceFiles.AccountManager.ToString();
ListObjectsV2Response response;
var result = new List<string>();
do
{
response = await GetListObjectResponse(request);
if (!(response?.S3Objects?.Any() ?? false))
return null; | {
"domain": "codereview.stackexchange",
"id": 44494,
"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#, amazon-web-services",
"url": null
} |
c#, amazon-web-services
if (!(response?.S3Objects?.Any() ?? false))
return null;
var toBeAdded = from s3Object in response.S3Objects
let delimiterIndex = s3Object.Key.IndexOf("~")
where delimiterIndex >= 0
let keyPrefix = s3Object.Key[..delimiterIndex]
where customerOutput.Equals(keyPrefix, StringComparison.OrdinalIgnoreCase) && shouldIncludeSpecificOnly
|| accountManager.Equals(keyPrefix, StringComparison.OrdinalIgnoreCase) && shouldIncludeSpecificOnly
|| !shouldIncludeSpecificOnly
select s3Object.Key;
result.AddRange(toBeAdded);
request.ContinuationToken = response.NextContinuationToken;
}
while (response.IsTruncated);
return result;
}
Receive the bucket's name as parameter
"Compute" the customerOuput and accountManager strings only once
Issue the request
Examine the response
I've tried to make checking logic more concise
I've used null conditional operators, null-coalescing operator, and LINQ's Any
Filter the response's objects
I've rewrote it to use LINQ
The interesting part is the second where which combines all the conditions
Retrieve the next chunk
If any of the code piece is not clear, please let me know and I will add more description. | {
"domain": "codereview.stackexchange",
"id": 44494,
"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#, amazon-web-services",
"url": null
} |
php, array, shuffle
Title: PHP Fisher-Yates shuffle with random_int
Question: The PHP manual states that the regular shuffle() function isn't cryptographically secure, but that random_int() is. I thought, then, that I'd make something to leverage the latter for the former purpose. (PHP 8.2 includes Random\Engine, which includes a shuffler, but I wasn't aware of that when I started thinking about this, and my web server doesn't have 8.2 support yet anyway.)
After a search, I found out about the Fisher-Yates shuffle, and attempted to implement a PHP version based on the pseudocode provided in the Wikipedia article:
function shuffle_rint($a){
// To shuffle an array $a of $n elements (indices 0..$n-1)
$n = count($a);
for ($i = $n - 1; $i >= 1; $i--)
{
$j = random_int(0,$i);
$ai = $a[$i];
$a[$i] = $a[$j];
$a[$j] = $ai;
}
return $a;
}
Are there any glaring defects here? hrtime seems to suggest that it's a little slower than the regular shuffle, but I expect that is an unavoidable cost of using the secure numbers.
Answer: Swaps from one index to same index could be avoided
You asked:
Are there any glaring defects here?
As J_H mentioned in their answer
You swap even when $i == $j
The code could check for this condition and in that case avoid swapping values since it would be a waste of operations. The difference in speed would likely be negligible.
Follow common conventions for readability
While there is no de-facto rules about readability conventions and it is up to individuals/teams to decide their conventions, idiomatic PHP code often follows the PHP Standards Recommendations - e.g. PSR-12: Extended Coding Style. The code presented follows many of the recommendations though not all.
Perhaps it was a copy and paste issue but the lines inside the function block should be indented one level. This way anyone reading the function can easily see the code inside the function.
Other things I notice that do not follow the conventions of PSR-12 are:
$j = random_int(0,$i); | {
"domain": "codereview.stackexchange",
"id": 44495,
"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": "php, array, shuffle",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.