text stringlengths 1 2.12k | source dict |
|---|---|
python, unit-testing, functional-programming, modules
# calculate the total number of each weekday the paper was delivered (if it is supposed to be delivered)
# multiply this number by the cost of each day
# add all the costs together and return the result
return sum([
(number_of_each_weekday[day_id] - number_of_days_per_weekday_not_received[day_id]) * cost
if delivered else 0
for day_id, (delivered, cost) in enumerate(cost_and_delivered_data)
])
def calculate_cost_of_all_papers(undelivered_strings: dict[int, list[str]], month: int, year: int) -> tuple[
dict[int, float],
float,
dict[int, set[date_type]]
]:
"""calculate the cost of all papers for the full month
- return data about the cost of each paper, the total cost, and dates when each paper was not delivered"""
NUMBER_OF_EACH_WEEKDAY = list(get_number_of_each_weekday(month, year))
cost_and_delivery_data = {}
# get the IDs of papers that exist
with connect(DATABASE_PATH) as connection:
papers = connection.execute("SELECT paper_id FROM papers;").fetchall()
# get the data about cost and delivery for each paper
cost_and_delivery_data = [
get_cost_and_delivery_data(paper_id, connection)
for paper_id, in papers # type: ignore
]
connection.close()
# initialize a "blank" dictionary that will eventually contain any dates when a paper was not delivered
undelivered_dates: dict[int, set[date_type]] = {
int(paper_id): set()
for paper_id, in papers # type: ignore
}
# calculate the undelivered dates for each paper
for paper_id, strings in undelivered_strings.items():
undelivered_dates[paper_id].update(
parse_undelivered_strings(month, year, *strings)
) | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
# calculate the cost of each paper
costs = {
paper_id: calculate_cost_of_one_paper(
NUMBER_OF_EACH_WEEKDAY,
undelivered_dates[paper_id],
cost_and_delivery_data[index]
)
for index, (paper_id,) in enumerate(papers) # type: ignore
}
# calculate the total cost of all papers
total = sum(costs.values())
return costs, total, undelivered_dates
def save_results(
costs: dict[int, float],
undelivered_dates: dict[int, set[date_type]],
month: int,
year: int,
custom_timestamp: datetime | None = None
) -> None:
"""save the results of undelivered dates to the DB
- save the dates any paper was not delivered
- save the final cost of each paper"""
timestamp = (custom_timestamp if custom_timestamp else datetime.now()).strftime(r'%d/%m/%Y %I:%M:%S %p')
with connect(DATABASE_PATH) as connection:
# create log entries for each paper
log_ids = {
paper_id: connection.execute(
"""
INSERT INTO logs (paper_id, month, year, timestamp)
VALUES (?, ?, ?, ?)
RETURNING logs.log_id;
""",
(paper_id, month, year, timestamp)
).fetchone()[0]
for paper_id in costs.keys()
}
# create cost entries for each paper
for paper_id, log_id in log_ids.items():
connection.execute(
"""
INSERT INTO cost_logs (log_id, cost)
VALUES (?, ?);
""",
(log_id, costs[paper_id])
) | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
# create undelivered date entries for each paper
for paper_id, dates in undelivered_dates.items():
for date in dates:
connection.execute(
"""
INSERT INTO undelivered_dates_logs (log_id, date_not_delivered)
VALUES (?, ?);
""",
(log_ids[paper_id], date.strftime("%Y-%m-%d"))
)
connection.close()
def format_output(costs: dict[int, float], total: float, month: int, year: int) -> Generator[str, None, None]:
"""format the output of calculating the cost of all papers"""
# output the name of the month for which the total cost was calculated
yield f"For {date_type(year=year, month=month, day=1).strftime(r'%B %Y')},\n"
# output the total cost of all papers
yield f"*TOTAL*: {total:.2f}"
# output the cost of each paper with its name
with connect(DATABASE_PATH) as connection:
papers = dict(connection.execute("SELECT paper_id, name FROM papers;").fetchall())
for paper_id, cost in costs.items():
yield f"{papers[paper_id]}: {cost:.2f}"
connection.close()
def add_new_paper(name: str, days_delivered: list[bool], days_cost: list[float]) -> None:
"""add a new paper
- do not allow if the paper already exists"""
with connect(DATABASE_PATH) as connection:
# check if the paper already exists
if connection.execute(
"SELECT EXISTS (SELECT 1 FROM papers WHERE name = ?);",
(name,)).fetchone()[0]:
raise npbc_exceptions.PaperAlreadyExists(f"Paper \"{name}\" already exists."
)
# insert the paper
paper_id = connection.execute(
"INSERT INTO papers (name) VALUES (?) RETURNING papers.paper_id;",
(name,)
).fetchone()[0] | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
# create cost and delivered entries for each day
for day_id, (delivered, cost) in enumerate(zip(days_delivered, days_cost)):
connection.execute(
"INSERT INTO cost_and_delivery_data (paper_id, day_id, delivered, cost) VALUES (?, ?, ?, ?);",
(paper_id, day_id, delivered, cost)
)
connection.close()
def edit_existing_paper(
paper_id: int,
name: str | None = None,
days_delivered: list[bool] | None = None,
days_cost: list[float] | None = None
) -> None:
"""edit an existing paper
do not allow if the paper does not exist"""
with connect(DATABASE_PATH) as connection:
# check if the paper exists
if not connection.execute(
"SELECT EXISTS (SELECT 1 FROM papers WHERE paper_id = ?);",
(paper_id,)).fetchone()[0]:
raise npbc_exceptions.PaperNotExists(f"Paper with ID {paper_id} does not exist."
)
# update the paper name
if name is not None:
connection.execute(
"UPDATE papers SET name = ? WHERE paper_id = ?;",
(name, paper_id)
)
# update the costs of each day
if days_cost is not None:
for day_id, cost in enumerate(days_cost):
connection.execute(
"UPDATE cost_and_delivery_data SET cost = ? WHERE paper_id = ? AND day_id = ?;",
(cost, paper_id, day_id)
)
# update the delivered status of each day
if days_delivered is not None:
for day_id, delivered in enumerate(days_delivered):
connection.execute(
"UPDATE cost_and_delivery_data SET delivered = ? WHERE paper_id = ? AND day_id = ?;",
(delivered, paper_id, day_id)
)
connection.close() | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
connection.close()
def delete_existing_paper(paper_id: int) -> None:
"""delete an existing paper
- do not allow if the paper does not exist"""
with connect(DATABASE_PATH) as connection:
# check if the paper exists
if not connection.execute(
"SELECT EXISTS (SELECT 1 FROM papers WHERE paper_id = ?);",
(paper_id,)).fetchone()[0]:
raise npbc_exceptions.PaperNotExists(f"Paper with ID {paper_id} does not exist."
)
# delete the paper
connection.execute(
"DELETE FROM papers WHERE paper_id = ?;",
(paper_id,)
)
# delete the costs and delivery data for the paper
connection.execute(
"DELETE FROM cost_and_delivery_data WHERE paper_id = ?;",
(paper_id,)
)
connection.close()
def add_undelivered_string(month: int, year: int, paper_id: int | None = None, *undelivered_strings: str) -> None:
"""record strings for date(s) paper(s) were not delivered
- if no paper ID is specified, all papers are assumed"""
# validate the strings
validate_undelivered_string(*undelivered_strings)
# if a paper ID is given
if paper_id:
# check that specified paper exists in the database
with connect(DATABASE_PATH) as connection:
if not connection.execute(
"SELECT EXISTS (SELECT 1 FROM papers WHERE paper_id = ?);",
(paper_id,)).fetchone()[0]:
raise npbc_exceptions.PaperNotExists(f"Paper with ID {paper_id} does not exist."
)
# add the string(s)
params = [
(month, year, paper_id, string)
for string in undelivered_strings
]
connection.executemany("INSERT INTO undelivered_strings (month, year, paper_id, string) VALUES (?, ?, ?, ?);", params)
connection.close()
# if no paper ID is given
else: | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
connection.close()
# if no paper ID is given
else:
# get the IDs of all papers
with connect(DATABASE_PATH) as connection:
paper_ids = [
row[0]
for row in connection.execute(
"SELECT paper_id FROM papers;"
)
]
# add the string(s)
params = [
(month, year, paper_id, string)
for paper_id in paper_ids
for string in undelivered_strings
]
connection.executemany("INSERT INTO undelivered_strings (month, year, paper_id, string) VALUES (?, ?, ?, ?);", params)
connection.close()
def delete_undelivered_string(
string_id: int | None = None,
string: str | None = None,
paper_id: int | None = None,
month: int | None = None,
year: int | None = None
) -> None:
"""delete an existing undelivered string
- do not allow if the string does not exist"""
# initialize parameters for the WHERE clause of the SQL query
parameters = []
values = []
# check each parameter and add it to the WHERE clause if it is given
if string_id:
parameters.append("string_id")
values.append(string_id)
if string:
parameters.append("string")
values.append(string)
if paper_id:
parameters.append("paper_id")
values.append(paper_id)
if month:
parameters.append("month")
values.append(month)
if year:
parameters.append("year")
values.append(year)
# if no parameters are given, raise an error
if not parameters:
raise npbc_exceptions.NoParameters("No parameters given.")
with connect(DATABASE_PATH) as connection:
# check if the string exists
check_query = "SELECT EXISTS (SELECT 1 FROM undelivered_strings" | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
conditions = ' AND '.join(
f"{parameter} = ?"
for parameter in parameters
)
if (1,) not in connection.execute(f"{check_query} WHERE {conditions});", values).fetchall():
raise npbc_exceptions.StringNotExists("String with given parameters does not exist.")
# if the string did exist, delete it
delete_query = "DELETE FROM undelivered_strings"
connection.execute(f"{delete_query} WHERE {conditions};", values)
connection.close()
def get_papers() -> list[tuple[int, str, int, int, float]]:
"""get all papers
- returns a list of tuples containing the following fields:
paper_id, paper_name, day_id, paper_delivered, paper_cost"""
raw_data = []
query = """
SELECT papers.paper_id, papers.name, cost_and_delivery_data.day_id, cost_and_delivery_data.delivered, cost_and_delivery_data.cost
FROM papers
INNER JOIN cost_and_delivery_data ON papers.paper_id = cost_and_delivery_data.paper_id
ORDER BY papers.paper_id, cost_and_delivery_data.day_id;
"""
with connect(DATABASE_PATH) as connection:
raw_data = connection.execute(query).fetchall()
connection.close()
return raw_data
def get_undelivered_strings(
string_id: int | None = None,
month: int | None = None,
year: int | None = None,
paper_id: int | None = None,
string: str | None = None
) -> list[tuple[int, int, int, int, str]]:
"""get undelivered strings
- the user may specify as many as they want parameters
- available parameters: string_id, month, year, paper_id, string
- returns a list of tuples containing the following fields:
string_id, paper_id, year, month, string"""
# initialize parameters for the WHERE clause of the SQL query
parameters = []
values = []
data = [] | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
# check each parameter and add it to the WHERE clause if it is given
if string_id:
parameters.append("string_id")
values.append(string_id)
if month:
parameters.append("month")
values.append(month)
if year:
parameters.append("year")
values.append(year)
if paper_id:
parameters.append("paper_id")
values.append(paper_id)
if string:
parameters.append("string")
values.append(string)
with connect(DATABASE_PATH) as connection:
# generate the SQL query
main_query = "SELECT string_id, paper_id, year, month, string FROM undelivered_strings"
if not parameters:
query = f"{main_query};"
else:
conditions = ' AND '.join(
f"{parameter} = ?"
for parameter in parameters
)
query = f"{main_query} WHERE {conditions};"
data = connection.execute(query, values).fetchall()
connection.close()
# if no data was found, raise an error
if not data:
raise npbc_exceptions.StringNotExists("String with given parameters does not exist.")
return data
def get_logged_data(
query_paper_id: int | None = None,
query_log_id: int | None = None,
query_month: int | None = None,
query_year: int | None = None,
query_timestamp: date_type | None = None
) -> Generator[tuple[int, int, int, int, str, str | float], None, None]:
"""get logged data
- the user may specify as parameters many as they want
- available parameters: paper_id, log_id, month, year, timestamp
- yields: tuples containing the following fields:
log_id, paper_id, month, year, timestamp, date | cost."""
# initialize parameters for the WHERE clause of the SQL query
parameters = []
values = () | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
# check each parameter and add it to the WHERE clause if it is given
if query_paper_id:
parameters.append("paper_id")
values += (query_paper_id,)
if query_log_id:
parameters.append("log_id")
values += (query_log_id,)
if query_month:
parameters.append("month")
values += (query_month,)
if query_year:
parameters.append("year")
values += (query_year,)
if query_timestamp:
parameters.append("timestamp")
values += (query_timestamp.strftime(r'%d/%m/%Y %I:%M:%S %p'),)
# generate the SQL query
logs_base_query = """
SELECT log_id, paper_id, timestamp, month, year
FROM logs
ORDER BY log_id, paper_id
"""
if parameters:
conditions = ' AND '.join(
f"{parameter} = ?"
for parameter in parameters
)
logs_query = f"{logs_base_query} WHERE {conditions};"
else:
logs_query = f"{logs_base_query};"
dates_query = "SELECT log_id, date_not_delivered FROM undelivered_dates_logs;"
costs_query = "SELECT log_id, cost FROM cost_logs;"
with connect(DATABASE_PATH) as connection:
logs = {
log_id: [paper_id, month, year, timestamp]
for log_id, paper_id, timestamp, month, year in connection.execute(logs_query, values).fetchall()
}
dates = connection.execute(dates_query).fetchall()
costs = connection.execute(costs_query).fetchall()
for log_id, date in dates:
yield tuple(logs[log_id] + [date])
for log_id, cost in costs:
yield tuple(logs[log_id] + [float(cost)])
connection.close()
def get_previous_month() -> date_type:
"""get the previous month, by looking at 1 day before the first day of the current month (duh)"""
return (datetime.today().replace(day=1) - timedelta(days=1)).replace(day=1) | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
return (datetime.today().replace(day=1) - timedelta(days=1)).replace(day=1)
def validate_month_and_year(month: int | None = None, year: int | None = None) -> None:
"""validate month and year
- month must be an integer between 1 and 12 inclusive
- year must be an integer greater than 0"""
if isinstance(month, int) and not (1 <= month <= 12):
raise npbc_exceptions.InvalidMonthYear("Month must be between 1 and 12.")
if isinstance(year, int) and (year <= 0):
raise npbc_exceptions.InvalidMonthYear("Year must be greater than 0.")
test_core.py
"""
test data-independent functions from the core
- none of these depend on data in the database
"""
from datetime import date as date_type
from pytest import raises
import npbc_core
from npbc_exceptions import InvalidMonthYear, InvalidUndeliveredString
def test_get_number_of_each_weekday():
test_function = npbc_core.get_number_of_each_weekday
assert list(test_function(1, 2022)) == [5, 4, 4, 4, 4, 5, 5]
assert list(test_function(2, 2022)) == [4, 4, 4, 4, 4, 4, 4]
assert list(test_function(3, 2022)) == [4, 5, 5 ,5, 4, 4, 4]
assert list(test_function(2, 2020)) == [4, 4, 4, 4, 4, 5, 4]
assert list(test_function(12, 1954)) == [4, 4, 5, 5, 5, 4, 4]
def test_validate_undelivered_string():
test_function = npbc_core.validate_undelivered_string
with raises(InvalidUndeliveredString):
test_function("a")
test_function("monday")
test_function("1-mondays")
test_function("1monday")
test_function("1 monday")
test_function("monday-1")
test_function("monday-1") | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
test_function("")
test_function("1")
test_function("6")
test_function("31")
test_function("31","")
test_function("3","1")
test_function("3","1","")
test_function("3","1")
test_function("3","1")
test_function("3","1")
test_function("1","2","3-9")
test_function("1","2","3-9","11","12","13-19")
test_function("1","2","3-9","11","12","13-19","21","22","23-29")
test_function("1","2","3-9","11","12","13-19","21","22","23-29","31")
test_function("1","2","3","4","5","6","7","8","9")
test_function("mondays")
test_function("mondays,tuesdays")
test_function("mondays","tuesdays","wednesdays")
test_function("mondays","5-21")
test_function("mondays","5-21","tuesdays","5-21")
test_function("1-monday")
test_function("2-monday")
test_function("all")
test_function("All")
test_function("aLl")
test_function("alL")
test_function("aLL")
test_function("ALL")
def test_undelivered_string_parsing():
MONTH = 5
YEAR = 2017
test_function = npbc_core.parse_undelivered_strings
assert test_function(MONTH, YEAR, '') == set([])
assert test_function(MONTH, YEAR, '1') == set([
date_type(year=YEAR, month=MONTH, day=1)
])
assert test_function(MONTH, YEAR, '1-2') == set([
date_type(year=YEAR, month=MONTH, day=1),
date_type(year=YEAR, month=MONTH, day=2)
]) | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
assert test_function(MONTH, YEAR, '5-17') == set([
date_type(year=YEAR, month=MONTH, day=5),
date_type(year=YEAR, month=MONTH, day=6),
date_type(year=YEAR, month=MONTH, day=7),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=9),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=11),
date_type(year=YEAR, month=MONTH, day=12),
date_type(year=YEAR, month=MONTH, day=13),
date_type(year=YEAR, month=MONTH, day=14),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=16),
date_type(year=YEAR, month=MONTH, day=17)
])
assert test_function(MONTH, YEAR, '5-17', '19') == set([
date_type(year=YEAR, month=MONTH, day=5),
date_type(year=YEAR, month=MONTH, day=6),
date_type(year=YEAR, month=MONTH, day=7),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=9),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=11),
date_type(year=YEAR, month=MONTH, day=12),
date_type(year=YEAR, month=MONTH, day=13),
date_type(year=YEAR, month=MONTH, day=14),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=16),
date_type(year=YEAR, month=MONTH, day=17),
date_type(year=YEAR, month=MONTH, day=19)
]) | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
assert test_function(MONTH, YEAR, '5-17', '19-21') == set([
date_type(year=YEAR, month=MONTH, day=5),
date_type(year=YEAR, month=MONTH, day=6),
date_type(year=YEAR, month=MONTH, day=7),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=9),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=11),
date_type(year=YEAR, month=MONTH, day=12),
date_type(year=YEAR, month=MONTH, day=13),
date_type(year=YEAR, month=MONTH, day=14),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=16),
date_type(year=YEAR, month=MONTH, day=17),
date_type(year=YEAR, month=MONTH, day=19),
date_type(year=YEAR, month=MONTH, day=20),
date_type(year=YEAR, month=MONTH, day=21)
])
assert test_function(MONTH, YEAR, '5-17', '19-21', '23') == set([
date_type(year=YEAR, month=MONTH, day=5),
date_type(year=YEAR, month=MONTH, day=6),
date_type(year=YEAR, month=MONTH, day=7),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=9),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=11),
date_type(year=YEAR, month=MONTH, day=12),
date_type(year=YEAR, month=MONTH, day=13),
date_type(year=YEAR, month=MONTH, day=14),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=16),
date_type(year=YEAR, month=MONTH, day=17),
date_type(year=YEAR, month=MONTH, day=19),
date_type(year=YEAR, month=MONTH, day=20),
date_type(year=YEAR, month=MONTH, day=21),
date_type(year=YEAR, month=MONTH, day=23)
]) | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
assert test_function(MONTH, YEAR, 'mondays') == set([
date_type(year=YEAR, month=MONTH, day=1),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=22),
date_type(year=YEAR, month=MONTH, day=29)
])
assert test_function(MONTH, YEAR, 'mondays', 'wednesdays') == set([
date_type(year=YEAR, month=MONTH, day=1),
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=15),
date_type(year=YEAR, month=MONTH, day=22),
date_type(year=YEAR, month=MONTH, day=29),
date_type(year=YEAR, month=MONTH, day=3),
date_type(year=YEAR, month=MONTH, day=10),
date_type(year=YEAR, month=MONTH, day=17),
date_type(year=YEAR, month=MONTH, day=24),
date_type(year=YEAR, month=MONTH, day=31)
])
assert test_function(MONTH, YEAR, '2-monday') == set([
date_type(year=YEAR, month=MONTH, day=8)
])
assert test_function(MONTH, YEAR, '2-monday', '3-wednesday') == set([
date_type(year=YEAR, month=MONTH, day=8),
date_type(year=YEAR, month=MONTH, day=17)
])
def test_calculating_cost_of_one_paper():
DAYS_PER_WEEK = [5, 4, 4, 4, 4, 5, 5]
COST_AND_DELIVERY_DATA: list[tuple[bool, float]] = [
(False, 0),
(False, 0),
(True, 2),
(True, 2),
(True, 5),
(False, 0),
(True, 1)
]
test_function = npbc_core.calculate_cost_of_one_paper
assert test_function(
DAYS_PER_WEEK,
set([]),
COST_AND_DELIVERY_DATA
) == 41
assert test_function(
DAYS_PER_WEEK,
set([]),
[
(False, 0),
(False, 0),
(True, 2),
(True, 2),
(True, 5),
(False, 0),
(False, 1)
]
) == 36 | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
assert test_function(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=8)
]),
COST_AND_DELIVERY_DATA
) == 41
assert test_function(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=8),
date_type(year=2022, month=1, day=8)
]),
COST_AND_DELIVERY_DATA
) == 41
assert test_function(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=8),
date_type(year=2022, month=1, day=17)
]),
COST_AND_DELIVERY_DATA
) == 41
assert test_function(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=2)
]),
COST_AND_DELIVERY_DATA
) == 40
assert test_function(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=2),
date_type(year=2022, month=1, day=2)
]),
COST_AND_DELIVERY_DATA
) == 40
assert test_function(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=6),
date_type(year=2022, month=1, day=7)
]),
COST_AND_DELIVERY_DATA
) == 34
assert test_function(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=6),
date_type(year=2022, month=1, day=7),
date_type(year=2022, month=1, day=8)
]),
COST_AND_DELIVERY_DATA
) == 34
assert test_function(
DAYS_PER_WEEK,
set([
date_type(year=2022, month=1, day=6),
date_type(year=2022, month=1, day=7),
date_type(year=2022, month=1, day=7),
date_type(year=2022, month=1, day=7),
date_type(year=2022, month=1, day=8),
date_type(year=2022, month=1, day=8),
date_type(year=2022, month=1, day=8)
]),
COST_AND_DELIVERY_DATA
) == 34 | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
def test_validate_month_and_year():
test_function = npbc_core.validate_month_and_year
test_function(1, 2020)
test_function(12, 2020)
test_function(1, 2021)
test_function(12, 2021)
test_function(1, 2022)
test_function(12, 2022)
with raises(InvalidMonthYear):
test_function(-54, 2020)
test_function(0, 2020)
test_function(13, 2020)
test_function(45, 2020)
test_function(1, -5)
test_function(12, -5)
test_function(1.6, 10) # type: ignore
test_function(12.6, 10) # type: ignore
test_function(1, '10') # type: ignore
test_function(12, '10') # type: ignore
npbc_regex.py
"""
regex used by other files
- MATCH regex are used to validate (usually user input)
- SPLIT regex are used to split strings (usually user input)
"""
from calendar import day_name as WEEKDAY_NAMES_ITERABLE
from re import compile as compile_regex
## regex used to match against strings
# match for a list of comma separated values. each value must be/contain digits, or letters, or hyphens. spaces are allowed between values and commas. any number of values are allowed, but at least one must be present.
CSV_MATCH_REGEX = compile_regex(r'^[-\w]+( *, *[-\w]+)*( *,)?$')
# match for a single number. must be one or two digits
NUMBER_MATCH_REGEX = compile_regex(r'^[\d]{1,2}?$')
# match for a range of numbers. each number must be one or two digits. numbers are separated by a hyphen. spaces are allowed between numbers and the hyphen.
RANGE_MATCH_REGEX = compile_regex(r'^\d{1,2} *- *\d{1,2}$')
# match for weekday name. day must appear as "daynames" (example = "mondays"). all lowercase.
DAYS_MATCH_REGEX = compile_regex(f"^{'|'.join(map(lambda x: x.lower() + 's', WEEKDAY_NAMES_ITERABLE))}$") | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
# match for nth weekday name. day must appear as "n-dayname" (example = "1-monday"). all lowercase. must be one digit.
N_DAY_MATCH_REGEX = compile_regex(f"^\\d *- *({'|'.join(map(lambda x: x.lower(), WEEKDAY_NAMES_ITERABLE))})$")
# match for the text "all" in any case.
ALL_MATCH_REGEX = compile_regex(r'^[aA][lL]{2}$')
# match for seven values, each of which must be a 'Y' or an 'N'. there are no delimiters.
DELIVERY_MATCH_REGEX = compile_regex(r'^[YN]{7}$')
## regex used to split strings
# split on hyphens. spaces are allowed between hyphens and values.
HYPHEN_SPLIT_REGEX = compile_regex(r' *- *')
test_regex.py
import npbc_regex
def test_regex_number():
assert npbc_regex.NUMBER_MATCH_REGEX.match('') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('1') is not None
assert npbc_regex.NUMBER_MATCH_REGEX.match('1 2') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('1-2') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('11') is not None
assert npbc_regex.NUMBER_MATCH_REGEX.match('11-12') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('11-12,13') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('11-12,13-14') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('111') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('a') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('1a') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('1a2') is None
assert npbc_regex.NUMBER_MATCH_REGEX.match('12b') is None | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
def test_regex_range():
assert npbc_regex.RANGE_MATCH_REGEX.match('') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('1') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('1 2') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('1-2') is not None
assert npbc_regex.RANGE_MATCH_REGEX.match('11') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('11-') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('11-12') is not None
assert npbc_regex.RANGE_MATCH_REGEX.match('11-12-1') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('11 -12') is not None
assert npbc_regex.RANGE_MATCH_REGEX.match('11 - 12') is not None
assert npbc_regex.RANGE_MATCH_REGEX.match('11- 12') is not None
assert npbc_regex.RANGE_MATCH_REGEX.match('11-2') is not None
assert npbc_regex.RANGE_MATCH_REGEX.match('11-12,13') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('11-12,13-14') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('111') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('a') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('1a') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('1a2') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('12b') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('11-a') is None
assert npbc_regex.RANGE_MATCH_REGEX.match('11-12a') is None | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
def test_regex_CSVs():
assert npbc_regex.CSV_MATCH_REGEX.match('') is None
assert npbc_regex.CSV_MATCH_REGEX.match('1') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('a') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('adcef') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('-') is not None
assert npbc_regex.CSV_MATCH_REGEX.match(' ') is None
assert npbc_regex.CSV_MATCH_REGEX.match('1,2') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('1-3') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('monday') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('monday,tuesday') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('mondays') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('tuesdays') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('1,2,3') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('1-3') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('monday,tuesday') is not None
assert npbc_regex.CSV_MATCH_REGEX.match('mondays,tuesdays') is not None
assert npbc_regex.CSV_MATCH_REGEX.match(';') is None
assert npbc_regex.CSV_MATCH_REGEX.match(':') is None
assert npbc_regex.CSV_MATCH_REGEX.match(':') is None
assert npbc_regex.CSV_MATCH_REGEX.match('!') is None
assert npbc_regex.CSV_MATCH_REGEX.match('1,2,3,4') is not None
def test_regex_days():
assert npbc_regex.DAYS_MATCH_REGEX.match('') is None
assert npbc_regex.DAYS_MATCH_REGEX.match('1') is None
assert npbc_regex.DAYS_MATCH_REGEX.match('1,2') is None
assert npbc_regex.DAYS_MATCH_REGEX.match('1-3') is None
assert npbc_regex.DAYS_MATCH_REGEX.match('monday') is None
assert npbc_regex.DAYS_MATCH_REGEX.match('monday,tuesday') is None
assert npbc_regex.DAYS_MATCH_REGEX.match('mondays') is not None
assert npbc_regex.DAYS_MATCH_REGEX.match('tuesdays') is not None | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
def test_regex_n_days():
assert npbc_regex.N_DAY_MATCH_REGEX.match('') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('1') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('1-') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('1,2') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('1-3') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('monday') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('monday,tuesday') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('mondays') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('1-tuesday') is not None
assert npbc_regex.N_DAY_MATCH_REGEX.match('11-tuesday') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('111-tuesday') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('11-tuesdays') is None
assert npbc_regex.N_DAY_MATCH_REGEX.match('1 -tuesday') is not None
assert npbc_regex.N_DAY_MATCH_REGEX.match('1- tuesday') is not None
assert npbc_regex.N_DAY_MATCH_REGEX.match('1 - tuesday') is not None | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
def test_regex_all_text():
assert npbc_regex.ALL_MATCH_REGEX.match('') is None
assert npbc_regex.ALL_MATCH_REGEX.match('1') is None
assert npbc_regex.ALL_MATCH_REGEX.match('1-') is None
assert npbc_regex.ALL_MATCH_REGEX.match('1,2') is None
assert npbc_regex.ALL_MATCH_REGEX.match('1-3') is None
assert npbc_regex.ALL_MATCH_REGEX.match('monday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('monday,tuesday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('mondays') is None
assert npbc_regex.ALL_MATCH_REGEX.match('tuesdays') is None
assert npbc_regex.ALL_MATCH_REGEX.match('1-tuesday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('11-tuesday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('111-tuesday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('11-tuesdays') is None
assert npbc_regex.ALL_MATCH_REGEX.match('1 -tuesday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('1- tuesday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('1 - tuesday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('all') is not None
assert npbc_regex.ALL_MATCH_REGEX.match('all,tuesday') is None
assert npbc_regex.ALL_MATCH_REGEX.match('all,tuesdays') is None
assert npbc_regex.ALL_MATCH_REGEX.match('All') is not None
assert npbc_regex.ALL_MATCH_REGEX.match('AlL') is not None
assert npbc_regex.ALL_MATCH_REGEX.match('ALL') is not None | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
def test_delivery_regex():
assert npbc_regex.DELIVERY_MATCH_REGEX.match('') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('a') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('1') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('1.') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('1.5') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('1,2') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('1-2') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('1;2') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('1:2') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('1,2,3') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('Y') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('N') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YY') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYY') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYYY') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYYYY') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYYYYY') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYYYYYY') is not None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYYYYYYY') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('NNNNNNN') is not None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('NYNNNNN') is not None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('NYYYYNN') is not None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('NYYYYYY') is not None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('NYYYYYYY') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('N,N,N,N,N,N,N') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('N;N;N;N;N;N;N') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('N-N-N-N-N-N-N') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('N N N N N N N') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYYYYYy') is None | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYYYYYy') is None
assert npbc_regex.DELIVERY_MATCH_REGEX.match('YYYYYYn') is None | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
def test_regex_hyphen():
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1-2') == ['1', '2']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1-2-3') == ['1', '2', '3']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1 -2-3') == ['1', '2', '3']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1 - 2-3') == ['1', '2', '3']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1- 2-3') == ['1', '2', '3']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1') == ['1']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1-') == ['1', '']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1-2-') == ['1', '2', '']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1-2-3-') == ['1', '2', '3', '']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1,2-3') == ['1,2', '3']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1,2-3-') == ['1,2', '3', '']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('1,2, 3,') == ['1,2, 3,']
assert npbc_regex.HYPHEN_SPLIT_REGEX.split('') == ['']
npbc_exceptions.py
"""
provide exceptions for other modules
- these are custom exceptions used to make error handling easier
- none of them inherit from BaseException
"""
from sqlite3 import OperationalError
class InvalidInput(ValueError): ...
class InvalidUndeliveredString(InvalidInput): ...
class PaperAlreadyExists(OperationalError): ...
class PaperNotExists(OperationalError): ...
class StringNotExists(OperationalError): ...
class InvalidMonthYear(InvalidInput): ...
class NoParameters(ValueError): ...
If you need it, here is a link to the GitHub repo for this project. It's at the same commit as the code above, and I won't edit this so that any discussion is consistent.
https://github.com/eccentricOrange/npbc/tree/041a949bbba018531ec590a2193523f1530659aa
Answer: Pretty good!
This pattern:
# if in a development environment, set the paths to the data folder
if environ.get('NPBC_DEVELOPMENT') or environ.get('CI'):
DATABASE_DIR = Path('data')
SCHEMA_PATH = Path('data') / 'schema.sql' | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
is a little risky. Rather than having secondary flags (DEVELOPMENT) that derive other settings (DATABASE_DIR) in the code, have the code fetch those settings (DATABASE_DIR) directly from the environment. The development environment will set those settings differently from the production environment. You ask:
I don't understand what you mean when you say "risky" about environment variables—do you mean that I might get an error if they're not defined? I wanted to leverage the CI variable built into both GitHub and GitLab CI/CD.
Leveraging that variable is not a good idea. Applications should be categorically unable to vary their behaviour based on knowledge of which environment they're in; they should only pay attention to well-defined configuration points like your database directory. There will soon come a time when you have a problem, and you need to understand why the problem manifests one way in production and a different way in development. Configuration between these environments will naturally vary, but the application must be unable to vary its behaviour based on direct knowledge of which environment it's in or else there will be a complexity explosion that makes such debugging more difficult. It's easy to use GitHub actions to expose a different set of configuration variables based on which environment you're in.
I'd expect, rather than .db, to see .sqlite as the database extension; though this is minor.
For WEEKDAY_NAMES use a tuple instead of a list as the former is immutable.
Put your connection.close in a finally.
for i, _ in enumerate is not a good use of enumerate; instead just use range(len.
This:
if string and not (
npbc_regex.NUMBER_MATCH_REGEX.match(string) or
npbc_regex.RANGE_MATCH_REGEX.match(string) or
npbc_regex.DAYS_MATCH_REGEX.match(string) or
npbc_regex.N_DAY_MATCH_REGEX.match(string) or
npbc_regex.ALL_MATCH_REGEX.match(string)
): | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
python, unit-testing, functional-programming, modules
can be expressed as
if string and not any(
pattern.match(string) for pattern in (
npbc_regex.NUMBER_MATCH_REGEX,
npbc_regex.RANGE_MATCH_REGEX,
npbc_regex.DAYS_MATCH_REGEX,
npbc_regex.N_DAY_MATCH_REGEX,
npbc_regex.ALL_MATCH_REGEX,
)
):
It's odd to alias date as date_type. Probably don't do this.
if date > 0 and date <= monthrange(year, month)[1]: can use the if 0 < date <= monthrange ... syntax.
I find list(map to be less legible than a plain old comprehension, as in
[
(bool(row[0]), row[1])
for row in connection.execute(query, (paper_id,)).fetchall()
]
This:
(custom_timestamp if custom_timestamp else datetime.now())
can just be
(custom_timestamp or datetime.now())
Broadly, you have an issue with connection management. You open and close your connection too often. You should open it only once per program run. You ask:
Can you advise how to manage connections? Should I make a global variable or try to pass around function arguments? I would have done it in main() but Core does not have a main()
Identify the highest point in the application stack where a connection is needed. Spin it up there, don't put it in globals, and pass it to the functions that need it.
Use tuples instead of lists in your test functions. | {
"domain": "codereview.stackexchange",
"id": 43413,
"lm_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, unit-testing, functional-programming, modules",
"url": null
} |
c#, multithreading, networking, tcp
Title: Multithreaded tcp server accepting two clients with task factory and graceful shutdown
Question: as an exercise from multithreading and networking I have decided to create my own implementation of TCP server accepting connections from two clients (which is I think a pretty common case e.g. chess online games). The works as I wanted it to. Clients are connecting to server, messages from one client are passed to the other client and if server shutsdown or client decides to end the connection all application are shuting down. I would like to ask for code review in terms of code quality and performance. Is there anything I could do better?
TCP server implementation:
public sealed class TcpServer
{
public static async Task Main()
{
var ipAddress = IPAddress.Parse("127.0.0.1");
var ipEndpoint = new IPEndPoint(ipAddress, 12345);
var tcpServer = new TcpListener(ipEndpoint);
tcpServer.Start();
Console.Write("Waiting for connections... ");
var clientOne = await tcpServer.AcceptTcpClientAsync();
Console.WriteLine("Client one connected!\nWaiting for client two...");
var clientTwo = await tcpServer.AcceptTcpClientAsync();
Console.WriteLine("Client two connected!");
var taskFactory = new TaskFactory();
var tokenSource = new CancellationTokenSource();
var cancellationToken = tokenSource.Token;
var taskArray = new Task[3];
taskArray[0] = taskFactory.StartNew(() => MessagingTask(clientOne, clientTwo, tokenSource, cancellationToken), cancellationToken);
taskArray[1] = taskFactory.StartNew(() => MessagingTask(clientTwo, clientOne, tokenSource, cancellationToken), cancellationToken);
taskArray[2] = taskFactory.StartNew(() => ServerConsole(tokenSource, cancellationToken), cancellationToken);
Task.WaitAny(taskArray);
} | {
"domain": "codereview.stackexchange",
"id": 43414,
"lm_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#, multithreading, networking, tcp",
"url": null
} |
c#, multithreading, networking, tcp
Task.WaitAny(taskArray);
}
private static void ServerConsole(CancellationTokenSource tokenSource, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
while (Console.ReadLine() != "q")
{
}
Console.WriteLine("Closing application...");
tokenSource.Cancel();
}
}
private static void MessagingTask(TcpClient clientOne, TcpClient clientTwo, CancellationTokenSource tokenSource, CancellationToken cancellationToken)
{
var bytes = new byte[256];
var clientOneStream = clientOne.GetStream();
var clientTwoStream = clientTwo.GetStream();
while (!cancellationToken.IsCancellationRequested)
{
int i;
while ((i = clientOneStream.Read(bytes)) != 0)
{
var data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine($"{DateTime.Now}: {data}");
var msg = Encoding.ASCII.GetBytes(data);
clientTwoStream.Write(msg);
}
if (i == 0)
{
Console.WriteLine($"Client {clientOne.Client.LocalEndPoint} disconnected");
tokenSource.Cancel();
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43414,
"lm_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#, multithreading, networking, tcp",
"url": null
} |
c#, multithreading, networking, tcp
TCP client implementation:
public sealed class TcpClientTwo
{
public static async Task Main()
{
var ipAddress = IPAddress.Parse("127.0.0.1");
var ipEndpoint = new IPEndPoint(ipAddress, 12346);
var tcpClient = new TcpClient(ipEndpoint);
await tcpClient.ConnectAsync(ipAddress, 12345);
var stream = tcpClient.GetStream();
var taskFactory = new TaskFactory();
var tokenSource = new CancellationTokenSource();
var cancellationToken = tokenSource.Token;
var taskArray = new Task[3];
taskArray[0] = taskFactory.StartNew(() => ReadingThread(tcpClient, cancellationToken), cancellationToken);
taskArray[1] = taskFactory.StartNew(() => SendingThread(tcpClient, tokenSource, cancellationToken), cancellationToken);
taskArray[2] = taskFactory.StartNew(() => ConnectionStatusThread(tcpClient, tokenSource, cancellationToken), cancellationToken);
Task.WaitAny(taskArray);
stream.Close();
tcpClient.Close();
}
private static void ConnectionStatusThread(TcpClient tcpClient, CancellationTokenSource tokenSource, CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
if (!tcpClient.Client.Connected)
{
Console.WriteLine("Server disconnected");
tokenSource.Cancel();
}
Task.Delay(1000);
}
}
private static void ReadingThread(TcpClient tcpClient, CancellationToken cancellationToken)
{
var bytes = new byte[256];
var stream = tcpClient.GetStream();
while (true)
{
int i;
while ((i = stream.Read(bytes)) != 0)
{
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Server disconnected");
return;
} | {
"domain": "codereview.stackexchange",
"id": 43414,
"lm_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#, multithreading, networking, tcp",
"url": null
} |
c#, multithreading, networking, tcp
var data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine($"{DateTime.Now}: {data}");
}
}
}
private static void SendingThread(TcpClient tcpClient, CancellationTokenSource tokenSource, CancellationToken cancellationToken)
{
var stream = tcpClient.GetStream();
string userInput = "";
while (true)
{
userInput = Console.ReadLine();
if (cancellationToken.IsCancellationRequested)
{
Console.WriteLine("Server disconnected");
return;
}
if (string.IsNullOrEmpty(userInput))
continue;
if (userInput.Equals("q"))
{
Console.WriteLine("Closing application...");
tokenSource.Cancel();
}
var bytes = Encoding.ASCII.GetBytes(userInput);
stream.Write(bytes);
}
}
Answer: In this post let me focus only on the TcpServer class.
I will post another review about the TcpClientTwo class next week.
Main
Waiting indefinitely for client
Your AcceptTcpClientAsync can wait indefinitely
If you want to avoid this situation then you have multiple options
.NET 6
You can pass a CancellationToken which was setup to timeout
Please note that the overload which can accept a CancellationToken was introduced in .NET 6
Related link (Applies to section)
var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
...
await tcpServer.AcceptTcpClientAsync(timeout.Token);
Prior .NET 6
you can call Stop on the TcpListener in case of timeout
var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(30));
timeout.Register(() => tcpServer.Stop());
There are several SO topics which details the different options: 1, 2, etc.
Task.Run vs Task.Factory.StartNew
Generally please prefer Task.Run over Task.Factory.StartNew | {
"domain": "codereview.stackexchange",
"id": 43414,
"lm_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#, multithreading, networking, tcp",
"url": null
} |
c#, multithreading, networking, tcp
Task.Run vs Task.Factory.StartNew
Generally please prefer Task.Run over Task.Factory.StartNew
The former one does support async delegates while the latter doesn't
It is hard to define a StartNew in a correct way (using the good values for all of its parameters)
Related SO topics: 1, 2, etc.
Related Articles: 1, 2, etc.
In case of long-running jobs prefer a dedicated Thread over Task.Run
If your clients are connected for a couple of minutes (not hours) then Task.Run is fine
var tokenSource = new CancellationTokenSource();
Task.WaitAny(new Task[]
{
Task.Run(() => MessagingTask(clientOne, clientTwo, tokenSource)),
Task.Run(() => MessagingTask(clientTwo, clientOne, tokenSource)),
Task.Run(() => ServerConsole(tokenSource)),
});
Since you are passing the CancellationTokenSource you don't need to pass the CancellationToken itself
Also you don't have to pass the CancellationToken to the Task.Run because it can only cancel those jobs which were not started yet.
ServerConsole
I'm not really sure why do you need the outer while, since according to my understanding you will enter into the loop only once
I would also suggest to accept capital Q as well
From a naming perspective the method name should start with a verb, like WaitForUserCancellation, ReadConsoleForUserCommands, etc..
MessagingTask
It is a synchronous method, not an asynchronous one, so using Task as a suffix is misleading
IMHO a better name could be TransferDataBetweenClients, HandleMessagingBetweenParties, etc.
Also calling parameters like clientOne and clientTwo are not really helpful
Calling them sourceClient and targetClient express your intent better
Same applies to variable i, please prefer readBytes
The if (i == 0) is pointless since that's your exit condition from the while loop
var buffer = new byte[256];
var sourceStream = sourceClient.GetStream();
var targetStream = targetClient.GetStream(); | {
"domain": "codereview.stackexchange",
"id": 43414,
"lm_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#, multithreading, networking, tcp",
"url": null
} |
c#, multithreading, networking, tcp
while (!tokenSource.Token.IsCancellationRequested)
{
int readBytes;
while ((readBytes = sourceStream.Read(buffer)) != 0)
{
var message = Encoding.ASCII.GetString(buffer, 0, readBytes);
Console.WriteLine($"{DateTime.Now}: {message}");
targetStream.Write(Encoding.ASCII.GetBytes(message));
}
Console.WriteLine($"Client {sourceClient.Client.LocalEndPoint} disconnected");
tokenSource.Cancel();
}
Please bear in mind that 256 bytes for the buffer might not be enough
If you are sending a larger string then Encoding.ASCII.GetString won't be able to read the whole message | {
"domain": "codereview.stackexchange",
"id": 43414,
"lm_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#, multithreading, networking, tcp",
"url": null
} |
c, sorting
Title: A Sorting Algorithm
Question: I've written this sorting algorithm in C. It looks for the element with the max value every iteration and adds it to the end of the array, swapping it with other smaller elements. This way, by almost n swaps, an n element array can be sorted.
#include <stdio.h>
int max(int arr1[],int l){
int max = 0;
for(int i = 0; i <= l;i++)
max = (arr1[i] > arr1[max]) ? (i) : (max);
return max;
}
void swap(int arr[], int a,int b){
if(arr[a] != arr[b]){
arr[a] += arr[b];
arr[b] = arr[a] - arr[b];
arr[a] -= arr[b];
}
}
int main(){
int arr[] = {1,5,7,2,8,9,10,32,4};
int len = sizeof(arr) / sizeof(arr[0]);
for(int i = 0; i < len; i++)
swap(arr,(len - i - 1),max(arr,(len - i -1)));
printf("\nSorted Array:\n");
for(int i = 0; i < len;i++)
printf("%d ",arr[i]);
}
Any suggestions/constructive criticism are very welcome. I'm a beginner, please point out any mistakes I made. | {
"domain": "codereview.stackexchange",
"id": 43415,
"lm_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, sorting",
"url": null
} |
c, sorting
Answer: The Swap
It's the good old "arithmetic swap", a variant of the XOR-swap that uses addition and subtraction instead of XOR. It avoids naming a temporary variable, which was not a significant cost, and instead introduces a handful of extra operations.. and the potential for integer overflow (admittedly it is likely to work in practice, and will work for this example thanks to the small numbers).
Here's the assembly for that kind of swap vs a "traditional swap", as compiled by Clang:
swap: # @swap
movsxd rax, esi
mov esi, dword ptr [rdi + 4*rax]
movsxd rcx, edx
mov edx, dword ptr [rdi + 4*rcx]
cmp esi, edx
je .LBB0_2
add edx, esi
mov dword ptr [rdi + 4*rax], edx
sub edx, dword ptr [rdi + 4*rcx]
mov dword ptr [rdi + 4*rcx], edx
sub dword ptr [rdi + 4*rax], edx
.LBB0_2:
ret
swap_tmp: # @swap2
movsxd rax, esi
mov ecx, dword ptr [rdi + 4*rax]
movsxd rdx, edx
mov esi, dword ptr [rdi + 4*rdx]
mov dword ptr [rdi + 4*rax], esi
mov dword ptr [rdi + 4*rdx], ecx
ret
I don't recommend the XOR-swap except in special cases (it does work well to swap bits within an integer), I don't recommend the arithmetic-swap basically at all.
Passing the highest valid index vs the length
The parameter l passed to max is not a length (which its name sort of suggests it is), it's the highest valid index. That's possible of course, but not idiomatic, and leads to a random-looking "subtract 1", and an out-of-place-looking <= in the condition of a for-loop. That works for now, but it would cause more problems if you used size_t for the indices and lengths instead of int. | {
"domain": "codereview.stackexchange",
"id": 43415,
"lm_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, sorting",
"url": null
} |
beginner, bash, installer
Title: Download Ubuntu daily ISOs and make them into VMs for alpha and beta testing
Question: I'm an Ubuntu contributor, and I finally got tired of the workflow for ISO testing I was using (zsync, gpg, sha256sum, create Gnome Boxes VM, install, delete VM). So I decided to make a Bash script to automate a bunch of the process for me.
Trouble is, Bash is not my "native" programming language. The code works properly in my testing, but it looks like something died in the explosion.
In addition to suggestions to clean up the code, I'd be interested in knowing what techniques I can use to avoid writing such messy code in the future. This is my third major Bash script I've written, and all three looked pretty bad, so anything I can do to avoid that in the future would be helpful.
The code is available on my GitHub repository, ArrayBolt3/vm-isotest. It has quite a few features, modes, and options, so you will probably want to read the README on GitHub to get a good idea of what all the arguments do. Here's the full script. I'm running it on Ubuntu Studio 22.04, which I believe is using Bash 5.1.
#! /bin/bash
# vm-isotest - Automatically zsync and verify ISOs, and build quick testing VMs out of them.
# Checks to see if the virtual disk repo exists, creates it if it doesn't, and throws a fit if something gets in its way.
if [ -e "$HOME/vm-isotest-virtdisks" ] && [ -d "$HOME/vm-isotest-virtdisks" ]; then
if [ ! -e "$HOME/vm-isotest-virtdisks/vmisotestmark" ]; then
echo "Fatal error: ~/vm-isotest-virtdisks directory exists and is not marked safe."
exit
fi
else
if [ -e "$HOME/vm-isotest-virtdisks" ]; then
echo "Fatal error: a file named ~/vm-isotest-virtdisks exists."
exit
else
mkdir "$HOME/vm-isotest-virtdisks"
echo 0 > "$HOME/vm-isotest-virtdisks/vmisotestmark"
fi
fi | {
"domain": "codereview.stackexchange",
"id": 43416,
"lm_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, bash, installer",
"url": null
} |
beginner, bash, installer
# Argument parser
initMode=0
finalArgCount=0
getArgValue="no"
hitArgListEnd="no"
cntr=0
params=( "$@" )
while [ $cntr -le $(($# - 1)) ]; do
arg=${params[$cntr]}
if [ "$arg" = "-d" ]; then
if [ $initMode -eq 0 ]; then
vmmode="d"
initMode=1
cntr=$(($cntr + 1))
continue
else
echo "Fatal error: unexpected argument -d"
exit
fi
elif [ "$arg" = "-l" ]; then
if [ $initMode -eq 0 ]; then
vmmode="l"
initMode=1
cntr=$(($cntr + 1))
continue
else
echo "Fatal error: unexpected argument -l"
exit
fi
elif [ "$arg" = "-b" ]; then
if [ $initMode -eq 0 ]; then
vmmode="b"
initMode=1
cntr=$(($cntr + 1))
continue
else
echo "Fatal error: unexpected argument -b"
exit
fi
elif [ "$arg" = "-dlonly" ]; then
if [ $initMode -eq 0 ]; then
vmmode="dlonly"
initMode=1
cntr=$(($cntr + 1))
continue
else
echo "Fatal error: unexpected argument -dlonly"
exit
fi
fi
if [ "$getArgValue" = "no" ]; then
hitArgListEnd="yes"
if [ "$arg" = "-cpus" ]; then
hitArgListEnd="no"
getArgValue="cpus"
elif [ "$arg" = "-m" ]; then
hitArgListEnd="no"
getArgValue="m"
elif [ "$arg" = "-space" ]; then
hitArgListEnd="no"
getArgValue="space"
elif [ "$arg" = "-graphics" ]; then
hitArgListEnd="no"
getArgValue="graphics"
elif [ "$arg" = "-efi" ]; then
hitArgListEnd="no"
efiFirmware="yes"
elif [ "$arg" = "-persist" ]; then
hitArgListEnd="no"
persistDisk="yes"
elif [ "$arg" = "-ramdisk" ]; then
hitArgListEnd="no" | {
"domain": "codereview.stackexchange",
"id": 43416,
"lm_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, bash, installer",
"url": null
} |
beginner, bash, installer
elif [ "$arg" = "-ramdisk" ]; then
hitArgListEnd="no"
useRAMDisk="yes"
elif [ "$arg" = "-live" ]; then
hitArgListEnd="no"
liveTest="yes"
elif [ "$arg" = "-nodisk" ]; then
hitArgListEnd="no"
noDisk="yes"
fi
else
if [ "$getArgValue" = "cpus" ]; then
numCPUs=$arg
elif [ "$getArgValue" = "m" ]; then
ramSize=$arg
elif [ "$getArgValue" = "space" ]; then
diskSpace=$arg
elif [ "$getArgValue" = "graphics" ]; then
graphicsMode=$arg
fi
getArgValue="no"
fi
if [ "$hitArgListEnd" = "yes" ]; then
if [ "$vmmode" = "d" ] || [ "$vmmode" = "dlonly" ]; then
if [ $cntr -lt $(($# - 3)) ]; then
echo "Fatal error: unrecognized argument $arg."
exit
elif [ $finalArgCount -eq 0 ]; then
zsyncURL=$arg
elif [ $finalArgCount -eq 1 ]; then
gpgURL=$arg
elif [ $finalArgCount -eq 2 ]; then
sha256URL=$arg
fi
finalArgCount=$(($finalArgCount + 1))
else
if [ $cntr -ne $(($# - 1)) ]; then
echo "Fatal error: unrecognized argument $arg."
exit
else
imgPath=$arg
fi
fi
fi
cntr=$(($cntr + 1))
done | {
"domain": "codereview.stackexchange",
"id": 43416,
"lm_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, bash, installer",
"url": null
} |
beginner, bash, installer
# Do sanity checks and set defaults
if [ "$vmmode" = "d" ] || [ "$vmmode" = "dlonly" ]; then
if [ "$zsyncURL" = "" ]; then
echo "Fatal error: no zsync URL provided."
exit
elif [ "$gpgURL" = "" ]; then
echo "Fatal error: no GPG verification URL provided."
exit
elif [ "$sha256URL" = "" ]; then
echo "Fatal error: no SHA256SUMS URL provided."
exit
fi
fi
if [ "$numCPUs" = "" ]; then
numCPUs=2
fi
if [ "$ramSize" = "" ]; then
ramSize="4G"
fi
if [ "$diskSpace" = "" ]; then
if [ "$useRAMDisk" = "yes" ]; then
diskSpace=15G
else
diskSpace=20G
fi
fi
if [ "$graphicsMode" = "" ]; then
graphicsMode="qxl"
fi
# zsync the ISO
if [ "$vmmode" = "d" ] || [ "$vmmode" = "dlonly" ]; then
zsync $zsyncURL
rm SHA256SUMS
rm SHA256SUMS.gpg
wget $gpgURL > /dev/null
wget $sha256URL > /dev/null
gpg --keyid-format=long --verify SHA256SUMS.gpg SHA256SUMS
sha256sum -c --ignore-missing SHA256SUMS
read -n1 -s # Wait for the user to check the results of the download and test before proceeding.
fi
# Create the VM
if [ "$vmmode" = "d" ] || [ "$vmmode" = "l" ]; then
if [ "$noDisk" != "yes" ]; then
# Read the counter from the vmisotestmark file, and increment the counter. This counter is used to ensure unique VM disk image names.
vmNameCounter=`cat ~/vm-isotest-virtdisks/vmisotestmark`
vmNameCounter=$(($vmNameCounter + 1))
rm ~/vm-isotest-virtdisks/vmisotestmark
echo $vmNameCounter > ~/vm-isotest-virtdisks/vmisotestmark | {
"domain": "codereview.stackexchange",
"id": 43416,
"lm_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, bash, installer",
"url": null
} |
beginner, bash, installer
# Now do the actual VM creation.
if [ "$useRAMDisk" = "yes" ]; then
if [ ! -e /dev/shm/vm-isotest/img$vmNameCounter ]; then
qemu-img create -f qcow2 "/dev/shm/vm-isotest-img$vmNameCounter" $diskSpace
else
echo "Fatal error - could not create VM disk image. Attempting to run the command again, unmodified, should work."
exit
fi
else
if [ ! -e ~/vm-isotest-virtdisks/vm-isotest-img$vmNameCounter ]; then
qemu-img create -f qcow2 "$HOME/vm-isotest-virtdisks/vm-isotest-img$vmNameCounter" $diskSpace
else
echo "Fatal error - could not create VM disk image. Attempting to run the command again, unmodified, should work."
exit
fi
fi
fi
fi
# Determine ISO name when in d mode
if [ "$vmmode" = "d" ]; then
zsyncFilename=`echo "$zsyncURL" | cut -f7 -d "/"`
if [ "$zsyncFilename" = "" ]; then # The plain Ubuntu ISOs have a path with one fewer slashes in it than the Ubuntu flavours' paths, so if the 7th field is empty, we try the 6th instead.
zsyncFilename=`echo "$zsyncURL" | cut -f6 -d "/"`
fi
imgPath=`echo $zsyncFilename | head -c -7 -`
fi | {
"domain": "codereview.stackexchange",
"id": 43416,
"lm_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, bash, installer",
"url": null
} |
beginner, bash, installer
# Launch and clean up the VM
if [ "$vmmode" != "dlonly" ]; then
qemuCmdline="-enable-kvm -smp $numCPUs -m $ramSize -machine q35 -device qemu-xhci -device usb-tablet -device usb-kbd -device intel-hda -device hda-duplex"
if [ "$efiFirmware" = "yes" ]; then
qemuCmdline="$qemuCmdline -bios /usr/share/ovmf/OVMF.fd"
fi
if [ "$graphicsMode" = "qxl" ]; then
qemuCmdline="$qemuCmdline -vga qxl"
elif [ "$graphicsMode" = "virgl" ]; then
qemuCmdline="$qemuCmdline -vga virtio -display gtk,gl=on"
else # VGA graphics, unaccelerated
qemuCmdline="$qemuCmdline -vga std"
fi
if [ "$vmmode" = "b" ]; then
qemuInitCmdline="$qemuCmdline -hda $imgPath"
else
if [ "$noDisk" = "yes" ]; then
qemuInitCmdline="$qemuCmdline -cdrom $imgPath"
else
if [ "$useRAMDisk" = "yes" ]; then
qemuInitCmdline="$qemuCmdline -boot dc -cdrom $imgPath -hda /dev/shm/vm-isotest-img$vmNameCounter"
qemuCmdline="$qemuCmdline -hda /dev/shm/vm-isotest-img$vmNameCounter"
else
qemuInitCmdline="$qemuCmdline -boot dc -cdrom $imgPath -hda $HOME/vm-isotest-virtdisks/vm-isotest-img$vmNameCounter"
qemuCmdline="$qemuCmdline -hda $HOME/vm-isotest-virtdisks/vm-isotest-img$vmNameCounter"
fi
fi
fi
qemu-system-x86_64 $qemuInitCmdline
if [ "$liveTest" != "yes" ] && [ "$vmmode" != "b" ]; then
qemu-system-x86_64 $qemuCmdline
fi
if [ "$persistDisk" != "yes" ] && [ "$vmmode" != "b" ] && [ "$noDisk" != "yes" ]; then
if [ "$useRAMDisk" = "yes" ]; then
rm "/dev/shm/vm-isotest-img$vmNameCounter"
else
rm "$HOME/vm-isotest-virtdisks/vm-isotest-img$vmNameCounter"
fi
fi
fi | {
"domain": "codereview.stackexchange",
"id": 43416,
"lm_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, bash, installer",
"url": null
} |
beginner, bash, installer
Answer: The code is totally clean and readable. There is nothing to be embarrassed about here. You've picked sane variable names and consistently followed good indentation. Nesting the thens on the line with the ifs is good for readability and idiomatic shell. You're doing better than code I've seen from proprietary software developers writing installers.
nits
Check out shellcheck. It will encourage you to quote your variable substitutions and not use $ inside of $(( ))-style calculations.
Using [[ ]] - double square brackets - instead of single square brackets will help avoid some surprises.
You can combine your conditionals in one set of brackets. So [ "$vmmode" = "d" ] || [ "$vmmode" = "l" ] becomes [ "$vmmode" == "d" || "$vmmode" == "l" ]. This also shows that using == is good for indicating an equality check so that a single equals is clearly an assignment.
It is a good habit to use $!/usr/bin/env bash to support systems that have bash in a non-standard path.
suggestions
Most of your code is dealing with arguments. You will probably find that getopt will let you do that with less code on your part.
For code this long I would try to split it up into functions. As I've noted elsewhere this is good for readability and gives you variable scoping, if you want it.
If you want to push your shell ability further, consider reading the Google Shell Style Guide. I don't agree with all of their suggestions, but they explain their reasoning well enough that you can consider what will be beneficial for you. | {
"domain": "codereview.stackexchange",
"id": 43416,
"lm_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, bash, installer",
"url": null
} |
c#, .net, escaping, utf-8
Title: Wielding .NET masterfully to encode non-alphanumeric characters into utf-8 hex representation
Question: I have these two methods that work, but I also hate because they almost certainly can be improved. I'm hoping to gain some guidance from others who are more knowledgable of .NET's offering for encodings and byte manipulation.
Given a string, any character that is not a-z, A-Z, 0-9 is replaced by hex values enclosed in square brackets.
abc123 => abc123
abc-123 => abc[2D]123
abc[]123 => abc[5B][5D]123
abc©def => abc[C2][A9]def
What magic is out there? I'm on .NET Core 3.1, but everything is appreciated.
public static string Encode(string str) => String.Concat(Encoding.UTF8.GetBytes(str).Select(cc =>
{
if ('a' <= cc && cc <= 'z' || 'A' <= cc && cc <= 'Z' || '0' <= cc && cc <= '9')
{
// convert byte back to a character
return $"{Convert.ToChar(cc)}";
}
else
{
// convert byte to hex representation
return $"[{Convert.ToInt32(cc):X}]";
}
}));
public static string Decode(string str)
{
List<byte> bytes = new List<byte>();
StringBuilder hex = new StringBuilder();
bool inHex = false;
foreach (char cc in str.ToCharArray())
{
if (cc == '[')
{
inHex = true;
}
else if (cc == ']')
{
inHex = false;
// convert the hex string to a byte
bytes.Add(Convert.ToByte(hex.ToString(), fromBase: 16));
hex.Clear();
}
else if (inHex)
{
hex.Append(cc);
}
else
{
bytes.Add((byte)cc);
}
}
return Encoding.UTF8.GetString(bytes.ToArray());
}
Answer:
There is no arguments validations. this is important, as you need to validate the arguments before processing them. In your case, ArgumentNullException would be suitable. to check if the passed arguments are null or empty strings (whitespace perhaps). | {
"domain": "codereview.stackexchange",
"id": 43417,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, escaping, utf-8",
"url": null
} |
c#, .net, escaping, utf-8
you can use char.IsLetterOrDigit(char c) instead of
if ('a' <= cc && cc <= 'z' || 'A' <= cc && cc <= 'Z' || '0' <= cc && cc <= '9')
using Convert.ToXX extensions is fine in safe-senarios (where the values are always valid), however, in most cases you should consider using TryParse as a safe and less error prone parsing approach. (e.g. char.TryParse, int.TryParse ..etc.).
str.ToCharArray() is unnecessary as you can access to the string chars directly using indexing.
In Decode your List<byte> is not needed, as you can store the two-characters in a temporary string, and then convert it from hexadecimal to its original form, and append the results to the StringBuilder. (or you can store the start index, and use it for the conversion.
Decode method assumes that there is an open and close brackets, how do you think it would behave if there is missing close brackets or duplicated brackets or a bracket that is not intent to be a part of the conversion process ?. For simple processing, you can use IndexOf to check the next bracket index, and get the hexadecimal value between them, hence, Substring would be useful here (also Range would be much modern approach). Although, if the hexdecimal value will always have fixed length (in your code you only use one-hexdecimal that would take two characters, so the length is fixed to 2-chars). You can define that in your class, and decode it based on the fixed length (in this case, you would use Substring or Range directly, and you only check for the current index plus the next index (which is index + fixed length)).
(untested) see the Update Below
Example of applying some of the above notes :
public static string Encode(string str)
{
// no need to do anything, just return the source.
if (string.IsNullOrWhiteSpace(str)) return str;
StringBuilder builder = new StringBuilder();
for(int x = 0; x < str.Length; x++)
{
var character = str[x]; | {
"domain": "codereview.stackexchange",
"id": 43417,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, escaping, utf-8",
"url": null
} |
c#, .net, escaping, utf-8
for(int x = 0; x < str.Length; x++)
{
var character = str[x];
if(!char.IsLetterOrDigit(character))
{
builder.Append($"[{((byte)character):X2}]");
}
else
{
builder.Append(character);
}
}
return builder.ToString();
}
public static string Decode(string str)
{
// no need to do anything, just return the source.
if (string.IsNullOrWhiteSpace(str)) return str;
StringBuilder builder = new StringBuilder();
for (int i = 0; i < str.Length; i++)
{
char character = str[i];
if (character == '[')
{
var nextIndex = str.IndexOf(']', i) - 1;
if(nextIndex > 0)
{
var temp = str.Substring(i + 1, nextIndex - i);
builder.Append(Encoding.UTF8.GetString(new[] { Convert.ToByte(temp, 16) }));
i = nextIndex + 1;
}
}
else
{
builder.Append(character);
}
}
return builder.ToString();
}
In the Encode method, I didn't use LINQ; because it would be more readable and easy to follow if I just use a simple loop. As I prefer readability over LINQ approach, and also it gives more harmony to the code between both Decode and Encode methods.
If you want another way of Decoding you could use Regex.Replace this would give you the same results, but with shorter code:
public static string Decode(string str)
{
// no need to do anything, just return the source.
if (string.IsNullOrWhiteSpace(str)) return str;
return Regex.Replace(str, "\\[([^]]+)\\]", new MatchEvaluator((match) =>
{
return Encoding.UTF8.GetString(new[] { Convert.ToByte(match.Groups[1].Value, 16) });
}), RegexOptions.IgnoreCase);
} | {
"domain": "codereview.stackexchange",
"id": 43417,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, escaping, utf-8",
"url": null
} |
c#, .net, escaping, utf-8
UPDATE
I've done some testing on the above example (thanks to @pm100 for mention it), I just changed it to a better one. The following would only serves the same logic as the original, however, it can be expanded to adopt any new requirements. You can override GetEncodeCharacterBytes to manipulate how the character would be encoded. (the default would returns a hexadecimal bytes).
public class DefaultNonAlphanumericEncoder : NonAlphanumericEncoder
{
// default configurations
public DefaultNonAlphanumericEncoder() : base('[', ']', Encoding.UTF8) { }
}
public abstract class NonAlphanumericEncoder
{
private readonly byte _openTag;
private readonly byte _closeTag;
private Encoding _encoding;
/// <summary>
/// An open constructor to define the open/close tags along with an encoding.
/// </summary>
/// <param name="openTag"></param>
/// <param name="closeTag"></param>
/// <param name="encoding"></param>
/// <exception cref="ArgumentNullException"></exception>
public NonAlphanumericEncoder(char openTag, char closeTag, Encoding encoding)
{
_openTag = (byte)openTag;
_closeTag = (byte)closeTag;
_encoding = encoding ?? throw new ArgumentNullException(nameof(encoding));
}
protected virtual IEnumerable<byte> GetEncodeCharacterBytes(byte character) => _encoding.GetBytes($"[{character:X2}]");
private IEnumerable<byte> InternalEncode(byte[] bytes)
{
if (bytes?.Length == 0) yield break;
for (int i = 0; i < bytes.Length; i++)
{
byte c = bytes[i];
if (IsNonAlphanumeric(c))
{
var encodedBytes = GetEncodeCharacterBytes(c);
foreach (var encoded in encodedBytes)
yield return encoded;
}
else
{
yield return c;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43417,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, escaping, utf-8",
"url": null
} |
c#, .net, escaping, utf-8
}
}
private IEnumerable<byte> InternalDecode(byte[] bytes)
{
byte[] hexBytes = new byte[2];
for (int i = 0; i < bytes.Length; i++)
{
byte b = bytes[i];
// covers case 4
if ((i + 1) < bytes.Length && bytes[i] == _closeTag && bytes[i + 1] == _openTag) { continue; }
if (b != _openTag)
{
yield return b;
}
else
{
hexBytes[0] = bytes[++i];
hexBytes[1] = bytes[++i];
yield return Convert.ToByte(_encoding.GetString(hexBytes), 16);
// we assumed that the next index would hold the close tag
// for this, we increament by 1 to skip it.
i++;
}
}
}
public string Encode(string str)
{
// no need to do anything, just return the source.
if (string.IsNullOrWhiteSpace(str)) return str;
var sourceBytes = _encoding.GetBytes(str);
var encodedBytes = InternalEncode(sourceBytes).ToArray();
return _encoding.GetString(encodedBytes);
}
public string Decode(string str)
{
// no need to do anything, just return the source.
if (string.IsNullOrWhiteSpace(str)) return str;
var sourceBytes = _encoding.GetBytes(str);
var decodedBytes = InternalDecode(sourceBytes).ToArray();
return _encoding.GetString(decodedBytes);
}
// helpers
private bool IsNumber(byte character) => character >= '0' && character <= '9';
private bool IsLetter(byte character) => (character >= 'A' && character <= 'Z') || (character >= 'a' && character <= 'z');
private bool IsNonAlphanumeric(byte character) => !IsLetter(character) && !IsNumber(character);
} | {
"domain": "codereview.stackexchange",
"id": 43417,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, escaping, utf-8",
"url": null
} |
c#, .net, escaping, utf-8
}
usage :
// Default encoder uses UTF-8 with [] tags
var encoder = new DefaultNonAlphanumericEncoder();
var encoded = encoder.Encode("abc©def");
var decoded = encoder.Decode(encoded); | {
"domain": "codereview.stackexchange",
"id": 43417,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, escaping, utf-8",
"url": null
} |
python, beginner, python-3.x, battleship
Title: Python battleship game - Code to place random ships on the board
Question: I am writing code to randomly place ships on a board in Python. I need help reducing the amount of Global variables I have in this code. I have thought about using a Ship class here but I'm not very comfortable with OOPS yet.
I have also thought about passing these global variables by as function arguments but that would lead to a lot of functions having arguments they never use, for e.g place_ships_helper would need ship_positions and board which it never uses.
Would really appreciate any help here. Thankyou !
import random
display_board = [['@']*10 for i in range(10)]
board = [[0]*10 for i in range(10)]
total_ships = 4
sunk_ships = 0
turns = 10
ship_positions = [[]]
#-----------------------------------------------------------------------------------------------------------------------------------
# PLACE SHIPS LOGIC
#-----------------------------------------------------------------------------------------------------------------------------------
def place_ships(start_row,end_row,start_col,end_col):
valid = True
for r in range(start_row,end_row):
for c in range(start_col,end_col):
if board[r][c] != 0:
valid = False
break
if valid:
ship_positions.append([start_row,end_row,start_col,end_col])
for r in range(start_row,end_row):
for c in range(start_col,end_col):
board[r][c] = 1
#print(board)
return valid
def place_ships_helper(row,col,length,direction):
start_row, end_row, start_col, end_col = row, row + 1, col, col + 1
if direction == "left":
if col - length < 0:
return False
start_col = col - length + 1
elif direction == "right":
if col + length >= board.size():
return False
end_col = col + length | {
"domain": "codereview.stackexchange",
"id": 43418,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, battleship",
"url": null
} |
python, beginner, python-3.x, battleship
elif direction == "up":
if row - length < 0:
return False
start_row = row - length + 1
elif direction == "down":
if row + length >= board.size():
return False
end_row = row + length
return place_ships(start_row, end_row, start_col, end_col)
def generate_ships():
ships_placed = 0
rows,cols = board.size(),board.size()
while ships_placed != total_ships:
random_row = random.randint(0, rows - 1)
random_col = random.randint(0, cols - 1)
direction = random.choice(["left", "right", "up", "down"])
ship_size = random.randint(3, 5)
if place_ships_helper(random_row, random_col, ship_size, direction):
ships_placed += 1
def print_board():
generate_ships()
for i in board:
print(i)
if __name__ == "__main__":
print_board() | {
"domain": "codereview.stackexchange",
"id": 43418,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, battleship",
"url": null
} |
python, beginner, python-3.x, battleship
if __name__ == "__main__":
print_board()
Answer: The program had several unused items. I ignored and ultimately deleted them.
Stop using global variables and ignore OOP for now. Absolutely, stop using
global variables from this point forward. They are never needed except under
quite unusual circumstances -- none that you are likely to encounter at this
stage of your journey. And before dealing with OOP, first develop some
proficiency in building programs from small, focused, well-designed functions.
Until you do that, OOP will be at best a distraction and at worst a crutch
allowing you to smuggle global-variable thinking into your code while
pretending that you're not.
Functions: a few best practices. Build functions that take data as input
and return data as output. Whenever feasible, do not ask functions to mutate
the data they are given. The basic model: information in, information out, and
never mess with someone else's information.
Step 1: move the globals into print_board(). Try to run the program.
You'll encounter a series of problems. For example, first we see that
generate_ships() will have no access to board. The solution is to have the
function return the board that it creates. While we're doing that, we also move
the ship-counting logic to that function, because that's where the information
needs to be managed. Run the program again: you'll see that we need to pass
board down the call chain, but that's easy enough to do. After a few edits
like that, you'll have a running program.
Step 2: tidy up. Define constants for empty and full. Put spaces after commas
and other operators. For consistency, one should also define constants for the
directions, but that topic raises other issues, so let's defer that. And
rearrange the functions so that they agree with the narrative flow and
structural hierarchy of the program. Here's the code after those adjustments.
import random
EMPTY = '.'
FULL = 'x' | {
"domain": "codereview.stackexchange",
"id": 43418,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, battleship",
"url": null
} |
python, beginner, python-3.x, battleship
EMPTY = '.'
FULL = 'x'
def print_board():
board = generate_ships(4)
for row in board:
print(' '.join(row))
def generate_ships(total_ships):
board = [[EMPTY]*10 for i in range(10)]
ships_placed = 0
rows, cols = len(board), len(board)
while ships_placed != total_ships:
random_row = random.randint(0, rows - 1)
random_col = random.randint(0, cols - 1)
direction = random.choice(["left", "right", "up", "down"])
ship_size = random.randint(3, 5)
ships_placed += place_ships_helper(board, random_row, random_col, ship_size, direction)
return board
def place_ships_helper(board, row, col, length, direction):
start_row, end_row, start_col, end_col = row, row + 1, col, col + 1
if direction == "left":
if col - length < 0:
return False
start_col = col - length + 1
elif direction == "right":
if col + length >= len(board):
return False
end_col = col + length
elif direction == "up":
if row - length < 0:
return False
start_row = row - length + 1
elif direction == "down":
if row + length >= len(board):
return False
end_row = row + length
return place_ships(board, start_row, end_row, start_col, end_col)
def place_ships(board, start_row, end_row, start_col, end_col):
for r in range(start_row, end_row):
for c in range(start_col, end_col):
if board[r][c] != EMPTY:
return False
for r in range(start_row, end_row):
for c in range(start_col, end_col):
board[r][c] = FULL
return True
if __name__ == "__main__":
print_board() | {
"domain": "codereview.stackexchange",
"id": 43418,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, battleship",
"url": null
} |
python, beginner, python-3.x, battleship
if __name__ == "__main__":
print_board()
Step 3. assess. Things are considerably better: we have no global
variables! But our functions are defined entirely around mutation, which we'd
like to avoid. And our modeling of directions data seems awkward, resulting in
four chunks of semi-repetitive code.
Step 4. directions as change values. The noted problems spring
from a poor modeling of data. Currently, we are using English words to
represent directions, but those words have no connection to the underlying data
used by the program. We have a board with rows, columns, and cells. Using the
language of such data, how does one represent a direction? There are various
options, but one common approach is to represent a direction as pairs of
(row_change, col_change).
Step 5. stop mutating. Rather than asking lower-level functions to mutate
the board that we give them, we should build the board up at the top level by
asking lower-level functions go give us helpful data to achieve that. One
approach is to ask a lower-level function to generate a single valid ship. How
do we represent a ship in terms of the data? Again, a sequence of pairs will
work, specifically (row, col) pairs. So print_board() will ask
generate_board() to return the board and ships that it creates. To do that,
generate_board() will ask generate_ship() for a ship until there are enough
of them. And generate_ship() will delegate secondary calculations to utility
functions, in particular the check for whether a needed cell is both valid and
empty.
import random
EMPTY = '.'
FULL = 'x'
DIRECTIONS = (
(0, 1), # Right
(0, -1), # Left
(1, 0), # Up
(-1, 0), # Down
)
MIN_SIZE = 3
MAX_SIZE = 5
def print_board():
board, ships = generate_board(10, 4)
for row in board:
print(' '.join(row)) | {
"domain": "codereview.stackexchange",
"id": 43418,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, battleship",
"url": null
} |
python, beginner, python-3.x, battleship
def generate_board(board_size, n_ships):
# A board without ship information is ambiguous so return both.
board = [[EMPTY] * board_size for _ in range(board_size)]
ships = []
while len(ships) < n_ships:
row = random.randint(0, board_size - 1)
col = random.randint(0, board_size - 1)
direction = random.choice(DIRECTIONS)
ship_size = random.randint(MIN_SIZE, MAX_SIZE)
ship = generate_ship(board, row, col, ship_size, direction)
if ship:
ships.append(ship)
for r, c in ship:
board[r][c] = FULL
return (board, ships)
def generate_ship(board, row, col, ship_size, direction):
r = row
c = col
dr, dc = direction
cells = []
for _ in range(ship_size):
if is_empty(board, r, c):
cells.append((r, c))
r += dr
c += dc
else:
return None
return cells
def is_empty(board, row, col):
try:
return min(row, col) >= 0 and board[row][col] == EMPTY
except IndexError:
pass
return False
if __name__ == "__main__":
print_board() | {
"domain": "codereview.stackexchange",
"id": 43418,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, beginner, python-3.x, battleship",
"url": null
} |
c#, thread-safety, async-await
Title: Deleting entities asynchronously in C#
Question: I have a method that takes a collection of objects, and in turn calls a method that handles a single object. My question is, do I need to handle the tasks coming from the DeleteSingleAsync method since it's not really an async method or is this safe since the concrete implementation is just returning a completed task.
My initial gut concern is with exceptions/cancelation tokens not being handled correctly, or a slim possibility of a race condition in the tableTransactionActions object.
private readonly IList<TableTransactionAction> tableTransactionActions;
public Task DeleteSingleAsync(TEntity entity, CancellationToken cancellationToken = default)
{
cancellationToken.ThrowIfCancellationRequested();
tableTransactionActions.Add(new TableTransactionAction(TableTransactionActionType.Delete, entity));
return Task.CompletedTask;
}
public Task DeleteAsync(IEnumerable<TEntity> entities, CancellationToken cancellationToken = default)
{
foreach (var entity in entities)
{
DeleteSingleAsync(entity, cancellationToken);
}
return Task.CompletedTask;
}
Answer: Not waiting in DeleteAsync should be safe but I wouldn't pass it from a code review perspective as in the future if DeleteSingleAsync changes to be truly async and someone doesn't know they also need to change DeleteAsync bugs could come out of it. This is coding to the implementation and not the interface, which is bad practice IMO. We still don't need to await it in DeleteAsync just do
return Task.WhenAll(entities.Select(entity => DeleteSingleAsync(entity, cancellationToken)) | {
"domain": "codereview.stackexchange",
"id": 43419,
"lm_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#, thread-safety, async-await",
"url": null
} |
c#, thread-safety, async-await
Now in the future if we change DeleteSingleAsync to be async DeleteAsync is still good to go.
If tableTransactionActions is a standard C# List<> then it is not thread safe. Without knowing more of how this is used outside of this small snippet I would suggest to use the ConcurrentQueue, or possibly ConcurrentStack, instead of List. But to know which Thread Safe class to use would need more information then the current code shown. Thread safety isn't about async it's about being called in parallel from multiple threads at the same time. | {
"domain": "codereview.stackexchange",
"id": 43419,
"lm_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#, thread-safety, async-await",
"url": null
} |
c#, algorithm, computational-geometry, unity3d
Title: Union Polygon Algorithm
Question: This is my attempt at creating a Union Algorithm for an arbitrary set of any number of arbitrary simple polygons. It works for both convex and concave polygons.
public static List<List<Vector2>> UnionPolygon(List<List<Vector2>> uvPolygons)
{
List<List<Vector2>> newPolygons = new List<List<Vector2>>();
#region Fix Winding Order
for (int i = 0; i < uvPolygons.Count; i++)
{
float sum = new float();
for (int j = 0; j < uvPolygons[i].Count; j++)
{
Vector3 a = uvPolygons[i][j];
Vector3 b = uvPolygons[i][(j + 1) % uvPolygons[i].Count];
sum += (b.x - a.x) * (b.y + a.y);
}
if (Mathf.Sign(sum) < 0)
uvPolygons[i].Reverse();
}
#endregion
#region Find Outside Point
Vector2 pointOutside = new Vector2();
for (int i = 0; i < uvPolygons.Count; i++)
{
for (int j = 0; j < uvPolygons[i].Count; j++)
{
if (uvPolygons[i][j].x > pointOutside.x)
{
pointOutside = uvPolygons[i][j];
}
}
}
pointOutside += new Vector2(1f, 0);
#endregion
while (uvPolygons.Count > 0)
{
List<Vector2> newPolygon = new List<Vector2>();
int P = 0; //currentPolygon
int I = 0; //currentIndex
#region Setup First Point
//Make sure starting point is not in any polygons
for (int p = 0; p < uvPolygons.Count; p++)
{
if (p != P)
{
if (!CheckIndex(I, 0, uvPolygons[0].Count))
break;
if (IsPointInPolygon(uvPolygons[0][I], uvPolygons[p], pointOutside))
{
p = 0;
I++;
continue;
}
}
}
#endregion
HashSet<int> hashedPolygons = new HashSet<int>();
while (true)
{
hashedPolygons.Add(P); | {
"domain": "codereview.stackexchange",
"id": 43420,
"lm_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#, algorithm, computational-geometry, unity3d",
"url": null
} |
c#, algorithm, computational-geometry, unity3d
while (true)
{
hashedPolygons.Add(P);
if (newPolygon.Contains(uvPolygons[P][I % uvPolygons[P].Count]))
break;
Vector2 a = uvPolygons[P][I % uvPolygons[P].Count];
Vector2 b = uvPolygons[P][(I + 1) % uvPolygons[P].Count];
newPolygon.Add(a);
bool intersected = false;
Vector3 intersection = new Vector3();
Vector3 closestIntersection = new Vector3();
float closestDistance = new float();
int tp = new int();
int ti = new int();
for (int p = 0; p < uvPolygons.Count; p++)
{
if (p != P)
{
for (int i = 0; i < uvPolygons[p].Count; i++)
{
Vector2 x = uvPolygons[p][i];
Vector2 y = uvPolygons[p][(i + 1) % uvPolygons[p].Count];
if (AreLinesIntersecting(a, b, x, y, false))
{
if (LineLineIntersection(a, (b - a).normalized, x, (y - x).normalized, out intersection))
{
if (newPolygon.Contains(intersection))
continue;
if (!intersected)
{
closestIntersection = intersection;
closestDistance = Vector3.Distance(a, intersection); | {
"domain": "codereview.stackexchange",
"id": 43420,
"lm_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#, algorithm, computational-geometry, unity3d",
"url": null
} |
c#, algorithm, computational-geometry, unity3d
tp = p;
ti = i;
intersected = true;
}
else if (Vector3.Distance(a, intersection) < closestDistance)
{
closestIntersection = intersection;
closestDistance = Vector3.Distance(a, intersection);
tp = p;
ti = i;
}
}
}
}
}
}
if (intersected)
{
newPolygon.Add(closestIntersection);
P = tp;
I = ti;
}
I++;
}
if (hashedPolygons.Count == 1)
{
newPolygons.Add(new List<Vector2>(newPolygon));
uvPolygons.RemoveAt(0);
continue;
}
for (int i = uvPolygons.Count - 1; i >= 0; i--)
if (hashedPolygons.Contains(i))
uvPolygons.RemoveAt(i);
if (uvPolygons.Count > 0)
uvPolygons.Add(new List<Vector2>(newPolygon));
}
return newPolygons;
}
public static bool CheckIndex(int i, int min, int max)
{
if (i >= min && i < max)
return true;
else
return false;
}
public static bool AreLinesIntersecting(Vector2 p1x, Vector2 p1y, Vector2 p2x, Vector2 p2y, bool shouldIncludeEndPoints)
{
bool isIntersecting = false;
float denominator = (p2y.y - p2x.y) * (p1y.x - p1x.x) - (p2y.x - p2x.x) * (p1y.y - p1x.y); | {
"domain": "codereview.stackexchange",
"id": 43420,
"lm_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#, algorithm, computational-geometry, unity3d",
"url": null
} |
c#, algorithm, computational-geometry, unity3d
float denominator = (p2y.y - p2x.y) * (p1y.x - p1x.x) - (p2y.x - p2x.x) * (p1y.y - p1x.y);
//Make sure the denominator is > 0, if not the lines are parallel
if (denominator != 0f)
{
float u_a = ((p2y.x - p2x.x) * (p1x.y - p2x.y) - (p2y.y - p2x.y) * (p1x.x - p2x.x)) / denominator;
float u_b = ((p1y.x - p1x.x) * (p1x.y - p2x.y) - (p1y.y - p1x.y) * (p1x.x - p2x.x)) / denominator;
//Are the line segments intersecting if the end points are the same
if (shouldIncludeEndPoints)
{
//Is intersecting if u_a and u_b are between 0 and 1 or exactly 0 or 1
if (u_a >= 0f && u_a <= 1f && u_b >= 0f && u_b <= 1f)
{
isIntersecting = true;
}
}
else
{
//Is intersecting if u_a and u_b are between 0 and 1
if (u_a > 0f && u_a < 1f && u_b > 0f && u_b < 1f)
{
isIntersecting = true;
}
}
}
return isIntersecting;
}
public static bool LineLineIntersection(Vector3 linePoint1, Vector3 lineVec1, Vector3 linePoint2, Vector3 lineVec2, out Vector3 intersection)
{
Vector3 lineVec3 = linePoint2 - linePoint1;
Vector3 crossVec1and2 = Vector3.Cross(lineVec1, lineVec2);
Vector3 crossVec3and2 = Vector3.Cross(lineVec3, lineVec2);
float planarFactor = Vector3.Dot(lineVec3, crossVec1and2);
//is coplanar, and not parallel
if (Mathf.Abs(planarFactor) < 0.0001f
&& crossVec1and2.sqrMagnitude > 0.0001f)
{
float s = Vector3.Dot(crossVec3and2, crossVec1and2)
/ crossVec1and2.sqrMagnitude;
intersection = linePoint1 + (lineVec1 * s);
return true;
}
else
{
intersection = Vector3.zero;
return false;
}
}
public static bool IsPointInPolygon(Vector2 point, List<Vector2> polygonPoints, Vector2 pointOutside)
{
int numIntersections = 0; | {
"domain": "codereview.stackexchange",
"id": 43420,
"lm_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#, algorithm, computational-geometry, unity3d",
"url": null
} |
c#, algorithm, computational-geometry, unity3d
for (int j = 0; j < polygonPoints.Count; j++)
{
Vector2 uv1 = polygonPoints[j];
Vector2 uv2 = polygonPoints[(j + 1) % polygonPoints.Count];
if (AreLinesIntersecting(point, pointOutside, uv1, uv2, true))
numIntersections++;
}
if (numIntersections == 0 || numIntersections % 2 == 0)
return false;
else
return true;
}
Briefly on how this algorithm works is it follows a polygon through its winding order until it detects an intersection. Upon intersection, it jumps to the intersected polygon. Repeat until it has made its way around to the beginning.
Setup requirements for this to work correctly:
The Starting Index Must Be Outside All Other Polygons
All Polygons Must Share Winding Order
All Polygons Must Be Simple (i.e. not open or self intersecting)
Finally, if two polygons share an intersecting edge, the algorithm will "jump over" the second polygon. (as seen in figure 1) So it keeps track of the number of starting polygons and will repeat until all are accounted for.
It has a superficial resemblance to the Weiler Atherton algorithm
Answer: Regions
Well, regions can help group some things together, but most of the times having regions indicates the code in question has some problems.
Regions grouping methods inside a class normally indicates that the method has too many responsibilities which is a design flaw.
Regions inside a method is just a no go, because they indicate that the method itself is doing too much and tends to be a god-method.
#region Fix Winding Order just screams for a method which is doing just what the regions-text says, which applies for
#region Find Outside Point and #region Setup First Point as well.
float sum = new float();
Why don't you use float sum = 0f; ? that would be consistent. You have int P = 0; as well instead of int P = new int(); Beeing consistent in the way the code is written makes it much easier to read and understand. | {
"domain": "codereview.stackexchange",
"id": 43420,
"lm_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#, algorithm, computational-geometry, unity3d",
"url": null
} |
c#, algorithm, computational-geometry, unity3d
public static bool CheckIndex(int i, int min, int max)
{
if (i >= min && i < max)
return true;
else
return false;
}
A construct, like if a condition is true return true otherwise return false, can and should be shortened to just return the codition like
public static bool CheckIndex(int i, int min, int max)
{
return i >= min && i < max;
}
In addition, omitting braces althought they might be optional can lead to hidden and therefor hard to find bugs.
If AreLinesIntersecting() is behaving as it should, it could be greatly enhanced by
returning early for denominator ==0f, well at the second glance that only could be true. If it is true then the comment //Make sure the denominator is > 0, if not the lines are parallel is a lie.
combining the if and the else` branche into one statement
like so (taking into account that the code returns the same results as the former method):
public static bool AreLinesIntersecting(Vector2 p1x, Vector2 p1y, Vector2 p2x, Vector2 p2y, bool shouldIncludeEndPoints)
{
float denominator = (p2y.y - p2x.y) * (p1y.x - p1x.x) - (p2y.x - p2x.x) * (p1y.y - p1x.y);
//Make sure the denominator is > 0, if not the lines are parallel
if (denominator == 0f) { return false; }
float u_a = ((p2y.x - p2x.x) * (p1x.y - p2x.y) - (p2y.y - p2x.y) * (p1x.x - p2x.x)) / denominator;
float u_b = ((p1y.x - p1x.x) * (p1x.y - p2x.y) - (p1y.y - p1x.y) * (p1x.x - p2x.x)) / denominator;
return u_a > 0f && u_a < 1f && u_b > 0f && u_b < 1f;
} | {
"domain": "codereview.stackexchange",
"id": 43420,
"lm_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#, algorithm, computational-geometry, unity3d",
"url": null
} |
javascript, html, chat
Title: Simple code example for WebRTC
Question: I'm trying to make a simple and straightforward example for WebRTC without a signaling server. The code works (whole HTML file below), but it feels like I'm overshadowing something in the logic that I can't pinpoint. I need help simplifying this code for easier readability. There are little limitations in regards to legacy.
<!DOCTYPE html>
<meta charset="utf-8">
<title>miniWebRTC</title>
<div id="createRoom">
<h3>Create or join a room?</h3>
<button id="createBtn">BOB: Create</button>
<button id="joinBtn">ALICE: Join</button>
</div>
<div id="bobPrompt">
<h3>BOB: Send your local offer to ALICE</h3>
<input id="localOffer">
<h3>Then, paste the "answer" you received</h3>
<input id="remoteAnswer">
<br>
<br>
<button id="answerRecdBtn">Okay, I pasted it.</button>
</div>
<div id="alicePrompt">
<h3>ALICE: Paste the "offer" you received</h3>
<input id="remoteOffer">
<br>
<br>
<button id="offerRecdBtn">Okay, I pasted it.</button>
<h3>Then, send your local answer to BOB</h3>
<input id="localAnswer">
</div>
<div id="chatPrompt">
<h1>Chat</h1>
<br>
<div id="chatlog" style="height:200px; overflow:auto; border:1px solid"></div>
<br>
<input type="text" id="messageTextBox" placeholder="Type your message here">
<button onclick="sendMessage()">Send message</button>
</div>
<script>
// @ts-check
const config = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] };
// The local browser's RTCPeerConnection
const peerConnection = new RTCPeerConnection(config)
/** @type {RTCDataChannel | null} data channel */
let activeDataChannel = null; | {
"domain": "codereview.stackexchange",
"id": 43421,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, chat",
"url": null
} |
javascript, html, chat
/** @type {RTCDataChannel | null} data channel */
let activeDataChannel = null;
function sendMessage() {
if (messageTextBox.value) {
activeDataChannel.send(JSON.stringify({ message: messageTextBox.value }));
chatlog.innerHTML += `<span>ME: ${messageTextBox.value}</span><br/>`;
messageTextBox.value = "";
}
}
/**
* Shows one of the 4 div elements in the webpage, and hides the rest.
*
* @param {part} part The part to show.
*/
function showPart(part) {
const divList = [createRoom, bobPrompt, alicePrompt, chatPrompt]
// Hide all elements that are not part
divList.forEach(div => div.style.display = (part == div ? "block" : "none"));
}
showPart(createRoom);
// BOB: create room
createBtn.addEventListener("click", async () => {
showPart(bobPrompt);
const dataChannel = peerConnection.createDataChannel('chat');
activeDataChannel = dataChannel;
peerConnection.setLocalDescription(await peerConnection.createOffer())
// Once all ice candidates are collected, set the value
peerConnection.addEventListener("icecandidate", ({ candidate }) => {
if (candidate == null) {
localOffer.value = JSON.stringify(peerConnection.localDescription);
}
})
// BOB: pasted Alice's answer
answerRecdBtn.addEventListener("click", async () => {
const answer = remoteAnswer.value;
const answerDesc = new RTCSessionDescription(JSON.parse(answer))
await peerConnection.setRemoteDescription(answerDesc);
}, { once: true });
// ALICE sent a message to BOB
dataChannel.addEventListener("message", e => {
const data = JSON.parse(e.data)
chatlog.innerHTML += `<span>THEM: ${data.message}</span><br/>`;
chatlog.scrollTop = chatlog.scrollHeight
}) | {
"domain": "codereview.stackexchange",
"id": 43421,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, chat",
"url": null
} |
javascript, html, chat
peerConnection.addEventListener("connectionstatechange", e => {
if (peerConnection.connectionState === "connected") {
// Connected!
showPart(chatPrompt);
}
})
}, { once: true });
// ALICE: listen to room
joinBtn.addEventListener("click", () => {
showPart(alicePrompt);
// ALICE: pasted Bob's answer
offerRecdBtn.addEventListener("click", async () => {
const offer = remoteOffer.value;
const offerDesc = new RTCSessionDescription(JSON.parse(offer))
await peerConnection.setRemoteDescription(offerDesc)
await peerConnection.setLocalDescription(await peerConnection.createAnswer())
peerConnection.addEventListener("icecandidate", e => {
if (e.candidate == null) {
localAnswer.value = JSON.stringify(peerConnection.localDescription);
}
})
}, { once: true });
peerConnection.addEventListener("datachannel", ({ channel }) => {
// Connected!
activeDataChannel = channel;
showPart(chatPrompt);
activeDataChannel.addEventListener("message", e => {
const data = JSON.parse(e.data)
chatlog.innerHTML += `<span>THEM: ${data.message}</span><br/>`;
chatlog.scrollTop = chatlog.scrollHeight
})
})
}, { once: true });
</script>
Answer: It might be a lot clearer if you move the inline functions out of the main body. This allow the main body to concentrate on how the parts are used, gives the parts distinct and useful names, and will likely be more readible in the future when your working model has degraded (or fresh eyes come to it).
I like to think of it in terms of a 'conductor' of an 'orchestra'. First define the players and their instruments, and the guide them through the process.
Instead of:
createBtn.addEventListener("click", async () => {
showPart(bobPrompt);
const dataChannel = peerConnection.createDataChannel('chat');
activeDataChannel = dataChannel;
// ...
}, { once: true }) | {
"domain": "codereview.stackexchange",
"id": 43421,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, chat",
"url": null
} |
javascript, html, chat
// ...
}, { once: true })
try:
function onCreateButtonClick() {
// ...
}
function onJoinButtonClick() {
// ...
}
// main body (IIFE to indicate discreet work)
(() => {
createBtn.addEventListener('click', onCreateButtonClick, { once: true })
joinBtn.addEventListener('click', onJoinButtonClick, { once: true })
})()
Obviously I'm paraphrasing in the example, but this approach can be used for all of the inline functions used as event listener callbacks.
I'd also recommend being more explicit with method names such as sendMessage and showPart so that its clear from the naming what its doing. Having removed clutter from the main body, its easier to use verbosity to aid understanding without it adding more 'noise'.
I used an IIFE to indicate what was 'main', there are several alternatives:
function main() {
// ...
}
main()
Or:
(function main() {
// ...
})()
The purpose of encapsulating, rather than just having more declarations in the at script level scope is that it shows that its a discreet piece of work. The IIFE signature is quote common so becomes easy to spot without having to be pedantic about naming.
Whilst your application is quite simple, you're realising that as things get more complex there is a need to add modularity to help clarify what things are doing. It would be worth reading up on the Single Responsibility Principle to help inform just how much any discrete piece of code should be doing.
As the application becomes more complex, you'll likely want to start using discreet source modules. This will then give you a new challenge, as at present you are relying on globals/module scope to allow access to your peer connection instance. You might well need to think about how to inject dependent variables into those helper functions, for example, passing dependencies as parameters, something like:
function onCreateButtonClick(peerConnection) {
// ...
}
(() => { | {
"domain": "codereview.stackexchange",
"id": 43421,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, chat",
"url": null
} |
javascript, html, chat
(() => {
const peerConnection = new RTCPeerConnection(/*config*/)
createBtn.addEventListener(
'click',
() => onCreateButtonClick(peerConnection),
{ once: true }
) | {
"domain": "codereview.stackexchange",
"id": 43421,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, chat",
"url": null
} |
python, performance, excel
Title: Gathering data from a file and analyzing it
Question: Recently started learning python, and it's quite a difference coming from C and knowledge taught in CS1. Overall, I am trying to build a team building script for my summer side-project (probably will become a full application eventually), but specifically, am I using python dictionaries and classes correctly with what I am trying to do in these early stages.
Find text file, if there is not one, allow user to input employees (for now) and their info.
Gather data using python dictionaries.
Produce excel tables of this said information (2 as of right now: List of their senorities and a table of all the positions).
I'm unsure if I am efficiently solving this problem. The code starts towards the bottom of the code block. You can also ignore the 2 blocks of code where I am trying to create teams - I've researched and found that it's a "knapsack" problem and will be trying to learn that over the next week.
from distutils.command.build import build
import os
from os.path import exists
import csv
import sys
#from tkinter import Y
from openpyxl import Workbook, load_workbook
from openpyxl.worksheet.table import Table, TableStyleInfo
from openpyxl.styles import Color, PatternFill, Font, Border, Alignment
#from openpyxl.cell import Cell
class Positions:
def __init__(self, position):
self.position = position
self.total = 1
class Employee:
total_num_of_employees = 0
total_num_of_seniors = 0
total_num_of_juniors = 0
total_num_of_sophomores = 0
total_num_of_freshman = 0
def __init__(self, emp_num, name, position, senority):
self.emp_num = emp_num
self.name = name
self.position = position
self.senority = senority
Employee.total_num_of_employees += 1
Employee.totals(self.senority) | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
def totals(senority):
if senority == "senior":
Employee.total_num_of_seniors += 1
elif senority == "junior":
Employee.total_num_of_juniors += 1
elif senority == "sophomore":
Employee.total_num_of_sophomores += 1
elif senority == "freshman":
Employee.total_num_of_freshman += 1
def showData(self):
print("ID\t\t:", self.emp_num)
print("Name\t\t:", self.name)
print("Positon\t\t:", self.position)
print("Seniority\t:", self.senority)
def createTeams(employees, numOfTeammates, numOfTeams):
# Create teams
teams = {}
for i in range(numOfTeams):
teams[i] = []
for j in range(numOfTeammates): # N^2 plus doesn't work, gross.
teams[i].append(employees[j])
return teams
def setupTeams(employees):
# Set up number of teams and number of teammates
numOfTeammates = int(input("How many teammates do you want to have in each team? "))
if(Employee.total_num_of_employees % numOfTeammates == 0):
numOfTeams = int(Employee.total_num_of_employees / numOfTeammates)
teams = createTeams(employees, numOfTeammates, numOfTeams)
else:
remainder = Employee.total_num_of_employees % numOfTeammates # how many teams that will have 1 extra player
numOfTeams = int(Employee.total_num_of_employees / numOfTeammates) + remainder
return teams
# Excel Cell Location
def getCellLoc(column_int):
start_index = 1 # starts at A
letter = ''
while column_int > 25 + start_index:
letter += chr(65 + int((column_int-start_index)/26) - 1)
column_int = column_int - (int((column_int-start_index)/26))*26
letter += chr(65 - start_index + (int(column_int)))
return letter
def tableExists(tables, table_name):
for table in tables:
if table == table_name:
return True
return False | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
def numOfEmployeesTable():
column_num = Employee.total_num_of_employees + 8 # 8 extra spaces to the right.
loc = getCellLoc(column_num) # get excel cell location (letter)
# Create total table for each senority level
wb = load_workbook("Team Creator.xlsx")
ws = wb.active
# Create styles
greenFill = PatternFill(start_color='C6E0B4',
end_color='C6E0B4',
fill_type='solid')
yellowFill = PatternFill(start_color='FFE699',
end_color='FFE699',
fill_type='solid')
blueFill = PatternFill(start_color='B4C6E7',
end_color='B4C6E7',
fill_type='solid')
redFill = PatternFill(start_color='F8CBAD',
end_color='F8CBAD',
fill_type='solid')
greyFill = PatternFill(start_color='BFBFBF',
end_color='BFBFBF',
fill_type='solid')
# Populate table with totals
ws[loc + str(1)] = "Total"
ws[loc + str(2)] = Employee.total_num_of_seniors
ws[loc + str(2)].fill = greenFill
ws[loc + str(2)].alignment = Alignment(horizontal='center')
ws[loc + str(3)] = Employee.total_num_of_juniors
ws[loc + str(3)].fill = yellowFill
ws[loc + str(3)].alignment = Alignment(horizontal='center')
ws[loc + str(4)] = Employee.total_num_of_sophomores
ws[loc + str(4)].fill = blueFill
ws[loc + str(4)].alignment = Alignment(horizontal='center')
ws[loc + str(5)] = Employee.total_num_of_freshman
ws[loc + str(5)].fill = redFill
ws[loc + str(5)].alignment = Alignment(horizontal='center')
ws[loc + str(6)] = Employee.total_num_of_employees
ws[loc + str(6)].fill = greyFill
ws[loc + str(6)].alignment = Alignment(horizontal='center')
loc = getCellLoc(column_num + 1) # Move one letter over to the right
ws.column_dimensions[loc].width = 20
ws[loc + str(1)] = "Class" | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
ws[loc + str(2)] = "Senior Class"
ws[loc + str(3)] = "Junior Class"
ws[loc + str(4)] = "Sophomore Class"
ws[loc + str(5)] = "Freshman Class"
ws[loc + str(6)] = "Total"
wb.save("Team Creator.xlsx")
def positionsTable(employees):
column_num = Employee.total_num_of_employees + 8
loc = getCellLoc(column_num)
wb = load_workbook("Team Creator.xlsx")
ws = wb.active
current_tables = ws._tables
# Styles
lighestColor = PatternFill(start_color='FF9999',
end_color='FF9999',
fill_type='solid')
lighterColor = PatternFill(start_color='FF7A7A',
end_color='FF7A7A',
fill_type='solid')
lightColor = PatternFill(start_color='FF5E5E',
end_color='F8CBAD',
fill_type='solid')
darkerColor = PatternFill(start_color='FF3030',
end_color='FF3030',
fill_type='solid')
darkestColor = PatternFill(start_color='FF1212',
end_color='FF1212',
fill_type='solid')
tabStyle = TableStyleInfo(name="TableStyleLight1", showFirstColumn=True, showLastColumn=False, showRowStripes=False, showColumnStripes=True)
positions = {} # dictionary to hold position objects
pos_total = 0
for key in employees:
pos = employees[key].position
if(pos in positions):
positions[pos].total += 1
continue # if position is already in dictionary, increment total
data = Positions(pos)
positions[pos] = data
pos_total += 1
if(tableExists(current_tables, "Positions_Table")): # if a table already exists, delete it
# Hack solution to obtain reference of a table and to delete it.
tables = ws.tables.items()
ref = tables[0][1]
del ws._tables["Positions_Table"] # delete table
ws.delete_rows(int(ref[2]), int(ref[6])) # delete rows | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
if(pos_total < 6): # if less than 6 positions, create a small list otherwise create table.
# Populate list with pos. totals
row_num = 9 # starting location for list
ws[loc + str(row_num)] = "Total"
next_column = getCellLoc(column_num + 1)
ws[next_column + str(row_num)] = "Positions"
for key in positions:
row_num += 1
new_loc = loc + str(row_num) # letter + number for cell location
ws[new_loc] = positions[key].total
ws[new_loc].alignment = Alignment(horizontal='center')
# Color Code Positions (lightest to darkest)
if(positions[key].total < 3):
ws[new_loc].fill = lighestColor
elif(positions[key].total < 6):
ws[new_loc].fill = lighterColor
elif(positions[key].total < 9):
ws[new_loc].fill = lightColor
elif(positions[key].total < 12):
ws[new_loc].fill = darkerColor
else:
ws[new_loc].fill = darkestColor
ws[next_column + str(row_num)] = key
else:
# Populate table with pos. totals
column_num += 3 # Move table over 3 columns to make room for bigger table
loc = getCellLoc(column_num)
ws[loc + str(1)] = "Total"
next_loc = getCellLoc(column_num + 1)
ws[next_loc + str(1)] = "Position"
ws.column_dimensions[next_loc].width = 12 | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
row_num = 2 # starting location for table
for key in positions:
new_loc = loc + str(row_num) # letter + number for cell location
ws[new_loc] = positions[key].total
ws[new_loc].alignment = Alignment(horizontal='center')
# Color Code Cells (lightest to darkest)
if(positions[key].total < 3):
ws[new_loc].fill = lighestColor
elif(positions[key].total < 6):
ws[new_loc].fill = lighterColor
elif(positions[key].total < 9):
ws[new_loc].fill = lightColor
elif(positions[key].total < 12):
ws[new_loc].fill = darkerColor
else:
ws[new_loc].fill = darkestColor
ws[next_loc + str(row_num)] = key # add position to table
row_num += 1
# Create new table
table_column = (loc + str(1)) + ":" + (next_loc + str(row_num - 1))
tab = Table(displayName="Positions_Table", ref=table_column)
tab.tableStyleInfo = tabStyle
ws.add_table(tab)
wb.save("Team Creator.xlsx")
def createTotalTables(employees):
# Create total tables in excel file
positionsTable(employees)
numOfEmployeesTable()
def createTextFile():
# Create text file with employee info
print("There is no employees.txt file in the current directory.\n")
ans = input("Would you like to create one? (Y/N): ")
if ans == "y" or ans == "Y":
with open("employees.txt", "w") as file:
file.write("Name \t Position \t Seniority\n")
ans = input("Enter employee information with name, position, and senority separated by spaces (e.g.: J.Doe SE Senior):\n")
subject = ans.split(" ") | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
# Write employee info to file
for field in range(len(subject)):
if field != 0 and field % 3 == 0: # if field is divisible by 3, it is a new employee
file.write("\n")
file.write("{} \t".format(subject[field]))
else:
print("No employees.txt file created. Exiting program...\n")
sys.exit()
def checkExcel():
cwd = os.getcwd()
# Build Excel file
wb = Workbook()
if not(os.path.exists("Team Creator.xlsx")):
wb.save("Team Creator.xlsx") # save excel to current directory
else:
wb = load_workbook("Team Creator.xlsx")
wb.save("Team Creator - old.xlsx")
# Delete old excel file
file_path = os.path.join(cwd, 'Team Creator.xlsx')
if os.path.exists(file_path):
os.remove(file_path)
wb.save("Team Creator.xlsx") # save new excel to current directory
# Get Delimiter from CSV file
def get_delimiter(file_path):
with open(file_path, newline="") as file:
secondline = file.readlines()[2]
dialect = csv.Sniffer().sniff(secondline, delimiters=';,|\t') # sniff for these probable delimiters
return dialect.delimiter
def createEmployees(file_path, delimit):
# Read CSV file - Build Employee objects
emp_num = 0
with open(file_path, newline="") as file:
e_reader = csv.reader(file, delimiter=delimit)
employees = {} # dictionary to hold employee objects
skip_first_row = False
for line in e_reader:
if not skip_first_row: # Skip first row
skip_first_row = True
continue
name = line[0]
pos = line[1]
senority = line[2]
senority = senority.lower() | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
emp = Employee(emp_num, name, pos, senority)
employees[emp_num] = emp # add employee to dictionary, with key as employee number
emp_num += 1
return employees
# Check employees.txt File, create one if doesn't exist.
def checkTextFile():
cwd = os.getcwd()
if not(os.path.exists("employees.txt")):
createTextFile()
else:
# Get File Location
employee_file = 'employees.txt'
file_path = os.path.join(cwd, employee_file)
delimit = get_delimiter(file_path)
ans = input("There is an employees.txt file, would you like to use it (If NO, more options will come up)? (Y/N): ")
if ans == "y" or ans == "Y":
employees = createEmployees(file_path, delimit)
return employees
else:
ans = input("Would you like to create a new employees.txt file, or edit? (Type New/Edit): ")
ans = ans.lower()
if ans == "new":
with open("employees.txt", "r") as oldFile, open('employees-old.txt', 'a') as newFile: # Copy employees.txt into a new file
for line in oldFile:
newFile.write(line)
os.remove(file_path) # Remove employees.txt
createTextFile() # Create new employees.txt
employees = createEmployees(file_path, delimit)
return employees
else:
print("Edit is not implemented yet, so exiting program...\n")
sys.exit()
# TODO: Add edit functionality - possibly when I integrate a GUI
# Possible window shows a text box with current employees.txt file, and allows user to edit it (something similar to a JList)
# Select an employee, choose delete, or edit
# Or a button to add a new employee | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
# Start up script - Create excel file & Employee objects
def startUpScript():
checkExcel()
employees = checkTextFile()
createTotalTables(employees)
return employees
def main():
# Build Excel file, Employee objects, and create total tables
employees = startUpScript()
# Create Teams
#teams = setupTeams(employees)
#for team in teams.items():
# print()
#for key in employees:
# Employee.showData(employees[key])
# print("\n")
if __name__ == "__main__":
main()
Any tips, information, or brutal comments are welcomed. Thank you!
Answer: You have a lot of imported symbols that are unused. If you use any self-respecting Python IDE, it will tell you about these and help you delete them.
In Employee, you have a handful of static-likes (your total_ variables). This is not a well-modelled class. If you really want object-oriented code, consider pulling these out to non-static members of a separate class named perhaps EmployeeSummary.
It's not spelled "senority", but "seniority"; and "Positon" is "Position".
All of your camelCase names should be replaced with lower_snake_case; i.e. createTeams should be create_teams.
Delete all of the parentheses surrounding your if conditions; you aren't in Java/C/etc.
Don't write numeric ASCII values such as 65. Write the actual letter (A) and use chr and ord accordingly.
Rather than int(x/26), use x//26 floor division.
str(1) is just '1', but more importantly, any time that you write out a literal series of 1, 2, 3, etc. that's a significant code smell and calls for a loop. For example, your ws block can instead be something like
for y, (colour, total) in enumerate((
(green_fill, Employee.total_num_of_seniors),
(yellow_fill, Employee.total_num_of_juniors),
# ...
), 2):
cell = loc + str(y)
ws[cell] = total
ws[cell].fill = colour
ws[cell].alignment = Alignment(horizontal='center') | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
python, performance, excel
You probably shouldn't do this:
wb = load_workbook("Team Creator.xlsx")
wb.save("Team Creator - old.xlsx")
Instead, just shutil.copyfile.
This:
name = line[0]
pos = line[1]
senority = line[2]
should be replaced with tuple unpacking:
name, pos, seniority = line
checkTextFile (which should be named check_text_file) has a big problem in its return type. In some cases it returns employees, but in your very first case - where the file doesn't exist - you implicitly return None. This None leaks through your createTotalTables call and then crashes.
main() has a bunch of commented-out code that needs to be deleted, or if you need it to be conditionally enabled, put it behind an if that checks a settings flag. | {
"domain": "codereview.stackexchange",
"id": 43422,
"lm_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, excel",
"url": null
} |
javascript
Title: Parse sports events
Question: this is actually my first question so please don't go hard with me. I am in the process of learning my Javascript skills and I am wondering if there are some valuable suggestions to better write the below code to be more optimized/readable etc?
I didn't put any comments within the code itself but what it basically does is return an Array of sports events (I believe that it is quite self-descriptive).
So, would you leave it as is, break it into smaller methods, or change something else, etc.
The question is a little bit "subjective" but in general I would like to know if I am on a good path with this.
Thanks a lot in advance.
const events = response.events.map((event) => {
const dateTime = getDateTime(event.start);
return {
id: event.id,
date: dateTime.slice(0, 10),
time: dateTime.slice(11, 19),
name: event.name.trim(),
participants: event["event-participants"].map((participant, index) => {
return {
id: participant.id,
name: participant["participant-name"].trim(),
sortOrder: index + 1
};
}),
metaTags: event["meta-tags"].map((metaTag) => {
return {
id: metaTag.id,
type: metaTag.type.trim(),
name: metaTag.name.trim()
}
}),
markets: event.markets.map((market) => {
return {
id: market.id,
name: market.name.trim(),
selections: market.runners.map((selection) => {
return {
id: selection.id,
name: selection.name.trim()
};
})
};
})
};
}); | {
"domain": "codereview.stackexchange",
"id": 43423,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
Answer: There is nothing wrong with the structure of the code, but we have to 'read' the code to figure out what it is doing. Put the mapping function (the inline callback) into a discreet, named function that tells anyone reading the code what it does. I'm guessing what the data types might be here, but hopefully you'll get the gist:
function rawEventToEventModel(event) {
const dateTime = getDateTime(event.start);
return {
id: event.id,
date: dateTime.slice(0, 10),
time: dateTime.slice(11, 19),
name: event.name.trim(),
participants: event["event-participants"].map((participant, index) => ({
id: participant.id,
name: participant["participant-name"].trim(),
sortOrder: index + 1
})),
metaTags: event["meta-tags"].map((metaTag) => ({
id: metaTag.id,
type: metaTag.type.trim(),
name: metaTag.name.trim()
})),
markets: event.markets.map((market) => ({
id: market.id,
name: market.name.trim(),
selections: market.runners.map((selection) => ({
id: selection.id,
name: selection.name.trim()
}))
}))
};
}
// ...
const events = response.events.map(rawEventToEventModel);
You could also do that for the inner maps (i.e. participants, metaTags and markets).
The convenience of arrow functions sometimes encourages peoples into the "I'm only going to use this once so don't need a separate function" mentality, but function 'names' do actually convey important information that make code more readable (less code does not always equate to more readable).
I've also taken the liberty to show that you can use arrow function returns to remove the verbiage of return { /* ... */ }, but you might argue that obscures what's going on to some extent. | {
"domain": "codereview.stackexchange",
"id": 43423,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
python, performance, datetime, pandas
Title: Extract the last row in a dataframe with a timestamp before some given time
Question: Related questions: I need to take specific row from different df to generate new df. How can I make my code faster?
I want to take the last data before the specified time from different time intervals df:
generate_data is for demo purpose, selecte_time and get_result_df is for production application.
select_time and get_result_df needs to be run a few million times in total.
How can I make get_result_df execute faster? My code is as follows:
import numpy as np
import datetime
import pandas as pd
np.random.seed(2022)
durations = ['T', '5T', '15T', '30T', 'H', '2H', 'D', 'W', 'BM']
datas = {}
time_selected = None
def generate_data():
global durations, datas
start_dt = '2018-01-01'
end_dt = '2022-05-02'
for duration in durations:
datas[duration] = pd.DataFrame(index=pd.date_range(start_dt, end_dt, freq=duration))
datas[duration]['duration'] = duration
datas[duration]['data'] = np.random.random(len(datas[duration])) * 100
return
def selecte_time():
global time_selected
start_dt = datetime.datetime(2018, 3, 1)
end_dt = datetime.datetime(2022, 5, 2)
idx = pd.date_range(start_dt, end_dt, freq='T')
time_selected = np.random.choice(idx)
return time_selected
def get_result_df():
global durations, datas, time_selected
t_df = {}
col = ['duration', 'data']
for duration in durations:
df = datas[duration]
t_df[duration] = df[df.index <= time_selected][col].iloc[-1]
df = pd.DataFrame(t_df[duration] for duration in durations)
return df
def main():
generate_data()
selecte_time()
df = get_result_df()
print(df)
if __name__ == '__main__':
main()
On my computer, the running time of get_result_df() is 204ms, how can I speed up the running speed of get_result_df()?
%timeit get_result_df()
204 ms ± 4.1 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) | {
"domain": "codereview.stackexchange",
"id": 43424,
"lm_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, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
I optimized it, and the running time was reduced to 53ms. Is there any room for improvement?
def get_result_df():
global durations, datas, time_selected
t_df = {}
col = ['duration', 'data']
for duration in durations:
df = datas[duration]
dt = df.index.to_numpy()
dt1 = dt[dt <= time_selected][-1]
t_df[duration] = df[df.index == dt1][col].iloc[-1]
df = pd.DataFrame(t_df[duration] for duration in durations)
return df
%timeit get_result_df()
53.3 ms ± 7.75 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
Answer: Don't use np.random; it's deprecated in favour of the new generator methods in the family of default_rng.
durations = [ should be DURATIONS = (, i.e. a capitalised tuple.
Don't leave datas or time_selected in the global namespace.
data is already a plural, so don't write datas.
Add PEP484 type hints.
Don't use np.random.random with a post-multiply; once you have an RNG instance call uniform passing 100 for your maximum.
selecte is spelled select.
selecte_time is deeply inefficient: you create an array of millions of elements, only to select one and throw the works away. Instead, calculate a random datetime between your two endpoints.
get_result_df is also deeply inefficient. Your inner loop should be using a bisection of the kind that search_sorted offers. Neither left nor right exactly matches what you're doing, so you have to check and conditionally decrement after the bisection.
col needs to go away.
I'm not convinced that it's a good idea to pass a generator expression like this:
df = pd.DataFrame(t_df[duration] for duration in durations)
into the DataFrame constructor. You can build up lists for your new index and data columns, and pass those in directly.
Add unit tests.
Suggested
Covering some of the above,
import numpy as np
import datetime
import pandas as pd
from pandas import Timestamp
rand = np.random.default_rng(seed=0)
DURATIONS = ('T', '5T', '15T', '30T', 'H', '2H', 'D', 'W', 'BM') | {
"domain": "codereview.stackexchange",
"id": 43424,
"lm_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, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
def generate_data() -> dict:
datas = {}
start_dt = datetime.date(2018, 1, 1)
end_dt = datetime.date(2022, 5, 2)
for duration in DURATIONS:
datas[duration] = pd.DataFrame(index=pd.date_range(start_dt, end_dt, freq=duration))
datas[duration]['duration'] = duration
datas[duration]['data'] = rand.uniform(low=0, high=100, size=len(datas[duration]))
return datas
def select_time() -> np.datetime64:
start_dt = datetime.datetime(2018, 3, 1)
end_dt = datetime.datetime(2022, 5, 2)
range_hours = (end_dt - start_dt) / datetime.timedelta(hours=1)
hour_selected = int(rand.integers(range_hours))
time_selected = start_dt + datetime.timedelta(hours=hour_selected)
return np.datetime64(time_selected)
def get_result_df(datas: dict, time_selected: np.datetime64) -> pd.DataFrame:
index = []
data = []
for duration in DURATIONS:
df = datas[duration]
y = df.index.searchsorted(time_selected)
while True: # Executes between 1 and 2 times
row = df.iloc[y, :]
if row.name <= time_selected:
break
y -= 1
index.append(row.name)
data.append(row.data)
df = pd.DataFrame(
{'duration': DURATIONS, 'data': data},
index=index,
)
return df
def main() -> None:
datas = generate_data()
time_selected = select_time()
df = get_result_df(datas, time_selected)
assert df.shape == (9, 2)
assert tuple(df.duration) == DURATIONS
assert tuple(df.index) == (
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 20:00:00'),
Timestamp('2018-07-16 00:00:00'),
Timestamp('2018-07-15 00:00:00'),
Timestamp('2018-06-29 00:00:00'),
) | {
"domain": "codereview.stackexchange",
"id": 43424,
"lm_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, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
assert np.allclose(
df.data,
(
2.41440894, 28.33886947, 56.0277365, 92.21785259, 84.13760397,
44.99816704, 20.3228723, 6.17753546, 83.78495657,
),
)
print(df)
if __name__ == '__main__':
main()
O(1) interpolation
Even a bisection is overkill. You already know that the temporal index is linear, so you can simply interpolate. This is O(1) in time.
import numpy as np
import datetime
import pandas as pd
from pandas import Timestamp
rand = np.random.default_rng(seed=0)
DURATIONS = ('T', '5T', '15T', '30T', 'H', '2H', 'D', 'W', 'BM')
def generate_data() -> dict:
datas = {}
start_dt = datetime.date(2018, 1, 1)
end_dt = datetime.date(2022, 5, 2)
for duration in DURATIONS:
datas[duration] = pd.DataFrame(index=pd.date_range(start_dt, end_dt, freq=duration))
datas[duration]['duration'] = duration
datas[duration]['data'] = rand.uniform(low=0, high=100, size=len(datas[duration]))
return datas
def select_time() -> np.datetime64:
start_dt = datetime.datetime(2018, 3, 1)
end_dt = datetime.datetime(2022, 5, 2)
range_hours = (end_dt - start_dt) // datetime.timedelta(hours=1)
hour_selected = int(rand.integers(range_hours))
time_selected = start_dt + datetime.timedelta(hours=hour_selected)
return np.datetime64(time_selected)
def get_result_df(datas: dict, time_selected: np.datetime64) -> pd.DataFrame:
index = []
data = []
# Assuming that get_result_df has no knowledge of generate_data.
# If it does, just pass these endpoints in.
start_dt, end_dt = datas['T'].index[[0, -1]]
target_fraction = (time_selected - start_dt)/(end_dt - start_dt) | {
"domain": "codereview.stackexchange",
"id": 43424,
"lm_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, datetime, pandas",
"url": null
} |
python, performance, datetime, pandas
for duration in DURATIONS:
df = datas[duration]
y = int(target_fraction * len(df.index))
for time, datum in df.data.iloc[y::-1].items(): # Executes between 1 and 2 times
if time <= time_selected:
index.append(time)
data.append(datum)
break
df = pd.DataFrame(
{'duration': DURATIONS, 'data': data},
index=index,
)
return df
def main() -> None:
datas = generate_data()
time_selected = select_time()
df = get_result_df(datas, time_selected)
assert df.shape == (9, 2)
assert tuple(df.duration) == DURATIONS
assert tuple(df.index) == (
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 21:00:00'),
Timestamp('2018-07-16 20:00:00'),
Timestamp('2018-07-16 00:00:00'),
Timestamp('2018-07-15 00:00:00'),
Timestamp('2018-06-29 00:00:00'),
)
assert np.allclose(
df.data,
(
2.41440894, 28.33886947, 56.0277365, 92.21785259, 84.13760397,
44.99816704, 20.3228723, 6.17753546, 83.78495657,
),
)
print(df)
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43424,
"lm_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, datetime, pandas",
"url": null
} |
swift, grand-central-dispatch
Title: Clean way to listen to asynchronous messages
Question: I am currently writing an Engine that runs on a background thread which produces outputs asynchronously. Those outputs are gathered by a Pipe, whith a readabilityHandler that sends back the messages the main thread using DispatchQueue.main.async like so:
private init() {
myPipe.fileHandleForReading.readabilityHandler = { [weak self] handle in
let data = handle.availableData
if let chunk = String(data: data, encoding: .utf8), chunk.trimmingCharacters(in: .whitespacesAndNewlines) != "" {
DispatchQueue.main.async {
self?.processOutput(chunk: chunk)
}
}
}
}
On the processOutput method, I gather those messages (that can sometimes arrive as a block separated by newLine characters), I parse them, and I perform an action when a specific message is obtained. Ex:
Manager.shared.send("my command")
output:
> info calculating...
> info calculating...
> info calculating...
> info calculating...
> result 42 // -> triggers an action
> info calculating...
> info calculating...
To achieve this I rely on """listeners""" like so:
private var listeners: [(token: String, handler: (String) -> ())] = []
private func processOutput(chunk: String) {
let split = chunk.components(separatedBy: .newlines)
let messages = split.map({ String($0) }).filter({ $0 != "" })
messages.forEach{ message in
NSLog(" \(message)")
// 1. for each message, I get the listeners, if any
self.listeners.filter({ message.starts(with: $0.token) }).forEach { listener in
// 2. they perform their action (main thread)
listener.handler(message)
}
// 3. I discard the listener when done
self.listeners.removeAll(where: { message.starts(with: $0.token) })
}
} | {
"domain": "codereview.stackexchange",
"id": 43425,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "swift, grand-central-dispatch",
"url": null
} |
swift, grand-central-dispatch
Therefore, when I need to get a message from a command I write:
Manager.shared.listeners.append( (token: "result", handler: { print($0) }) )
Manager.shared.send("my command")
// or
Manager.shared.send("my command", awaits:"result") { print($0) }
It actually works pretty fine for now, but I have the strange feeling that this listener method is way to convoluted. I don't like the fact that I'm keeping track of all the listeners in an array, then remove it manually from it when done, I reckon it should be releasing itself. Plus in the future, I want to be able to have listeners that perform their task for a given amount of time (e.g. get options) or until the end of a timer (e.g. error handling when the response never comes).
Isn't there a cleaner way to achieve this? Is there a pattern I can read about that covers this very specific subject?
Sidenote: The Engine is actually a 3rd party library game engine that I cannot modify. I cannot pass those messages directly into my methods, I have to rely on sending commands, reading the output via a pipe, but this part works actually pretty well. Its only the listenir part that I'm affraid of doing wrong. Thank you a lot
Answer: A few observations:
You should be careful with readabilityHandler. Your code presumes that a chunk coming will represent a full line of output. But you risk having it capture fractional portions of one or more lines. You shouldn’t make any assumptions in this regard. It may be working right now, but it is brittle, subject to significant behavior change resulting from innocuous and undocumented changes in the process you are piping.
I might advise reading the Data into a buffer until you reach an end of line. A “read line” sort of pattern. You could buffer this yourself, but you can also use lines, an AsyncSequence provided by Swift concurrency, fileHandleForReading.bytes.lines. The you can use for try await line in lines { … } pattern. See ProcessWithLines in this answer. | {
"domain": "codereview.stackexchange",
"id": 43425,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "swift, grand-central-dispatch",
"url": null
} |
swift, grand-central-dispatch
Regarding your “listeners” structure:
I agree that this “closure lookup” sort of pattern feels over-engineered. This sort of approach is generally used if you are writing some general-purpose third-party API and app developers are going to be passing tokens/strings and closures to some SDK. But if you are integrating with some well-established 3rd party engine, this feels like overkill.
Also, assuming for a second that you really wanted this “closure lookup” sort of structure, a dictionary seems more promising/logical approach. It could conceivably have O(1) performance, rather than the O(n) scan through an array of tuples. Now, clearly, if it was going to be something more dynamic like regex lookups or some awk-like pattern matching, perhaps you’re stuck with this O(n) sort of pattern, but it seems like a strange overhead to introduce without some compelling need. (Again, if I understand your goals, you are trying to integrate with an established 3rd party engine, presumably not to design a general purpose API that works with any random pipe.)
In short, we need to see more information about the nature of the commands and responses you will be getting via these pipes before we can advise you further on alternatives to this “listeners” pattern. | {
"domain": "codereview.stackexchange",
"id": 43425,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "swift, grand-central-dispatch",
"url": null
} |
javascript, algorithm, html, ecmascript-6
Title: Generate an HTML table using JavaScript from an array of objects
Question: I've an array of objects and I want to convert it into a visual table in HTML; so I did it last night, but I was tired. I don't think it is the right way of doing it, even though it's working and gives the expected result.
let notes = [
{ note: "n1", subject: "subject1", value: 10 },
{ note: "n2", subject: "subject2", value: 15 },
{ note: "n2", subject: "subject2", value: 5 },
{ note: "n3", subject: "subject2", value: 20 },
]; | {
"domain": "codereview.stackexchange",
"id": 43426,
"lm_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, algorithm, html, ecmascript-6",
"url": null
} |
javascript, algorithm, html, ecmascript-6
function make_matrix(objs) {
let rows = [...new Set(objs.map(({ subject }) => subject))];
let columns = [...new Set(objs.map(({ note }) => note))];
let array_objs = {};
for (const obj of objs) {
let { note, subject, value } = obj;
if (array_objs[subject + "-" + note])
array_objs[subject + "-" + note] = [
...array_objs[subject + "-" + note],
obj,
];
else array_objs[subject + "-" + note] = [obj];
}
for (const [k, v] of Object.entries(array_objs)) {
total = v.map(({ value }) => +value).reduce((a, b) => a + b);
array_objs[k] = total;
}
let od = {};
for (const [k, v] of Object.entries(array_objs)) {
const [key, value] = k.split("-");
if (od[key]) {
od[key] = [...od[key], { [value]: v }];
} else {
od[key] = [{ [value]: v }];
}
}
let trs = "";
for (const [key, value] of Object.entries(od)) {
trs += "<tr><th>" + key + "</th>";
for (const col of columns) {
const entry = value
.map((x) => Object.entries(x)[0])
.find((x) => x[0] == col);
if (
value
.map((x) => Object.entries(x)[0])
.map((x) => x[0])
.includes(col)
) {
trs += "<td>" + entry[1] + "</td>";
} else {
trs += "<td>0</td>";
}
}
trs += "</tr>";
}
let table = `<table>
<tr><th>Subjects</th><th>${columns.join(
"</th><th>"
)}</th></tr>
${trs}
</table>`;
return table;
}
document.querySelector(".content").innerHTML = make_matrix(notes);
table {
border-collapse: collapse;
border: 1px solid;
}
tr,
th,
td {
border: 1px solid;
padding: 3px 10px;
}
<div class="content"></div>
Is it the right way of doing it? | {
"domain": "codereview.stackexchange",
"id": 43426,
"lm_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, algorithm, html, ecmascript-6",
"url": null
} |
javascript, algorithm, html, ecmascript-6
Is it the right way of doing it?
Answer: Use the DOM APIs
For performance avoid adding markup (HTML) to the page via JavaScript. The DOM APIs are much faster and can be abstracted to make more readable code (DOM APIs are very verbose).
Source complexity
Your solution is convoluted and hard to read. It looks like you tackled the whole problem in one big step. More than a dozen lines of code should be seen as more than one problem to solve.
To solve complex or multi step problem break them into smaller single role parts.
Find all rows names
Find all columns names
Find value by row column name
Create DOM elements
Append a DOM elements
Create a table.
Each of these sub problems can then be solved by defining a function. When you have all the functions you can solve the main problem by combining the sub problems.
Try to make the functions generic. Property names should be dynamic so that you need only minor changes when the data changes. The example show 4 tables, to change your code to provide the different tables would take a lot more work than adding 3 more calls to the main function.
Example
The rewrite breaks the problem into the pars described above. The title, and the names of the row and column properties are passed to the function.
You can see the flexibility of this approach as the table can easily be rotated and transformed by changing the argument order and properties to use for columns and rows.
const notes = [{note: "n1", subject: "subject1", value: 10 }, {note: "n2", subject: "subject2", value: 15 }, {note: "n2", subject: "subject2", value: 5 }, {note: "n3", subject: "subject2", value: 20 }];
const tag = (tagName, props = {}) => Object.assign(document.createElement(tagName), props);
const txtTag = (tagName, str, props = {}) => tag(tagName, {textContent: str, ...props});
const append = (el, ...sibs) => sibs.reduce((p, sib) => (p.appendChild(sib), p), el); | {
"domain": "codereview.stackexchange",
"id": 43426,
"lm_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, algorithm, html, ecmascript-6",
"url": null
} |
javascript, algorithm, html, ecmascript-6
append(document.body,
createTable("Subjects", "note", "subject", "value", notes),
createTable("Notes", "subject", "note", "value", notes),
createTable("Notes", "value", "note", "value", notes),
createTable("Values", "subject", "value", "value", notes));
function createTable(title, colKey, rowKey, valKey, data) {
const byKey = key => [...new Set(data.map(rec => rec[key]))];
const byRowCol = (row, col) => data.reduce((val, rec) =>
val + (rec[rowKey] === row && rec[colKey] === col ? rec[valKey] : 0), 0);
const rows = byKey(rowKey), cols = byKey(colKey);
return append(tag("table"),
append(tag("tbody"),
append(tag("tr"),
txtTag("th", title),
...cols.map(str => txtTag("th", str))
),
...rows.map(row =>
append(tag("tr"),
txtTag("th", row),
...cols.map(col => txtTag("td", byRowCol(row, col)))
)
)
)
)
}
* {font-family: arial}
table, tr, th, td {
border-collapse: collapse;
border: 1px solid;
padding: 3px 10px;
margin: 4px;
} | {
"domain": "codereview.stackexchange",
"id": 43426,
"lm_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, algorithm, html, ecmascript-6",
"url": null
} |
c++, c++11, integer
Title: Safe Integer Library in C++
Question: I've designed a single-file safe integer library in C++. It catches undefined behavior prior to integer overflows or underflows and throws the respective exceptions. I intend this to be portable, to not rely on undefined behavior, and to rely as little on implementation-defined behavior as possible.
safe_integer.hpp:
/*
* Copyright © 2020 James Larrowe
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef SAFE_INTEGER_HPP
# define SAFE_INTEGER_HPP 1
#include <limits>
#include <stdexcept>
#include <type_traits>
template<typename I,
typename std::enable_if<std::is_integral<I>::value, bool>::type = true>
class safe_int
{
I val;
public:
typedef I value_type;
static constexpr I max = std::numeric_limits<I>::max();
static constexpr I min = std::numeric_limits<I>::min();
safe_int(I i) : val { i } { };
operator I() const { return val; }
I &operator=(I v) { val = v; }
safe_int operator+()
{
return *this;
}
safe_int operator-()
{
if(val < -max)
throw std::overflow_error("");
return safe_int(-val);
}
safe_int &operator++()
{
if(val == max)
throw std::overflow_error("");
++val;
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43427,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, integer",
"url": null
} |
c++, c++11, integer
++val;
return *this;
}
safe_int &operator--()
{
if(val == min)
throw std::underflow_error("");
--val;
return *this;
}
safe_int operator++(int)
{
if(val == max)
throw std::overflow_error("");
return safe_int(val++);
}
safe_int operator--(int)
{
if(val == min)
throw std::underflow_error("");
return safe_int(val--);
}
safe_int &operator+=(I rhs)
{
if( val > 0 && rhs > max - val )
throw std::overflow_error("");
else if( val < 0 && rhs < min - val )
throw std::underflow_error("");
val += rhs;
return *this;
}
safe_int &operator-=(I rhs)
{
if( val >= 0 && rhs < -max )
throw std::overflow_error("");
if( val < 0 && rhs > max + val )
throw std::overflow_error("");
else if( val > 0 && rhs < min + val )
throw std::underflow_error("");
val -= rhs;
return *this;
}
safe_int &operator*=(I rhs)
{
if(val > 0)
{
if(rhs > max / val)
throw std::overflow_error("");
}
else if(val < 0)
{
if(val == -1)
{
if(rhs < -max)
throw std::overflow_error("");
goto no_overflow;
}
if(rhs > min / val)
throw std::underflow_error("");
}
no_overflow:
val *= rhs;
return *this;
}
safe_int &operator/=(I rhs)
{
if( rhs == -1 && val < -max )
throw std::underflow_error("");
else if(rhs == 0)
throw std::domain_error("");
val /= rhs;
return *this;
} | {
"domain": "codereview.stackexchange",
"id": 43427,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, integer",
"url": null
} |
c++, c++11, integer
val /= rhs;
return *this;
}
safe_int &operator%=(I rhs)
{
if( rhs == -1 && val < -max )
throw std::underflow_error("");
else if(rhs == 0)
throw std::domain_error("");
val %= rhs;
return *this;
}
safe_int operator+(I rhs)
{
return safe_int(val) += rhs;
}
safe_int operator-(I rhs)
{
return safe_int(val) -= rhs;
}
safe_int operator*(I rhs)
{
return safe_int(val) *= rhs;
}
safe_int operator/(I rhs)
{
return safe_int(val) /= rhs;
}
safe_int operator%(I rhs)
{
return safe_int(val) %= rhs;
}
safe_int &operator+=(safe_int rhs)
{
return *this += static_cast<I>(rhs);
}
safe_int &operator-=(safe_int rhs)
{
return *this -= static_cast<I>(rhs);
}
safe_int &operator*=(safe_int rhs)
{
return *this *= static_cast<I>(rhs);
}
safe_int &operator/=(safe_int rhs)
{
return *this /= static_cast<I>(rhs);
}
safe_int &operator%=(safe_int rhs)
{
return *this %= static_cast<I>(rhs);
}
safe_int operator+(safe_int rhs)
{
return safe_int(val) += static_cast<I>(rhs);
}
safe_int operator-(safe_int rhs)
{
return safe_int(val) -= static_cast<I>(rhs);
}
safe_int operator*(safe_int rhs)
{
return safe_int(val) *= static_cast<I>(rhs);
}
safe_int operator/(safe_int rhs)
{
return safe_int(val) /= static_cast<I>(rhs);
}
safe_int operator%(safe_int rhs)
{
return safe_int(val) %= static_cast<I>(rhs);
}
};
#endif
This should work on non-two's complement systems and with any integer type.
Here's a little example:
#include "safe_integer.hpp"
int main(void)
{
safe_int<int> i = 0;
i -= -0x80000000;
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 43427,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, integer",
"url": null
} |
c++, c++11, integer
int main(void)
{
safe_int<int> i = 0;
i -= -0x80000000;
return 0;
}
Output:
terminate called after throwing an instance of 'std::overflow_error'
what():
Aborted
What I'm particularly interested in:
Are there any corner cases I've missed?
Is there any undefined behavior (probably not)?
Is there any way I can simplify all of the (somewhat redundant) operator overloads?
What I'm not interested in:
efficiency. I agree that my solution may not perform well but my personal opinion is that leaving the checks in unconditionally and not using undefined behavior to get a faster result are worth the cost.
Answer: You can get rid of the goto in operator*= by adding an else to the if (val == -1) statement.
The % operator cannot underflow, as the result always has a magnitude less than the rhs value. So you don't need your underflow check (which is incorrect anyways, as it would throw rather than return a 0).
An "underflow" represents a number that is too small to represent, and is typically applied to floating point types. A calculation that gives a number that is negative and too large to store in the result (i.e., is less than min) is still an overflow, as the result has overflowed the storage space available. So all those places that you throw an underflow_error should be overflow_error (unless you're changing the usage of underflow to represent too large of a negative value).
How does the code behave if I instantiate a safe_int<unsigned>? The evaluation of -max in that case will not give the correct result, and possibly cause a compiler warning (for negation of an unsigned value). | {
"domain": "codereview.stackexchange",
"id": 43427,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, c++11, integer",
"url": null
} |
c++, performance, simulation, finance
Title: Heston model implementation in C++
Question: I have implemented an option pricing algorithm following the Heston model. The simulation involves specifying the number of simulations, then generating a discretized path for each simulation (code below). Setting N = 10000 and M = 10000 results in a fairly slow runtime on my machine. Is there any way I can speed this code up? Additionally, I'm looking to get rid of any bad habits when I code, so please feel free to point them out. For example, is there a better way than these nested loops?
#include <iostream>
#include <vector>
#include <cmath>
#include <algorithm>
#include <random>
std::vector<double> linspace(double start, double end, unsigned long long int N)
{
std::vector<double> v(N);
for (std::vector<double>::size_type i = 0; i <= v.size(); i++)
{
v[i] = start + i*(end - start)/static_cast<double>(N);
}
return v;
}
int main()
{
// Specify input parameters
char type{'c'};
double S0{50};
double K{50};
double T{0.5};
double r{0.02};
double q{0.0};
unsigned long long int N{1000}; // Number of steps
int M{1000}; // Number of simulations
// Build time array
std::vector<double> t_array{linspace(0.0, T, N)};
double dt{t_array[1] - t_array[0]};
// Stochastic volatility parameters
double v0{pow(0.15, 2)}; // Starting volatility
double theta{pow(0.15, 2)}; // Long-term mean volatility
double kappa{0.5}; // Speed of reversion
double xi{0.05}; // Volatility of the volatility
// lambda parameter for multidimensional Girsanov theorem
double lambda{0.02}; // Needs to be estimate in practice somehow, I choose this arbitrarily for now
// Generate standard normal random variables under risk-neutral probability measure
double rho{0.3}; // Correlation between W1 and W2 brownian motions under the risk-neutral probability measure | {
"domain": "codereview.stackexchange",
"id": 43428,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, simulation, finance",
"url": null
} |
c++, performance, simulation, finance
std::random_device rd; // random number generator
std::normal_distribution<> N1(0, 1);
std::normal_distribution<> N3(0, 1);
// Variables to hold standard normals generated during path simulation
double z1{};
double z2{};
// Run M number of simulations
double payoff_total_sum{0};
double S{};
double v{};
for (int h = 0; h < M; h++)
{
// Reset initial values
S = S0;
v = v0;
// Generate stock paths under risk neutral measure
for (std::vector<double>::size_type i = 0; i < t_array.size(); i++)
{
// Generate N1 and N3 standard normals
z1 = N1(rd);
z2 = rho*z1 + pow(1 - pow(rho, 2), 0.5)*N3(rd); // N2 is correlated to N1
// Update stock path under risk-neutral measure
S = S + (r - q)*S*dt + S*pow(v*dt, 0.5)*z1;
// Update stochastic volatility under risk-neutral measure
v = v + (kappa*theta - (kappa + lambda)*std::max(v, 0.0))*dt + xi*pow(std::max(v, 0.0)*dt, 0.5)*z2;
}
if (type == 'c')
{
payoff_total_sum += std::max(S - K, 0.0);
}
else
{
payoff_total_sum += std::max(K - S, 0.0);
}
}
double option_price{exp(-r*T)*payoff_total_sum/static_cast<double>(M)};
std::cout << option_price;
return 0;
}
Answer: You obtain random numbers directly from random_device:
std::random_device rd;
....
z1 = N1(rd);
It is extremely expensive. See a comment in cppreference Random Device article:
++hist[dist(rd)]; // note: demo only: the performance of many
// implementations of random_device degrades sharply
// once the entropy pool is exhausted. For practical use
// random_device is generally only used to seed
// a PRNG such as mt19937 | {
"domain": "codereview.stackexchange",
"id": 43428,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, simulation, finance",
"url": null
} |
c++, performance, simulation, finance
You need
std::random_device rd;
std::mt19937 gen{rd()};
....
z1 = N1(gen);
t_array is a waste of space and time. It is only used to compute dt. Just say
dt{(end - start)/N};
and use N as the loop limit.
There is no need to static_cast<double>(M). It is OK to divide double by an integer. | {
"domain": "codereview.stackexchange",
"id": 43428,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, simulation, finance",
"url": null
} |
java, unit-testing, junit
Title: Table Driven Test in Java using Junit4
Question: I was creating some solving algorithm and write test for it. this is the tests :
@Test
public void test1(){
boolean expected = true;
int n = 7;
DigitIncreasing digitIncreasing = new DigitIncreasing();
assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
}
@Test
public void test2(){
boolean expected = true;
int n =36;
DigitIncreasing digitIncreasing = new DigitIncreasing();
assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
}
@Test
public void test3(){
boolean expected = true;
int n = 984;
DigitIncreasing digitIncreasing = new DigitIncreasing();
assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
}
@Test
public void test4(){
boolean expected = true;
int n = 7404;
DigitIncreasing digitIncreasing = new DigitIncreasing();
assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
}
@Test
public void test5(){
boolean expected = false;
int n = 37;
DigitIncreasing digitIncreasing = new DigitIncreasing();
assertEquals(expected,digitIncreasing.isDigitIncreasing(n));
}
So from here I got some idea to write the test using Table driven approach like this :
public class testObject {
private int input;
private boolean expected;
public testObject(int input, boolean expected) {
this.input = input;
this.expected = expected;
}
public int getInput() {
return input;
}
public boolean isExpected() {
return expected;
}
} | {
"domain": "codereview.stackexchange",
"id": 43429,
"lm_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, unit-testing, junit",
"url": null
} |
java, unit-testing, junit
public boolean isExpected() {
return expected;
}
}
public void DigitIncreasing(int input, boolean expected){
try{
DigitIncreasing digitIncreasing = new DigitIncreasing();
assertEquals(expected,digitIncreasing.isDigitIncreasing(input));
}catch (AssertionError ex){
System.out.println("input = "+input);
System.out.println("expected = "+expected);
ex.printStackTrace();
}
}
@Test
public void testTable(){
testObject[] testObjects = new testObject[]{
new testObject(7,true),
new testObject(36,true),
new testObject(984,true),
new testObject(7404,true),
new testObject(37,false),
};
for (testObject test : testObjects){
DigitIncreasing(test.getInput(),test.isExpected());
}
}
Using Table Driven test makes me easily add another test case. any better approach or idea? since I'm adding the catch exception to get failed test.
You can find source code here.
Answer: JUnit 4 has a Parameterized test runner that does most of the work for you. For your tests, it would look like:
import maharishi.DigitIncreasing;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class DigitIncreasingTest {
@Parameters(name = "Test {index}: isDigitIncreasing({0})={1}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ 7, true }, { 36, true }, { 984, true }, { 7404, true }, { 37, false }
});
}
private int input;
private boolean expected;
private DigitIncreasing digitIncreasing = new DigitIncreasing(); | {
"domain": "codereview.stackexchange",
"id": 43429,
"lm_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, unit-testing, junit",
"url": null
} |
java, unit-testing, junit
private boolean expected;
private DigitIncreasing digitIncreasing = new DigitIncreasing();
public DigitIncreasingTest(int input, boolean expected) {
input = input;
expected = expected;
}
@Test
public void test() {
assertEquals(expected, digitIncreasing.isDigitIncreasing(input));
}
}
This is easier to understand (in my opinion) than your formulation, where you shadow the name of the class under test, and actually runs each case as a separate test. | {
"domain": "codereview.stackexchange",
"id": 43429,
"lm_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, unit-testing, junit",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.