text stringlengths 1 2.12k | source dict |
|---|---|
php, array, shuffle
$j = random_int(0,$i);
There is no space after the comma separating the arguments in the call to random_int().
for ($i = $n - 1; $i >= 1; $i--)
{
Per PSR-12 Section 5.4 for:
The closing parenthesis and opening brace MUST be placed together on their own line with one space between them.
Idiomatic PHP developers might simply write the middle condition as $i since 0 is considered false
for ($i = $n - 1; $i; $i--) {
Variables can be swapped without a temporary variable
As was mentioned in this review Variables can be swapped without the use of a temporary variable using array destructuring assignment in PHP 7.1+.
Instead of:
$ai = $a[$i];
$a[$i] = $a[$j];
$a[$j] = $ai;
It could be as simple as:
[$a[$i], $a[$j]] = [$a[$j], $a[$i]]; | {
"domain": "codereview.stackexchange",
"id": 44495,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, array, shuffle",
"url": null
} |
python, programming-challenge
Title: Validating a Sudoku Board in Python
Question: The problem statement is as follows:
Sudoku is a game played on a 9x9 grid. The goal of the game is to fill
all cells of the grid with digits from 1 to 9, so that each column,
each row, and each of the nine 3x3 sub-grids (also known as blocks)
contain all of the digits from 1 to 9.
Sudoku Solution Validator
**Write a function that accepts a Sudoku board, and returns true if it is a valid Sudoku solution, or false otherwise. The cells of the input
Sudoku board may also contain 0's, which will represent empty cells.
Boards containing one or more zeroes are considered to be invalid
solutions.
Here is my code which passes all the test cases.
I would like feedback on performance, clarity, and readability.
Thank you
def has_valid_rows(rows):
VALID_ROW = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for row in rows:
if 0 in row or set(row) != set(VALID_ROW):
return False
return True
def has_valid_columns(columns):
VALID_COLUMN = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for column in columns:
if 0 in column or set(column) != set(VALID_COLUMN):
return False
return True
def has_valid_subgrids(input_board):
VALID_SUBGRID = [1, 2, 3, 4, 5, 6, 7, 8, 9]
top_left_subgrid = input_board[0][:3] + input_board[1][:3] + input_board[2][:3]
top_middle_subgrid = input_board[0][3:6] + input_board[1][3:6] + input_board[2][3:6]
top_right_subgrid = input_board[0][6::] + input_board[1][6::] + input_board[2][6::]
middle_left_subgrid = input_board[3][:3] + input_board[4][:3] + input_board[5][:3]
middle_middle_subgrid = input_board[3][3:6] + input_board[4][3:6] + input_board[5][3:6]
middle_right_subgrid = input_board[3][6::] + input_board[4][6::] + input_board[5][6::] | {
"domain": "codereview.stackexchange",
"id": 44496,
"lm_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, programming-challenge",
"url": null
} |
python, programming-challenge
bottom_left_subgrid = input_board[6][:3] + input_board[7][:3] + input_board[8][:3]
bottom_middle_subgrid = input_board[6][3:6] + input_board[7][3:6] + input_board[8][3:6]
bottom_right_subgrid = input_board[6][6::] + input_board[7][6::] + input_board[8][6::]
subgrids = [top_left_subgrid, top_middle_subgrid, top_right_subgrid, middle_left_subgrid, middle_middle_subgrid, middle_right_subgrid, bottom_left_subgrid, bottom_middle_subgrid, bottom_right_subgrid]
for subgrid in subgrids:
if set(subgrid) != set(VALID_SUBGRID) or 0 in subgrid:
return False
return True
def validate_sudoku(board):
rows = board
columns = zip(*board)
if has_valid_rows(rows) and has_valid_columns(columns) and has_valid_subgrids(board):
return True
return False | {
"domain": "codereview.stackexchange",
"id": 44496,
"lm_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, programming-challenge",
"url": null
} |
python, programming-challenge
return False
Answer: Naming
Your function names has_valid_rows has_valid_columns and has_valid_subgrids are misleading: they imply that a board with any valid row/column/subgrid would return True.
validate_<region> would be a better fit.
Simplification
You can remove the 0 in <region> conditions in your validation methods, as the sets wouldn't be equal if this were True.
Redundancy 1
You define 3 function-level constants (VALID_ROW, VALID_COLUMN and VALID_SUBGRID) to have the same value. Define a single module-level constant instead. And since you ultimately don't need a list but a set, define that constant to be a set: VALID_SET = {1, 2, 3, 4, 5, 6, 7, 8, 9}.
Redundancy 2
has_valid_rows and has_valid_columns are logically identical, only variable names differ. has_valid_subgrids also has similar logic. They could be combined into a single function which could get passed different arguments.
Consistency
You split the board in rows and columns inside of the main function before passing them to the validating methods, but split the board in subgrids inside the has_valid_subgrids method. It would be better to have consistent calling conventions.
Use built-ins
The all built-in methods allows to check if a condition if True for all elements in an iterable, simplifying your various validation methods a bit, and possibly improving performance:
all(set(row) == VALID_SET for row in board)
Return a boolean directly
In your validate_sudoku function, the pattern:
if <condition>:
return True
return False
can be simplified to:
return <condition>
Extracting subgrids
Hard-coding each subgrid individually is probably not the best way of getting them. Try to use a list comprehension or a loop instead. | {
"domain": "codereview.stackexchange",
"id": 44496,
"lm_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, programming-challenge",
"url": null
} |
python, performance, python-3.x, excel
Title: Update an Excel master workbook with values from new workbook
Question: I have a master .xlsx file on which other spreadsheets depend. Each week, I export a new .xlsx file (from MRP) that may or may not be the same as the master. The columns are always identical. Rows may increase or decrease. Cell values may change, usually just one (price value, column AB).
I wrote a Python program that reviews the differences, and updates the master with the new values.
I wanted this program to update the master workbook to match the new values. Any new rows in the new workbook would be appended to the master as well.
Problems:
This is slow. Is there a more efficient way to do this? Luckily there are only about 2 - 4k rows. As in VBA code instead? Or another language altogether?
Any Pythonification updates I could make? I am a beginner so I'd like to learn how to optimize code as I go.
Any other advice or help would also be appreciated.
import sys
import openpyxl
import openpyxl.utils
from datetime import datetime as dt
import os
#get teh mater path
hm_dir = "C:\\path\\MASTER SHEETS"
suffix = ".xlsx"
#loop to get the choice of master workbook to update
while True:
wb_choice = input("Enter the master sheet you want to update:\n" \
"a for Main Warehouse\n"\
"c for Composite Item List\n"\
"i for Item Master\n")
if wb_choice.lower() == "a":
old_workbook_path = os.path.join(hm_dir, "Main_WHSE.xlsx")
break
if wb_choice.lower() == "c":
old_workbook_path = os.path.join(hm_dir, "COMPOSITE.xlsx")
break
if wb_choice.lower() == "i":
old_workbook_path = os.path.join(hm_dir, "ITEMS.xlsx")
break
else:
print("Enter A C or I")
continue | {
"domain": "codereview.stackexchange",
"id": 44497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, excel",
"url": null
} |
python, performance, python-3.x, excel
# Get the paths to the new workbook
new_workbook_fn= input("Enter the filename of the new workbook" \
" It must be xlsx format and " \
"it must be in the same folder as the master" \
" sheets, which is: \n" \
+ str(hm_dir) \
+ "\n\nFilename: ")
new_workbook_path = os.path.join(hm_dir, new_workbook_fn + suffix)
# Load the older and newer workbooks
old_workbook = openpyxl.load_workbook(old_workbook_path)
new_workbook = openpyxl.load_workbook(new_workbook_path)
# Select the active sheet in each workbook
old_sheet = old_workbook["Item"]
new_sheet = new_workbook["Item"]
sheet2 = old_workbook["Sheet 2"]
#copies the current max rows of the mater worksheet before updating
current_row = sheet2.max_row + 1
sheet2.cell(row=current_row, column=4).value = old_sheet.max_row
# Create a dictionary to map unique IDs to row numbers in the new workbook
new_id_map = {}
for i in range(2, new_sheet.max_row + 1):
new_id_map[new_sheet.cell(row=i, column=1).value] = i
#Create a dictionary to map unique IDs to row numbers in the old workbook
old_id_map = {}
for i in range(2, old_sheet.max_row + 1):
old_id_map[old_sheet.cell(row=i, column=1).value] = i | {
"domain": "codereview.stackexchange",
"id": 44497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, excel",
"url": null
} |
python, performance, python-3.x, excel
# Loop through the rows in the older workbook
rows_updated = 0
for j in range(2, old_sheet.max_row + 1):
old_id = old_sheet.cell(row=j, column=1).value
if old_id in new_id_map:
# If the ID is found in the new workbook, update the data in the old workbook
new_row_num = new_id_map[old_id]
updated = False # flag to keep track of whether row was updated or not
for k in range(1, new_sheet.max_column + 1):
old_value = old_sheet.cell(row=j, column=k).value
new_value = new_sheet.cell(row=new_row_num, column=k).value
if old_value != new_value:
# update the value only if it is different from the new value
old_sheet.cell(row=j, column=k).value = new_value
updated = True # mark the row as updated
if updated:
rows_updated += 1
# Loop through the rows in the new workbook and add any missing rows to the old workbook
for j in range(2, new_sheet.max_row + 1):
new_id = new_sheet.cell(row=j, column=1).value
if new_id not in old_id_map:
# If the ID is not found in the old workbook, add a new row to the old workbook
old_sheet.append([new_sheet.cell(row=j, column=k).value for k in range(1,
new_sheet.max_column + 1)])
old_id_map[new_id] = old_sheet.max_row
rows_updated += 1
# Save the changes to the older workbook
old_workbook.save(old_workbook_path)
# Add a row to Sheet 2 of the old workbook with the date
sheet2.cell(row=current_row, column=1).value =
dt.now().strftime("%m/%d/%Y %H:%M:%S")
sheet2.cell(row=current_row, column=3).value = new_sheet.max_row
# Save the changes to the old workbook
old_workbook.save(old_workbook_path)
# Display the number of rows updated
print(f"Number of rows updated: {rows_updated}") | {
"domain": "codereview.stackexchange",
"id": 44497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, excel",
"url": null
} |
python, performance, python-3.x, excel
# Display the number of rows updated
print(f"Number of rows updated: {rows_updated}")
Answer: Too big for a comment, this is an alternative approach:
Suppose you have some different files like this:
The image shows 3 tables of data, each representing a different file, each with a File Created column, each with the same column names, each with an ID column and some fields of data.
I've also highlighted where a new piece of data differs from the same ID in a previous table.
To merge these, we can use the following algorithm:
Load all tables and append them
Group duplicate data; rows where the ID and fields are identical, but set a new "Last Modification Date" to be the oldest date in that group - i.e. the data has remained unchanged since that date
e.g. M002 is no different between 1-Jan (blue table) and 15-Jan (Orange Table). So group into a single row and set the last modified date to 1-Jan
Now for each ID, keep only the most recent "last modification" as this is the most up-to-date data
This can be achieved by sorting the "Last Modification Date" newest -> Oldest and dropping any rows with duplicate IDs
Finally sort alphabetically by ID or by modification date, whatever you find most logical.
Following that algorithm you get a table like this:
See how M004 has remained unchanged the whole time and so its last update was 1-Jan, M005 was updated 2-Feb etc.
Hopefully this is what you are after. The whole thing can be achieved using Excel's builtin PowerQuery | {
"domain": "codereview.stackexchange",
"id": 44497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, excel",
"url": null
} |
python, performance, python-3.x, excel
Add a blank query to your Master Workbook and then go to View -> Advanced Editor and paste the following code:
let
FieldNames = {"MRP ID", "Field 1", "Field 2", "Field 3"},
IDField = List.First(FieldNames),
SourceFolder = "C:\path\MASTER SHEETS\MRP Data",
Source = Folder.Contents(SourceFolder),
#"Filter MRP Files" = Table.SelectRows(Source, each ([Extension] = ".xlsx") and ([Name] = "MRP1.xlsx" or [Name] = "MRP2.xlsx" or [Name] = "MRP3.xlsx") and ([Attributes]?[Hidden]? <> true)),
#"Read Tables from Files" = Table.AddColumn(#"Filter MRP Files", "First Table", each Excel.Workbook([Content]){[Kind="Table"]}[Data]),
#"Discard Other Columns" = Table.SelectColumns(#"Read Tables from Files", {"Date created", "First Table"}),
#"Merge Tables" = Table.ExpandTableColumn(#"Discard Other Columns", "First Table", FieldNames),
#"Squish Unchanged Data" = Table.Group(#"Merge Tables", FieldNames, {{"Last Modified", each List.Min([Date created]), type nullable datetime}}),
#"Force Most Recent files to top" = Table.Buffer(Table.Sort(#"Squish Unchanged Data",{{"Last Modified", Order.Descending}})),
#"Drop out-dated Data" = Table.Distinct(#"Force Most Recent files to top", {IDField}),
#"Sort Alphabetically" = Table.Sort(#"Drop out-dated Data",{{IDField, Order.Ascending}})
in
#"Sort Alphabetically"
You should end up with something like this:
Now in the Home tab of the powerquery editor click Close and Load to a table in your workbook. Refresh using the refresh all command in Excel.
The reason to do it this way is:
Very fast compared to what's easily achievable in python without a lot more thought, as PowerQuery is optimised for working with Tabular Data
Simple Expressive code is easier to maintain, again PQ is the tool for the job and makes it easier to write simple code in this instance.
Built into Excel so no added dependencies easier to maintain and distribute | {
"domain": "codereview.stackexchange",
"id": 44497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, excel",
"url": null
} |
python, performance, python-3.x, excel
It is possible to pass params like filepaths, column names etc from VBA to PowerQuery if you want interactivity. By default the data will refresh whenever you open or close the workbook.
Note, modify the FieldNames parameter in the query to match the columns in your workbook, make sure there is an ID column (right now it just uses the first column as ID)
This uses file creation date to find the most recent data.
If a row of data is changed then changed back, the "Last Change" column will find the first occasion where the product had those values. You can get around this by deleting old data, or adjusting the algorithm
Table.Buffer is needed to prevent PQ lazily evaluating the sort, since this would result in random records being dropped, not necessarily the oldest ones | {
"domain": "codereview.stackexchange",
"id": 44497,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, excel",
"url": null
} |
react.js, typescript, jsx
Title: Function component wrapper for the js-year-calendar widget
Question: I have this class component from the rc-year-calendar library.
import React from "react";
import PropTypes from 'prop-types';
import JsCalendar from "js-year-calendar";
import 'js-year-calendar/dist/js-year-calendar.css';
export default class Calendar extends React.Component {
static propsTypes = {
// opsions
allowOverlap: PropTypes.bool,
alwaysHalfDay: PropTypes.bool,
contextMenuItems: PropTypes.arrayOf(PropTypes.shape({
text: PropTypes.string,
click: PropTypes.func,
visible: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
items: PropTypes.array
})),
customDayRenderer: PropTypes.func,
customDataSourceRenderer: PropTypes.func,
dataSource: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.shape({
startDate: PropTypes.instanceOf(Date),
endDate: PropTypes.instanceOf(Date),
name: PropTypes.string
})),
PropTypes.func
]),
disabledDays: PropTypes.arrayOf(PropTypes.instanceOf(Date)),
disabledWeekDays: PropTypes.arrayOf(PropTypes.number),
displayDisabledDataSource: PropTypes.bool,
displayHeader: PropTypes.bool,
displayWeekNumber: PropTypes.bool,
enableContextMenu: PropTypes.bool,
enableRangeSelection: PropTypes.bool,
hiddenWeekDays: PropTypes.arrayOf(PropTypes.number),
language: PropTypes.string,
loadingTemplate: PropTypes.string,
maxDate: PropTypes.instanceOf(Date),
minDate: PropTypes.instanceOf(Date),
roundRangeLimits: PropTypes.bool,
selectRange: PropTypes.bool,
style: PropTypes.string,
weekStart: PropTypes.number,
year: PropTypes.number, | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
// Events
onDayClick: PropTypes.func,
onDayContextMenu: PropTypes.func,
onDayEnter: PropTypes.func,
onDayLeave: PropTypes.func,
onRenderEnd: PropTypes.func,
onSelectRange: PropTypes.func,
onYearChanged: PropTypes.func
};
static locales = JsCalendar.locales; // Map the "locales" property to the js-year-calendar "locales" property, in order to make the locale files compatible
constructor(props) {
super(props);
} | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
constructor(props) {
super(props);
}
componentDidMount() {
this.JsCalendar = new JsCalendar(this.container, {
// opsions
allowOverlap: this.props.allowOverlap,
alwaysHalfDay: this.props.alwaysHalfDay,
contextMenuItems: this.props.contextMenuItems,
customDayRenderer: this.props.customDayRenderer,
customDataSourceRenderer: this.props.customDataSourceRenderer,
dataSource: this.props.dataSource,
disabledDays: this.props.disabledDays,
disabledWeekDays: this.props.disabledWeekDays,
displayDisabledDataSource: this.props.displayDisabledDataSource,
displayHeader: this.props.displayHeader,
displayWeekNumber: this.props.displayWeekNumber,
enableContextMenu: this.props.enableContextMenu,
enableRangeSelection: this.props.enableRangeSelection,
hiddenWeekDays: this.props.hiddenWeekDays,
language: this.props.language,
loadingTemplate: this.props.loadingTemplate,
maxDate: this.props.maxDate,
minDate: this.props.minDate,
roundRangeLimits: this.props.roundRangeLimits,
style: this.props.style,
weekStart: this.props.weekStart,
numberMonthsDisplayed: this.props.numberMonthsDisplayed,
startYear: this.props.year != null ? this.props.year : this.props.defaultYear,
startDate: this.props.startDate != null ? this.props.startDate : this.props.defaultStartDate, | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
// Events
clickDay: this.props.onDayClick,
dayContextMenu: this.props.onDayContextMenu,
mouseOnDay: this.props.onDayEnter,
mouseOutDay: this.props.onDayLeave,
renderEnd: this.props.onRenderEnd,
selectRange: this.props.onRangeSelected,
periodChanged: this.props.onPeriodChanged,
yearChanged: this.props.onYearChanged
});
}
compare(a, b) {
if (typeof a === "function" && typeof b === "function") {
return a.toString() != b.toString();
}
else if (a instanceof Date && b instanceof Date) {
return a.getTime() != b.getTime();
}
else if (a !== null && typeof a === "object" && b !== null && typeof b === "object") {
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return true;
}
else {
return aKeys.some(key => this.compare(a[key], b[key]));
}
}
else {
return a != b;
}
}
updateEvent(eventName, oldListener, newListener) {
this.container.removeEventListener(eventName, oldListener);
this.container.addEventListener(eventName, newListener);
}
componentWillReceiveProps(nextProps) {
const cal = this.JsCalendar;
const ops = []; | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
// opsions
if (this.compare(nextProps.allowOverlap, this.props.allowOverlap)) ops.push(() => cal.setAllowOverlap(nextProps.allowOverlap));
if (this.compare(nextProps.alwaysHalfDay, this.props.alwaysHalfDay)) ops.push(() => cal.setAlwaysHalfDay(nextProps.alwaysHalfDay, true));
if (this.compare(nextProps.contextMenuItems, this.props.contextMenuItems)) ops.push(() => cal.setContextMenuItems(nextProps.contextMenuItems, true));
if (this.compare(nextProps.customDayRenderer, this.props.customDayRenderer)) ops.push(() => cal.setCustomDayRenderer(nextProps.customDayRenderer, true));
if (this.compare(nextProps.customDataSourceRenderer, this.props.customDataSourceRenderer)) ops.push(() => cal.setCustomDataSourceRenderer(nextProps.customDataSourceRenderer, true));
if (this.compare(nextProps.dataSource, this.props.dataSource)) ops.push(() => cal.setDataSource(nextProps.dataSource, true));
if (this.compare(nextProps.disabledDays, this.props.disabledDays)) ops.push(() => cal.setDisabledDays(nextProps.disabledDays, true));
if (this.compare(nextProps.disabledWeekDays, this.props.disabledWeekDays)) ops.push(() => cal.setDisabledWeekDays(nextProps.disabledWeekDays, true));
if (this.compare(nextProps.displayDisabledDataSource, this.props.displayDisabledDataSource)) ops.push(() => cal.setDisplayDisabledDataSource(nextProps.displayDisabledDataSource, true));
if (this.compare(nextProps.displayHeader, this.props.displayHeader)) ops.push(() => cal.setDisplayHeader(nextProps.displayHeader, true));
if (this.compare(nextProps.displayWeekNumber, this.props.displayWeekNumber)) ops.push(() => cal.setDisplayWeekNumber(nextProps.displayWeekNumber, true));
if (this.compare(nextProps.enableContextMenu, this.props.enableContextMenu)) ops.push(() => cal.setEnableContextMenu(nextProps.enableContextMenu, true)); | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
if (this.compare(nextProps.enableRangeSelection, this.props.enableRangeSelection)) ops.push(() => cal.setEnableRangeSelection(nextProps.enableRangeSelection, true));
if (this.compare(nextProps.hiddenWeekDays, this.props.hiddenWeekDays)) ops.push(() => cal.setHiddenWeekDays(nextProps.hiddenWeekDays, true));
if (this.compare(nextProps.language, this.props.language)) ops.push(() => cal.setLanguage(nextProps.language, true));
if (this.compare(nextProps.loadingTemplate, this.props.loadingTemplate)) ops.push(() => cal.setLoadingTemplate(nextProps.loadingTemplate, true));
if (this.compare(nextProps.maxDate, this.props.maxDate)) ops.push(() => cal.setMaxDate(nextProps.maxDate, true));
if (this.compare(nextProps.minDate, this.props.minDate)) ops.push(() => cal.setMinDate(nextProps.minDate, true));
if (this.compare(nextProps.roundRangeLimits, this.props.roundRangeLimits)) ops.push(() => cal.setRoundRangeLimits(nextProps.roundRangeLimits, true));
if (this.compare(nextProps.style, this.props.style)) ops.push(() => cal.setStyle(nextProps.style, true));
if (this.compare(nextProps.weekStart, this.props.weekStart)) ops.push(() => cal.setWeekStart(nextProps.weekStart, true));
if (this.compare(nextProps.numberMonthsDisplayed, this.props.numberMonthsDisplayed)) ops.push(() => cal.setWeekStart(nextProps.numberMonthsDisplayed, true));
if (this.compare(nextProps.startDate, this.props.startDate)) ops.push(() => cal.setStartDate(nextProps.startDate));
if (this.compare(nextProps.year, this.props.year)) ops.push(() => cal.setYear(nextProps.year)); | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
// Events
if (this.compare(nextProps.onDayClick, this.props.onDayClick)) this.updateEvent('clickDay', this.props.onDayClick, nextProps.onDayClick);
if (this.compare(nextProps.onDayContextMenu, this.props.onDayContextMenu)) this.updateEvent('dayContextMenu', this.props.onDayContextMenu, nextProps.onDayContextMenu);
if (this.compare(nextProps.onDayEnter, this.props.onDayEnter)) this.updateEvent('mouseOnDay', this.props.onDayEnter, nextProps.onDayEnter);
if (this.compare(nextProps.onDayLeave, this.props.onDayLeave)) this.updateEvent('mouseOutDay', this.props.onDayLeave, nextProps.onDayLeave);
if (this.compare(nextProps.onRenderEnd, this.props.onRenderEnd)) this.updateEvent('renderEnd', this.props.onRenderEnd, nextProps.onRenderEnd);
if (this.compare(nextProps.onRangeSelected, this.props.onRangeSelected)) this.updateEvent('selectRange', this.props.onRangeSelected, nextProps.onRangeSelected);
if (this.compare(nextProps.onPeriodChanged, this.props.onPeriodChanged)) this.updateEvent('periodChanged', this.props.onPeriodChanged, nextProps.onPeriodChanged);
if (this.compare(nextProps.onYearChanged, this.props.onYearChanged)) this.updateEvent('yearChanged', this.props.onYearChanged, nextProps.onYearChanged);
if (ops.length > 0) {
ops.forEach(op => op());
if (nextProps.year == this.props.year && nextProps.startDate == this.props.startDate) {
// If the year has changed, the calendar has automatically been rendered
cal.render();
}
}
}
render() {
return (
<div ref={elt => this.container = elt}></div>
);
}
} | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
This component is the official React.js wrapper for the js-year-calendar widget.
But the rc-year-calendar library has some peer dependencies issues and I am unable to install and I am using TypeScript, rc-year-calendar has no @types/rc-year-calendar.
So I decided to create my own wrapper since js-year-calendar is written in TypeScript and I made it a function component.
import { useEffect, useRef } from "react";
import Calendar from "js-year-calendar";
import CalendarOptions from "js-year-calendar/dist/interfaces/CalendarOptions";
import CalendarDataSourceElement from "js-year-calendar/dist/interfaces/CalendarDataSourceElement";
import 'js-year-calendar/dist/js-year-calendar.css'
export interface CalendarEvent extends CalendarDataSourceElement {
details?: string
}
export default function YearCalendar(props?: CalendarOptions<CalendarEvent>) {
const calendarRef = useRef<any>()
const previousProps = useRef<CalendarOptions<CalendarEvent> | undefined>()
useEffect(() => {
// function properties are not to be compared
const getDifference = (a: any, b: any) => Object.fromEntries(Object.entries(b).filter(([key, val]) => key in a && a[key] !== val && typeof a[key] !== 'function'));
if (previousProps.current !== undefined) {
if (Object.keys(getDifference(previousProps.current, props)).length === 0) {
return
}
}
previousProps.current = props
new Calendar(calendarRef.current, props)
}, [props])
return <div ref={elt => calendarRef.current = elt} />
}
I want to get some feedback on how well my function component is written and how I can make it better | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
Answer: Looking at your wrapper component, it already seems pretty neat. There are a few things I would change in order to improve readability and maintainability and also add a few changes in terms of typings.
Generally, I'd discourage the usage of any, as it is the root of all evil.
So for example the usage of useRef<any>, would be come something like useRef<HTMLElement | null>.
As far as I've seen it correctly, the Calendar constructor requires string | HTMLElement, which is a bummer.
Based on the constructor I'd recommend to go with this quirk and cast it as any, that means we are swallowing the bitter pill there and only there.
For others to keep track of this explicit decision, you could add a comment explaining WHY this decision was made and if needed disable any linters complaining about the any usage.
For example this would like this:
export default function YearCalendar(props?: CalendarOptions<CalendarEvent>) {
const calendarRef = useRef<HTMLElement | null>()
// abbreviated for readability
useEffect(() => {
/* abbreviated for readability */
// constructor requires ref to be of type HTMLElement | string rather than HTMLElement | null
// casting is intended to any is intended to keep the typing throughout this component "correct"
new Calendar(calendarRef.current as any, props)
}, [props])
return <div ref={elt => calendarRef.current = elt} />
}
Which has the advantage, that if there was ever any change or further method accessing and manipulating the ref, it would be properly typed.
The getDifference method is standalone and should be pulled out of the component, this increases readability and it is not allocated everytime the useEffect hook executes.
Avoid nesting multiple ifs together, this is rather ugly and has a high mental complexity. Also, try to express the statements in some more readable manner. Both statements could be summarized to: | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
when previousProps have a value assigned and previousProps and currentProps
are equal then quit the useEffect hook
Applying the above would result in something along those lines:
const getDifference = (a: any, b: any) => Object.fromEntries(Object.entries(b).filter(([key, val]) => key in a && a[key] !== val && typeof a[key] !== 'function'));
const areEqual = (a: any, b: any) => Object.keys(getDifference(a, b)).length === 0;
const isAssigned = <T extends object>(x: T | null | undefined): x is T => x !== undefined && x !== null;
export default function YearCalendar(props?: CalendarOptions<CalendarEvent>) {
const calendarRef = useRef<HTMLElement | null>()
const previousProps = useRef<CalendarOptions<CalendarEvent> | undefined>()
useEffect(() => {
if (isAssigned(previousProps.current) && areEqual(previousProps.current, props)) {
return;
}
previousProps.current = props
new Calendar(calendarRef.current as any, props)
}, [props])
return <div ref={elt => calendarRef.current = elt} />
}
So combining everything together, this is the code I'd come up with (omitting all comments for abbreviation):
import { useEffect, useRef } from "react";
import Calendar from "js-year-calendar";
import CalendarOptions from "js-year-calendar/dist/interfaces/CalendarOptions";
import CalendarDataSourceElement from "js-year-calendar/dist/interfaces/CalendarDataSourceElement";
import 'js-year-calendar/dist/js-year-calendar.css'
export interface CalendarEvent extends CalendarDataSourceElement {
details?: string
}
const getDifference = (a: any, b: any) => Object.fromEntries(Object.entries(b).filter(([key, val]) => key in a && a[key] !== val && typeof a[key] !== 'function'));
const areEqual = (a: any, b: any) => Object.keys(getDifference(a, b)).length === 0;
const isAssigned = <T extends object>(x: T | null | undefined): x is T => x !== undefined && x !== null; | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
export default function YearCalendar(props?: CalendarOptions<CalendarEvent>) {
const calendarRef = useRef<HTMLElement | null>()
const previousProps = useRef<CalendarOptions<CalendarEvent> | undefined>()
useEffect(() => {
if (isAssigned(previousProps.current) && areEqual(previousProps.current, props)) {
return;
}
previousProps.current = props
new Calendar(calendarRef.current as any, props)
}, [props])
return <div ref={elt => calendarRef.current = elt} />
}
PS: If you notice, that throughout your code base, you want to access previousProps more often in various useEffect hooks, I'd pledge to extract that logic into its own hook calling e.g. usePrevious.
Addendum
As seen in the comments, I didn't clearly express what I meant with the usePrevious hook.
Currently the wrapper manages its previous props on its own. Those two lines are responsible for it:
const previousProps = useRef<CalendarOptions<CalendarEvent> | undefined>();
// somewhere below
previousProps.current = props
So for the wrapper alone, this is a valid solution. As soon as this logic is used more than once (maybe another wrapper component), it might be useful to keep in mind, that it can be extracted.
I personally tend to extract such general functionality in order to keep my stuff clean and follow the single-responsibility pattern.
So for example another component relying on previous props, without extracting it, would then look like this:
export const SomeOtherComponent = (props) => {
const previousProps = useRef<SomeType>();
useEffect(() => {
// DO SOMETHING
previousProps.current = props
}, [previousProps]);
} | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
react.js, typescript, jsx
useEffect(() => {
// DO SOMETHING
previousProps.current = props
}, [previousProps]);
}
Extracting this sort of logic, then enables us to concisely describe that we want to access the previousProps of the component without all the technical verbosity and implementation details - as seen above.
Compare the usage below with the usage above:
// somewhere-else.tsx
export const SomeOtherComponent = (props) => {
const previousProps = usePrevious(props);
useEffect(() => {
// DO SOMETHING
}, [previousProps]);
}
The usage would be similar, in your wrapper component - take a look at the usage without usePrevious and with. Notice that a bunch of useRef related access is now gone:
// YearCalendar.tsx
export default function YearCalendar(props?: CalendarOptions<CalendarEvent>) {
const calendarRef = useRef<HTMLElement | null>()
const previousProps = usePrevious(props);
useEffect(() => {
if (isAssigned(previousProps) && areEqual(previousProps, props)) {
return;
}
new Calendar(calendarRef.current as any, props)
}, [props])
return <div ref={elt => calendarRef.current = elt} />
}
In terms of implementing this hook, an implementation can be found here: https://usehooks.com/usePrevious/ but using the whole package could be a lot of bloat. So it essentially boils down to this:
export const usePrevious<T> = (value: T): T => {
const ref = useRef<T>();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
} | {
"domain": "codereview.stackexchange",
"id": 44498,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "react.js, typescript, jsx",
"url": null
} |
c++, recursion, lambda, c++20, variadic
Title: A Function Applier for Applying Various Algorithms on Nested Container Things in C++
Question: This is a follow-up question for A recursive_replace_if Template Function Implementation in C++, A recursive_copy_if Template Function Implementation in C++, A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++ and A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++. After implemented recursive_replace_if and recursive_copy_if, I am trying to generalize the operation of applying a function on elements in nested container. The unwrap level parameter is used here instead of std::invocable as the termination condition of the recursion process.
The experimental implementation
The experimental implementation is as below.
// recursive_function_applier implementation
template<std::size_t unwrap_level, class F, std::ranges::range Range, class... Args>
constexpr auto recursive_function_applier(const F& function, const Range& input, Args... args)
{
if constexpr (unwrap_level >= 1)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&function, &args...](auto&& element) { return recursive_function_applier<unwrap_level - 1>(function, element, args...); }
);
return output;
}
else
{
Range output{};
function(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
args...);
return output;
}
}
Test cases
Test cases with using std::ranges::copy function
// std::copy test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_vector)); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_vector2));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::copy, test_string_vector
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::copy, test_string_vector2
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_deque));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_deque2));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_list));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_list2));
recursive_print(
recursive_function_applier<10>(
std::ranges::copy,
n_dim_container_generator<10, std::list>(test_list, 3)
)
); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
Test cases with using std::ranges::replace_copy_if function
// std::ranges::replace_copy_if test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::replace_copy_if, test_string_vector, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::replace_copy_if, test_string_vector2, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_deque, [](int x) { return (x % 2) == 0; }, 0));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_deque2, [](int x) { return (x % 2) == 0; }, 0)); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_list, [](int x) { return (x % 2) == 0; }, 0));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_list2, [](int x) { return (x % 2) == 0; }, 0));
recursive_print(
recursive_function_applier<10>(
std::ranges::replace_copy_if,
n_dim_container_generator<10, std::list>(test_list, 3),
[](int x) { return (x % 2) == 0; },
0
)
);
Test cases with using std::ranges::remove_copy function
// std::remove_copy test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_vector, 5));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_vector2, 5));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::remove_copy, test_string_vector, "0"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::remove_copy, test_string_vector2, "0"
)
); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_deque, 1));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_deque2, 1));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_list, 1));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_list2, 1));
recursive_print(
recursive_function_applier<10>(
std::ranges::remove_copy,
n_dim_container_generator<10, std::list>(test_list, 3),
1
)
);
Test cases with using std::ranges::remove_copy_if function
// std::remove_copy_if test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5))); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::remove_copy_if, test_string_vector, [](std::string x) { return (x == "0"); }
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::remove_copy_if, test_string_vector2, [](std::string x) { return (x == "0"); }
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_deque, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_deque2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_list, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_list2, std::bind(std::less<int>(), std::placeholders::_1, 5))); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
recursive_print(
recursive_function_applier<5>(
std::ranges::remove_copy_if,
n_dim_container_generator<5, std::list>(test_list, 3),
std::bind(std::less<int>(), std::placeholders::_1, 5)
)
);
Full Testing Code
The full testing code:
// A Function Applier for Applying Various Algorithms on Nested Container Things in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <exception>
#include <execution>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
template<typename T>
concept is_inserterable = requires(T x)
{
std::inserter(x, std::ranges::end(x));
};
#ifdef USE_BOOST_MULTIDIMENSIONAL_ARRAY
template<typename T>
concept is_multi_array = requires(T x)
{
x.num_dimensions();
x.shape();
boost::multi_array(x);
};
#endif
// recursive_copy_if function
template <std::ranges::input_range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate>
constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate)
{
Range output{};
std::ranges::copy_if(std::ranges::cbegin(input), std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate);
return output;
}
template <
std::ranges::input_range Range,
class UnaryPredicate>
constexpr auto recursive_copy_if(const Range& input, const UnaryPredicate& unary_predicate)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate](auto&& element) { return recursive_copy_if(element, unary_predicate); }
);
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// recursive_count implementation
template<std::ranges::input_range Range, typename T>
constexpr auto recursive_count(const Range& input, const T& target)
{
return std::count(std::ranges::cbegin(input), std::ranges::cend(input), target);
}
// transform_reduce version
template<std::ranges::input_range Range, typename T>
requires std::ranges::input_range<std::ranges::range_value_t<Range>>
constexpr auto recursive_count(const Range& input, const T& target)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [target](auto&& element) {
return recursive_count(element, target);
});
}
// recursive_count implementation (with execution policy)
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::count(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), target);
}
template<class ExPo, std::ranges::input_range Range, typename T>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_count(ExPo execution_policy, const Range& input, const T& target)
{
return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [execution_policy, target](auto&& element) {
return recursive_count(execution_policy, element, target);
});
}
// recursive_count_if implementation
template<class T, std::invocable<T> Pred>
constexpr std::size_t recursive_count_if(const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
} | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
template<std::ranges::input_range Range, class Pred>
requires (!std::invocable<Pred, Range>)
constexpr auto recursive_count_if(const Range& input, const Pred& predicate)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (with execution policy)
template<class ExPo, class T, std::invocable<T> Pred>
requires (std::is_execution_policy_v<std::remove_cvref_t<ExPo>>)
constexpr std::size_t recursive_count_if(ExPo execution_policy, const T& input, const Pred& predicate)
{
return predicate(input) ? 1 : 0;
}
template<class ExPo, std::ranges::input_range Range, class Pred>
requires ((std::is_execution_policy_v<std::remove_cvref_t<ExPo>>) && (!std::invocable<Pred, Range>))
constexpr auto recursive_count_if(ExPo execution_policy, const Range& input, const Pred& predicate)
{
return std::transform_reduce(execution_policy, std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if(element, predicate);
});
}
// recursive_count_if implementation (the version with unwrap_level)
template<std::size_t unwrap_level, std::ranges::range T, class Pred>
auto recursive_count_if(const T& input, const Pred& predicate)
{
if constexpr (unwrap_level > 1)
{
return std::transform_reduce(std::ranges::cbegin(input), std::ranges::cend(input), std::size_t{}, std::plus<std::size_t>(), [predicate](auto&& element) {
return recursive_count_if<unwrap_level - 1>(element, predicate);
});
}
else
{
return std::count_if(std::ranges::cbegin(input), std::ranges::cend(input), predicate);
}
} | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// recursive_function_applier implementation
template<std::size_t unwrap_level, class F, std::ranges::range Range, class... Args>
constexpr auto recursive_function_applier(const F& function, const Range& input, Args... args)
{
if constexpr (unwrap_level >= 1)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&function, &args...](auto&& element) { return recursive_function_applier<unwrap_level - 1>(function, element, args...); }
);
return output;
}
else
{
Range output{};
function(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
args...);
return output;
}
}
// recursive_print implementation
template<std::ranges::input_range Range>
constexpr auto recursive_print(const Range& input, const int level = 0)
{
auto output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& x)
{
std::cout << std::string(level, ' ') << x << std::endl;
return x;
}
);
return output;
}
template<std::ranges::input_range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_print(const Range& input, const int level = 0)
{
auto output = input;
std::cout << std::string(level, ' ') << "Level " << level << ":" << std::endl;
std::ranges::transform(std::ranges::cbegin(input), std::ranges::cend(input), std::ranges::begin(output),
[level](auto&& element)
{
return recursive_print(element, level + 1);
}
);
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// recursive_replace_copy_if implementation
template<std::ranges::range Range, std::invocable<std::ranges::range_value_t<Range>> UnaryPredicate, class T>
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::replace_copy_if(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
unary_predicate,
new_value);
return output;
}
template<std::ranges::input_range Range, class UnaryPredicate, class T>
requires (!std::invocable<UnaryPredicate, std::ranges::range_value_t<Range>>)
constexpr auto recursive_replace_copy_if(const Range& input, const UnaryPredicate& unary_predicate, const T& new_value)
{
Range output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&unary_predicate, &new_value](auto&& element) { return recursive_replace_copy_if(element, unary_predicate, new_value); }
);
return output;
}
// recursive_size implementation
template<class T> requires (!std::ranges::range<T>)
constexpr auto recursive_size(const T& input)
{
return 1;
}
template<std::ranges::range Range> requires (!(std::ranges::input_range<std::ranges::range_value_t<Range>>))
constexpr auto recursive_size(const Range& input)
{
return std::ranges::size(input);
}
template<std::ranges::range Range> requires (std::ranges::input_range<std::ranges::range_value_t<Range>>)
constexpr auto recursive_size(const Range& input)
{
return std::transform_reduce(std::ranges::begin(input), std::end(input), std::size_t{}, std::plus<std::size_t>(), [](auto& element) {
return recursive_size(element);
});
} | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// recursive_transform implementation
// recursive_invoke_result_t implementation
// from https://stackoverflow.com/a/65504127/6667035
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>> &&
std::ranges::input_range<Container<Ts...>> &&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
template <std::ranges::range Range>
constexpr auto get_output_iterator(Range& output)
{
return std::inserter(output, std::ranges::end(output));
}
template <class T, std::invocable<T> F>
constexpr auto recursive_transform(const T& input, const F& f)
{
return std::invoke(f, input); // use std::invoke() instead, https://codereview.stackexchange.com/a/283364/231235
}
template <
std::ranges::input_range Range,
class F>
requires (!std::invocable<F, Range>)
constexpr auto recursive_transform(const Range& input, const F& f)
{
recursive_invoke_result_t<F, Range> output{};
std::ranges::transform(
std::ranges::cbegin(input),
std::ranges::cend(input),
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform(element, f); }
);
return output;
} | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
template<std::size_t dim, class T>
constexpr auto n_dim_vector_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_vector_generator<dim - 1>(input, times);
std::vector<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, std::size_t times, class T>
constexpr auto n_dim_array_generator(T input)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_array_generator<dim - 1, times>(input);
std::array<decltype(element), times> output;
std::fill(std::begin(output), std::end(output), element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_deque_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_deque_generator<dim - 1>(input, times);
std::deque<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, class T>
constexpr auto n_dim_list_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
auto element = n_dim_list_generator<dim - 1>(input, times);
std::list<decltype(element)> output(times, element);
return output;
}
}
template<std::size_t dim, template<class...> class Container = std::vector, class T>
constexpr auto n_dim_container_generator(T input, std::size_t times)
{
if constexpr (dim == 0)
{
return input;
}
else
{
return Container(times, n_dim_container_generator<dim - 1, Container, T>(input, times));
}
}
void copy_test();
void replace_copy_if_test();
void remove_copy_test();
void remove_copy_if_test();
int main()
{
copy_test();
replace_copy_if_test();
remove_copy_test();
remove_copy_if_test();
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
void copy_test()
{
// std::copy test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_vector));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_vector2));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::copy, test_string_vector
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::copy, test_string_vector2
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_deque));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_deque2));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::copy, test_list)); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::copy, test_list2));
recursive_print(
recursive_function_applier<5>(
std::ranges::copy,
n_dim_container_generator<5, std::list>(test_list, 3)
)
);
return;
}
void replace_copy_if_test()
{
// std::ranges::replace_copy_if test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5), 55));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::replace_copy_if, test_string_vector, [](std::string x) { return (x == "1"); }, "11"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::replace_copy_if, test_string_vector2, [](std::string x) { return (x == "1"); }, "11"
)
); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_deque, [](int x) { return (x % 2) == 0; }, 0));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_deque2, [](int x) { return (x % 2) == 0; }, 0));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::replace_copy_if, test_list, [](int x) { return (x % 2) == 0; }, 0));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::replace_copy_if, test_list2, [](int x) { return (x % 2) == 0; }, 0));
recursive_print(
recursive_function_applier<5>(
std::ranges::replace_copy_if,
n_dim_container_generator<5, std::list>(test_list, 3),
[](int x) { return (x % 2) == 0; },
0
)
);
return;
}
void remove_copy_test()
{
// std::remove_copy test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_vector, 5));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_vector2, 5)); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::remove_copy, test_string_vector, "0"
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::remove_copy, test_string_vector2, "0"
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_deque, 1));
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_deque2, 1));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy, test_list, 1));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy, test_list2, 1));
recursive_print(
recursive_function_applier<5>(
std::ranges::remove_copy,
n_dim_container_generator<5, std::list>(test_list, 3),
1
)
);
return;
} | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
void remove_copy_if_test()
{
// std::remove_copy_if test cases
// std::vector<int>
std::vector<int> test_vector{ 5, 7, 4, 2, 8, 6, 1, 9, 0, 3 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_vector, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::vector<std::vector<int>>
std::vector<decltype(test_vector)> test_vector2{ test_vector , test_vector , test_vector };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_vector2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::vector<std::string>
std::vector<std::string> test_string_vector{ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20" };
recursive_print(
recursive_function_applier<0>(
std::ranges::remove_copy_if, test_string_vector, [](std::string x) { return (x == "0"); }
)
);
// std::vector<std::vector<std::string>>
std::vector<decltype(test_string_vector)> test_string_vector2{ test_string_vector , test_string_vector , test_string_vector };
recursive_print(
recursive_function_applier<1>(
std::ranges::remove_copy_if, test_string_vector2, [](std::string x) { return (x == "0"); }
)
);
// std::deque<int>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(2);
test_deque.push_back(3);
test_deque.push_back(4);
test_deque.push_back(5);
test_deque.push_back(6);
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_deque, std::bind(std::less<int>(), std::placeholders::_1, 5))); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
// std::deque<std::deque<int>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_deque2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::list<int>
std::list<int> test_list = { 1, 2, 3, 4, 5, 6 };
recursive_print(recursive_function_applier<0>(std::ranges::remove_copy_if, test_list, std::bind(std::less<int>(), std::placeholders::_1, 5)));
// std::list<std::list<int>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
recursive_print(recursive_function_applier<1>(std::ranges::remove_copy_if, test_list2, std::bind(std::less<int>(), std::placeholders::_1, 5)));
recursive_print(
recursive_function_applier<5>(
std::ranges::remove_copy_if,
n_dim_container_generator<5, std::list>(test_list, 3),
std::bind(std::less<int>(), std::placeholders::_1, 5)
)
);
return;
}
A Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_replace_if Template Function Implementation in C++,
A recursive_copy_if Template Function Implementation in C++,
A recursive_count_if Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++ and
A recursive_count_if Function For Various Type Arbitrary Nested Iterable Implementation in C++
What changes has been made in the code since last question?
I am trying to implement a recursive_function_applier template function as a function applier for applying various algorithms on nested container. | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
Why a new review is being asked for?
Not sure the design of recursive_function_applier template function is a good idea or not. Whatever, this structure seems to be working fine in std::ranges::copy, std::ranges::replace_copy_if, std::ranges::remove_copy and std::ranges::remove_copy_if cases. If there is any possible improvement, please let me know.
Answer: What does it do?
I am trying to generalize the operation of applying a function on elements in nested container.
If you say that, I would think that your recursive_transform() would already cover it. It seems that this "function applier" is actually more a "container algorithm applier"; it recurses a nested container to a given level, expects that every element at that point is also a container, and then calls the given function, expecting it to have a similar interface as STL algorithms such as std::copy(): they get two input iterators and an output iterator as arguments.
An alternative approach
I think the only reason for this function is to deal with the fact that STL algorithms never return a container. You could say that they are not working in a functional programming style. If they did, then you could just easily compose your recursive_transform() with a copy() function that does return a container. So maybe you should make those instead? Consider:
struct SameAsInput;
template<typename Output = SameAsInput, typename Input>
auto return_copy(const Input& input) {
std::conditional_t<
std::is_same_v<Output, SameAsInput>,
Input,
Output
> output;
std::ranges::copy(input, std::inserter(output, std::ranges::end(output)));
return output;
}
Then instead of:
recursive_function_applier<0>(std::ranges::copy, test_vector);
You could write:
recursive_transform<0>(test_vector, return_copy); | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, recursion, lambda, c++20, variadic
You could write:
recursive_transform<0>(test_vector, return_copy);
You can make return_copy_n(), return_remove_copy(), return_remove_copy_if(), and so on.
Restricting the container type
You are using the concept std::ranges::range to restrict the type of input. However, you want to create a container that has the same type of input, and not every range is a container. For example, views are ranges too. Unfortunately, there is no std::container concept, but you can make one yourself. | {
"domain": "codereview.stackexchange",
"id": 44499,
"lm_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++, recursion, lambda, c++20, variadic",
"url": null
} |
c++, api, interface, overloading, bigint
Title: API design for Implementing NaN/Unknown values for custom numeric type
Question: I'm gradually writing an arbitrary-precision arithmetic library for C++. I've decided it could be useful to have the default constructor produce an object of indeterminate value, rather than relying upon {} = 0, to make my code more explicit.
I'm not yet sure whether I want operations like division by zero or square root of negatives to return NaN —currently I throw an exception for zero division, but it could be used for these later too.
I also think that for my library, it is more useful for NaN to compare equal with itself —I know this is the opposite behaviour to floating point, but I'm not intending to ever implement fp behaviour with my library and from reading up the history of why float NaN doesn't equal itself, it seems this was done mostly for technical limitations at the time rather than reasoning.
Here's the implementation I have come up with, using an empty tag-like struct to represent NaN, so it can be used with multiple different arbitrary-precision types easily:
#include <cstdint>
#include <compare>
static constexpr struct {} NaN = {};
class Number {
public:
constexpr Number() : Number(NaN) {}
constexpr Number(decltype(NaN)) : _is_nan(true) {}
constexpr Number(std::intmax_t number) : _number(number) {}
constexpr std::partial_ordering operator<=>(const Number& rhs) const {
// NaNs are stritly unordered --unless when checking for NaN == NaN
if (_is_nan or rhs._is_nan) { return std::partial_ordering::unordered; }
// otherwise compare values by default
return _number <=> rhs._number; // NOTE: implicitly converts strong to partial ordering
}
// for our equality operator, we actually *DO* want the default, as we want NaN == NaN
constexpr bool operator==(const Number& rhs) const = default;
private:
std::intmax_t _number = 0;
bool _is_nan = false;
}; | {
"domain": "codereview.stackexchange",
"id": 44500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, api, interface, overloading, bigint",
"url": null
} |
c++, api, interface, overloading, bigint
int main() {
static_assert(Number(0) == Number(0));
static_assert(Number() == Number());
static_assert(Number() == NaN);
static_assert(Number() == Number(NaN));
static_assert(Number(45) <= Number(67));
static_assert(Number(37) >= 21);
static_assert(not (Number(32) > NaN));
static_assert(not (Number() > Number()));
static_assert(not (Number() <= NaN));
static_assert(not (Number() < NaN));
}
Notes:
Obviously this class isn't arbitrary precision. That code is too long and it's not relevant to this question, which is about API design. I have included only a tiny stub implementation of the value part of the class here, to focus on the implementation of NaNs.
In practice, I will probably represent NaN internally as an object with no digits in its digit array, and there will be no _is_nan flag.
Yes, constexpr is deliberate and yes, the existing current working version of the library does provide a fully working constexpr arbitrary-precision type. You can use it at compile-time but only if it's deallocated before the constant expression it is used in goes out of scope. This limits its utility but it is still a highly useful thing to have.
All code is C++20
What do you think of my API design? I pondered whether I should just use a static constant NAN in the class and use that to get NAN, but this approach feels more user-friendly because one constant can be used with all of the arbitrary-precision classes I'm going to provide.
Answer: Avoid surprising behaviour
I've decided it could be useful to have the default constructor produce an object of indeterminate value, rather than relying upon {} = 0, to make my code more explicit.
I don't see how it makes anything more explicit, you just changed the implicit behaviour of the default constructor. And when you write:
Number n{}; // NaN
It now works very different compared to regular integeres:
int n{}; // 0 | {
"domain": "codereview.stackexchange",
"id": 44500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, api, interface, overloading, bigint",
"url": null
} |
c++, api, interface, overloading, bigint
It now works very different compared to regular integeres:
int n{}; // 0
Which will be surprising for programmers used to the behaviour of the built-in types.
for our equality operator, we actually DO want the default, as we want NaN == NaN
Are you really sure you want that? Consider a scenario where you did allow division by zero and the square root of a negative number to return a NaN instead of throwing an exception, would you want the following expression to be true?
Number(0) / Number(0) == Number(-1).sqrt()
There is a good reason why NaNs don't compare equal to themselves, and often this will cause code that was not written specifically to handle NaNs to do the better thing. And as J_H mentioned, programmers who know about IEE754 NaNs might rely on your NaNs to behave the same, and will be surprised if they don't.
Be careful with implicit constructors
The following constructor allows implicit conversion of any integer type to a Number:
constexpr Number(std::intmax_t number) : _number(number) {}
However, it will first convert the value you give it to a std::intmax_t. Consider that there is also a std::uint_max_t, and that is has an implicit conversion operator to std::intmax_t, which will change the actual value if it was larger than the maximum value std::intmax_t can hold. This will lead to surprising results, especially if one did not enable or pay attention to compiler warnings.
It is better to make this constructor explicit, but then it would only work on values that have exactly the same type as std::intmax_t. You could add overloads for all integer types of course. Alternatively, it might be possible to provide both implicit constructors for std::intmax_t and std::uintmax_t. In any case, I would add unit tests that check these kinds of corner cases. | {
"domain": "codereview.stackexchange",
"id": 44500,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, api, interface, overloading, bigint",
"url": null
} |
c, networking, socket
Title: struct sockaddr_storage initialization by network format string
Question: I am writing a wrapper library for network functionality in C and wanted to let the user let the user initialize a struct sockaddr_storage with a format string.
Format ist like: "proto:host:port/servicename"
Example: "tcp:localhost:8080", "udp:8.8.8.8:dns"
Possible Protocols Strings: tcp, tcp4, tcp6, udp, udp4, udp6
Some questions I'v got now.
Am I using to many comments?
Am I using to much register variables?
Is this code readable?
Do you see parts of the code that I can reduce?
I get the following timing: - see my main function
2:2001::124:2144:153:80 - 0.000163 ms
3:172.217.16.195:80 - 0.000135 ms
0:127.0.0.1:8080 - 0.000013 ms
0:127.129.41.24:463 - 0.000005 ms
Why is the time going rapidly down?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <unistd.h>
#include <time.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <netdb.h>
typedef enum {tcp, tcp4, tcp6, udp, udp4, udp6} network_id;
typedef struct Addr {
network_id proto; /* protocol (can be): tcp, tcp4, tcp6, udp, udp4, udp6, _unix (unix), unixgram, unixpacket */
char addr[40]; /* string containng either ipv4 or ipv6 address */
int port; /* port number */
} Addr;
#ifndef strncpy_s
int strncpy_s(char *dest, size_t destsz, const char *src, size_t n)
{
if(dest == NULL)
return -1;
while(destsz-- && n-- && *src != '\0')
*dest++ = *src++;
*dest = '\0';
return 0;
}
#endif | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
return 0;
}
#endif
/* compare functions that compared until delimiter is found either in str1 or in str2 */
int compare_until_delim(const char *str1, const char *str2, char delim)
{
/* *str1 != delim xor *str2 == 0 and *str2 != delim xor *str2 == 0 */
while((!(*str1 != delim) != !(*str1 == '\0')) && (!(*str2 != delim) != !(*str2 == '\0'))) {
if(*str1 != *str2)
return false;
str1++;
str2++;
}
if(*str1 != *str2)
return false;
return true;
}
/* protocol table containing supported protocol for socket configuration */
const char *protocol_table[] =
{
"tcp:",
"tcp4:",
"tcp6:",
"udp:",
"udp4:",
"upd6:",
};
/* simple compare until dilimiter check for the protocol table above */
int check_protocol(const char *str)
{
int i, table_size;
table_size = sizeof(protocol_table) / sizeof(*protocol_table);
for(i = 0; i < table_size ; i++) {
if(compare_until_delim(protocol_table[i], str, ':'))
return i;
}
return -1; /* not found */
}
/** ipstr_to_addr - initializes struct Addr and struct sockaddr_in by string containing specific ip address format
* return@int: (0 on success, -2 = inet_pton error, -1 = parsing error at start index 0, 1...n = error at index)
* param@ipstr: format string like format "proto:host:service"
* param@addr: struct Addr (internal use) (contains printable addr infos, except protocol) if NULL only the _sockaddr_storage
* param@_sockaddr_in: struct sockaddr_in, will be setup regarding to the format string
*/
int ipstr_to_addr(const char *ipstr, Addr *addr, struct sockaddr_storage *_sockaddr_storage, int *socktype)
{
assert(_sockaddr_storage != NULL);
register const char *start_ip, *end_ipv6;
register const char *service_start;
register char *domain_p;
struct Addr local; | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
char domain_buffer[256]; /* will temporary hold ipv4 and domain format to convert later from */
bool ipv6;
int proto, port, err;
if(addr == NULL)
addr = &local;
domain_p = domain_buffer;
/* set service start to beginning of ipstr and use it as a seperator to service/port */
service_start = ipstr;
ipv6 = false;
err = 0;
/* get internal protocol id */
proto = check_protocol(ipstr);
if(proto == -1) {
err = -1;
goto cleanup_error;
}
service_start = service_start + strlen(protocol_table[proto]);
/* if first char after protocol is [ check for ] to say it is an ipv6 address */
if(*service_start == '[') {
/* go latest until null byte */
start_ip = service_start + 1;
while(*service_start != '\0') {
/* if enclosure bracket ] was found set ipv6 true and increment service_start */
if(*service_start == ']') {
end_ipv6 = service_start;
ipv6 = true;
service_start++;
break;
}
service_start++;
}
/* service_start should point to ':' in format string right before service/port */
}
/* ip not ipv6 assume ipv4 or domain name */
if(ipv6 == false) {
/* go latest until null byte */
while(*service_start != '\0') {
/* service_start points to seperator ':', increment domain_p first and set to null byte */
if(*service_start == ':') {
*domain_p = '\0';
break;
}
/* write a copy to domain_buffer */
*domain_p++ = *service_start++;
}
/* service_start should point to ':' in format string right before service/port too */
} | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
/* if not ':' we should be at the end of the string which leads to incomplete format, return position of error */
if(*service_start != ':') {
err = service_start - ipstr;
goto cleanup_error;
}
service_start++; /* increase by one to get the real service start position */
port = atoi(service_start); /* try to get port number after ':' */
/* if port port was set to 0, try get port by name */
if(port == 0) {
/* NOTE: maybe use getservent_r for thread safety */
struct servent *service = getservbyname(service_start, NULL);
if(service == NULL) {
err = service_start - ipstr;
goto cleanup_error;
}
port = htons(service->s_port); /* convert to host byte order */
}
/*********************/
/* setup struct Addr */
addr->proto = proto;
addr->port = port;
if(ipv6) {
ipstr++;
strncpy_s(addr->addr, sizeof(addr->addr), start_ip, end_ipv6 - start_ip);
}
else {
///* add check for ipv6 protocol later
struct hostent *entry = gethostbyname(domain_buffer);
strncpy(addr->addr, inet_ntoa(*(struct in_addr*)entry->h_addr_list[0]), sizeof(addr->addr));
}
if(ipv6 && addr->proto == tcp)
addr->proto = tcp6;
else if(ipv6 && addr->proto == udp)
addr->proto = udp6; | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
/****************************/
/* setup struct sockaddr_in */
switch(addr->proto) {
case tcp6:
case udp6:
((struct sockaddr_in6*)_sockaddr_storage)->sin6_family = AF_INET6;
break;
case tcp: /* NOTE: add later should only be usable for listener if calls like 'tcp::port' */
case udp: /* NOTE: same as tcp */
case tcp4:
case udp4:
((struct sockaddr_in*)_sockaddr_storage)->sin_family = AF_INET;
break;
default:
err = -3; /* if this happens and internal error occured because this function should check strict and returns if something not parsed correctly*/
goto cleanup_error;
break;
}
/* set port */
((struct sockaddr_in*)_sockaddr_storage)->sin_port = htons(addr->port);
if(ipv6) {
if(inet_pton(((struct sockaddr_in6*)_sockaddr_storage)->sin6_family, addr->addr, &((struct sockaddr_in6*)_sockaddr_storage)->sin6_addr) != 1) {
err = -2;
goto cleanup_error;
}
}
else { /* ipv4 */
if(inet_pton(((struct sockaddr_in*)_sockaddr_storage)->sin_family, addr->addr, &((struct sockaddr_in*)_sockaddr_storage)->sin_addr) != 1) {
err = -2;
goto cleanup_error;
}
}
/* set correct socket type */
if(addr->proto >= tcp && addr->proto <= tcp6)
*socktype = SOCK_STREAM; /* socket is tcp socket */
else if(addr->proto >= udp && addr->proto <= udp6)
*socktype = SOCK_DGRAM; /* socket is udp socket */
return err; /* error is 0 (success) */
/* if some error occure you land here handle the struct Addr properly */
cleanup_error: {
*addr->addr = '\0';
addr->port = -1;
addr->proto = -1;
return err;
}
}
int main(void)
{
Addr test;
struct sockaddr_storage addr;
int socktype;
clock_t clock_start, clock_end; | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
clock_t clock_start, clock_end;
clock_start = clock();
printf("%d\n", ipstr_to_addr("tcp:[2001::124:2144:153]:http", &test, &addr, &socktype));
clock_end = clock();
printf("%d:%s:%d - ", test.proto, test.addr, test.port);
printf("%f ms\n", (double) (clock_end - clock_start) / CLOCKS_PER_SEC);
clock_start = clock();
ipstr_to_addr("udp:www.google.de:http", &test, &addr, &socktype);
clock_end = clock();
printf("%d:%s:%d - ", test.proto, test.addr, test.port);
printf("%f ms\n", (double) (clock_end - clock_start) / CLOCKS_PER_SEC);
clock_start = clock();
ipstr_to_addr("tcp:localhost:8080", &test, &addr, &socktype);
clock_end = clock();
printf("%d:%s:%d - ", test.proto, test.addr, test.port);
printf("%f ms\n", (double) (clock_end - clock_start) / CLOCKS_PER_SEC);
clock_start = clock();
ipstr_to_addr("tcp:127.129.41.24:463", &test, &addr, &socktype);
clock_end = clock();
printf("%d:%s:%d - ", test.proto, test.addr, test.port);
printf("%f ms\n", (double) (clock_end - clock_start) / CLOCKS_PER_SEC);
/* open listener with netcat and run this */
int sock = socket(addr.ss_family, SOCK_STREAM, 0);
if(sock == -1) {
perror("socket error");
exit(1);
}
if(connect(sock, (struct sockaddr*) &addr, sizeof addr)) {
perror("connection failed");
exit(1);
}
send(sock, "Hallo Meister\n", 15, 0);
close(sock);
}
```
Answer:
Am I using too many comments?
No.
Am I using too much register variables?
Yes. The register keyword is completely obsolete these days. It was intended as an optimisation hint to the compiler, which the compiler can shamelessly and freely ignore.
A declaration of an identifier for an A declaration of an identifier
for an object with storage-class specifier register suggests that
access to the object be as fast as possible. The extent to which such
suggestions are effective is implementation-defined. | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
Most compiler optimizers can do a better job at optimizing code, and you should leave the keyword where it belongs — in the past.
Eliminate magic numbers:
typedef struct Addr {
network_id proto; /* protocol (can be): tcp, tcp4, tcp6, udp, udp4, udp6, _unix (unix), unixgram, unixpacket */
char addr[40]; /* string containng either ipv4 or ipv6 address */
int port; /* port number */
} Addr;
Instead of that magic number 40, code could use INET_ADDRSTRLEN and INET6_ADDRSTRLEN defined in <netinet/in.h>
INET_ADDRSTRLEN -- storage for an IPv4 address
INET6_ADDRSTRLEN --
storage for an IPv6 address
Similarly, in:
char domain_buffer[256]
256 should be a named constant.
#define DOMAIN_BUFSIZ 256
char domain_buffer[DOMAIN_BUFSIZ];
It eases maintainability; requires just one change to the constant instead of all occurrences of the number.
Is this code readable?
Short-term memory and the field of vision are small:
ipstr_to_addr() is too long, complex, and hurts readability. Consider breaking it down into 3-4 (or more) smaller functions.
For instance, this:
/* set correct socket type */
if(addr->proto >= tcp && addr->proto <= tcp6)
*socktype = SOCK_STREAM; /* socket is tcp socket */
else if(addr->proto >= udp && addr->proto <= udp6)
*socktype = SOCK_DGRAM; /* socket is udp socket */
deserves to be a separate set_socktype() function. So does this:
if(ipv6) {
if(inet_pton(((struct sockaddr_in6*)_sockaddr_storage)->sin6_family, addr->addr, &((struct sockaddr_in6*)_sockaddr_storage)->sin6_addr) != 1) {
err = -2;
goto cleanup_error;
}
}
else { /* ipv4 */
if(inet_pton(((struct sockaddr_in*)_sockaddr_storage)->sin_family, addr->addr, &((struct sockaddr_in*)_sockaddr_storage)->sin_addr) != 1) {
err = -2;
goto cleanup_error;
}
}
Do you see parts of the code that I can reduce? | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
Do you see parts of the code that I can reduce?
int compare_until_delim(const char *str1, const char *str2, char delim)
{
/* *str1 != delim xor *str2 == 0 and *str2 != delim xor *str2 == 0 */
while((!(*str1 != delim) != !(*str1 == '\0')) && (!(*str2 != delim) != !(*str2 == '\0'))) {
if(*str1 != *str2)
return false;
str1++;
str2++;
}
if(*str1 != *str2)
return false;
return true;
}
can be shortened to just:
bool compare_until_delim(const char *str1, const char *str2, char delim)
{
/* *str1 != delim xor *str2 == 0 and *str2 != delim xor *str2 == 0 */
while((!(*str1 != delim) != !(*str1 == '\0')) && (!(*str2 != delim) != !(*str2 == '\0'))) {
if(*str1++ != *str2++) {
return false;
}
}
return *str1 == *str2;
}
with no loss of readability.
NB that I changed the return type from int to bool because the function returns true / false. Use the correct types regardless of any implicit conversions.
And:
int check_protocol(const char *str)
{
int i, table_size;
table_size = sizeof(protocol_table) / sizeof(*protocol_table);
for(i = 0; i < table_size ; i++) {
if(compare_until_delim(protocol_table[i], str, ':'))
return i;
}
return -1; /* not found */
}
can be shortened to:
int check_protocol(const char *str)
{
for (size_t i = 0; i < sizeof(protocol_table) / sizeof (*protocol_table); i++) {
if(compare_until_delim(protocol_table[i], str, ':'))
return i;
}
return -1; /* not found */
}
Use a consistent style:
While I do prefer the shorter one, use a consistent style throughout the code:
while((!(*str1 != delim)
// if(dest == NULL)
if (!dest)
// if(ipv6 == false)
if (!ipv6)
Simplify:
// while((!(*str1 != delim) ...
while ((*str1 == delim) ... /* -- @Toby */
atoi() lacks error checking:
port = atoi(service_start); | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
atoi() lacks error checking:
port = atoi(service_start);
errno is not set on error so there is no way to distinguish
between 0 as an error and as the converted value. No checks for
overflow or underflow are done. Only base-10 input can be
converted. It is recommended to instead use the strtol() and
strtoul() family of functions in new programs.
Limit the scope of variables and only declare where needed:
//int i, table_size;
// table_size = sizeof(protocol_table) / sizeof(*protocol_table);
// for(i = 0; i < table_size ; i++) {
// ...
// }
size_t table_size = sizeof(protocol_table) / sizeof(*protocol_table);
// Use unsigned types for array and loop indexing.
// sizeof() also returns size_t.
for (size_t i = 0; i < table_size; i++) {
...
}
Don't define more variables than you need:
We can forego table_size, as it's not used anywhere else in the function.
for (size_t i = 0; i < sizeof(protocol_table) / sizeof(*protocol_table); i++) {
...
}
Or if that is too long for your liking, here's a handy function-like macro:
#define ARRAY_CARDINALITY(x) (sizeof(x) / sizeof((x)[0]))
for (size_t i = 0; ARRAY_CARDINALITY (protocol_table); i++) {
...
}
Specify internal linkage:
Functions have external linkage by default in C. But you are not exporting anything from this single translation unit, so specify internal linkage for all functions except main():
// int check_protocol(const char *str)
static int check_protocol (const char *str)
Braces not required:
//cleanup_error: {
// *addr->addr = '\0';
// addr->port = -1;
// addr->proto = -1;
// return err;
// }
/* Following the convention that macros and goto labels are in all caps.
* This makes it easier to spot.
*/
CLEANUP_ERROR:
*addr->addr = '\0'; /* Note that `->` binds more tightly than `*. */
addr->port = -1;
addr->proto = -1;
return -1; | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
return -1;
Implementation doesn't match documentation:
typedef struct Addr {
network_id proto; /* protocol (can be): tcp, tcp4, tcp6, udp, udp4, udp6, _unix (unix), unixgram, unixpacket */
char addr[40]; /* string containng either ipv4 or ipv6 address */
int port; /* port number */
} Addr;
I see 9 protocols in the above comment. But, there are only 6 in protocol_table.
Prefer returning from main():
Use named constants EXIT_SUCCESS and EXIT_FAILURE as return values for main():
//if(sock == -1) {
// perror("socket error");
// exit(1);
//}
if (sock == -1) {
perror ("socket:");
return EXIT_FAILURE;
}
TCP is a byte stream:
send() and recv() doesn't necessarily send and receive all bytes with a single call.
send() returns the number of bytes actually sent out—this might be
less than the number you told it to send! See, sometimes you tell it
to send a whole gob of data and it just can't handle it. It'll fire
off as much of the data as it can, and trust you to send the rest
later. Remember, if the value returned by send() doesn't match the
value in len, it's up to you to send the rest of the string. The good
news is this: if the packet is small (less than 1K or so) it will
probably manage to send the whole thing all in one go. Again, -1 is
returned on error, and errno is set to the error number.
— Beej's guide to Network Programming
The convention is to call it in a loop until all bytes are sent, and check its return value.
Upon a successful return, send() shall return the number of bytes sent. Otherwise, it returns -1 to indicate a failure, or 0 to indicate a closed connection.
The return value of strncpy_s is discarded:
// strncpy_s(addr->addr, sizeof(addr->addr), start_ip, end_ipv6 - start_ip);
/* Add */
if (strncpy_s (addr->addr, sizeof addr->addr, start_ip, end_ipv6 - start_ip) == -1) {
complain();
} | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c, networking, socket
Why return a value when you're just going to ignore it?
Similarly, ipstr_to_addr is documented to return an error code, but its return value is discarded.
/** ipstr_to_addr - initializes struct Addr and struct sockaddr_in by string containing specific ip address format
* return@int: (0 on success, -2 = inet_pton error, -1 = parsing error at start index 0, 1...n = error at index)
Use braces around if/else/for..:
It's generally considered a good practice to use braces even if it's just a single statement.
//if(ipv6 && addr->proto == tcp)
// addr->proto = tcp6;
// else if(ipv6 && addr->proto == udp)
// addr->proto = udp6;
if(ipv6 && addr->proto == tcp) {
addr->proto = tcp6;
}
else if(ipv6 && addr->proto == udp) {
addr->proto = udp6;
}
Consider what happens when you add another statement before the else and forgot to add braces? The first one would be rightly bounded to the if statement, but the second? It wouldn't remain conditional at all. This could lead to some nasty bugs. See, for instance, Apple's SSL/TSL bug.
gethostbyname is an obsolete function:
The gethostbyname*(), gethostbyaddr*(), herror(), and hstrerror()
functions are obsolete. Applications should use getaddrinfo(3),
getnameinfo(3), and gai_strerror(3) instead.
strncpy_s risks invoking undefined behavior:
while(destsz-- && n-- && *src != '\0')
*dest++ = *src++;
You did not check whether src was a valid pointer. Your code would invoke undefined behavior if src was a NULL pointer. | {
"domain": "codereview.stackexchange",
"id": 44501,
"lm_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, networking, socket",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: A recursive_transform Template Function with Unwrap Level for std::array Implementation in C++
Question: This is a follow-up question for A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++. I am following the suggestions proposed by G. Sliepen in the answer. The techniques including passing a range to std::ranges::transform() and using std::invoke() are performed in the updated version recursive_transform implementation. On the other hand, recursive_depth function is used here for handling incorrect unwrap levels more gracefully. For dealing with std::array type, another overload is proposed.
The experimental implementation
The experimental implementation of recursive_transform function with the unwrap level parameter is as follows.
recursive_transform function implementation
// recursive_transform function implementation (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T, class F>
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
static_assert(unwrap_level <= recursive_depth<T>(),
"unwrap level higher than recursion depth of input"); // trying to handle incorrect unwrap levels more gracefully
recursive_invoke_result_t<F, T> output{};
std::ranges::transform(
input, // passing a range to std::ranges::transform()
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return std::invoke(f, input); // use std::invoke()
}
} | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* This overload of recursive_transform is to support std::array.
*/
template< std::size_t unwrap_level = 1,
template<class T, std::size_t> class Container,
typename F,
typename T,
std::size_t N >
requires is_iterable<Container<T, N>>
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_invoke_result_t<F, T>, N> output;
std::transform( std::begin(input),
std::end(input),
std::begin(output),
[f](auto &x){ return std::invoke(f, x); }
);
return output;
}
recursive_depth helper function implementation
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return 0;
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + 1;
}
Full Testing Code
The full testing code:
// A recursive_transform Template Function with Unwrap Level for std::array Implementation in C++
#include <algorithm>
#include <array>
#include <cassert>
#include <chrono>
#include <complex>
#include <concepts>
#include <deque>
#include <execution>
#include <exception>
#include <functional>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <mutex>
#include <numeric>
#include <optional>
#include <ranges>
#include <stdexcept>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <variant>
#include <vector>
template<class T>
concept is_iterable = requires(T x)
{
*std::begin(x);
std::end(x);
};
// recursive_depth function implementation
template<typename T>
constexpr std::size_t recursive_depth()
{
return 0;
}
template<std::ranges::input_range Range>
constexpr std::size_t recursive_depth()
{
return recursive_depth<std::ranges::range_value_t<Range>>() + 1;
} | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
// recursive_invoke_result_t implementation
template<typename, typename>
struct recursive_invoke_result { };
template<typename T, std::invocable<T> F>
struct recursive_invoke_result<F, T> { using type = std::invoke_result_t<F, T>; };
template<typename F, template<typename...> typename Container, typename... Ts>
requires (
!std::invocable<F, Container<Ts...>>&&
std::ranges::input_range<Container<Ts...>>&&
requires { typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type; })
struct recursive_invoke_result<F, Container<Ts...>>
{
using type = Container<typename recursive_invoke_result<F, std::ranges::range_value_t<Container<Ts...>>>::type>;
};
template<typename F, typename T>
using recursive_invoke_result_t = typename recursive_invoke_result<F, T>::type;
// recursive_transform implementation (the version with unwrap_level)
template<std::size_t unwrap_level = 1, class T, class F>
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
static_assert(unwrap_level <= recursive_depth<T>(),
"unwrap level higher than recursion depth of input"); // trying to handle incorrect unwrap levels more gracefully
recursive_invoke_result_t<F, T> output{};
std::ranges::transform(
input, // passing a range to std::ranges::transform()
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return std::invoke(f, input); // use std::invoke()
}
} | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
/* This overload of recursive_transform is to support std::array
*/
template< std::size_t unwrap_level = 1,
template<class T, std::size_t> class Container,
typename F,
typename T,
std::size_t N >
requires is_iterable<Container<T, N>>
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
Container<recursive_invoke_result_t<F, T>, N> output;
std::transform( std::begin(input),
std::end(input),
std::begin(output),
[f](auto &x){ return std::invoke(f, x); }
);
return output;
}
int main()
{
// non-nested input test, lambda function applied on input directly
int test_number = 3;
std::cout << "non-nested input test, lambda function applied on input directly: \n"
<< recursive_transform<0>(test_number, [](auto&& element) { return element + 1; }) << '\n';
// test with array container
static constexpr std::size_t D = 3;
auto test_array = std::array< double, D >{1, 2, 3};
std::cout << "test with array container: \n"
<< recursive_transform<1>(test_array, [](auto&& element) { return element + 1; })[0] << '\n';
// nested input test, lambda function applied on input directly
std::vector<int> test_vector = {
1, 2, 3
};
std::cout << recursive_transform<0>(test_vector, [](auto element)
{
element.push_back(4);
element.push_back(5);
return element;
}).size() << '\n';
// std::vector<int> -> std::vector<std::string>
auto recursive_transform_result = recursive_transform<1>(
test_vector,
[](int x)->std::string { return std::to_string(x); }
); // For testing | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "std::vector<int> -> std::vector<std::string>: " +
recursive_transform_result.at(0) << '\n'; // recursive_transform_result.at(0) is a std::string
// std::vector<string> -> std::vector<int>
std::cout << "std::vector<string> -> std::vector<int>: "
<< recursive_transform<1>(
recursive_transform_result,
[](std::string x) { return std::atoi(x.c_str()); }).at(0) + 1 << '\n'; // std::string element to int
// std::vector<std::vector<int>> -> std::vector<std::vector<std::string>>
std::vector<decltype(test_vector)> test_vector2 = {
test_vector, test_vector, test_vector
};
auto recursive_transform_result2 = recursive_transform<2>(
test_vector2,
[](int x)->std::string { return std::to_string(x); }
); // For testing
std::cout << "string: " + recursive_transform_result2.at(0).at(0) << '\n'; // recursive_transform_result.at(0).at(0) is also a std::string
// std::deque<int> -> std::deque<std::string>
std::deque<int> test_deque;
test_deque.push_back(1);
test_deque.push_back(1);
test_deque.push_back(1);
auto recursive_transform_result3 = recursive_transform<1>(
test_deque,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result3.at(0) << '\n';
// std::deque<std::deque<int>> -> std::deque<std::deque<std::string>>
std::deque<decltype(test_deque)> test_deque2;
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
test_deque2.push_back(test_deque);
auto recursive_transform_result4 = recursive_transform<2>(
test_deque2,
[](int x)->std::string { return std::to_string(x); }); // For testing | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
std::cout << "string: " + recursive_transform_result4.at(0).at(0) << '\n';
// std::list<int> -> std::list<std::string>
std::list<int> test_list = { 1, 2, 3, 4 };
auto recursive_transform_result5 = recursive_transform<1>(
test_list,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result5.front() << '\n';
// std::list<std::list<int>> -> std::list<std::list<std::string>>
std::list<std::list<int>> test_list2 = { test_list, test_list, test_list, test_list };
auto recursive_transform_result6 = recursive_transform<2>(
test_list2,
[](int x)->std::string { return std::to_string(x); }); // For testing
std::cout << "string: " + recursive_transform_result6.front().front() << '\n';
return 0;
}
The output of the test code above:
non-nested input test, lambda function applied on input directly:
4
test with array container:
2
5
std::vector<int> -> std::vector<std::string>: 1
std::vector<string> -> std::vector<int>: 2
string: 1
string: 1
string: 1
string: 1
string: 1
A Godbolt link is here.
All suggestions are welcome.
The summary information:
Which question it is a follow-up to?
A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++
What changes has been made in the code since last question?
I am trying to implement another version recursive_transform template function for dealing with various types including std::array.
Why a new review is being asked for?
If there is any possible improvement, please let me know. | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Why a new review is being asked for?
If there is any possible improvement, please let me know.
Answer: It's just getting better and better!
Use a constraint instead of static_assert()
You can trivially turn the static_assert() you have in recursive_transform() into a constraint:
template<std::size_t unwrap_level = 1, class T, class F>
requires (unwrap_level <= recursive_depth<T>())
constexpr auto recursive_transform(const T& input, const F& f)
{
…
}
The problem with the static_assert() is that it only triggers when your function has already recursed as much as possible. The error message that the compilers generate will then be quite large. By using a requires clause, the mistake is caught immediately at the outer call to recursive_transform(), resulting in a much shorter error message. The only drawback is that you cannot include a custom error message in this case. Here is the number of lines of error messages for each method at a given recursion depth:
Method @ depth
GCC 12
Clang 17
requires @ 1
22
19
requires @ 2
34
19
requires @ 3
30
19
static_assert @ 1
30
46
static_assert @ 2
114
68
static_assert @ 3
138
105
Use only one method to check if a type is a container
You currently have two ways to check if a type is a container: std::ranges::input_range and is_iterable. These are slightly different, and it's best to use only one of them, on the off-chance that there is a type which satisfies one but not the other, as I imagine this would cause some very hard to debug compiler error.
I think you can just write:
template<…>
requires std::ranges::input_range<Container<T, N>>
constexpr auto recursive_transform(const Container<T, N>& input, const F& f)
{
…
} | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Use std::ranges::transform() for std::arrays as well
For the overload that handles std::array, you can use std::ranges::transform() just like you did in the more generic overload.
Nested std::arrays are not handled
Your code does not handle std::arrays that contain other containers, including other std::arrays.
Ideally, there is only one overload of recursive_transform() that handles all container types. recursive_invoke_result_t<> should handle arrays. The only other issue is that there is no std::inserter<> that works on arrays. You can add some if constexpr code to handle that difference, or create a struct recursive_output_iterator<> to give you the right output iterator.
Call reserve() if possible
Some containers have a reserve() member function (like std::vector and std::deque), and it would help performance a lot if you called it.
What if the input is an rvalue?
Something we haven't looked at is if it makes sense to handle inputs that are rvalues. In case the function we are passing has a return type that is the same as its input, then you can just std::transform() the innermost containers in-place. If not, then there still is the possibility of moving the original values in the input into the function that is being applied. I don't think even std::ranges::transform() does that though.
Handling non-default-constructible containers
You are currently assuming that once you have determined the type of a container using recursive_invoke_result_t<>, that you can default-construct a new container. However, that might not be the case; for example, if an allocator is used that doesn't have a default constructor. | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Most STL containers have a get_allocator() member function that will return the allocater object that was used to construct it. You can pass that to the container you want to construct. Of course, that means an increase in complexity of your code. Ideally, you would create an out-of-class function that can create an empty copy of any container, so that you can write:
template<std::size_t unwrap_level = 1, class T, class F>
requires (unwrap_level <= recursive_depth<T>())
constexpr auto recursive_transform(const T& input, const F& f)
{
if constexpr (unwrap_level > 0)
{
auto output = clone_empty_container(input);
std::ranges::transform(
input,
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return std::invoke(f, input);
}
} | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
You could even consider having it handle comparator and hash objects passed to containers like std::map and std::unordered_map, call reserve() based on the size of the input, handle container adapters like std::stack() that take a container as a parameter in the constructor, and maybe even upcoming types like std::flat_set. | {
"domain": "codereview.stackexchange",
"id": 44502,
"lm_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++, recursion, template, c++20, constrained-templates",
"url": null
} |
performance, c, vectorization, portability
Title: Vectorized 16-bit addition in Standard C
Question: The idea is to add a given 16-bit number N to each element of an array of 16-bit integers of arbitrary length, taking advantage of 64-bit integer types and instructions to perform the additions 4 at a time. The function accepts an arbitrary nonzero length. As far as I can tell there is no undefined behavior, but I would like to confirm that this is in fact portable.
_Static_assert(~0==-1, "Unsupported sign representation");
#include <stdint.h>
#include <stddef.h>
typedef union Short2 {
int16_t a[2];
int32_t i;
} Short2;
typedef union Short4 {
Short2 a[2];
int64_t i;
} Short4;
void add16(int16_t *b, const int16_t a, size_t c) {
// c == 0 causes unpredictable behavior
if ((uintptr_t)b&2) { // Handle first element if unaligned; remaining elements will be 4 byte aligned
*b++ += a;
--c;
}
if (c >= 2) {
Short4 i;
const int n = a < 0; // If `a` < 0, simply concatenating 4 copies together leads to unexpected results; the positive version must be copied and concatenated instead, and the resulting 64 bit word negated
i.a[1] = i.a[0] = (Short2){.a = {a-n, a-n}};
i.i += n;
if ((uintptr_t)b&4) { // Handle next pair of elements if unaligned; remaining elements will be 8 byte aligned
(*(Short2 *)b).i += i.a[0].i;
b += 2;
c -= 2;
}
while (c >= 4) { // Handle all remaining complete batches of 4 elements
(*(Short4 *)b).i += i.i;
b += 4;
c -= 4;
}
if (c&2) { // Handle remaining pair of 2 elements if needed
(*(Short2 *)b).i += i.a[0].i;
b += 2;
}
}
if (c&1) // Handle remaining element if needed
*b += a;
} | {
"domain": "codereview.stackexchange",
"id": 44503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, vectorization, portability",
"url": null
} |
performance, c, vectorization, portability
Code to test the function (for convenience, no need to review this):
#include <stdio.h>
#include <stdlib.h>
int main(void) {
size_t s = rand()&127;
int16_t *arr = malloc(s*sizeof(int16_t));
for (int i = 0; i < s; ++i) {
printf("%d, ", arr[i] = rand());
}
putchar('\n');
add16(arr, 3, s);
for (int i = 0; i < s; ++i) {
printf("%d, ", arr[i]);
}
putchar('\n');
free(arr);
return 0;
}
Answer: You Have an XY-Problem
Let’s take a look at a very naïve loop to do this in C:
void vec_add16( int16_t *const b, const int16_t x, const size_t n ) {
for ( size_t i = 0; i < n; ++i ) {
b[i] += x;
}
}
Compiling this on Clang 15.0.0 with -std=c17 -march=x86-64-v3 -O3 (Godbolt), the inner loop becomes:
.LBB0_8: # =>This Inner Loop Header: Depth=1
vpaddw ymm1, ymm0, ymmword ptr [rdi + 2*rcx]
vpaddw ymm2, ymm0, ymmword ptr [rdi + 2*rcx + 32]
vpaddw ymm3, ymm0, ymmword ptr [rdi + 2*rcx + 64]
vpaddw ymm4, ymm0, ymmword ptr [rdi + 2*rcx + 96]
vmovdqu ymmword ptr [rdi + 2*rcx], ymm1
vmovdqu ymmword ptr [rdi + 2*rcx + 32], ymm2
vmovdqu ymmword ptr [rdi + 2*rcx + 64], ymm3
vmovdqu ymmword ptr [rdi + 2*rcx + 96], ymm4
vpaddw ymm1, ymm0, ymmword ptr [rdi + 2*rcx + 128]
vpaddw ymm2, ymm0, ymmword ptr [rdi + 2*rcx + 160]
vpaddw ymm3, ymm0, ymmword ptr [rdi + 2*rcx + 192]
vpaddw ymm4, ymm0, ymmword ptr [rdi + 2*rcx + 224]
vmovdqu ymmword ptr [rdi + 2*rcx + 128], ymm1
vmovdqu ymmword ptr [rdi + 2*rcx + 160], ymm2
vmovdqu ymmword ptr [rdi + 2*rcx + 192], ymm3
vmovdqu ymmword ptr [rdi + 2*rcx + 224], ymm4
sub rcx, -128
add r9, -2
jne .LBB0_8 | {
"domain": "codereview.stackexchange",
"id": 44503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, vectorization, portability",
"url": null
} |
performance, c, vectorization, portability
The compiler vectorizes this code and unrolls the loop sixty-four times per iteration, using the packed 128-bit vector instructions and preloading the next thirty-two elements. In other words, a modern optimizer can see what you’re doing and already optimizes the loop into better code than you would get by tricking it into using a poor-man’s SIMD on 64-bit instructions.
Fortunately, the compiler sees through that, too, mostly ignores what you told it, and optimizes your version to have a nearly-identical inner loop:
.LBB1_10: # =>This Inner Loop Header: Depth=1
vpaddq ymm1, ymm0, ymmword ptr [rdi + rcx]
vpaddq ymm2, ymm0, ymmword ptr [rdi + rcx + 32]
vpaddq ymm3, ymm0, ymmword ptr [rdi + rcx + 64]
vpaddq ymm4, ymm0, ymmword ptr [rdi + rcx + 96]
vmovdqu ymmword ptr [rdi + rcx], ymm1
vmovdqu ymmword ptr [rdi + rcx + 32], ymm2
vmovdqu ymmword ptr [rdi + rcx + 64], ymm3
vmovdqu ymmword ptr [rdi + rcx + 96], ymm4
vpaddq ymm1, ymm0, ymmword ptr [rdi + rcx + 128]
vpaddq ymm2, ymm0, ymmword ptr [rdi + rcx + 160]
vpaddq ymm3, ymm0, ymmword ptr [rdi + rcx + 192]
vpaddq ymm4, ymm0, ymmword ptr [rdi + rcx + 224]
vmovdqu ymmword ptr [rdi + rcx + 128], ymm1
vmovdqu ymmword ptr [rdi + rcx + 160], ymm2
vmovdqu ymmword ptr [rdi + rcx + 192], ymm3
vmovdqu ymmword ptr [rdi + rcx + 224], ymm4
add rcx, 256
add rbx, -2
jne .LBB1_10 | {
"domain": "codereview.stackexchange",
"id": 44503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, vectorization, portability",
"url": null
} |
performance, c, vectorization, portability
So, in the end, the hand-tuned version performs only slightly worse: the initialization is longer, but that’s just constant time.
You might get shorter, simpler code to analyze if you also tell the compiler -Os or -fno-unroll-loops.
Although the main lesson here is that this kind of trick only worked in the last century and is pessimal today, there are a few other tips, useful in general, that jump out at me.
Offsets are size_t (or Maybe ptrdiff_t), not int!
On many systems today, int is a signed 32-bit type with a maximum value of 2,147,483,647. There are some very old or embedded systems where it’s only 32,767, and one compiler in the ’90s made int 64-bit but long 32-bit (which the Standards Committee prohibited the next time it met).
Arrays can have more elements than that! Even a 32-bit system could, in theory, fit an array with INT_MAX+1 16-bit elements into memory and overflow the int, counter. This is undefined behavior! Which is bad for you because most C compilers will take that as permission to silently break your program.
If you want a signed type for this, so that the difference of pointers or indices will never wrap around, the type you want is ptrdiff_t from <stddef.h>.
I have no idea why this is such a common mistake of C programmers. It was even more of an obvious bug to use int array indices before the 32-bit era, when it would break on just a few dozen kilobytes of data. It doesn’t seem to go back to K&R, which sometimes used long (You can forgive Dennis Ritchie for not worrying about a computer having more than 2 GiB of memory back in 1973) and sometimes unsigned. Is it just because int has the shortest name?
Beware of Endian-Ness
You assume little-endian code. Since x86 won on the desktop, most other architectures that used to use big-endian order went bi-endian, but this code will most likely still break on a big-endian machine. (Or if someone tried to compile this on a VAX for laughs.)
Use Static Single Assignments Where Possible | {
"domain": "codereview.stackexchange",
"id": 44503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, vectorization, portability",
"url": null
} |
performance, c, vectorization, portability
Use Static Single Assignments Where Possible
It’s rare to want to modify a function argument, although sometimes coders get cute and write a loop that either increments the base pointer or decrements n. Generally, though, you’ll make it harder for yourself to write bugs, and easier for the optimizer, if you make most of your variables const and assign them their unchanging value as soon as they are created.
In this case, the array pointer cannot be a const int16_t*, because it overwrites the input array in place, but it can be int16_t* const because it’s never modified within the function. What’s especially important in a loop like
for ( size_t i = 0; i < n; ++i ) | {
"domain": "codereview.stackexchange",
"id": 44503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, vectorization, portability",
"url": null
} |
performance, c, vectorization, portability
is to make sure that the compiler knows nothing outside the loop will be modifying either i or n. This code accomplishes that by declaring const size_t n and declaring i within the scope of the loop. If the compiler is sure nothing can, it can perform the optimizations we saw above. If, however, either of those variables could “escape” and be used or modified while the loop is running, the compiler suddenly needs to make the loop do what you literally wrote, which is slower than what it could do if it doesn’t ever need the actual values of i or n.
Give Your Variables Better Names
You currently name them a, b, c, and so forth, apparently in the order that you added them to the code. This is a terrible way to name your variables. In my re-implementation, I kept the one-letter names, but at least used letters with somewhat conventional meanings: i for a loop index, b for a base pointer, n for an array size, and x for an input value. Your IDE will autocomplete longer variable names for you anyway, so there’s no reason to avoid them. | {
"domain": "codereview.stackexchange",
"id": 44503,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, c, vectorization, portability",
"url": null
} |
c++, concurrency, c++20, locking
Title: C++20 simple RwSeqLock
Question: I recently discovered the atomic wait/notify mechanism in C++20 and wrote this readers-writer lock in the style of Linux kernel Seqlock. Writes have to be inside a lock/unlock, while reads are optimistic. It is very fast, but I am wondering if it's wrong in some way, e.g. could it lock up beyond hypothetical timing issues (e.g. reads taking a lot longer than writes).
#include <atomic>
class RwSeqLock
{
// *** NB this can indeed lock up and is dangerous. see stackexchange replies ***
std::atomic<uint64_t> m_count = { 0 };
std::atomic<uint64_t> m_waiting = { 0 };
public:
void lock()
{
uint64_t count = m_count.load();
if (!(count & 1) && m_count.compare_exchange_weak(count, count + 1))
return;
count = m_count.load();
m_waiting.fetch_add(1);
while (1)
{
if (!(count & 1))
{
if (m_count.compare_exchange_weak(count, count + 1))
{
m_waiting.fetch_sub(1);
return;
}
}
else
{
m_count.wait(count);
count = m_count.load();
}
}
}
void unlock()
{
m_count.fetch_add(1);
if (m_waiting.load())
m_count.notify_one();
}
template<class Func>
auto read(const Func& func)
{
uint64_t count = m_count.load();
if (!(count & 1))
{
auto val = func();
if (m_count.load() == count)
return val;
} | {
"domain": "codereview.stackexchange",
"id": 44504,
"lm_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++, concurrency, c++20, locking",
"url": null
} |
c++, concurrency, c++20, locking
count = m_count.load();
m_waiting.fetch_add(1);
while (1)
{
if (!(count & 1))
{
auto val = func();
uint64_t count_after = m_count.load();
if (count_after == count)
{
m_waiting.fetch_sub(1);
return val;
}
else
count = count_after;
}
else
{
m_count.wait(count);
count = m_count.load();
}
}
}
// stats
uint64_t count() const { return m_count.load(); }
uint64_t waiting() const { return m_waiting.load(); }
};
Answer: About those hypothetical timing issues
I think you are referring to the fact that seqlocks can livelock readers. However, this is not hypothetical at all, it is a real property of seqlocks. That's why they should only be used in scenarios where writes are rare compared to reads.
Readers can steal notifications other threads are waiting on
Both readers (in read()) and writers (in lock()) can call m_count.wait(). So when you have two writers and one reader, and one writer has the lock, the second reader and writer can both be waiting. However, when the first writer unlocks, it calls m_count.notify_one(). If the reader gets this notification, the second writer will not get woken.
A similar situation is when you have one writer but two readers both waiting. Only one will get notified.
One solution is to call m_count.notify_all() in unlock(); this makes sure all threads that are waiting get notified. This might result in the thundering herd issue if you have lots of writers queued up, but that should be rare, or else you shouldn't have used seqlocks to begin with (see above).
Another solution is to have the reader check if m_waiting is not zero after calling m_waiting.fetch_sub(1), and if so, call m_count.notify() to pass it on to the next waiter. | {
"domain": "codereview.stackexchange",
"id": 44504,
"lm_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++, concurrency, c++20, locking",
"url": null
} |
rust, vectors
Title: Implementing a function that takes in 2 collections of strings and compares them as if they are unordered in Rust
Question: I'm new to Rust and I would like to implement a function to compare 2 collections of strings. The function should compare them as if they are unordered.
In Python, I would implement something like this:
from collections.abc import Iterator
def unordered_eq(a: Iterator[str], b: Iterator[str]):
a = sorted(a)
b = sorted(b)
assert a == b
I then tried implementing something similar in Rust. I'm trying to collect both iterators into new Vec<&str> instances, then sort() each of those vectors, then finally do a simple assert_eq!(a, b).
fn unordered_eq<'a, T, U>(a: T, b: U)
where
T: Iterator<Item = &'a str>,
U: Iterator<Item = &'a str>,
{
let mut a: Vec<&str> = a.collect();
let mut b: Vec<&str> = b.collect();
a.sort();
b.sort();
assert_eq!(a, b);
}
// Example usage:
struct Item { path: String };
let items: Vec<Item> = ...;
unordered_eq(
items.iter().map(|x| x.path.as_str()),
["hello", "hello2", "hello3", "hello4", "world"].iter().copied(),
)
Is this the correct / idiomatic way to implement this in Rust? How can I improve it?
Answer: I'd make three suggestions.
Since the function asserts, name is assert_unordered_eq, right now its surprising given the name that it asserts rather than returns a boolean.
It's typical when taking an iterator as an argument to take IntoIterator instead of Iterator. You call into_iter() on the IntoIterator to get an Iterator and then proceed as normal. The advantage is that your function can then take not only Iterators (which implement IntoIterator in a trivial manner) but also other items like Vec and slices.
Since your function is already generic over the lifetimes of the str, I'd take it a step further and making it generic over any type that supports Ord and Debug | {
"domain": "codereview.stackexchange",
"id": 44505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, vectors",
"url": null
} |
rust, vectors
Here's a sample implementation:
fn assert_unordered_eq<X: Ord + std::fmt::Debug, T, U>(a: T, b: U)
where
T: IntoIterator<Item = X>,
U: IntoIterator<Item = X>,
{
let mut a: Vec<_> = a.into_iter().collect();
let mut b: Vec<_> = b.into_iter().collect();
a.sort();
b.sort();
assert_eq!(a, b);
}
Taking it a step further, for an assert function like this, I'd look at having it do some sort of diff between the two collections and tell me explicitly what's missing/added to make diagnosing test failures (where I assume you'd use this function) easier. | {
"domain": "codereview.stackexchange",
"id": 44505,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust, vectors",
"url": null
} |
python, pygame
Title: pygame bullet spawner
Question: I am currently making a game for myself and i have a lot of code in a function which does almost the exact same thing with some minor differences. I was wondering if there is an way to optimize this
code and still get the same output.
import pygame, os, random
def draw_game():
player = pygame.Rect(450, 350, HOOFD_HEIGHT, HOOFD_WIDTH)
BULLETS_L = []
BULLETS_R = []
BULLETS_UP = [] | {
"domain": "codereview.stackexchange",
"id": 44506,
"lm_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, pygame",
"url": null
} |
python, pygame
BULLETS_L = []
BULLETS_R = []
BULLETS_UP = []
HITPOINTS = 4
B_SPAWN = random.uniform(1000, 6000)# a random number between 1000 and 6000
E1 = pygame.USEREVENT + 3 #an custom event
pygame.time.set_timer(E1, 1 * int(B_SPAWN))# this activates the event after 1 to 6 seconds
B_SPAWN = random.uniform(1000, 6000)
E2 = pygame.USEREVENT + 4
pygame.time.set_timer(E2, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E3 = pygame.USEREVENT + 5
pygame.time.set_timer(E3, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E4 = pygame.USEREVENT + 6
pygame.time.set_timer(E4, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E5 = pygame.USEREVENT + 7
pygame.time.set_timer(E5, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E6 = pygame.USEREVENT + 8
pygame.time.set_timer(E6, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E7 = pygame.USEREVENT + 9
pygame.time.set_timer(E7, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E8 = pygame.USEREVENT + 10
pygame.time.set_timer(E8, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E9 = pygame.USEREVENT + 11
pygame.time.set_timer(E9, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E10 = pygame.USEREVENT + 12
pygame.time.set_timer(E10, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E11 = pygame.USEREVENT + 13
pygame.time.set_timer(E11, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E12 = pygame.USEREVENT + 14
pygame.time.set_timer(E12, 1 * int(B_SPAWN))
B_SPAWN = random.uniform(1000, 6000)
E13 = pygame.USEREVENT + 15
pygame.time.set_timer(E13, 1 * int(B_SPAWN))
clock = pygame.time.Clock()
run = True
while run == True:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit() | {
"domain": "codereview.stackexchange",
"id": 44506,
"lm_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, pygame",
"url": null
} |
python, pygame
if event.type == E1:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E1, 1 * int(B_SPAWN))
bullet = pygame.Rect(0, 280, BULLET_WIDTH, BULLET_HEIGHT)
BULLETS_L.append(bullet)
if event.type == E2:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E2, 1 * int(B_SPAWN))
bullet = pygame.Rect(0, 70, BULLET_WIDTH, BULLET_HEIGHT)
BULLETS_L.append(bullet)
if event.type == E3:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E3, 1 * int(B_SPAWN))
bullet = pygame.Rect(0, 620, BULLET_WIDTH, BULLET_HEIGHT)
BULLETS_L.append(bullet)
if event.type == E4:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E4, 1 * int(B_SPAWN))
bullet = pygame.Rect(0, 430, BULLET_WIDTH, BULLET_HEIGHT)
BULLETS_L.append(bullet)
if event.type == E5:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E5, 1 * int(B_SPAWN))
bullet = pygame.Rect(WIDTH, 350, BULLET_WIDTH, BULLET_HEIGHT)
BULLETS_R.append(bullet)
if event.type == E6:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E6, 1 * int(B_SPAWN))
bullet = pygame.Rect(WIDTH, 175, BULLET_WIDTH, BULLET_HEIGHT)
BULLETS_R.append(bullet)
if event.type == E7:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E7, 1 * int(B_SPAWN))
bullet = pygame.Rect(WIDTH, 525, BULLET_WIDTH, BULLET_HEIGHT)
BULLETS_R.append(bullet) | {
"domain": "codereview.stackexchange",
"id": 44506,
"lm_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, pygame",
"url": null
} |
python, pygame
if event.type == E8:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E8, 1 * int(B_SPAWN))
bullet = pygame.Rect(350, HEIGHT, BULLET_HEIGHT, BULLET_WIDTH)
BULLETS_UP.append(bullet)
if event.type == E9:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E9, 1 * int(B_SPAWN))
bullet = pygame.Rect(550, HEIGHT, BULLET_HEIGHT, BULLET_WIDTH)
BULLETS_UP.append(bullet)
if event.type == E10:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E10, 1 * int(B_SPAWN))
bullet = pygame.Rect(750, HEIGHT, BULLET_HEIGHT, BULLET_WIDTH)
BULLETS_UP.append(bullet)
if event.type == E11:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E11, 1 * int(B_SPAWN))
bullet = pygame.Rect(50, HEIGHT, BULLET_HEIGHT, BULLET_WIDTH)
BULLETS_UP.append(bullet)
if event.type == E12:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E12, 1 * int(B_SPAWN))
bullet = pygame.Rect(235, HEIGHT, BULLET_HEIGHT, BULLET_WIDTH)
BULLETS_UP.append(bullet)
if event.type == E13:
B_SPAWN = random.uniform(1000, 6000)
pygame.time.set_timer(E13, 1 * int(B_SPAWN))
bullet = pygame.Rect(1050, HEIGHT, BULLET_HEIGHT, BULLET_WIDTH)
BULLETS_UP.append(bullet)
if event.type == PLAYER_HIT:
HITPOINTS -= 1
BULLET_HIT_SOUND.play()
keys_pressed = pygame.key.get_pressed()
movement(keys_pressed, player) | {
"domain": "codereview.stackexchange",
"id": 44506,
"lm_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, pygame",
"url": null
} |
python, pygame
handle_bullets_R(BULLETS_R, player)
handle_bullets_L(BULLETS_L, player)
handle_bullets_up(BULLETS_UP, player)
draw_window(player, BULLETS_L, HITPOINTS, BULLETS_R, BULLETS_UP)
DEAD_TXT = ""
if HITPOINTS <= 0:
DEAD_TXT = "GAME OVER"
if DEAD_TXT != "":
end_text(DEAD_TXT)
run = False
if run == False:
draw_menu()
as seen above, there is alot of code pieces which could probably be optimized way better.
thanks in advance
Answer:
a lot of code ... which does almost the exact same thing
I am glad that you recognize this and wish to learn how to
DRY
it up.
There is a separate structural difficulty in this code
that we should address.
The function draw_game is entirely too long,
and should be broken up via Extract Helper.
We strive to write functions that can be visually
taken in all at once, with no scrolling,
as an aid to human comprehension.
Usually that means if we've gone on for more than
about fifty lines of source, it's time to break
it into smaller chunks that focus on doing just
one thing.
I'm not sure, but I think that possibly you have
a player which is HOOFD_HEIGHT tall that might be a horse?
Or some other hoofed animal?
In which case, prefer to spell it out: HOOFED_HEIGHT.
Or perhaps keep both dimensions together in a single tuple:
HOOFED_SIZE = (123, 456) # the original posting doesn't specify
player = pygame.Rect(450, 350, *HOOFED_SIZE)
That starred expression
will supply both numbers to the .Rect method.
BTW, kudos on naming these MANIFEST_CONSTANTS according to the
usual convention.
BULLETS_L = []
BULLETS_R = []
BULLETS_UP = [] | {
"domain": "codereview.stackexchange",
"id": 44506,
"lm_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, pygame",
"url": null
} |
python, pygame
BULLETS_L = []
BULLETS_R = []
BULLETS_UP = []
You mentioned you'd like to coalesce some things.
I haven't even see how these are used yet,
but the naming is suggestive.
We might combine the first two, or perhaps all three,
in a single datastructure that has a velocity
associated with it.
For example, "left" velocities might look like -1,
and "right" might correspondingly be 1.
We probably want lowercase names like bullets_l here,
as these don't seem to be constants.
Similarly for hitpoints.
HITPOINTS = 4
This is a magic number.
We could define INITIAL_HEALTH or INITIAL_HP somewhere.
But it would probably be more convenient to push the
magic number into the signature, as a value that
typically we just let default:
def draw_game(hitpoints=4):
One advantage of that practice is it lets
unit tests
conveniently alter the value according to their need.
B_SPAWN = random.uniform(1000, 6000)
E1 = pygame.USEREVENT + 3
pygame.time.set_timer(E1, 1 * int(B_SPAWN))
Push this repeated code down into a helper:
from enum import Enum
def spawn(event_type: EventType):
b_spawn = random.uniform(1000, 6000)
event = pygame.USEREVENT + event_type
pygame.time.set_timer(event, 1 * int(b_spawn))
return event
...
def draw_game...
...
e1 = spawn(EventType.BULLET)
e2 = spawn(EventType.MISSLE)
...
class EventType(Enum):
BULLET = 3
MISSLE = 4
...
If "b" denotes "bullet", please spell it out,
or at a minimum offer a # comment.
The source code is unclear, so I'm just guessing here.
An enum
is a classic way to create objects whose value is arbitrary
and they merely need to be distinct from one another.
That is, enums are one way of coping with magic numbers
and giving them meaningful names.
run = True | {
"domain": "codereview.stackexchange",
"id": 44506,
"lm_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, pygame",
"url": null
} |
python, pygame
run = True
This sounds like a verb, to me, and therefore a terrific
name for a def run(): function.
Variables OTOH often want noun identifiers,
and here an adjective would make sense,
perhaps running or active.
A common loop idiom is to define done = False
and then keep going while not done:
for event in pygame.event.get():
Break out a helper:
def dispatch(event):
...
Then the for loop mostly becomes a single helper call
and we can bury the complexity one level down.
if event.type == E1:
There's a lot of copy-n-paste going on here.
Rule of thumb: if you notice you keep leaning on the CMD-V paste key,
it's time to start think about parameters instead.
Using a bunch of ifs is not terrible, exactly;
feel free to keep that structure during initial
refactor.
But a dict that maps from event type to
its relevant parameters can be an excellent
way to implement such dispatch.
You can even put function objects into the map.
DEAD_TXT = ""
if HITPOINTS <= 0:
DEAD_TXT = "GAME OVER"
if DEAD_TXT != "":
end_text(DEAD_TXT)
run = False
if run == False:
draw_menu()
Prefer to deal with it all at once in a single if clause:
if HITPOINTS <= 0:
end_text("GAME OVER")
run = False
draw_menu()
Notice that the menu draw happens unconditionally when
we fall off the bottom of the loop.
You had a check which was redundant with the check
at top of loop.
Making the whole while loop fit in a single screenful
would have made that more obvious.
Overall?
Naming could be improved; that will come with practice.
Break up giant functions that don't fit within a screenful,
using Extract Helper. | {
"domain": "codereview.stackexchange",
"id": 44506,
"lm_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, pygame",
"url": null
} |
c++, c++11, multithreading
Title: Safely starting and stopping a thread owned by a class
Question: If I have a class running its own thread, I almost always try to write it like the following, with the thread started by the constructor. The reason for this is that an object can never be constructed on multiple threads, so there is never a danger of two threads trying to start the thread. This class prints a message every second until asked to stop, for example:
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>
#include <chrono>
#include <string>
class a_thread
{
public:
explicit a_thread(const std::string& msg)
: _msg(msg)
, _stop(false)
, _t(&a_thread::thread_main, this)
{
}
~a_thread()
{
stop();
}
void stop()
{
std::unique_lock<std::mutex> l(_m);
if (!_stop)
{
_stop = true;
l.unlock();
_cv.notify_all();
if (_t.joinable())
_t.join();
}
}
private:
// Disable copying (and moving)
a_thread(const a_thread&) = delete;
a_thread& operator=(const a_thread&) = delete;
void thread_main()
{
using namespace std::chrono;
auto next_print_time = steady_clock::now();
std::unique_lock<std::mutex> l(_m);
while (!_stop)
{
const auto now = steady_clock::now();
if (now >= next_print_time)
{
std::cout << _msg << '\n';
next_print_time = now + seconds(1);
}
else
{
_cv.wait_until(l, next_print_time);
}
}
}
std::string _msg;
bool _stop;
std::mutex _m;
std::condition_variable _cv;
std::thread _t;
}; | {
"domain": "codereview.stackexchange",
"id": 44507,
"lm_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, multithreading",
"url": null
} |
c++, c++11, multithreading
However, sometimes it is desirable to defer the starting of the thread, which I implement like so:
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>
#include <chrono>
#include <string>
class b_thread
{
public:
explicit b_thread(const std::string& msg)
: _msg(msg)
, _stop(true)
{
}
~b_thread()
{
stop();
}
void start()
{
std::unique_lock<std::mutex> l(_m);
if (_stop)
{
_stop = false;
l.unlock();
_t = std::thread(&b_thread::thread_main, this);
}
}
void stop()
{
std::unique_lock<std::mutex> l(_m);
if (!_stop)
{
_stop = true;
l.unlock();
_cv.notify_all();
if (_t.joinable())
_t.join();
}
}
private:
// Disable copying (and moving)
b_thread(const b_thread&) = delete;
b_thread& operator=(const b_thread&) = delete;
void thread_main()
{
using namespace std::chrono;
auto next_print_time = steady_clock::now();
std::unique_lock<std::mutex> l(_m);
while (!_stop)
{
const auto now = steady_clock::now();
if (now >= next_print_time)
{
std::cout << _msg << '\n';
next_print_time = now + seconds(1);
}
else
{
_cv.wait_until(l, next_print_time);
}
}
}
std::string _msg;
bool _stop;
std::mutex _m;
std::condition_variable _cv;
std::thread _t;
}; | {
"domain": "codereview.stackexchange",
"id": 44507,
"lm_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, multithreading",
"url": null
} |
c++, c++11, multithreading
Until today, I was confident that this code was thread-safe, in the sense that the stop() and start() functions could be safely called from multiple threads on the same instance of the class. However, I think the following code could result in a thread being destroyed without first being joined:
int main()
{
b_thread b("Hello world!");
// Let the main thread be called 'Z'
auto x = std::thread([&b] () { b.start(); }); // Thread X
auto y = std::thread([&b] () { b.stop(); }); // Thread Y
b.start();
x.join();
y.join();
}
If the timing is right then I believe the program could run as follows:
Thread X has assigned to _t, but _t has not yet acquired the mutex in thread_main(). _stop == false at the time X released mutex _m.
Thread Y saw _stop == false after acquiring the mutex and therefore it sets _stop = true before releasing the mutex. It is now calling _cv.notify_all().
Thread Z is able to acquire the mutex in this state, and sees _stop == true. It assigns to _t, and therefore destroys the thread constructed by X (which hasn't been join()ed yet). Badness ensues.
I also often use an atomic bool when my thread loop has a non-interruptible wait in it (for example, a loop calling poll()), like so. I believe it exhibits the same bug:
void start()
{
if (_stop.exchange(false))
_t = std::thread(&b_thread::thread_main, this);
}
void stop()
{
if (!_stop.exchange(true) && _t.joinable())
_t.join();
}
I'd appreciate thoughts on the following:
The a_thread class. This is a pattern I use a lot so I'd like to know if it could be improved.
Am I correct about the bug in b_thread?
If so, is there a way to make b_thread safe? What about with the atomic bool variant? | {
"domain": "codereview.stackexchange",
"id": 44507,
"lm_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, multithreading",
"url": null
} |
c++, c++11, multithreading
Answer: Don't let multiple threads access a std::thread object
Operations on a std::thread object are not thread-safe themselves. If you want to do this, you must hold a mutex such that only one thread can ever have access to it. You do have a mutex, but you unlock it before calling _t.join() and _t = std::thread(…), which in turn can cause undefined behavior.
Of course, not unlocking the mutex inside stop() is problematic, because keeping _m locked while calling _t.join() will cause a deadlock, as main_thread() is also holding the lock when it's not inside the call to wait_until(). To solve this issue, you could consider using two mutexes; one for the public API so only one operation can run at a time, and another one to modify _stop. The latter one you can unlock before calling _t.join().
Even if you have ensured access to _t is properly guarded at all times, I would still not recommend allowing multiple threads access to your a_thread and b_thread classes. The reason is that you will certainly get undeterministic behavior. If one thread calls start() and the other stop(), what will the end result be? A running thread_main() or nothing? In an actual program, this will almost certainly cause a problem.
Consider using std::jthread
You are not the only one that needs a thread object that properly cleans up after itself and that allows you to request the thread to stop itself. C++20 introduced std::jthread for this reason. Consider using that instead if possible. The semantics are a bit different though, and while it has the concept of a "stop token" that allows the thread to check whether it needs to stop, it doesn't provide a way to do timed waits on it like with a condition variable. If you want that, you have to provide your own mutex and condition variable. | {
"domain": "codereview.stackexchange",
"id": 44507,
"lm_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, multithreading",
"url": null
} |
c++, c++11, multithreading
If you cannot use C++20 yet, then consider whether reimplementing std::jthread instead of your a_thread and b_thread classes. That way, once you can use C++20, it is trivial to switch from your own class to a standard one.
Using an atomic flag
A std::atomic<bool> or std::atomic_flag only ensures atomic access to that boolean value. If you do:
void start()
{
if (_stop.exchange(false))
_t = std::thread(&b_thread::thread_main, this);
} | {
"domain": "codereview.stackexchange",
"id": 44507,
"lm_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, multithreading",
"url": null
} |
c++, c++11, multithreading
Then by the time it tries to assign something to _t, other threads might have accessed _stop atomically as well. You might think: but surely, if I just set _stop to false, then no other thread calling start() will be able to get true from the call to exchange()? But that is only true if no thread is calling stop().
So, you still need a proper mutex to ensure only one thread can call start() or stop() at any given time. But you can use an atomic flag to signal a running thread to stop, avoiding the need for the thread to hold any mutex.
Note that since C++20, the atomic types have wait() and notify_all() member functions, so you can still wait, but you don't need a mutex and condition variable. | {
"domain": "codereview.stackexchange",
"id": 44507,
"lm_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, multithreading",
"url": null
} |
c, strings, parsing, portability, duplicate-code
Title: Basic recursive descent parser in C | {
"domain": "codereview.stackexchange",
"id": 44508,
"lm_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, strings, parsing, portability, duplicate-code",
"url": null
} |
c, strings, parsing, portability, duplicate-code
Question: The purpose of this code is to evaluate simple integer expressions that make use of the C arithmetic and bitwise operators while respecting C operator precedence and parenthesis. I wrote this code with portability in mind, making no use of implementation defined, or undefined constructs to my knowledge. However there are a lot of duplicate patterns here, and if someone could provide some insight as to how to rewrite the code more compactly, and confirm that my code is in fact portable standard C, that would be great.
The code works by dividing the expression into groups separated by the lowest precedence operator, and then dividing those groups into groups separated by the second lowest precedence operator, and so on.
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <setjmp.h>
static jmp_buf jmp;
static unsigned long p6(const char **);
static unsigned long p0(const char **const str) {
if (isdigit(**str)) return strtoul(*str, (char **)str, 0);
else switch (*(*str)++) {
case '+':
return +p0(str);
case '-':
return -p0(str);
case '~':
return ~p0(str);
case '(': {
const unsigned long r = p6(str);
if (*(*str)++ == ')') return r;
}
}
longjmp(jmp, errno = EINVAL);
}
static unsigned long p1(const char **const str) {
unsigned long r = p0(str);
for (;;) {
switch (**str) {
case '*':
++*str;
r *= p0(str);
continue;
case '/':
++*str;
r /= p0(str);
continue;
case '%':
++*str;
r %= p0(str);
continue;
}
return r;
}
}
static unsigned long p2(const char **const str) {
unsigned long r = p1(str);
for (;;) {
switch (**str) {
case '+':
++*str;
r += p1(str); | {
"domain": "codereview.stackexchange",
"id": 44508,
"lm_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, strings, parsing, portability, duplicate-code",
"url": null
} |
c, strings, parsing, portability, duplicate-code
switch (**str) {
case '+':
++*str;
r += p1(str);
continue;
case '-':
++*str;
r -= p1(str);
continue;
}
return r;
}
}
static unsigned long p3(const char **const str) {
unsigned long r = p2(str);
for (;;) {
switch (**str) {
case '<':
++*str;
r <<= p2(str);
continue;
case '>':
++*str;
r >>= p2(str);
continue;
}
return r;
}
}
static unsigned long p4(const char **const str) {
unsigned long r = p3(str);
for (; **str == '&'; r &= p3(str)) ++*str;
return r;
}
static unsigned long p5(const char **const str) {
unsigned long r = p4(str);
for (; **str == '^'; r ^= p4(str)) ++*str;
return r;
}
static unsigned long p6(const char **const str) {
unsigned long r = p5(str);
for (; **str == '|'; r |= p5(str)) ++*str;
return r;
}
unsigned long parse(const char **const str) {
return setjmp(jmp) ? 0 : p6(str);
}
#include <stdio.h>
int main(const int argc, const char **argv) {
while (*++argv) {
const unsigned long r = parse(&(const char *){*argv});
if (errno) {
perror(*argv);
errno = 0;
continue;
}
if (printf("%lu\n", r) < 0)
return errno;
}
return 0;
} | {
"domain": "codereview.stackexchange",
"id": 44508,
"lm_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, strings, parsing, portability, duplicate-code",
"url": null
} |
c, strings, parsing, portability, duplicate-code
Answer: Portable?
"I wrote this code with portability in mind," --> Standard C lacks EINVAL.
longjmp(jmp, errno = EINVAL);
Negative char
isdigit(**str) is UB when **str < 0 and not EOF. Best to only pass unsigned char values to is...().
Pedantic: Code assumes argc > 0
If argc == 0, ++argv is a problem.
(Recall portability) Rather than seek the null pointer at the end of the argv[] list, consider indexing.
// int main(const int argc, const char **argv) {
// while (*++argv) {
// const unsigned long r = parse(&(const char *){*argv});
int main(const int argc, const char **argv) {
for (int i = 1; i < argc; i++) {
const unsigned long r = parse(&(const char *){argv[i]});
No white-space
I'd expect such parsers to be white-space friendly and not stop due to some ' '. I see how this may over complicate code for this initial effort.
<, > for shifting?
Consider << for shift and < for compare.
Vertical spacing
Some vertical space would improve code readability.
Non-standard main() signature
Drop the const.
Some compilers may whine. Note: "The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program," C17dr § 5.1.2.2.1 2.
// int main(const int argc, const char **argv) {
int main(int argc, char **argv) {
Minor: Unneeded else
// if (isdigit(**str)) return strtoul(*str, (char **)str, 0);
// else switch (*(*str)++) {
if (isdigit(**str)) return strtoul(*str, (char **)str, 0);
switch (*(*str)++) {
right-to-left Bug?
Evaluation of unary plus/minus and logical bitwise complement looks left-to-right. I'd expect right-to-left.
Subtle good code
Code uses parse(&(const char *){*argv}) rather than parse(argv). parse(argv) may modify *argv and that is potential UB.
Minor: errno = 0
Best set just before the parse() call.
With code as is, makes no difference, yet from a template POV, better to see example code setting errno = 0 explicitly.
errno = 0; // Add
const unsigned long r = parse(&(const char *){*argv}); | {
"domain": "codereview.stackexchange",
"id": 44508,
"lm_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, strings, parsing, portability, duplicate-code",
"url": null
} |
c, strings, parsing, portability, duplicate-code
printf() and errno
Unclear why code returns errno. printf() is not specified to set errno under any condition.
Consider:
if (printf("%lu\n", r) < 0)
// return errno;
return EXIT_FAILURE; | {
"domain": "codereview.stackexchange",
"id": 44508,
"lm_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, strings, parsing, portability, duplicate-code",
"url": null
} |
rust
Title: RUST-based weather logger. Makes HTTP request to get a JSON and write to .csv
Question: I've recently attempted to get into rust. I thought I would try convert my weather logging app from python to rust to maybe save some CPU cycles on my little Raspberry Pi.
I have a little ESP8266 with a web server that allows you to pull data from it, it returns a JSON:
{
"Readings": {
"temperature": 23.62999916,
"humidity": 55.01464844,
"pressure": 1025.828003
}
}
Now, I spent the best part of a few hours going from never having used rust before, to getting this program working and I feel like it is... not good. I'm still confused how to get error propagation working correctly. I feel as though my solution is not the standard way this would be done!
Any input is welcome, here is my code:
use serde::{Serialize, Deserialize};
use chrono::{DateTime, Utc};
use std::fs::OpenOptions;
use std::io::{Write, Result};
use std::path::Path;
use reqwest;
// Struct to hold the readings from the ESP8266
#[derive(Serialize, Deserialize, Debug)]
struct Readings {
temperature: f32,
humidity: f32,
pressure: f32,
}
// Makes a request to the ESP8266 and returns the readings
async fn make_request() -> std::result::Result<Readings, reqwest::Error> {
let response = reqwest::Client::new()
.get("http://192.168.0.190/json")
.send()
.await?;
let json_str = response.text().await?;
let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();
let reading: Readings = serde_json::from_value(json["Readings"].clone()).unwrap();
Ok(reading)
}
// Writes the data obtained from the make_request() function to a CSV file
fn write_to_csv(data: &Readings) -> Result<()> {
let path = Path::new("data/weather.csv");
// Check if file exists, if not create it and add headers
let mut file = OpenOptions::new()
.write(true)
.create(true)
.append(true)
.open(path)?; | {
"domain": "codereview.stackexchange",
"id": 44509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
if file.metadata()?.len() == 0 {
writeln!(file, "timestamp,temperature,humidity,pressure")?;
}
// Get the current UTC time
let timestamp: DateTime<Utc> = Utc::now();
// Write the data with timestamp to the CSV file
writeln!(file, "{},{},{},{}", timestamp, data.temperature, data.humidity, data.pressure)?;
Ok(())
}
#[tokio::main]
async fn main(){
// Make the request and write the data to the CSV file
let reading = make_request().await.unwrap();
_ = write_to_csv(&reading);
}
Answer: The first thing is error propagation. What you want is an error type that can handle multiple possible errors. The simplest way to get one is to use a crate that provides it. I like color-eyre because it gives me colored stack traces to help track error. Another crate anyhow is popular as well.
To use color_eyre, I add the following use statement:
use color_eyre::Result;
Now, I'd define my functions to return this Result like so:
async fn make_request() -> Result<Readings> {
Inside, make_request() the ? operator will automatically convert most any error into a color_eyre::Report. This means that I can use it both for errors from reqwest and serde_json even though they produce different error types.
For the main function, I do something like this:
#[tokio::main]
async fn main() -> Result<()> {
color_eyre::install()?;
// Make the request and write the data to the CSV file
let reading = make_request().await?;
write_to_csv(&reading)?;
Ok(())
}
Notice that I return the Result type. This will automatically do the right thing of return an error status and outputting a stack trace to stderr.
When you parse the object, you do in two stages, first to a json object, then you parse out the inner object.
let json: serde_json::Value = serde_json::from_str(&json_str)?;
let reading: Readings = serde_json::from_value(json["Readings"].clone())?; | {
"domain": "codereview.stackexchange",
"id": 44509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
rust
It's ok, but not fantastic. I'd define a struct to represent the whole response:
#[derive(Deserialize)]
struct ApiResponse {
readings: Readings
}
let json: ApiResponse = serde_json::from_str(&json_str)?;
Ok(json.readings)
Notice that you can define a struct inside a function. In this case it makes sense because the only reason to aid in parsing the response. This will work a bit better in terms of better errors (it won't panic in trying to read a non-existent json item and performance (it'll parse directly into the struct instead of a json object first. | {
"domain": "codereview.stackexchange",
"id": 44509,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "rust",
"url": null
} |
programming-challenge, haskell
Title: Count islands in a binary grid
Question: This is the No of Island code challenge.
Please review my implementation in Haskell. I know there must be some better way of doing this.
Given an m x n 2D binary grid grid which represents a map of '1's
(land) and '0's (water), return the number of islands.
An island is surrounded by water and is formed by connecting adjacent
lands horizontally or vertically. You may assume all four edges of the
grid are all surrounded by water.
Input:
1 1 1 1 0
1 1 0 1 0
1 1 0 0 0
0 0 0 0 0
Output:
1
Solution:
-- leetcode number of island
import qualified Data.Vector as V
import Data.Maybe
{--
1 1 1 1 0
1 1 0 1 0
1 1 0 0 0
0 0 0 0 0
--}
data Visited = N | O deriving (Eq, Show)
data Cell = Cell Int Int Visited deriving (Show)
-- Function to compare the cells
instance Eq Cell where
(==) (Cell r0 c0 _) (Cell r1 c1 _) = r0 == r1 && c0 == c1
-- main function takes the Vector Vector Int
islands :: V.Vector (V.Vector Int) -> [Cell]
islands v = islandhelper1 (0,0) []
where
-- fetch the row
islandhelper1 :: (Int, Int) -> [Cell] -> [Cell]
islandhelper1 b@(r, c) cell = case v V.!? r of
Just x -> islandhelper2 x b cell
_ -> cell
-- fetch the cell and then call neighbors on it
islandhelper2 :: V.Vector Int -> (Int, Int) -> [Cell] -> [Cell]
islandhelper2 rw (r, c) cells = case rw V.!? c of
Just 1 -> islandhelper2 rw (r, c + 1) (getNeighbors v (r,c) cells)
Just 0 -> islandhelper2 rw (r, c+ 1) cells
_ -> islandhelper1 (r + 1, 0) cells | {
"domain": "codereview.stackexchange",
"id": 44510,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, haskell",
"url": null
} |
programming-challenge, haskell
-- fetch the neighbors
-- add initial cell and neighboring cells
getNeighbors:: V.Vector (V.Vector Int) -> (Int, Int) -> [Cell] -> [Cell]
getNeighbors v (r, c) clls = initcl ++ getnbs4
where
getnbs4:: [Cell]
getnbs4 = catMaybes $ map clfilter [(0,1),(1, 0),(0, -1),(-1, 0)]
clfilter:: (Int, Int) -> Maybe Cell
clfilter (r', c') = let m = r' + r
n = c' + c
in case getCellValue v (m, n) of
Just (1, cl@(Cell m' n' _)) -> if cl `elem` clls then Nothing else Just (Cell m' n' O)
_ -> Nothing
initcl :: [Cell]
initcl = case getCellValue v (r,c) of
Just (1, cl@(Cell m' n' _)) -> if cl `elem` clls then clls else ((Cell m' n' N) : clls)
_ -> clls
-- get the cell value
getCellValue::V.Vector (V.Vector Int) -> (Int, Int) -> Maybe (Int, Cell)
getCellValue v (r, c) = case v V.!? r of
Just x -> case x V.!? c of
Just m -> Just (m, Cell r c O)
_ -> Nothing
_ -> Nothing
-- to Filter the cell based on N
isNew :: Cell -> Bool
isNew (Cell _ _ k) = k == N
-- Converts list to vector
ltoV :: [a] -> V.Vector a
ltoV = V.fromList
-- converts the String to Int vector
conV :: String -> V.Vector Int
conV = ltoV . map (read::String -> Int) . words
main::IO()
main = do
content <- ltoV . ( map conV) . lines <$> readFile "noofisland.txt"
print $ length . filter isNew $ islands content
Answer: Edit: all of the below was premature.
The basic algorithm you're using doesn't work. Try this test case:
0 0 0 0 0 0
0 1 1 1 1 0
0 0 0 0 1 0
0 1 0 0 1 0
0 1 1 1 1 0
0 0 0 0 0 0
The usual comments of Code Review apply: Use a linter. Name things clearly. (You've got at least one test case, so that's good!)
Some Haskell-specific code-smell stuff also applies: | {
"domain": "codereview.stackexchange",
"id": 44510,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, haskell",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.