text stringlengths 1 2.12k | source dict |
|---|---|
c, linked-list
Title: Doubly linked list optimally defined over 17 operations in C [4]?
Question: Previous versions of this question
First Version
Second Version
Third Version
Fourth Version
Changes
I built upon the previous singly linked list and implemented a doubly linked one.
You are not allowed to insert_sll at the front or back, but only in position i such that 0 < i < n=size-1.
Thanks in advance for any improvement ideas!
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* prev;
struct Node* next;
} Node;
Node* head = NULL;
Node* tail = NULL;
int size = 0;
Node* create_node(int elm) {
Node* node = malloc(sizeof * node), * exits = NULL;
if (!node) return exits;
node->data = elm;
node->prev = NULL;
node->next = NULL;
size += 1;
return node;
}
Node* get_tail() {
return tail;
}
int is_empty_sll() {
return head == NULL;
}
int size_sll() {
return size;
}
Node* node_k_sll(int k) { // 0-based index
int n = size_sll() - 1;
if (!is_empty_sll() && (k >= 0 && k <= n)) {
int i = 0;
Node* node = head;
while (i != k) {
i += 1;
node = node->next;
}
return node;
}
else {
printf("Invalid k or List is Empty");
Node* node = NULL;
return node;
}
}
void append_sll(int elm) { //O(1)
Node* cur = create_node(elm);
if (!head) {
head = cur;
}
else {
tail->next = cur;
cur->prev = tail;
}
tail = cur;
}
void prepend_sll(int elm) {
Node* updated_head = create_node(elm);
if (!head) {
head = updated_head;
tail = head;
}
else {
updated_head->next = head;
head->prev = updated_head;
head = updated_head;
}
} | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
void insert_sll(int elm, int i) {
if (!is_empty_sll()) {
int k = 1, n = size_sll(); // we don't prepend, so K > 0
if (i > 0 && i < n) { // 1 < i < n | 1:prepend, n:append
Node* cur = create_node(elm);
Node* last = head;
while (k != i) {
k += 1;
last = last->next;
}
cur->next = last->next;
(last->next)->prev = cur;
cur->prev = last;
last->next = cur;
}
else printf("Invalid i");
}
else printf("List Is Empty");
}
int delete_sll(int elm) {
int n = size_sll(), found = 0;
Node* node = head;
if (head->data == elm) {
head = head->next;
head->prev = NULL;
found = 1;
free(node);
}
else {
Node* prev = head;
for (int i = 0; i < n; i++) {
if (node->data != elm) {
prev = node; // if comment this, uncomment below
node = node->next;
}
else {
found = 1;
break;
}
}
/*(node->prev)->next = node->next;
(node->next)->prev = node->prev;*/
prev->next = node->next;
if (node->data != tail->data)
(node->next)->prev = prev;
else
tail = prev;
free(node);
}
if (found) {
size -= 1;
return 1;
}
else
return -1;
}
int find_sll(int elm) {// returns -1 if element not found
int found = 0;
if (!is_empty_sll()) {
int i, n = size_sll();
Node* last = head;
for (i = 0; i < n; i++) {
if (last->data != elm) {
last = last->next;
}
else {
found = 1;
break;
}
}
if (found) return i;
else return -1;
}
else return -1;
} | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
void swap_sll(int i, int j) {// swap value of position i with j
Node* node_i = node_k_sll(i);
Node* node_j = node_k_sll(j);
int temp = node_i->data;
node_i->data = node_j->data;
node_j->data = temp;
}
void print_sll(char p) {
if (p == 'f') {
Node* trav = head;
while (trav) {
printf("%d ", trav->data);
trav = trav->next;
}
}
else {
Node* trav = tail;
while (trav) {
printf("%d ", trav->data);
trav = trav->prev;
}
}
printf("\n");
}
void reverse_sll() {
if (!is_empty_sll()) {
Node* node = head, *temp, *prev;
while (node) {
prev = node;
node = node->next;
temp = prev->next;
prev->next = prev->prev;
prev->prev = temp;
}
temp = head;
head = tail;
tail = temp;
}
}
void clear_sll() { //O(n)
while (head) {
Node* temp = head;
head = head->next;
free(temp);
size -= 1;
}
printf("List Cleared!\n");
}
void rotate_sll(int k, char p) {
if (!is_empty_sll() && (k < size && size > 1)) {
int size = size_sll();
Node* k_node = node_k_sll(k);
head->prev = tail;
tail->next = head;
if (p == 'f') {
for (int i = 0; i < size; i++) {
printf("%d ", k_node->data);
k_node = k_node->next;
}
}
else {
for (int i = 0; i < size; i++) {
printf("%d ", k_node->data);
k_node = k_node->prev;
}
}
tail->next = NULL;
head->prev = NULL;
printf("\n");
}
else printf("List Is Empty or Invalid k");
}
void delete_front_sll() {
if (!is_empty_sll())
delete_sll(head->data);
else
printf("List is Empty!");
} | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
void delete_back_sll() {
if (!is_empty_sll())
delete_sll(tail->data);
else
printf("List is Empty!");
}
// void sort_sll() {//
// }
int main() {
prepend_sll(0);
append_sll(1);
append_sll(2);
append_sll(4);
insert_sll(3, 3);
print_sll('f');
reverse_sll();
print_sll('f');
rotate_sll(2, 'f');
insert_sll(3, 3);
print_sll('f');
prepend_sll(0);
print_sll('f');
printf("size: %d\n", size_sll());
printf("index of 3 is: %d\n", find_sll(3));
delete_sll(2);
print_sll('f');
swap_sll(0, 1);
print_sll('f');
reverse_sll();
print_sll('f');
append_sll(0);
append_sll(-1);
print_sll('f');
rotate_sll(2, 'f');
delete_front_sll();
print_sll('f');
delete_back_sll();
print_sll('f');
append_sll(20);
prepend_sll(-20);
print_sll('f');
clear_sll();
return 0;
}
Answer: These globals are a problem:
Node* head = NULL;
Node* tail = NULL;
int size = 0;
That means that we can only ever have a single list in any given program. We need to encapsulate these variables into a struct that we can instantiate as many times as we need (and use a more appropriate type for the size):
struct LinkedList {
Node* head = NULL;
Node* tail = NULL;
size_t size = 0;
};
create_node() ought to have static linkage, as Node shouldn't be part of the user-visible interface to the list.
Declare one variable per line. In fact, exits isn't needed, because it's only used in one place:
Node *create_node(int elm)
{
Node* node = malloc(sizeof *node);
if (!node) { return node; }
node->data = elm;
node->prev = NULL;
node->next = NULL;
++size;
return node;
} | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
Some of the function declarations are prototypes (they specify the arguments that can be passed) and some are not (they allow any number of arguments, of any type). It's better to be consistent, and use prototypes for all declarations:
Node *get_tail(void);
int is_empty_sll(void);
size_t size_sll(void);
void reverse_sll(void);
void clear_sll(void);
void delete_front_sll(void);
void delete_back_sll(void);
int main(void);
Also, why do most these functions have sll in the name? It's not clear what that stands for. | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
GCC believes that append_sll dereferences tail - you should check whether it's detected a bug:
283247.c: In function ‘append_sll’:
283247.c:64:20: warning: dereference of NULL ‘tail’ [CWE-476] [-Wanalyzer-null-dereference]
64 | tail->next = cur;
| ~~~~~~~~~~~^~~~~
‘main’: events 1-2
|
| 257 | int main()
| | ^~~~
| | |
| | (1) entry to ‘main’
| 258 | {
| 259 | prepend_sll(0);
| | ~~~~~~~~~~~~~~
| | |
| | (2) calling ‘prepend_sll’ from ‘main’
|
+--> ‘prepend_sll’: events 3-4
|
| 70 | void prepend_sll(int elm)
| | ^~~~~~~~~~~
| | |
| | (3) entry to ‘prepend_sll’
| 71 | {
| 72 | Node* updated_head = create_node(elm);
| | ~~~~~~~~~~~~~~~~
| | |
| | (4) calling ‘create_node’ from ‘prepend_sll’
|
+--> ‘create_node’: events 5-7
|
| 14 | Node* create_node(int elm)
| | ^~~~~~~~~~~
| | |
| | (5) entry to ‘create_node’
|......
| 17 | if (!node) { return node; }
| | ~
| | |
| | (6) following ‘false’ branch (when ‘node’ is non-NULL)...
| 18 | node->data = elm;
| | ~~~~~~~~~~~~~~~~
| | |
| | (7) ...to here
|
<------+
|
‘prepend_sll’: events 8-10
|
| 72 | Node* updated_head = create_node(elm); | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
|
| 72 | Node* updated_head = create_node(elm);
| | ^~~~~~~~~~~~~~~~
| | |
| | (8) returning to ‘prepend_sll’ from ‘create_node’
| 73 | if (!head) {
| | ~
| | |
| | (9) following ‘true’ branch...
| 74 | head = updated_head;
| | ~~~~~~~~~~~~~~~~~~~
| | |
| | (10) ...to here
|
<------+
|
‘main’: events 11-12
|
| 259 | prepend_sll(0);
| | ^~~~~~~~~~~~~~
| | |
| | (11) returning to ‘main’ from ‘prepend_sll’
| 260 | append_sll(1);
| | ~~~~~~~~~~~~~
| | |
| | (12) calling ‘append_sll’ from ‘main’
|
+--> ‘append_sll’: events 13-14
|
| 58 | void append_sll(int elm)
| | ^~~~~~~~~~
| | |
| | (13) entry to ‘append_sll’
| 59 | { //O(1)
| 60 | Node* cur = create_node(elm);
| | ~~~~~~~~~~~~~~~~
| | |
| | (14) calling ‘create_node’ from ‘append_sll’
|
+--> ‘create_node’: events 15-19
|
| 14 | Node* create_node(int elm)
| | ^~~~~~~~~~~
| | |
| | (15) entry to ‘create_node’
| 15 | {
| 16 | Node* node = malloc(sizeof * node);
| | ~~~~~~~~~~~~~~~~~~~~~
| | |
| | (16) allocated here | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
| | (16) allocated here
| 17 | if (!node) { return node; }
| | ~ ~~~~
| | | |
| | | (19) ...to here
| | (17) assuming ‘node’ is NULL
| | (18) following ‘true’ branch (when ‘node’ is NULL)...
|
<------+
|
‘append_sll’: events 20-23
|
| 60 | Node* cur = create_node(elm);
| | ^~~~~~~~~~~~~~~~
| | |
| | (20) return of NULL to ‘append_sll’ from ‘create_node’
| 61 | if (!head) {
| | ~
| | |
| | (21) following ‘false’ branch...
|......
| 64 | tail->next = cur;
| | ~~
| | |
| | (22) ...to here
| 65 | cur->prev = tail;
| | ~~~~~~~~~~~~~~~~
| | |
| | (23) state of ‘&HEAP_ALLOCATED_REGION(55)’: ‘null’ -> ‘stop’ (NULL origin)
|
<------+
|
‘main’: events 24-25
|
| 260 | append_sll(1);
| | ^~~~~~~~~~~~~
| | |
| | (24) returning to ‘main’ from ‘append_sll’
| 261 | append_sll(2);
| | ~~~~~~~~~~~~~
| | |
| | (25) calling ‘append_sll’ from ‘main’
|
+--> ‘append_sll’: events 26-27
|
| 58 | void append_sll(int elm)
| | ^~~~~~~~~~
| | |
| | (26) entry to ‘append_sll’
| 59 | { //O(1) | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
| | (26) entry to ‘append_sll’
| 59 | { //O(1)
| 60 | Node* cur = create_node(elm);
| | ~~~~~~~~~~~~~~~~
| | |
| | (27) calling ‘create_node’ from ‘append_sll’
|
+--> ‘create_node’: events 28-31
|
| 14 | Node* create_node(int elm)
| | ^~~~~~~~~~~
| | |
| | (28) entry to ‘create_node’
|......
| 17 | if (!node) { return node; }
| | ~ ~~~~
| | | |
| | | (31) ...to here
| | (29) ‘tail’ is NULL
| | (30) following ‘true’ branch (when ‘node’ is NULL)...
|
<------+
|
‘append_sll’: events 32-35
|
| 60 | Node* cur = create_node(elm);
| | ^~~~~~~~~~~~~~~~
| | |
| | (32) returning to ‘append_sll’ from ‘create_node’
| 61 | if (!head) {
| | ~
| | |
| | (33) following ‘false’ branch...
|......
| 64 | tail->next = cur;
| | ~~~~~~~~~~~~~~~~
| | | |
| | | (35) dereference of NULL ‘tail’
| | (34) ...to here
| | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
There are a number of other -fanalyzer warnings that should be checked and rectified.
I think the cause of most of these is that although we're careful to check whether malloc() returns a null pointer in create_node(), we then fail to check the return value of create_node() where we call it.
node_k_sll accepts a signed int, but rejects negative values. A more appropriate type for indexing into storage is size_t.
It's redundant to test the size and emptiness of the list (size should always be 0 when the list is empty).
The while loop has a control variable that's incremented each time around, so would be better (more easily recognised) as a for loop.
In the error case, we print to standard output - diagnostics such as that should go to the standard error stream. And output should always be complete lines.
Node* node_k_sll(size_t k)
{ // 0-based index
if (k >= size_sll()) {
fprintf(stderr, "Invalid k or List is Empty\n");
return NULL;
}
Node* node = head;
while (k--) {
node = node->next;
}
return node;
}
insert_sll fails if the list is empty, which seems wrong to me when we're inserting at position 0. In fact, we can always delegate to prepend_sll() in that case (and, for efficiency, delegate to append_sll() when inserting at the end; also consider walking the list from the end if inserting to the second half).
It's easier to consider the error cases first, and return early. That reduces the amount of context readers need to maintain:
bool insert_sll(int elm, size_t i)
{
if (i == 0) {
return prepend_sll(elm);
}
if (i == size_sll()) {
return append_sll(elm);
}
if (is_empty_sll()) {
fprintf(stderr, "List Is Empty");
return false;
} | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
Node *node = head;
Node *const new_node = create_node(elm);
if (!new_node) {
return false;
}
while (i--) {
node = node->next;
assert(node); /* given that initial i < size */
}
new_node->next = node;
new_node->prev = node->prev;
node->prev->next = new_node;
node->prev = new_node;
return true;
}
delete_sll() has a bug when it removes the only node from a single-element list:
head = head->next;
head->prev = NULL;
When head->next is null, we should be adjusting tail instead:
head = head->next;
if (head) {
head->prev = NULL;
} else {
tail = NULL;
}
delete_back_sll() has a bug that requires unravelling the undocumented behaviour of other functions. It actually deletes the first element that has the same value as the tail element. Delegating to the delete-by-value function doesn't cut it:
bool delete_back_sll(void)
{
Node *const node = tail;
if (!node) {
fprintf(stderr, "List is Empty!\n");
return false;
}
tail = node->prev;
if (tail) {
tail->next = NULL;
} else {
head = NULL;
}
free(node);
return true;
}
It may be a worthwhile idea to write an internal function
static bool delete_node(Node *node);
Swapping nodes by exchanging their contents is fine for int content. However, for lists of larger content, it can be more efficient to exchange their links instead. It might even be necessary if any content is the target of a pointer.
clear_sll has a bug - it leaves tail unchanged, likely a dangling pointer.
A lot of the complication of dealing with head and tail pointers in place of a node's prev and next can be eliminated by having a dummy Node to hold the head and tail of the list. You might recognise this as us using the Null Object pattern. | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c, linked-list
The main() program exercises the code, but it doesn't confirm the correctness of it. We should be verifying the results of operations, and returning EXIT_FAILURE if the behaviour is not as expected. | {
"domain": "codereview.stackexchange",
"id": 44455,
"lm_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, linked-list",
"url": null
} |
c#, beginner, winforms
Title: Bouncing balls program with speed up/speed down boxes and lines which change direction of ball
Question: I'm new to C#, background in Ada, C. This is my second lab in a course, output works correct but I feel like I've missed something about OOP. I've asked for feedback from lab 1, but didn't get any.
Main objective of this lab is Inheritance, Abstract classes, Interface.
Broad advice are as useful as detailed advice!
It uses WinForms. It's a "bouncing ball" program where lines will make the ball bounce, and boxes will speed up or speed down the ball.
Main will just run:
Engine engine = new Engine(); engine.Run();
Engine class:
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Bounce;
public class Engine
{
MainForm Form = new MainForm();
Timer Timer = new Timer();
List<Ball> Balls = new List<Ball>();
Random Random = new Random();
List<Line> Lines = new List<Line>();
List<SpeedBox> SpeedBoxes = new List<SpeedBox>();
public void Run()
{
InitializeLinesBoxes();
Form.BackColor = System.Drawing.Color.Black;
Form.Paint += Draw;
Timer.Tick += TimerEventHandler;
Timer.Interval = 1000 / 25;
Timer.Start();
Application.Run(Form);
} | {
"domain": "codereview.stackexchange",
"id": 44456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, winforms",
"url": null
} |
c#, beginner, winforms
Application.Run(Form);
}
void InitializeLinesBoxes()
{
for (int i = 0; i < 2; i++)
{
var vertical = new VerticalLine(Random.Next(1, 100) + 600 * i, Random.Next(1, 100) - 15 * i, 450);
Lines.Add(vertical);
var horizontal = new HorizontalLine(Random.Next(1, 100) + 15 * i, Random.Next(1, 100) + 400 * i, 550);
Lines.Add(horizontal);
var speedUp = new SpeedUp(Random.Next(100, 700), Random.Next(100, 500), Random.Next(5, 20) * 10, Random.Next(5, 20) * 10);
SpeedBoxes.Add(speedUp);
var speedDown = new SpeedDown(Random.Next(100, 700), Random.Next(100, 500), Random.Next(5, 20) * 10, Random.Next(5, 20) * 10);
SpeedBoxes.Add(speedDown);
}
}
void TimerEventHandler(Object obj, EventArgs args)
{
if (Random.Next(400) < 25)
{
var ball = new Ball(400, 300, 10);
Balls.Add(ball);
}
foreach (var ball in Balls) ball.Move();
foreach (var ball in Balls) ball.CheckCollision(Lines, SpeedBoxes);
Form.Refresh();
}
void Draw(Object obj, PaintEventArgs args)
{
foreach (var ball in Balls) ball.Draw(args.Graphics);
foreach (var line in Lines) line.Draw(args.Graphics);
foreach (var box in SpeedBoxes) box.Draw(args.Graphics);
}
}
Ball class:
using System;
using System.Collections.Generic;
using System.Drawing;
namespace Bounce;
public class Ball
{
Pen Pen = new Pen(Color.White);
PointF Position;
PointF Speed;
float Radius;
static Random Random = new Random();
private Rectangle Bounds; | {
"domain": "codereview.stackexchange",
"id": 44456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, winforms",
"url": null
} |
c#, beginner, winforms
static Random Random = new Random();
private Rectangle Bounds;
public Ball(float x, float y, float radius)
{
Position = new PointF(x, y);
Bounds = new Rectangle((int)x - (int)radius, (int)y - (int)radius, (int)radius * 2, (int)radius * 2);
var xd = Random.Next(1, 6);
var yd = Random.Next(1, 6);
if (Random.Next(0, 2) == 0) xd = -xd;
if (Random.Next(0, 2) == 0) yd = -yd;
Speed = new PointF(xd, yd);
Radius = radius;
}
public void Draw(Graphics g)
{
g.DrawEllipse(Pen, Position.X - Radius, Position.Y - Radius, 2 * Radius, 2 * Radius);
}
public void Move()
{
Position.X += Speed.X;
Position.Y += Speed.Y;
Bounds.X = (int)Position.X - (int)Radius;
Bounds.Y = (int)Position.Y - (int)Radius;
}
public void CheckCollision(List<Line> lines, List<SpeedBox> speedBoxes)
{
foreach (var line in lines)
{
if (Bounds.IntersectsWith(line.Bounds))
{
Speed = line.ChangeDirection(Speed);
}
}
foreach (var box in speedBoxes)
{
if (Bounds.IntersectsWith(box.Rectangle))
{
Speed = box.ChangeSpeed(Speed);
}
}
}
}
Line class:
using System.Drawing;
namespace Bounce
{
public abstract class Line
{
protected Point LineStart;
protected int Length;
public Rectangle Bounds { get; protected set; }
protected Line(int x, int y, int length)
{
LineStart = new Point(x, y);
Length = length;
}
public abstract PointF ChangeDirection(PointF speed);
public abstract void Draw(Graphics g);
} | {
"domain": "codereview.stackexchange",
"id": 44456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, winforms",
"url": null
} |
c#, beginner, winforms
public class VerticalLine : Line
{
Pen Pen = new Pen(Color.Yellow);
public VerticalLine(int x, int y, int length) : base(x, y, length)
{
Bounds = new Rectangle(x, y, 1, length);
}
public override PointF ChangeDirection(PointF speed)
{
speed.X *= (-1);
return speed;
}
public override void Draw(Graphics g)
{
g.DrawLine(Pen, LineStart.X, LineStart.Y, LineStart.X, LineStart.Y + Length);
}
}
public class HorizontalLine : Line
{
Pen Pen = new Pen(Color.Green);
public HorizontalLine(int x, int y, int length) : base(x, y, length)
{
Bounds = new Rectangle(x, y, length, 1);
}
public override PointF ChangeDirection(PointF speed)
{
speed.Y *= (-1);
return speed;
}
public override void Draw(Graphics g)
{
g.DrawLine(Pen, LineStart.X, LineStart.Y, LineStart.X + Length, LineStart.Y);
}
}
}
Box class:
using System.Drawing;
namespace Bounce;
public abstract class SpeedBox
{
public Rectangle Rectangle { get; protected set; }
public SpeedBox(int x, int y, int width, int height)
{
Rectangle = new Rectangle(x, y, width, height);
}
public abstract void Draw(Graphics g);
public abstract PointF ChangeSpeed(PointF speed);
}
public class SpeedUp : SpeedBox
{
Pen Pen = new Pen(Color.Red);
public SpeedUp(int x, int y, int width, int height) : base(x, y, width, height)
{
}
public override PointF ChangeSpeed(PointF speed)
{
speed.X *= 1.02f;
speed.Y *= 1.02f;
return speed;
}
public override void Draw(Graphics g)
{
g.DrawRectangle(Pen, Rectangle);
}
} | {
"domain": "codereview.stackexchange",
"id": 44456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, winforms",
"url": null
} |
c#, beginner, winforms
public class SpeedDown : SpeedBox
{
Pen Pen = new Pen(Color.Blue);
public SpeedDown(int x, int y, int width, int height) : base(x, y, width, height)
{
}
public override PointF ChangeSpeed(PointF speed)
{
speed.X *= 0.98f;
speed.Y *= 0.98f;
return speed;
}
public override void Draw(Graphics g)
{
g.DrawRectangle(Pen, Rectangle);
}
}
```
Answer: Welcome to Code Review. You claim your code runs fine, and I will take your word at that since I don't have time to try to load and run it. Since you (1) have working code and (2) want a code review with constructive advice, then I think your post is acceptable here.
It might help to know which version of .NET you are using: .NET 7, .NET 6, .NET Framework, etc.
The Good
Your code is easy enough to read. Decent indenting and other white spacing. Names are spelled out without cryptic abbreviations.
I do take exception to a variable named Speed that is a PointF or location. I would expect speed to be a float with some factor. 1.0f is normal starting speed. And you increase ( Speed *= 1.02 ) or decrease ( Speed *= 0.98 ) depending upon some play action such as colliding with a speed box.
I like that your Main is minimal. This probably reflects your experiences with other languages. Many newbies to coding in general will try to shove as much as they can into the Program class.
Opportunites
Yes, you could benefit from better OOP and to adhering to some C# principles.
Ball Class
Consider the Ball class that has Position, Speed, Radius, etc. These are defined as fields. I use the principle that if something is private or constant that I make it a field. Otherwise, I make it a Property where at the very least the getter is public. Example:
public float Radius { get; private set; } | {
"domain": "codereview.stackexchange",
"id": 44456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, winforms",
"url": null
} |
c#, beginner, winforms
And that would be only if you allow Radius to be changed during a ball's lifetime. If you expect it to never change, you would want it to be readonly, as:
public float Radius { get; }
Although it looks like Position and Speed can definitely change, in which case you want to keep the private setter.
I see Pen is a field. Since Pen doesn't seem to change value, it could be static. However, in the future you may desire to have a ball change color, in which case I would make Pen a public property. Whether the setter is private or not depends upon your uses.
SpeedBox stuff
My problems with your implementation is (1) that it is not OOP-ish. There are 2 methods there, both un-related to each other, and the ChangeSpeed method has ZERO interaction with any of a speed boxes fields/properties.
The ball class checks for collisions, and if a collision is detected the speed is changed. I think ChangeSpeed should be moved to the Ball class. That leaves SpeedBox as minimalist with nothing more than a size, location, pen, and a Draw method. And that's all SpeedBox should be. It's an object at some location. Leave it to other classes to determine if they have collided with that location as well as what should be done in response to the collision. During all that, the SpeedBox occupies a location and is totally oblivious to a collision with some other object as well as what that colliding object was. And after the collison, the SpeedBox is unchanged. | {
"domain": "codereview.stackexchange",
"id": 44456,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, winforms",
"url": null
} |
c#, beginner, console, error-handling, mathematics
Title: Dividing two numbers then handle the divide by zero exception with try/catch
Question: I am new to coding, I hope you can help me to improve my code :)
First of all: The code works correctly.
using System;
namespace _3_dividing_2numbers
{
class Program
{
static void Main(string[] args)
{
try
{
OperationDevide();
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Enter another number !");
OperationDevide();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
OperationDevide();
}
}
public static void OperationDevide()
{
Console.WriteLine("Enter your first number :");
var firstNum = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your second number :");
var secondNum = Convert.ToInt32(Console.ReadLine());
var result = firstNum / secondNum;
Console.WriteLine($"your result is : {result}");
}
}
}
Code description
I write a simple program that takes two int inputs and prints the result. but I want to check the possible errors so I used from try/catch for DivideByZeroException and all of the other errors by Exception.
My Problem
Do you have any idea to make this code better?
I want to keep asking the user until the inputs have the correct format. when I run my code after the second Zero input it's crashed and try/catch only works for the first round of Zero inputs. | {
"domain": "codereview.stackexchange",
"id": 44457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console, error-handling, mathematics",
"url": null
} |
c#, beginner, console, error-handling, mathematics
Answer: If you need a repetition either use a recursive call or a loop. In this situation a loop makes sense.
while (true) { // Loop forever or until e.g., return or break exits the loop.
try
{
OperationDevide();
break; // The operation succeeded. Exit the loop.
}
catch (DivideByZeroException ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Enter another number !");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Try again !");
}
}
Note that when an exception occurs, the control flow is redirected to a catch-statement and the break statement is not executed.
As others have mentioned, exceptions can be avoided here. Not only the division by zero but also parsing errors. Let's try another approach.
I refactor the division method to contain only logic and math, but no input or output operations. The aim is to a have a separation of concerns: the Main method does input and output. The other method does business logic, as this is often called.
// Returns null if the divisor was 0 and the integer quotient otherwise
public static int? Divide(int dividend, int divisor)
{
if (divisor == 0) {
return null;
}
return dividend / divisor;
} | {
"domain": "codereview.stackexchange",
"id": 44457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console, error-handling, mathematics",
"url": null
} |
c#, beginner, console, error-handling, mathematics
Let's use Int32.TryParse instead of Convert.ToInt32. The former returns a Boolean value return value indicating whether the operation succeeded and does not throw exceptions. The latter throws an exception if the string cannot be converted to an int. Also, since we have to input numbers repeatedly, we can also refactor out this procedure to yet another method. This also makes the main method clearer.
private static int ReadIntegerInput(string name)
{
while (true) {
Console.Write($"Enter the {name}: ");
string input = Console.ReadLine();
if (Int32.TryParse(input, out int number)) {
return number;
}
Console.WriteLine($"Your {name} input is not a valid integer. Please try again.");
}
}
An advantage is that we do not need to repeat entering both numbers if something goes wrong.
The body of the main method can the be written as:
int dividend = ReadIntegerInput("dividend");
while (true) {
int divisor = ReadIntegerInput("divisor");
int? result = Divide(dividend, divisor);
if (result == null) {
Console.WriteLine("The divisor cannot be zero. Please try another divisor.");
} else {
Console.WriteLine($"The integer quotient of {dividend}/{divisor} is : {result}");
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 44457,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, console, error-handling, mathematics",
"url": null
} |
java, shell
Title: Shell script to compile Java
Question: cd "$(dirname "$0")"
javac -d . -sourcepath Source Source/project/Main.java
rm "Project.jar" 2>"/dev/null"
jar cfm "Project.jar" "Manifest.txt" project/*
This script would be placed in a Project directory, in which is Manifest.txt and a Source directory which contains the base package, i.e., Main.java would start with package project;.
The script would compile the Java into classes, creating a directory of name project inside the Project directory, and then from the class files create Project.jar. I do not have any IDEs installed, but is this typically how they work to compile a project with multiple .java files into a single .jar file?
Answer: No #! line to specify interpreter. Perhaps not so important for something that's portable shell, but still helpful to write #!/bin/sh.
No checking that cd was successful. We really don't want to continue if that fails for any reason. Similarly if javac fails, we want to exit with non-zero status. We could add || exit after all commands, but it's easier and simpler to begin the script with set -e.
I'm guessing the redirection of rm's standard error is to cope with Project.jar not existing. I suggest using rm -f instead, which is silent in that case (but will remove read-only files, assuming the directory is writable).
Using shell might work for the short term, but as your project grows, you'll find that going through all the steps unconditionally becomes more and more time-consuming. That's the point to move to a tool that's designed for resolving dependencies and orchestrating builds, such as Ant or Make; other tools are available and recommended by Torben which might also be suitable. | {
"domain": "codereview.stackexchange",
"id": 44458,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, shell",
"url": null
} |
c, array, image, integer
Title: First attempt at making a sobel edge detection filter in c
Question: I made a borders filter in C. It works properly, but I think it could be optimized and better designed; the formatting is abysmal. It uses too many lines for the border cases and has too many variables.
Basic Color Struct
typedef struct
{
BYTE rgbtBlue;
BYTE rgbtGreen;
BYTE rgbtRed;
} __attribute__((__packed__))
RGBTRIPLE; | {
"domain": "codereview.stackexchange",
"id": 44459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array, image, integer",
"url": null
} |
c, array, image, integer
Sobel edge filter
void edges(int height, int width, RGBTRIPLE image[height][width])
{
//sobel operator
int gy[3][3] = {{-1,-2,-1},{0,0,0},{1,2,1}};
int gx[3][3] = {{-1,0,1},{-2,0,2},{-1,0,1}};
RGBTRIPLE temp[height][width];
for(int n = 0; n < height; n++) // loop to check every pixel
{
for(int k = 0; k < width; k++)
{
// variables to use later
int eqblue, eqred, eqgreen;
int h = 0;
int t = 0;
int j = -1;
int p = -1;
float xred, xblue, xgreen, yred, yblue, ygreen;
xred = xblue = xgreen = yred = yblue = ygreen = 0;
int widx = 3;
int hghtx = 3;
// conditionals for border cases
if(n == 0)
{
p = 0;
hghtx = 2;
h = 1;
}
if(n == height - 1)
{
p = -1;
hghtx = 2;
}
if(k == 0)
{
j = 0;
widx = 2;
t = 1;
}
if(k == width - 1)
{
j = -1;
widx = 2;
}
for(int u = 0; u < hghtx; u++) // matrix of pixels around the main pixel using the conditionals gathered before
for(int i = 0; i < widx; i++)// using sobel operator
{
xgreen = xgreen + image[n + p + u][k + j + i].rgbtGreen * gx[u + h][i + t];
xred = xred + image[n + p + u][k + j + i].rgbtRed * gx[u + h][i + t];
xblue = xblue + image[n + p + u][k + j + i].rgbtBlue * gx[u + h][i + t];
ygreen = ygreen + image[n + p + u][k + j + i].rgbtGreen * gy[u + h][i + t];
yblue = yblue + image[n + p + u][k + j + i].rgbtBlue * gy[u + h][i + t];
yred = yred + image[n + p + u][k + j + i].rgbtRed * gy[u + h][i + t];
} | {
"domain": "codereview.stackexchange",
"id": 44459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array, image, integer",
"url": null
} |
c, array, image, integer
}
//checks if the new color value surpasses 255
eqred = sqrt((pow(xred, 2) + pow(yred, 2))) + 0.5;
eqblue = sqrt((pow(xblue, 2) + pow(yblue, 2))) + 0.5;
eqgreen = sqrt((pow(xgreen, 2) + pow(ygreen, 2))) + 0.5;
if(eqgreen > 255)
eqgreen = 255;
if(eqblue > 255)
eqblue = 255;
if(eqred > 255)
eqred = 255;
//stores color in the temp array
temp[n][k].rgbtBlue = eqblue;
temp[n][k].rgbtRed = eqred;
temp[n][k].rgbtGreen = eqgreen;
}
}
// changes the original image to the filtered one
for(int n = 0; n < height; n++)
for(int k = 0; k < width; k++)
image[n][k] = temp[n][k];
} | {
"domain": "codereview.stackexchange",
"id": 44459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array, image, integer",
"url": null
} |
c, array, image, integer
Imput
Output
Answer: General Observations
We could provide a better review if the calling functions were included and any headers (math.h, etc.) were included.
The code is not portable, variable length arrays were made optional to compiler developers as of C11. The code will not compile on some systems.
Declare the variables as they are needed rather than at the top of logic blocks.
Possible Alignment issues
With the current declaration of RGBTRIPLE the struct is only 3 bytes, this is an odd size. The packed attribute is not necessarily considered safe.
It might be better to make the struct a field in a union where the other type is uint32_t. You might also want to add a padding BYTE to the struct.
Magic Numbers
This code contains the Magic Number 255:
if (eqgreen > 255)
eqgreen = 255;
if (eqblue > 255)
eqblue = 255;
if (eqred > 255)
eqred = 255;
It might be better to create a symbolic constant for them to make the code more readble and easier to maintain. These numbers may be used in many places and being able to change them by editing only one line makes maintenance easier.
Numeric constants in code are sometimes referred to as Magic Numbers, because there is no obvious meaning for them. There is a discussion of this on stackoverflow.
As a side note, the then clause and else clause of if statements have a tendency to grow, so it is always safer to make them compound statements by default:
#define MAX_RBG 255
if (eqgreen > MAX_RBG)
{
eqgreen = MAX_RBG;
}
if (eqblue > MAX_RBG)
{
eqblue = MAX_RBG;
}
if (eqred > MAX_RBG)
{
eqred = MAX_RBG;
}
The above code could possibly be shortened using conditional assignments:
eqgreen = (eqgreen > MAX_RBG)? MAX_RBG : eqgreen; | {
"domain": "codereview.stackexchange",
"id": 44459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array, image, integer",
"url": null
} |
c, array, image, integer
Complexity
The function edges() is too complex (does too much). There are multiple methods to determine complexity, one uses the number of lines in a function another might be the number of levels of indentation. The edges() function is 74 lines of code and there are at least 4 levels of indentation. Lines of code are used because any function larger than a single screen is very difficult to understand and maintain.
There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states:
that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. | {
"domain": "codereview.stackexchange",
"id": 44459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array, image, integer",
"url": null
} |
c, array, image, integer
Some things to consider are Don't Repeat Yourself (DRY code) and breaking the code into smaller functions.
This code should probably be a function due to the complexity:
for (int u = 0; u < hghtx; u++) // matrix of pixels around the main pixel using the conditionals gathered before
for (int i = 0; i < widx; i++)// using sobel operator
{
xgreen = xgreen + image[n + p + u][k + j + i].rgbtGreen * gx[u + h][i + t];
xred = xred + image[n + p + u][k + j + i].rgbtRed * gx[u + h][i + t];
xblue = xblue + image[n + p + u][k + j + i].rgbtBlue * gx[u + h][i + t];
ygreen = ygreen + image[n + p + u][k + j + i].rgbtGreen * gy[u + h][i + t];
yblue = yblue + image[n + p + u][k + j + i].rgbtBlue * gy[u + h][i + t];
yred = yred + image[n + p + u][k + j + i].rgbtRed * gy[u + h][i + t];
}
//checks if the new color value surpasses 255
eqred = sqrt((pow(xred, 2) + pow(yred, 2))) + 0.5;
eqblue = sqrt((pow(xblue, 2) + pow(yblue, 2))) + 0.5;
eqgreen = sqrt((pow(xgreen, 2) + pow(ygreen, 2))) + 0.5;
if (eqgreen > 255)
eqgreen = 255;
if (eqblue > 255)
eqblue = 255;
if (eqred > 255)
eqred = 255;
//stores color in the temp array
temp[n][k].rgbtBlue = eqblue;
temp[n][k].rgbtRed = eqred;
temp[n][k].rgbtGreen = eqgreen;
in fact just the nested for loops could be a function.
While I generally don't recommend writing macros, to reduce the repetitive nature of the code this code could be a macro or a function:
eqred = sqrt((pow(xred, 2) + pow(yred, 2))) + 0.5;
that way if you need to change how that calculation is done you only need to edit the code once rather than 3 times. | {
"domain": "codereview.stackexchange",
"id": 44459,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, array, image, integer",
"url": null
} |
c, strings, pointers
Title: Trim leading/trailing space in a string
Question: I'm practicing C and wrote a function to trim leading/trailing spaces in a string:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void string_trim(char **input) {
char *input_copy = strdup(*input);
int input_length = strlen(input_copy);
int start_index = 0;
while (*(input_copy++) == ' ') {
start_index++;
}
input_copy -= start_index + 1;
int end_index = input_length;
input_copy += input_length - 1;
while (*(input_copy--) == ' ') {
end_index--;
}
input_copy -= input_length - end_index + 1;
int new_length = end_index - start_index;
*input = realloc(*input, sizeof(char) * new_length + 1);
int index = 0;
for (int i = start_index; i < end_index; i++) {
(*input)[index] = input_copy[i];
index++;
}
(*input)[index] = '\0';
free(input_copy);
}
int main() {
char *str = malloc(sizeof(char) * 256);
strcpy(str, " hello ");
string_trim(&str);
printf("Result: '%s'\n", str);
free(str);
}
This works, but feels convoluted, is there a cleaner of doing it? Also, reallocating pointer that was passed to a function and allocated elsewhere first - I'm suspecting this would not be considered good practice or am I wrong? | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
Answer: You Have Several Buffer Overrun Bugs
If we pass in a pointer that isn’t properly terminated, this function will gleefully copy past the end of the input buffer, copying whatever is after the string into the new buffer. This could both cause a security bug (similar to Heartbleed) and potentially waste gigabytes of memory.
Always, always, always check for buffer overruns in C! It is never too soon to learn good habits!
Sizes are size_t, not int
On most 64-bit systems, a size_t is unsigned and 64-bits wide, and an int is signed and 32-bits wide. There are a huge number of bugs you can cause by converting a size_t to an int or vice versa. If your compiler does not warn you about this line:
int input_length = strlen(input_copy);
you need to enable more warnings. On GCC, Clang or ICX, I typically use -Wall -Wextra -Wpedantic -Wconversion -Wdeprecated and a -std= option. (It’s -Wconversion that should flag this.) On other compilers, check the documentation. Ideally, turn off warnings for headers from other projects, and compile with -Werror as well.
Check the Buffer Size
It’s good practice in C to pass in the maximum size of the input buffer, so that, even if the input array is unterminated, the function cannot overrun its buffer.
Return a String Slice
I agree with the other answers that you should be using a different API. I disagree that you should be making a deep copy of the string at all. In this case, you can represent the trimmed string as a slice of the original. This is both safer and more optimized.
You can still easily make a deep copy of the string slice if you need to—but you often won’t need to. And your program will run much faster and use less memory if you can avoid it.
So let’s say we define this data structure:
// A const string slice:
typedef struct str_cslice_t {
const char* s;
size_t n;
} str_cslice_t; | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
Here’s some code demonstrating two ways we could output a slice without making a copy:
#include <assert.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// A const string slice:
typedef struct str_cslice_t {
const char* s;
size_t n;
} str_cslice_t;
#define BUF_SIZE 1024U
// Not re-entrant:
int main(void)
{
static char buffer[BUF_SIZE] = " foo bar ";
const str_cslice_t slice = { &buffer[3], 7 };
assert( slice.n <= INT_MAX);
printf( "\"%.*s\"\n", (int)slice.n, slice.s );
memmove( buffer, slice.s, slice.n ); // Invalidates slice.s!
buffer[slice.n] = '\0';
printf( "\"%s\"\n", buffer );
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
Most good C APIs (and also the ANSI C standard library) let you pass in either the length or the maximum length of your string. This is primarily to make it at least theoretically possible to write C code without memory bugs, but it’s often faster too. Here, I used the %.*s format specifier to pass in the maximum length of the string, which lets us print a string slice. (A dangerous piece of technical debt in this interface is that the maximum length is passed as the “precision,” which has type int. Just on principle, I add an assertion that this cast will not overflow. The compiler can optimize it out at runtime. An alternative would be to use fwrite.)
After that, I re-used the original buffer by moving the slice to the beginning and then truncating it. You can re-use your input buffers this same way any time you no longer need the untrimmed string. That’s a lot of the time.
You can do most other things you could do with a deep copy of the string, using a string slice, as well. It’s normally faster and uses less memory, too! For example, you can concatenate slices with memcpy rather than strings with strncat.
If you really, truly need a deep copy of the slice, you can call strndup.
Is Checking for that One Byte Enough?
The program is certainly simpler if you can just search for that one byte. Unfortunately, in the twenty-first century, supporting ASCII doesn’t cut it, but the standard library’s support for internationalization is stuck in the ’90s (and Microsoft’s does not even support that). To work with UTF-8, you would in practice need to use some third-party library, such as libunicode.
Fortunately, if searching for the space character (or other ASCII whitespace) is enough, the same code will also run correctly on UTF-8 input. I’ll assume that’s the case for now.
Putting it All Together
First, something simpler and closer to your code than my original solutions.
With my suggested API, the signature of trim_string becomes: | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
With my suggested API, the signature of trim_string becomes:
str_cslice_t string_trim( const char* const s, const size_t n ) | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
If we add a function to convert a null-terminated string to_str_cslice, we decompose the problem into converting, and then calling a function to trim both ends of a string slice. The first is an important utility function to have anyway, and the second is simpler to write, since it doesn’t need to allocate any memory, copy anything or check the length.
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
/* A const string slice: Note that n is the actual length of the skice.
* Slices ARE NOT null-terminated.
*/
typedef struct str_cslice_t {
const char* s;
size_t n;
} str_cslice_t;
const str_cslice_t EMPTY_STR_CSLICE = { NULL, 0 };
/* Trims leading and trailing whitespace from a str_cslice_t.
*/
str_cslice_t str_cslice_trim( const str_cslice_t input )
{
if (input.s && input.n) {
const char* const end = input.s + input.n;
const char* first = input.s;
while ( first < end && *first == ' ' ) {
++first;
}
// We previously checked that n > 0.
const char *last = end - 1;
while ( last > first && *last == ' ' ) {
--last;
}
if (last > first || first > input.s) {
const str_cslice_t result = { first,
(size_t)(last - first + 1) };
return result;
}
}
return EMPTY_STR_CSLICE;
}
/* Converts a null-terminated string with a maximum length of n to a
* str_cslice_t.
*/
str_cslice_t to_str_cslice( const char* const s, const size_t n )
{
const size_t actual = strlen(s);
const str_cslice_t result = { s, actual < n ? actual : n };
return result;
}
/* Returns either a slice of the input string that does not include any
* leading and trailing spaces, or an empty slice if that substring is empty.
* The string is null-terminated, but its maximum length is n.
*/
str_cslice_t string_trim( const char* const s, const size_t n )
{
return str_cslice_trim(to_str_cslice(s, n));
}
#include <limits.h>
#include <stdio.h> | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
#include <limits.h>
#include <stdio.h>
// Not re-entrant:
int main(void)
{
{
static const char input[] = " foo bar ";
const str_cslice_t trim_both = string_trim( input, sizeof(input) );
assert( trim_both.n <= INT_MAX );
printf( "\"%.*s\"\n", (int)trim_both.n, trim_both.s );
}
{
static const char input[] = "foo bar ";
const str_cslice_t trim_right = string_trim( input, sizeof(input) );
assert( trim_right.n <= INT_MAX );
printf( "\"%.*s\"\n", (int)trim_right.n, trim_right.s );
}
{
static const char input[] = " foo bar";
const str_cslice_t trim_left = string_trim( input, UINT_MAX );
assert( trim_left.n <= INT_MAX );
printf( "\"%.*s\"\n", (int)trim_left.n, trim_left.s );
}
{
static const char input[] = " ";
const str_cslice_t empty = string_trim( input, sizeof(input) );
assert(empty.n == 0);
printf( "\"%.*s\"\n", (int)empty.n, empty.s );
}
{
static const char input[] = " ! ";
const str_cslice_t singleton = string_trim( input, sizeof(input) );
assert(singleton.n == 1);
printf( "\"%.*s\"\n", (int)singleton.n, singleton.s );
}
{
const str_cslice_t should_fail = string_trim( "", 0 );
assert( !should_fail.s && !should_fail.n );
}
{
const str_cslice_t should_fail = string_trim( NULL, UINT_MAX );
assert( !should_fail.s && !should_fail.n );
}
return EXIT_SUCCESS;
} | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
return EXIT_SUCCESS;
}
I include a simple test harness at the bottom, but it does not have complete code coverage. Caveat emptor.
A Refactored Version
I belatedly realized that I could clean up the code immensely by factoring out the trim-left and trim-right functions. We can also make both of these library functions take and return our str_cslice_t structures, same as before. The string_trim function is now the composition of three smaller functions, all of which are somewhat useful on their own: converting a null-terminated string into a string slice, trimming it on the left, and trimming it on the right.
Because I’m weird, I like to code in a functional style even in C. This can get complicated (as in my previous edits), but here, with the functions small enough, it becomes very straightforward. One advantage of this approach is that the entire program can be written with static single assignments. The local state is always updated together, at the same time. This eliminates several large categories of bugs.
Since this approach makes heavy use of tail recursion, and C was not designed for that, you need to make sure that the compiler optimizes tail calls. Clang and ICX have an extension for this, so I #define MUSTTAIL to expand to that attribute on those compilers, or to a no-op on other compilers. On GCC, you will need to compile this code with -O2, -O3, -Os, or at least -foptimize-sibling-calls.
#include <assert.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#if __clang__ || __INTEL_LLVM_COMPILER
# define MUSTTAIL __attribute((musttail))
#else
# define MUSTTAIL /**/
#endif
/* A const string slice: Note that n is the actual length of the skice.
* Slices ARE NOT null-terminated.
*/
typedef struct str_cslice_t {
const char* s;
size_t n;
} str_cslice_t;
const str_cslice_t EMPTY_STR_CSLICE = { NULL, 0 }; | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
const str_cslice_t EMPTY_STR_CSLICE = { NULL, 0 };
/* Trims leading whitespace from a slice.
*/
str_cslice_t str_cslice_trim_left( const str_cslice_t input )
{
if (!input.s || !input.n)
return EMPTY_STR_CSLICE;
if (*input.s != ' ')
return input;
MUSTTAIL return str_cslice_trim_left((struct str_cslice_t){ input.s+1, input.n-1 });
}
/* Trims trailing whitespace from a slice.
*/
str_cslice_t str_cslice_trim_right( const str_cslice_t input )
{
if (!input.s || !input.n)
return EMPTY_STR_CSLICE;
if (input.s[input.n-1] != ' ')
return input;
MUSTTAIL return str_cslice_trim_right((struct str_cslice_t){ input.s, input.n-1 });
}
/* Trims leading and trailing whitespace from a str_cslice_t.
*/
str_cslice_t str_cslice_trim( const str_cslice_t input )
{
MUSTTAIL return str_cslice_trim_right(str_cslice_trim_left(input));
}
/* Converts a null-terminated string with a maximum length of n to a
* str_cslice_t.
*/
str_cslice_t to_str_cslice( const char* const s, const size_t n )
{
const size_t actual = strlen(s);
const str_cslice_t result = { s, actual < n ? actual : n };
return result;
}
/* Returns either a slice of the input string that does not include any
* leading and trailing spaces, or an empty slice if that substring is empty.
* The string is null-terminated, but its maximum length is n.
*/
str_cslice_t string_trim( const char* const s, const size_t n )
{
return str_cslice_trim(to_str_cslice(s, n));
}
#include <limits.h>
#include <stdio.h>
// Not re-entrant:
int main(void)
{
{
static const char input[] = " foo bar ";
const str_cslice_t trim_both = string_trim( input, sizeof(input) );
assert( trim_both.n <= INT_MAX );
printf( "\"%.*s\"\n", (int)trim_both.n, trim_both.s );
}
{
static const char input[] = "foo bar ";
const str_cslice_t trim_right = string_trim( input, sizeof(input) );
assert( trim_right.n <= INT_MAX );
printf( "\"%.*s\"\n", (int)trim_right.n, trim_right.s );
} | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
c, strings, pointers
{
static const char input[] = " foo bar";
const str_cslice_t trim_left = string_trim( input, UINT_MAX );
assert( trim_left.n <= INT_MAX );
printf( "\"%.*s\"\n", (int)trim_left.n, trim_left.s );
}
{
static const char input[] = " ";
const str_cslice_t empty = string_trim( input, sizeof(input) );
assert(empty.n == 0);
printf( "\"%.*s\"\n", (int)empty.n, empty.s );
}
{
static const char input[] = " ! ";
const str_cslice_t singleton = string_trim( input, sizeof(input) );
assert(singleton.n == 1);
printf( "\"%.*s\"\n", (int)singleton.n, singleton.s );
}
{
const str_cslice_t should_fail = string_trim( "", 0 );
assert( !should_fail.s && !should_fail.n );
}
{
const str_cslice_t should_fail = string_trim( NULL, UINT_MAX );
assert( !should_fail.s && !should_fail.n );
}
return EXIT_SUCCESS;
}
ICX 2022 with -std=c17 -O3 -march=x86-64-v3 is able to inline these calls, resulting in extremely efficient code. Each of the test cases compiles to a block like the following:
mov edi, offset .L.str.2
mov edx, offset main.input+3
mov esi, 7
xor eax, eax
call printf
The non-inlined version optimizes into a tight loop as well, and this version does not use the heap at all, nor make a deep copy of any string.
One last footnote: if you are extremely security-conscious, you might want to use strnlen_s rather than strlen in the to_str_cslice function. This version is very fast and portable, but it’s theoretically possible that an unterminated string could make strlen run off the end of the buffer onto some unreadable page of memory and crash the program. | {
"domain": "codereview.stackexchange",
"id": 44460,
"lm_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, pointers",
"url": null
} |
jquery, html, css, html5
Title: CSS and HTML5 for this fixed header on scroll
Question: When I had to create a fixed header on scroll, I found a few examples on Stack Overflow but they were terrible in the sense that they relied on a fixed page height. Have a look at what I created which does not rely on a wrapper around the header and the content.
Default
On Scroll
Demo on CodePen.
HTML
<header>
<div class="header-banner">
<a href="/" class="logo"></a>
<h1>Art in Finland</h1>
</div>
<nav>
<ul>
<li><a href="/archive">Archive</a></li>
<li><a href="/events">Events</a></li>
<li><a href="/contact">Contact</a></li>
<ul>
</nav>
</header>
CSS
header {
height:360px;
z-index:10;
}
.header-banner {
background-color: #333;
background-image: url('http://37.media.tumblr.com/8b4969985e84b2aa1ac8d3449475f1af/tumblr_n3iftvUesn1snvqtdo1_1280.jpg');
background-position: center -300px;
background-repeat: no-repeat;
background-size: cover;
width: 100%;
height: 300px;
}
header .logo {
background-color: transparent;
background-image: url('http://www.futhead.com/static//img/14/clubs/1887.png');
background-position: center top;
background-repeat: no-repeat;
position: absolute;
top: 72px;
height: 256px;
width: 256px;
}
header h1 {
position: absolute;
top: 72px;
left: 240px;
color: #fff;
}
.fixed-header {
position: fixed;
top:0; left:0;
width: 100%;
}
nav {
width:100%;
height:60px;
background: #292f36;
postion:fixed;
z-index:10;
}
nav ul {
list-style-type: none;
margin: 0 auto;
padding-left:0;
text-align:right;
width: 960px;
}
nav ul li {
display: inline-block;
line-height: 60px;
margin-left: 10px;
}
nav ul li a {
text-decoration: none;
color: #a9abae;
} | {
"domain": "codereview.stackexchange",
"id": 44461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "jquery, html, css, html5",
"url": null
} |
jquery, html, css, html5
/* demo */
.content{ width: 960px; max-width: 100%; margin:0 auto; padding-top: 60px; }
article { width: 720px; float: left; }
article p:first-of-type { margin-top: 0; }
aside { width: 120px; float: right; }
aside img { max-width: 100%; }
body {
color: #292f36;
font-family: helvetica;
line-height: 1.6;
}
jQuery
$(window).scroll(function(){
if ($(window).scrollTop() >= 300) {
$('nav').addClass('fixed-header');
}
else {
$('nav').removeClass('fixed-header');
}
});
Answer: HTML
You might want to id that nav. It's because it might not be the only nav on the page, and the JS will pick it up and add .fixed-header to it. Something like:
<nav id="main-navigation">
CSS
On the CSS part, if only the nav gets a the .fixed-header class, you might want to consider declaring the CSS for .fixed-header like:
nav.fixed-header{...}
That way, it only applies to nav with that class. Scenario: You have another header that wants to be fixed at a certain position. It's logical to name it .fixed-header but it's not a nav. If you didn't do it this way, this style will also apply to the sidebar.
JS
It would be better if you cached the value of jQuery DOM pickups, rather than re-fetching them every time the scroll event fires. Additionally, as mentioned in the HTML section, it's better to identify that <nav>. This time, it's for performance.
When you do $('nav'), what jQuery does is pick up all <nav> in the page, and stores them in an array. When you call functions on it, jQuery loops through each one of them, and applies the function. You would want to avoid that looping, and so, you must limit what is being looped by being more specific with your query. Querying an id would be best since id should only happen once on the page.
var $window = $(window);
var nav = $('#main-navigation');
$window.scroll(function(){
if ($window.scrollTop() >= 300) {
nav.addClass('fixed-header');
}
else {
nav.removeClass('fixed-header');
}
}); | {
"domain": "codereview.stackexchange",
"id": 44461,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "jquery, html, css, html5",
"url": null
} |
c++, performance, eigen
Title: matrix multiplication in C++
Question: I have the following function that takes too long to execute.
I need to made this at least 2x times faster.
for (size_t i = 0; i < mat1.size(); ++i)
{
for (size_t k = 0; k < mat1[0].size(); ++k)
{
for (size_t j = 0; j < mat2[0].size(); ++j)
{
res[i][j] += mat1[i][k] * mat2[k][j];
}
}
}
Answer:
If you don't need the precision of double then go with single precision floats in the temporary vectors. This can double your performance if the compiler can vectorize it. And you can avoid needing to up-convert to double and then down-convert from double to float right in the innermost of the loop.
Even adding a static_cast<float> in the inner loop shrinks the generated code from 14 math + 3 loop instructions to 10 + 3 when checking on godbolt. But making all inputs single precision makes the inner loop as small as 6 + 3 per loop. (compiler was GCC 12.2 with -O3 -ffast-math and I picked the loops which got unrolled to handle 4 elements per iteration).
Consider transposing spectro and swapping the inner two loops. If you really need the precision of double then you can keep the temp result as a double and only do the conversion to single precision after the loop:
for (std::size_t i = 0; i < melBasis.size(); ++i)
{
for (std::size_t j = 0; j < spectro.size(); ++j)
{
const std::vector<double>& bas = melBasis[i];
const std::vector<double>& spec = spectro[j];
double res = 0;
for (std::size_t k = 0; k < bas.size(); ++k)
{
res += bas[k] * spec[k];
}
melS[i][j] = res;
}
}
That way the longest loop (1025 iterations) is the innermost one which means that less time is spent managing the outer loops (this comes out to 4 + 3 instructions in the inner most loop handling 2 elements). However if you make the inputs single precision then it will handle twice the amount of elements per loop. | {
"domain": "codereview.stackexchange",
"id": 44462,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, eigen",
"url": null
} |
c++, performance, eigen
Note that simply counting instructions isn't the best way to approximate performance as different instructions have different performance characteristics however it is a decent starting point.
Your eigen code is wrong because melBasis[0].data() will only return a pointer to the first row of data, while eigen expects the pointer to be the full data so it will read out of bounds. You will have to fill those matrices row by row. | {
"domain": "codereview.stackexchange",
"id": 44462,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, eigen",
"url": null
} |
c++, serialization
Title: Binary (de)serialization in c++
Question: I'm trying to make a simple library for de/serialization in c++, but I know it can be tricky to implement, so I'd really like to have my code reviewed to see if there's anything that stands out and/or can be improved. Here is the full repo containing all the code. Any other necessary code can be found there, as most of it was written by others.
binaryio/reader.h:
#include <memory>
#include <span>
#include <stdexcept>
#include "binaryio/interface.h"
#include "binaryio/swap.h"
#ifndef BINARYIO_READER_H
#define BINARYIO_READER_H
namespace binaryio {
class BinaryReader : IBinaryIO {
public:
BinaryReader(void* const begin, void* const end)
: m_begin(reinterpret_cast<char*>(begin)),
m_end(reinterpret_cast<char*>(end)),
m_current(reinterpret_cast<char*>(begin)){};
BinaryReader(void* const begin, void* const end, const endian& endianness)
: m_begin{reinterpret_cast<char*>(begin)},
m_end{reinterpret_cast<char*>(end)},
m_current{reinterpret_cast<char*>(begin)}, m_endian{endianness} {};
BinaryReader(void* const begin, const std::ptrdiff_t& size)
: m_begin{reinterpret_cast<char*>(begin)}, m_end{m_begin + size},
m_current{reinterpret_cast<char*>(begin)} {};
BinaryReader(void* const begin, const std::ptrdiff_t& size,
const endian& endianness)
: m_begin{reinterpret_cast<char*>(begin)}, m_end{m_begin + size},
m_current{reinterpret_cast<char*>(begin)}, m_endian{endianness} {};
void seek(std::ptrdiff_t offset) override {
if (m_begin + offset > m_end)
throw std::out_of_range("out of bounds seek");
m_current = m_begin + offset;
}
size_t tell() const override {
size_t offset{static_cast<size_t>(m_current - m_begin)};
return offset;
} | {
"domain": "codereview.stackexchange",
"id": 44463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, serialization",
"url": null
} |
c++, serialization
template <typename T>
T read() {
if (m_current + sizeof(T) > m_end)
throw std::out_of_range("out of bounds read");
T val = *(T*)m_current;
swap_if_needed_in_place(val, m_endian);
m_current += sizeof(T);
return val;
}
std::string read_string(size_t max_len = 0) {
if (m_current + max_len > m_end || max_len == 0)
max_len = m_end - m_current;
return {m_current, strnlen(m_current, max_len)};
}
template <typename T>
std::span<T> read_many(int count) {
if (m_current + sizeof(T) * count > m_end)
throw std::out_of_range("out of bound read");
std::span<T> vals{{}, count};
for (int i{0}; i < count; ++i) {
vals[i] = *(T*)m_current;
swap_if_needed_in_place(vals[i], m_endian);
m_current += sizeof(T);
}
return vals;
}
endian endianness() { return m_endian; }
void set_endianness(endian new_endian) { m_endian = new_endian; }
void swap_endianness() {
if (m_endian == endian::big)
m_endian = endian::little;
else
m_endian = endian::big;
}
private:
char* m_begin;
char* m_end;
char* m_current;
endian m_endian{endian::native};
};
} // namespace binaryio
#endif
binaryio/writer.h:
#include <memory>
#include <span>
#include <vector>
#include "binaryio/align.h"
#include "binaryio/interface.h"
#include "binaryio/swap.h"
#ifndef BINARYIO_WRITER_H
#define BINARYIO_WRITER_H
namespace binaryio {
class BinaryWriter : IBinaryIO {
public:
// Based on
// https://github.com/zeldamods/oead/blob/master/src/include/oead/util/binary_reader.h
BinaryWriter() = default;
BinaryWriter(endian byte_order) : m_endian{byte_order} {};
std::vector<uint8_t> finalize() { return std::move(m_storage); } | {
"domain": "codereview.stackexchange",
"id": 44463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, serialization",
"url": null
} |
c++, serialization
std::vector<uint8_t> finalize() { return std::move(m_storage); }
void seek(std::ptrdiff_t offset) override { m_offset = offset; };
size_t tell() const override { return m_offset; }
void write_bytes(const uint8_t* data, size_t size) {
std::span<const uint8_t> bytes{data, size};
if (m_offset + bytes.size() > m_storage.size())
m_storage.resize(m_offset + bytes.size());
std::memcpy(&m_storage[m_offset], bytes.data(), bytes.size());
m_offset += bytes.size();
};
template <typename T,
typename std::enable_if_t<!std::is_pointer_v<T> &&
std::is_trivially_copyable_v<T>>* = nullptr>
void write(T value) {
swap_if_needed_in_place(value, m_endian);
write_bytes(reinterpret_cast<const uint8_t*>(&value), sizeof(value));
}
void write(std::string_view str) {
write_bytes(reinterpret_cast<const uint8_t*>(str.data()), str.size());
}
void write_null() { write<uint8_t>(0); }
void write_cstr(std::string_view str) {
write(str);
write_null();
}
void align_up(size_t n) { seek(AlignUp(tell(), n)); }
private:
std::vector<uint8_t> m_storage;
size_t m_offset{0};
endian m_endian{endian::native};
};
} // namespace binaryio
#endif
And here's a test I wrote using a wav file as a base:
#include <iostream>
#include <fstream>
#include <filesystem>
#include "binaryio/reader.h"
#include "binaryio/writer.h"
struct FileHeader {
uint32_t magic;
uint32_t fileSize;
BINARYIO_DEFINE_FIELDS(FileHeader, magic, fileSize);
}; | {
"domain": "codereview.stackexchange",
"id": 44463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, serialization",
"url": null
} |
c++, serialization
struct WaveFile {
FileHeader riffHeader;
std::array<uint8_t, 4> magic;
std::array<uint8_t, 4> fmt;
uint32_t fmtSize;
uint16_t audioFormat;
uint16_t numChannels;
uint32_t sampleRate;
uint32_t byteRate;
uint16_t blockAlign;
uint16_t bitsPerSample;
std::array<uint8_t, 4> dataMagic;
uint32_t dataSize;
// Data starts
BINARYIO_DEFINE_FIELDS(WaveFile, riffHeader, magic, fmt, fmtSize, audioFormat, numChannels, sampleRate, byteRate, blockAlign, bitsPerSample, dataMagic, dataSize);
};
int main(int argc, char** argv)
try {
std::vector<uint8_t> bytes(std::filesystem::file_size(argv[1]));
{
std::ifstream ifs{argv[1]};
ifs.read(reinterpret_cast<char*>(bytes.data()), bytes.size());
}
// Read from the byte buffer
binaryio::BinaryReader reader{bytes.begin().base(), bytes.end().base()};
WaveFile wav {reader.read<WaveFile>()};
std::vector<uint8_t> data;
for (int i {sizeof(WaveFile)}; i<bytes.size(); ++i)
data.push_back(reader.read<uint8_t>());
std::cout << "Riff Magic: " << std::hex << wav.riffHeader.magic << std::endl;
std::cout << "Wave Magic: " << wav.magic.data() << std::endl;
// Write a new file
binaryio::BinaryWriter writer{binaryio::endian::little};
writer.write(wav);
for (uint8_t byte : data)
writer.write(byte);
bytes.clear();
bytes = writer.finalize();
{
std::ofstream ofs{"out_little.wav"};
ofs.write(reinterpret_cast<char*>(bytes.data()), bytes.size());
}
// Write a different file with its endianness swapped
writer = {binaryio::endian::big};
writer.write(wav);
for (uint8_t byte : data)
writer.write(byte);
bytes.clear();
bytes = writer.finalize();
{
std::ofstream ofs{"out_big.wav"};
ofs.write(reinterpret_cast<char*>(bytes.data()), wav.riffHeader.fileSize + sizeof(FileHeader));
} | {
"domain": "codereview.stackexchange",
"id": 44463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, serialization",
"url": null
} |
c++, serialization
// Read the new file, and compare the result with the original struct
reader = {bytes.begin().base(), bytes.end().base()};
if (reader.read<uint32_t>() == 0x52494646) {
reader.swap_endianness();
reader.seek(0);
}
WaveFile other_wav {reader.read<WaveFile>()};
std::cout << "Riff Magic: " << std::hex << other_wav.riffHeader.magic << std::endl;
std::cout << "Wave Magic: " << other_wav.magic.data() << std::endl;
if (wav.sampleRate == other_wav.sampleRate)
std::cout << "Data preserved, endianness swapped" << std::endl;
else {
throw std::runtime_error("Something went wrong and the data was changed");
}
return 0;
}
catch (std::runtime_error& err) {
std::cerr << err.what() << std::endl;
return 1;
}
```
Answer: Make the (de)serializer work on streams
If I look at your example main(), I see a lot of inefficiencies. Part of that is caused by having to read the data into a memory buffer before it can be deserialized, and similarly you have to completely fill a memory buffer before you can finalize the results and write it out. It would be much nicer if your code could work on files directly. Consider being able to write:
std::ifstream ifs{argv[1]};
binaryio::BinaryReader reader{ifs};
auto wav = reader.read<WaveFile>();
…
This could be implemented like so:
class BinaryReader {
std::istream& ifs;
public:
BinaryReader(std::ifstream& ifs): ifs{ifs} {}
template<typename T>
T read() {
T val;
if (!ifs.read(reinterpret_cast<char*>(&val), sizeof val))
throw std::out_of_range("out of bounds read");
swap_if_needed_in_place(val, m_endian);
return val;
}
…
}; | {
"domain": "codereview.stackexchange",
"id": 44463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, serialization",
"url": null
} |
c++, serialization
swap_if_needed_in_place(val, m_endian);
return val;
}
…
};
Now you might think: but what if my data is not in a file to begin with? The great thing about C++'s I/O functions is that they support more than just files. For example, the above reader can also work on std::istringstreams, and C++23 makes it easy to turn any contiguous buffer of memory into a stream using std::ispanstream.
Note that if your classes work on streams, it is no longer necessary to provide stream-like functions like tell() and seek() yourself.
The same goes for output.
Make it easy to read and write arrays
Your example shows reading the data from a WAV file byte by byte. That's potentially going to be slow, and it is inconvenient. It would be much nicer if you could write:
auto data = reader.read<std::vector<uint8_t>>(wav.datasize);
You can make this work by creating an overload for read() that checks if T is a container (in C++20, that is easy using concepts like std::ranges::output_range), and then creates a value of that type and read directly into it.
It might be some work to get it to work for all container types though, and you could instead consider creating a function that only returns std::vectors, or a function that takes a std::span to read into, so that you can write code like:
auto data = reader.read_vector<uint8_t>(wav.datasize);
// or:
std::vector<uint8_t> data(wav.datasize);
reader.read_span(std::span{data}); | {
"domain": "codereview.stackexchange",
"id": 44463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, serialization",
"url": null
} |
c++, serialization
About endianness
If you call reader.read<WaveFile>(), how does your code know how to swap endianness? Not everything is a 32-bit value in the WAV header, and the WAV data might contain samples in various formats, not just 8 bit values. If you swap 32 bits at a time, then two consecutive 16-bit fields in the header might get swapped. If your data consists of 8-bit samples, they should never be swapped.
Most serialization libraries allow you to provide custom serializers for your own types. That way, you can provide a serializer for WaveFile that serializes each header value separately. There are several approaches possible. For example, you could allow user code to overload the read and write functions, or you could check if a given type has serialize() and deserialize() member functions. Have a look at how Boost Serialization handles this. | {
"domain": "codereview.stackexchange",
"id": 44463,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, serialization",
"url": null
} |
python, python-3.x, type-hinting
Title: Type hints and expected types
Question: I'm unsure if this question belongs on Code Review or Stack Overflow.
Another developer told me that I should consider adding type hints to my open source project WordHoard.
I have never used type hints before and the documentation doesn't seem intuitive. So I need to guidance on how to implement this functionality in my code.
I've started looking at adding it some low level code pieces first.
For example:
from typing import AnyStr, Dict
def colorized_text(r: int, g: int, b: int, text: str) -> AnyStr:
"""
This function provides error messages color.
For example:
rgb(255, 0, 0) is displayed as the color red
rgb(0, 255, 0) is displayed as the color green
:param r: red color value
:param g: green color value
:param b: below color value
:param text: text to colorized
:return: string of colorized text
"""
return f"\033[38;2;{r};{g};{b}m{text}\033[0m"
Are type hints implemented correctly in the function colorized_text?
Here is another code example.
from typing import Optional
temporary_dict_antonyms = {}
def cache_antonyms(word: str) -> [bool, str]:
item_to_check = word
if item_to_check in temporary_dict_antonyms.keys():
values = temporary_dict_antonyms.get(item_to_check)
return True, list(sorted(set(values)))
else:
return False, None
def insert_word_cache_antonyms(word: str, values: list[str]) -> None:
if word in temporary_dict_antonyms:
deduplicated_values = set(values) - set(temporary_dict_antonyms.get(word))
temporary_dict_antonyms[word].extend(deduplicated_values)
else:
values = [value.strip() for value in values]
temporary_dict_antonyms[word] = values
How do I implement type hints correctly in the second example?
Thanks in advance for any guidance!
Answer:
Are type hints implemented correctly in the function colorized_text? | {
"domain": "codereview.stackexchange",
"id": 44464,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, type-hinting",
"url": null
} |
python, python-3.x, type-hinting
Answer:
Are type hints implemented correctly in the function colorized_text?
Almost; the return type should just be str, not AnyStr. AnyStr is for when (a) a function can take or return both str and bytes, (b) there are either multiple AnyStr arguments or one (or more) AnyStr arguments & an AnyStr return type, and (c) all AnyStr arguments/return types must be either all strs or all bytess when the function is actually called. A simple example would be a function that take two strs or two bytes and returns their concatenation; the arguments and return type would then all be AnyStr.
Also, you imported typing.Dict but don't use it.
How do I implement type hints correctly in the second example?
First, you need an annotation for temporary_dict_antonyms. It appears to be a dict mapping strs to lists of strs, so write temporary_dict_antonyms: dict[str, list[str]] = {}.
Secondly, to annotate a tuple (such as in cache_antonyms's return type), you need to write either tuple[ArgType1, ArgType2] etc. or tuple[ArgType, ...] for a tuple of variable length where all elements are the same type.
Now, cache_antonyms can return either a tuple of a bool and a list[str] or a bool and a None. I don't know why you feel the need to return a bool when the caller could just check whether the second field is non-None, but the simplest way to annotate the return value is -> tuple[bool, Optional[list[str]]].
By the way, I would recommend implementing cache_antonyms with a single dict query as follows:
def cache_antonyms(word: str) -> tuple[bool, Optional[list[str]]]:
try:
values = temporary_dict_antonyms[word]
except KeyError:
return (False, None)
else:
return (True, sorted(set(values))) # sorted() already returns a list | {
"domain": "codereview.stackexchange",
"id": 44464,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, type-hinting",
"url": null
} |
python, python-3.x, type-hinting
The annotations on insert_word_cache_antonyms are fine, but mypy will likely complain about set(temporary_dict_antonyms.get(word)), because the get() can return None, which is not a valid input to set(); change it to set(temporary_dict_antonyms[word]).
Additional comments:
If you want your code to run on Pythons before 3.9, then any parametrized dict, list, tuple, etc. in your annotations need to be swapped out for typing.Dict etc. — or, alternatively, just add from __future__ import annotations to the top of your code.
Since the values of temporary_dict_antonyms are always converted to sets after retrieval, you should probably just store sets in the dict in the first place instead.
In insert_word_cache_antonyms, you strip() the elements of values when the word is not in the dict, but you don't do it when adding to a pre-existing collection of values; are you sure that's what you want? | {
"domain": "codereview.stackexchange",
"id": 44464,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, type-hinting",
"url": null
} |
javascript, beginner, google-apps-script
Title: Sending Email Through App Script | {
"domain": "codereview.stackexchange",
"id": 44465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, google-apps-script",
"url": null
} |
javascript, beginner, google-apps-script
Question: Background
This is a function that is part of a library written in GAS. A function inside a library I've written is supposed to send out an email to another user or users with accompanying details (based on parameters) from the email account of whoever runs the function. Basically if I run the program from my google account, and your email address is one of the parameters, then you get an email from me. I realize that this is wrapped inside of Google's sendEmail function anyway, but I've added some of my own parameters.
What the function does specifically: when it is run, an email is sent to the specified email address/addresses with the accompanying subject and email body. Additionally, another email address can be added as a CC. Finally there is another option where, if the container the app script is attached to is a spreadsheet, you can specify which sheet on the spreadsheet you want converted into a PDF (specifying its PDF name), and have that sent with the email as well. Inside the function there can be six possible parameters: emailAddress, emailSubject, emailBody, emailCC, sheetName, and pdfName. I believe all of those are fairly self-explanatory besides the last two. As I previously mentioned, sheetName is the name of the sheet on the spreadsheet that you want converted into a PDF, and pdfName is the name you set your newly created PDF to.
My Request
I'm still somewhat new to GAS/JavaScript, and I wanted to challenge myself by making a library that contains a lot of the functions that my company uses on a regular basis so that I could learn more. Unfortunately, I'm very limited on who I can ask for guidance on how to improve my library. One of the methods that I was told about that was easier was to make separate functions for each of the combos of parameters within a top level object, but I have not been able to figure out how to properly implement that, so any assistance is appreciated.
My Code
function sendEmail(){ | {
"domain": "codereview.stackexchange",
"id": 44465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, google-apps-script",
"url": null
} |
javascript, beginner, google-apps-script
My Code
function sendEmail(){
var function1 = function(emailAddress, emailSubject, emailBody){
MailApp.sendEmail(emailAddress, emailSubject, emailBody)
} | {
"domain": "codereview.stackexchange",
"id": 44465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, google-apps-script",
"url": null
} |
javascript, beginner, google-apps-script
var function2 = function(emailAddress, emailSubject, emailBody, emailCC){
MailApp.sendEmail(emailAddress, emailSubject, emailBody, {cc: emailCC})
}
var function3 = function(emailAddress, emailSubject, emailBody, sheetName, pdfName){
MailApp.sendEmail(emailAddress, emailSubject, emailBody, {attachments: [pdfConversionPortrait(sheetName).setName(pdfName)]})
}
var function4 = function(emailAddress, emailSubject, emailBody, emailCC, sheetName, pdfName){
MailApp.sendEmail(emailAddress, emailSubject, emailBody, {
cc: emailCC,
attachments: [pdfConversionPortrait(sheetName).setName(pdfName)]})
}
try{
if(arguments.length === 3){
function1(arguments[0].toString(), arguments[1], arguments[2])
} else if(arguments.length === 4){
function2(arguments[0].toString(), arguments[1], arguments[2], arguments[3].toString())
} else if(arguments.length === 5){
function3(arguments[0].toString(), arguments[1], arguments[2], arguments[3], arguments[4])
} else if(arguments.length === 6){
function4(arguments[0].toString, arguments[1], arguments[2], arguments[3].toString, arguments[4], arguments[5])
}
} catch(e){
e instanceof TypeError ? Logger.log('Error: Specified sheet does not exist') : Logger.log(e)
}
}
Other Relevant Code
function pdfConversionPortrait(sheetName){
let ss = SpreadsheetApp.getActiveSpreadsheet()
let ss_id = ss.getId()
let sheet_id = ss.getSheetByName(sheetName).getSheetId()
let response = UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/" + ss_id + "/export?format=pdf&gid=" + sheet_id, {
muteHttpExceptions: true,
headers: {
Authorization: 'Bearer ' + ScriptApp.getOAuthToken(),
},
}).getBlob()
return response
}
Answer: Disclaimer
This is all untested code, written just based on reading the documentation.
If there's any inaccuracies, please just comment below and I will fix them. | {
"domain": "codereview.stackexchange",
"id": 44465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, google-apps-script",
"url": null
} |
javascript, beginner, google-apps-script
Instead of having a ton of functions, just to limit the number of arguments, how about you accept an object with the arguments?
I'm going to base my answer in the MailApp.sendEmail(object) variant.
I've based the argument names from Eric Koleda's answer in StackOverflow, regarding optional fields.
It's convention to use the prefix "opt_" for optional parameters, but it's not required.
Using the variant that takes a single object allows you to have much cleaner code, and you can still set all the options that you want, with better input validation.
This also removes the need for 4 weird functions that do the exact same thing: pass values to MailApp.sendEmail().
Here's a simple example I've written:
function sendEmail(toEmail, subject, body, opt_cc, opt_sheetName, opt_pdfName){
try {
var options = {
to: toEmail,
subject: subject,
body: body,
cc: null,
attachments: []
}
// If opt_cc was provided and isn't an empty string, add it
if(opt_cc) {
options.cc = opt_cc
}
// Adds the file if both opt_sheetName and opt_pdfName are provided
if(opt_sheetName && opt_pdfName) {
options.attachments = [
pdfConversionPortrait(sheetName).setName(pdfName)
]
} else if(opt_pdfName || opt_sheetName) {
// If just one of them is provided, throws an exception
throw "Sheet name and PDF name are required to attach a PDF file"
}
MailApp.sendEmail(options)
} catch(e){
e instanceof TypeError ? Logger.log('Error: Specified sheet does not exist') : Logger.log(e)
}
}
I took the liberty of simplifying the names of the arguments, to make them easier to read.
If the functionality to allow sending the CC information is a must, based on arguments, you can do like this:
function sendEmail(){
try {
var options = {
to: arguments[0],
subject: arguments[1],
body: arguments[2]
} | {
"domain": "codereview.stackexchange",
"id": 44465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, google-apps-script",
"url": null
} |
javascript, beginner, google-apps-script
// Both have the 4th argument as the CC
if(arguments.length === 4 || arguments.length >= 6) {
options.cc = arguments[3]
}
// 5 or more arguments have the sheet name and pdf name as arguments
if(arguments.length >= 5) {
/*
For 5 arguments, get the 4th and 5th arguments.
For 6 or more arguments, get the 5th and 6th arguments.
*/
var index = arguments.length === 5 ? 3 : 4;
options.attachments = [
pdfConversionPortrait(arguments[index])
.setName(arguments[index + 1])
]
}
MailApp.sendEmail(options)
} catch(e){
e instanceof TypeError ? Logger.log('Error: Specified sheet does not exist') : Logger.log(e)
}
}
It should have the same functionality as the 4 functions you've shown.
Something I would also change is this line:
e instanceof TypeError ? Logger.log('Error: Specified sheet does not exist') : Logger.log(e)
I would rewrite it to this:
Logger.log(e instanceof TypeError ? e : 'Error: Specified sheet does not exist')
It's a little bit shorter and aligns a little bit better with how one would use the ternary operator: to pass values based on a condition, instead of controlling the code execution (that's the job of an if).
Additionally, I would only wrap the pdfConversionPortrait(sheetName).setName(pdfName) in the try{ } catch block. | {
"domain": "codereview.stackexchange",
"id": 44465,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, beginner, google-apps-script",
"url": null
} |
java
Title: Longest substring without repeating characters
Question: I have the following O(N) code submitted:
class Solution {
public int lengthOfLongestSubstring(String s) {
int currentLongest = 0, idx = 0;
if (s.length() <= 1){ return s.length(); }
for (int i=1; i<s.length(); i++){
String str = s.substring(idx, i); //substring up to current char (exclusive)
int strLen = str.length();
int idxOf = str.indexOf(s.charAt(i)); //check if current char is in the substring
if (idxOf != -1){ //if contains duplicate
if (strLen > currentLongest){
currentLongest = strLen; //replace if it is the longest substring seen
}
idx += idxOf+1; //move front pointer after idxOf.
}
if (i == s.length() -1){ // if last iteration, do final check inclusive of last char
strLen = s.substring(idx, i+1).length();
if (strLen > currentLongest){
currentLongest = strLen;
}
}
}
return currentLongest;
}
}
which passes all the test cases, however, I feel its kind of a hodge podge mix of hacks and work arounds (ie the s.length() < 1 part). Not only that, I m unsure if the substring() and indexOf() calls are causing the performance to be worse as follows.
Runtime: 11 ms, faster than 71.13% of Java online submissions for Longest Substring Without Repeating Characters.
Memory Usage: 49.2 MB, less than 19.11% of Java online submissions for Longest Substring Without Repeating Characters.
Requirements:
Given a string s, find the length of the longest substring without repeating characters. | {
"domain": "codereview.stackexchange",
"id": 44466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
Given a string s, find the length of the longest substring without repeating characters.
Example 1:
Input: s = "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
Example 2:
Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.
Example 3:
Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.
Answer: Thinking about time complexity
Yes the solution runs in \$O(n)\$ time,
but only because of the finite size of the alphabet.
With a simple twist, changing the task from a string of characters to an array of numbers,
to find the longest sub-array without repeating numbers,
the algorithm would run in \$O(n^2)\$ time.
I thought it's worth noting, and something to think about.
Avoid unnecessary computations
The String::substring method creates a new string from the range of characters.
This has the cost of allocating memory and copying the range of characters.
It's good to avoid creating substrings when it can be avoided, especially in a loop.
For example in the loop it's wasteful to create an increasingly long substring in every iteration.
You could instead work with indexes and the indexOf and lastIndexOf methods.
Although this is only executed once, I want to call it out:
strLen = s.substring(idx, i+1).length();
Better use simple math:
strLen = i + 1 - idx;
Avoid special treatments
This can be avoided:
if (s.length() <= 1){ return s.length(); }
It takes a simple change in the initialization steps:
int currentLongest = 0, idx = 0;
for (int i=0; i<s.length(); i++){ | {
"domain": "codereview.stackexchange",
"id": 44466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
for (int i=0; i<s.length(); i++){
The special treatment for the last character can also be avoided,
by updating currentLongest always, not only when finding duplicates.
if (idxOf != -1) {
if (strLen > currentLongest){
currentLongest = strLen;
}
idx += idxOf+1;
} else {
strLen = i + 1 - idx;
if (strLen > currentLongest) {
currentLongest = strLen;
}
}
Btw, do you see what I'm seeing? A conditional is duplicated in both branches of an if-else, and it can be safely moved out:
if (idxOf != -1) {
idx += idxOf+1;
} else {
strLen = i + 1 - idx;
}
if (strLen > currentLongest) {
currentLongest = strLen;
}
Note that this simplification opportunity was less visible before.
By making just one thing simpler,
many times it leads to another thing that can be simpler,
then another, and so on.
Initialize variables inside the loop statement if they are not needed outside
Instead of this:
int currentLongest = 0, idx = 0;
for (int i=0; i<s.length(); i++){
This is better:
int currentLongest = 0;
for (int i=0, idx = 0; i<s.length(); i++){
Because idx is only used inside the loop.
If it's declared in the loop statement,
that makes it impossible to use it outside by mistake.
Use simpler natural names
Some of the variable names are a bit complex or cryptic, for example:
In currentLongest the term "current" is redundant, because there are no "other kind of longest" in the code. So it could be simply longest.
idx, is basically the start index of a sequence of unique characters. So it could be start or left.
strLen is a cryptic name. It contains a length, so it could be simply length.
idxOf... of what? It's the last index of the current char, so it could be lastIndex.
Alternative implementation
Eliminating the unnecessary string copies,
and applying other ideas from above:
int longest = 0;
for (int i = 0, left = 0; i < s.length(); i++) {
int lastIndex = s.lastIndexOf(s.charAt(i), i - 1); | {
"domain": "codereview.stackexchange",
"id": 44466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
java
if (lastIndex >= left) {
left = lastIndex + 1;
} else {
int length = i + 1 - left;
longest = Math.max(longest, length);
}
}
return longest; | {
"domain": "codereview.stackexchange",
"id": 44466,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java",
"url": null
} |
c++, recursion, template, c++20, constrained-templates
Title: A recursive_transform Template Function with Unwrap Level for Various Type Arbitrary Nested Iterable Implementation in C++
Question: This is a follow-up question for A recursive_transform Template Function Implementation with std::invocable concept in C++ and A recursive_transform Template Function Implementation with recursive_invoke_result_t and std::ranges::transform in C++. Besides the version using std::invocable, I am attempting to implement another type recursive_transform function with the unwrap level parameter so that the usage like recursive_transform<1>(Ranges, Lambda) is available.
The experimental implementation
The experimental implementation of recursive_transform function with the unwrap level parameter is as follows.
// 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; | {
"domain": "codereview.stackexchange",
"id": 44467,
"lm_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_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)
{
recursive_invoke_result_t<F, T> 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<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return f(input);
}
}
Test cases
// non-nested input test, lambda function applied on input directly
int test_number = 3;
std::cout << recursive_transform<0>(test_number, [](auto&& element) { return element + 1; }) << std::endl;
// 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() << std::endl;
// 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
std::cout << "std::vector<int> -> std::vector<std::string>: " +
recursive_transform_result.at(0) << std::endl; // 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 << std::endl; // std::string element to int | {
"domain": "codereview.stackexchange",
"id": 44467,
"lm_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::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) << std::endl; // 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) << std::endl;
// 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
std::cout << "string: " + recursive_transform_result4.at(0).at(0) << std::endl;
// 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() << std::endl; | {
"domain": "codereview.stackexchange",
"id": 44467,
"lm_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::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() << std::endl;
The output of the test code above:
4
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
Full Testing Code
The full testing code:
#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>
// 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; | {
"domain": "codereview.stackexchange",
"id": 44467,
"lm_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_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)
{
recursive_invoke_result_t<F, T> 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<unwrap_level - 1>(element, f); }
);
return output;
}
else
{
return f(input);
}
}
int main()
{
// non-nested input test, lambda function applied on input directly
int test_number = 3;
std::cout << recursive_transform<0>(test_number, [](auto&& element) { return element + 1; }) << std::endl;
// 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() << std::endl;
// 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": 44467,
"lm_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) << std::endl; // 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 << std::endl; // 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) << std::endl; // 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) << std::endl;
// 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": 44467,
"lm_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) << std::endl;
// 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() << std::endl;
// 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() << std::endl;
return 0;
}
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 Implementation with std::invocable concept in C++ and
A recursive_transform Template Function Implementation with recursive_invoke_result_t and std::ranges::transform in C++
What changes has been made in the code since last question?
The type recursive_transform function with the unwrap level parameter is the main idea here.
Why a new review is being asked for?
If there is any possible improvement, please let me know. | {
"domain": "codereview.stackexchange",
"id": 44467,
"lm_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: Use std::invoke()
I missed this in my reviews of your earlier code, but std::invoke(f, a) is not always the same as f(a). And especially if you use std::invoke_result_t to deduce the return type of calling f, you should use std::invoke().
Pass a range to std::ranges::transform()
The nice thing about std::ranges algorithms is that they can take a range as a parameter instead of two iterators. So I would write:
std::ranges::transform(
input,
std::inserter(output, std::ranges::end(output)),
[&f](auto&& element) { return recursive_transform<unwrap_level - 1>(element, f); }
);
Missing support for arrays and some other container types
Your recursive_invoke_result does not handle std::array<> and regular arrays. Recently, user Davislor created a recursive transform implementation based on your code that does handle this, see this answer.
Try to handle incorrect unwrap levels more gracefully
If unwrap_level is higher than the nesting level of the given container, then a compile error will happen when trying to call std::ranges::cbegin() on a non-container value. This happens deep within nested calls to recursive_transform(), so it will probably produce a horrible error message. It might be possible to add a requires clause that checks right at the outer call whether unwrap_level is not higher than the nesting level of input. If not, then a static_assert() would be another option. | {
"domain": "codereview.stackexchange",
"id": 44467,
"lm_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
} |
elisp
Title: elisp function to replace text in an org file
Question: I've made a little function for myself that replaces certain variables to text in an org file. I declare a bunch of variables in the beginning of the file and then the function replaces all references to the variable with the value. So for example
#+VAR:location=AAAAAA
text text text \v{location} text text text
becomes
text text text AAAAAA text text text
It's my first time really playing with elisp and I'm wondering if I used the language correctly and if there's possibility to improvement.
(defun mp/org-fill-variables ()
"Fill in the variables"
(interactive)
(let ((variable-count 0))
(goto-char 0)
(while (search-forward-regexp "^#\\+VAR:" nil t)
(set-mark-command nil)
(when (search-forward "=")
(backward-char)
(let ((variable (buffer-substring (region-beginning) (region-end))))
(forward-char)
(set-mark-command nil)
(end-of-line)
(let ((value (buffer-substring (region-beginning) (region-end))))
;; todo check if value non-nil
(replace-string-in-region (concat "\\v{" variable "}") value)
(setq variable-count (1+ variable-count))))))
(message "replaced %d variables" variable-count)))
Answer: You can make a better (interactive) declaration. Because this modifies the buffer, we want to disable it on read-only buffers. We do that this way:
(interactive "*")
Consider making the the function work within the active region, rather than the whole buffer:
(defun mp/org-fill-variables (start end)
"Fill in the variables"
(interactive "*r") | {
"domain": "codereview.stackexchange",
"id": 44468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "elisp",
"url": null
} |
elisp
search-forward-regexp is an alias for built-in function re-search-forward. I would prefer the latter as that's more familiar to other programmers. At first, I thought you had used one of the interactive functions.
We shouldn't be meddling with user's mark or position, so wrap the whole function in (save-excursion ), and don't use the interactive functions (forward-char) or (end-of-line).
(goto-char 0) is almost always wrong. Use (goto-char (point-min)) so that we do the Right Thing when narrowing is in effect.
Instead of (buffer-substring), we can get the variable name from the match results. That also allows us to be more specific about what a variable name looks like (e.g. no newlines):
(while (re-search-forward "^#\\+VAR:\\(.+\\)=\\(.+\\)" nil t)
(let ((name (match-string 1))
(value (match-string 2)))
Consider counting the number of replacements as well as the number of variables found.
Modified code:
(defun mp/org-fill-variables (start end)
"Fill in the variables."
(interactive "*r")
(save-excursion
(let ((variable-count 0)
(replacement-count 0))
(goto-char start)
(while (re-search-forward "^#\\+VAR:\\(.+\\)=\\(.+\\)" nil t)
(let* ((name (match-string 1))
(value (match-string 2))
(replaced (replace-string-in-region (concat "\\v{" name "}") value
start end)))
(setq variable-count (+ variable-count (if replaced 1 0))
replacement-count (+ replacement-count (or replaced 0)))))
(message "Replaced %d variable(s) in %d location(s)"
variable-count replacement-count)))) | {
"domain": "codereview.stackexchange",
"id": 44468,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "elisp",
"url": null
} |
c++, floating-point
Title: Floating point approximately equal
Question: I implemented the following code for determining if two floating point numbers are equal is_float_equal(...). It handles the tests for my use cases well, but I was wondering if the community could provide feedback on the implementation and its correctness?
My objectives are to consider two floating pointer numbers (represented by value_t) equal if their difference is subnormal or their difference is less than machine epsilon scaled by the largest number.
// feb 16 417 PM
#include <iostream>
#include <iomanip>
#include <cassert>
#include <limits>
#include <cmath>
#include <fstream>
std::fstream llog("out.txt", std::ios::out);
// https://en.cppreference.com/w/cpp/types/numeric_limits/epsilon
// https://stackoverflow.com/questions/17333/what-is-the-most-effective-way-for-float-and-double-comparison
// https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
/**
* @brief compares l and r floating point values for equality
* @param l the left value
* @param r the right value
* @returns true if l is equal to r
*/
template <typename value_t>
bool is_float_equal(value_t l, value_t r)
{
// https://en.cppreference.com/w/cpp/numeric/math/isnan
if (std::isnan(l) || std::isnan(r))
{
return false;
}
// https://en.cppreference.com/w/cpp/numeric/math/isinf
if (std::isinf(l) && std::isinf(r))
{
return l == r; // NOLINT
}
if (l < r)
{
value_t const t{l};
l = r;
r = t;
}
value_t const d{l - r};
value_t constexpr e{std::numeric_limits<value_t>::epsilon()};
value_t constexpr m{std::numeric_limits<value_t>::min()};
return d <= m || d <= l * e;
} | {
"domain": "codereview.stackexchange",
"id": 44469,
"lm_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++, floating-point",
"url": null
} |
c++, floating-point
void tests()
{
float const inf{std::numeric_limits<float>::infinity()};
assert(-inf == -inf && is_float_equal(-inf, -inf));
assert(-inf != inf && !is_float_equal(-inf, inf));
assert(inf != -inf && !is_float_equal(inf, -inf));
assert(inf == inf && is_float_equal(inf, inf));
float const zn{-0.0f};
float const zp{0.0f};
assert(zn == zn && is_float_equal(zn, zn));
assert(zp == zn && is_float_equal(zp, zn));
assert(zp == zp && is_float_equal(zp, zp));
assert(std::nextafter(zn, zp) == zp);
}
int main()
{
tests();
using value_t = float;
value_t constexpr e{std::numeric_limits<value_t>::epsilon()};
value_t constexpr max{std::numeric_limits<value_t>::max()};
value_t constexpr m{std::numeric_limits<value_t>::min()};
value_t l{std::numeric_limits<value_t>::lowest()};
value_t r{l};
value_t d{0};
unsigned long long ec{0};
unsigned long long tc{0};
std::cout << std::fixed << std::setprecision(50) << l << ' ' << r << ' ' << e << '\n';
while (r < max)
{
// https://en.wikipedia.org/wiki/Floating-point_arithmetic
// https://peps.python.org/pep-0485/
float d{r - l};
while (d <= m || std::abs((r - l) / r) <= e)
{
r = std::nextafter(r, max);
d = r - l;
} | {
"domain": "codereview.stackexchange",
"id": 44469,
"lm_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++, floating-point",
"url": null
} |
c++, floating-point
++tc;
double const p{static_cast<double>(ec) / static_cast<double>(tc)};
std::cout << std::fixed << std::setprecision(50) << l << ' ' << r << ' ' << d << ' ' << p << '\n';
if (!is_float_equal(l, l))
{
llog << std::endl
<< "l not equal to l\n";
is_float_equal(l, l);
return EXIT_FAILURE;
}
if (is_float_equal(l, r))
{
++ec;
llog << std::endl
<< ec << '\n'
<< "l equal to r\n";
is_float_equal(l, r);
if (ec > 1000)
{
return EXIT_FAILURE;
}
}
l = r;
}
return EXIT_SUCCESS;
}
Answer: When we multiply epsilon by the largest number (absolute value, as noted in chux's answer), we end up with a value that's about std::nextafter(l) - l. So we can replace all that work by simply testing whether the numbers are adjacent according to std::nextafter:
#include <cmath>
#include <limits>
#include <concepts>
template<std::floating_point value_t> [[nodiscard]]
constexpr bool is_float_equal(value_t l, value_t r)
{
constexpr auto infinity = std::numeric_limits<value_t>::infinity();
auto const min = std::nextafter(l, -infinity);
auto const max = std::nextafter(l, infinity);
return (min <= r && r <= max);
}
Simpler still (thanks to Ilmari Karonen, we can just take advantage of std::nextafter() doing what we need in terms of the "direction" argument and just write
template<std::floating_point value_t> [[nodiscard]]
constexpr bool is_float_equal(value_t l, value_t r)
{
return r == std::nextafter(l, r);
}
No need to std::swap() the arguments or to special-case NaNs and infinities.
Works well close to ±0.
No multiplications.
Constexpr - which it should already have been.
Full compliance with the test suite (until my timeout of 60 seconds expired, anyway). | {
"domain": "codereview.stackexchange",
"id": 44469,
"lm_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++, floating-point",
"url": null
} |
c++, floating-point
Style comments:
There's a huge amount of output, which I had to disable to get a reasonable amount of the test suite to run. A good test should be silent when everything is correct, and only print the failures.
Failure messages should go to std::cerr, not std::cout.
I dislike the test program writing files on my system (doesn't matter that the file is empty - the fact it overwrites any existing file is bad enough).
Unused variable: value_t d{0};. Worse, it's shadowed by another d of the same type in smaller scope.
There's a couple of places we call is_float_equal() and don't use the result. Adding [[nodiscard]] identifies these. | {
"domain": "codereview.stackexchange",
"id": 44469,
"lm_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++, floating-point",
"url": null
} |
c++, overloading
Title: Comparison operator for ranges C++
Question: If you want to lexicographically compare two vectors in C++, you can simply write vec1 <=> vec2. But instead, if you want to compare them reversed, it is not as simple as writing (vec1 | std::views::reverse) <=> (vec2 | std::views::reverse). So, I decided to write comparison operators for ranges in C++.
This is what I came up with:
inline constexpr auto operator==(const std::ranges::range auto& range1,
const std::ranges::range auto& range2)
-> decltype(begin(range1) == begin(range2)) {
return std::equal(
begin(range1), end(range1), begin(range2), end(range2));
}
inline constexpr auto operator<=>(const std::ranges::range auto& range1,
const std::ranges::range auto& range2)
-> decltype(begin(range1) <=> begin(range2)) {
return std::lexicographical_compare_three_way(
begin(range1), end(range1), begin(range2), end(range2));
}
Are the above functions correct?
These are currently generating other equality and comparison operators synthetically. But should I explicitly declare them as defaulted? If want to do so, how?
The unqualified names begin, end in above code are calling functions in std:: namespace or std::ranges:: namespace? Should I explicitly prefix them with std::ranges:: namespace.
Should I put these in their own namespace? If I do so, then I have to explicitly write using namespace rangecomp;, since these are not being detected by even ADL. So what to do? | {
"domain": "codereview.stackexchange",
"id": 44470,
"lm_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++, overloading",
"url": null
} |
c++, overloading
Answer: It does seem quite bold to provide these operators as such wide-ranging templates, which match all ranges. Not necessarily wrong, but it makes me slightly nervous of unintended side-effects!
I do think we should at least be constraining to accept only input ranges, as std::equal() and std::lexicographical_compare_three_way() require.
I don't think we need to be writing the return types, as plain auto is fine here - both std::equal() and std::lexicographical_compare_three_way() return the types we want. Not doing so avoids us needing to write unqualified begin and end - we can make the usings local to the functions, rather than polluting global namespace.
If we're providing ==, we should also provide !=. We can't use = default, because it's a template, and if we leave it undefined, it will be synthesised from <=> rather than from ==.
Modified code
#include <algorithm>
#include <ranges>
inline constexpr auto operator==(const std::ranges::input_range auto& range1,
const std::ranges::input_range auto& range2)
{
using std::ranges::begin;
using std::ranges::end;
return std::equal(begin(range1), end(range1),
begin(range2), end(range2));
}
inline constexpr auto operator!=(const std::ranges::input_range auto& range1,
const std::ranges::input_range auto& range2)
{
return !(range1 == range2);
}
inline constexpr auto operator<=>(const std::ranges::input_range auto& range1,
const std::ranges::input_range auto& range2)
{
using std::ranges::begin;
using std::ranges::end;
return std::lexicographical_compare_three_way(begin(range1), end(range1),
begin(range2), end(range2));
}
#include <array>
#include <vector>
int main()
{
int const a[] = { 1, 2, 3 };
auto const v = std::vector{ 1, 2, 3 };
auto const vr = std::vector{ 3, 2, 1 }; | {
"domain": "codereview.stackexchange",
"id": 44470,
"lm_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++, overloading",
"url": null
} |
c++, overloading
return false
| ((a | std::views::all) <=> a) != std::strong_ordering::equivalent
| (a | std::views::reverse) != ( v | std::views::reverse)
| (v | std::views::reverse) != vr
| !(a == v)
| (a <=> v) != std::strong_ordering::equivalent
| v < a
| v > a
;
}
Answers to questions
The functions seem reasonable, though std::ranges::equal() might make a better choice for the first (there's no std::ranges::lexicographical_compare_three_way yet, due to the algorithm arriving at the same time as Ranges).
We can't default the other comparison operators because they are templates. We could write them all, but I think it's better to let the compiler default them.
Don't inhibit ADL by calling std::ranges::begin specifically - have using within the function as shown. (I might be wrong here, as niebloids have special ADL behaviour).
Yes, declare a namespace, but don't using namespace unless the comparisons are the only things in that namespace. Client code should just alias the specific names needed, and in the smallest reasonable scope (e.g. using my_comparators::operator<=>;). Enclosing in a namespace allows applications greater control over which parts of their code will match these very broad templates.
The functions should be detected by ADL - unless the view types you are using are not in that namespace (e.g. the standard view adapters in std::ranges::views). If you can create a minimal example of ADL failing for non-niebloid types in the same namespace, that would make a good question for Stack Overflow. | {
"domain": "codereview.stackexchange",
"id": 44470,
"lm_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++, overloading",
"url": null
} |
c++, parsing, raytracing
Title: Parser for a custom scene definition format for a raytracer
Question: For a raytracer I’ve been writing with a classmate, we use a custom scene definition format that allows specifying shapes, composite shapes, materials, lights, cameras and transform and render commands.
The assets of a scene (i.e. shapes, composite shapes, materials, lights and cameras) are stored in the data transfer object Scene. The task of this parser is to take a text file with the scene definition, parse its rules and transform them into objects which populate a Scene object.
A few pieces of the code I left out of simplicity, because I want the review to focus on the parsing strategy. Here is a list of these things and what they do.
Logger: A simple logger class (a singleton) that prints messages when in debug mode. It’s also possible to generate a log file of the currently stored messages
load_file(file_path): Takes a path as a string, loads the file and returns its content as a string
sanitize_inputs(file_string): Removes leading/trailing spaces, consecutive spaces, comments (starting with #, anywhere in the line) and empty lines
split(file_string, delimiter): Takes a string and splits it by a character. Returns a vector of strings
order_rule_vector(rule_vector): Some rules in the scene definition format depend on other rules. To allow the user to write them out in any order, the vector of rules is partitioned first so that rules with dependencies come after their dependants
Also I left out the code for parsing lights, cameras, transform commands and render commands, because the strategy is identical to what’s shown in the code below.
Scene Definition Format
Our raytracer will implement the Phong reflection model. Currently there are regular spheres and axis-aligned boxes.
# name, ambient, diffuse, specular terms, shininess
define material red 1 0 0 1 0 0 1 0 0 1
# name, min, max positions, material name
define shape box b1 -100 -80 -20 1002 80 -100 red | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
c++, parsing, raytracing
# name, min, max positions, material name
define shape box b1 -100 -80 -20 1002 80 -100 red
# name, center position, radius, material name
define shape sphere s1 0 0 -100 50 blue
# name, shape(s)
define shape composite c1 b1 s1
The Parser
std::shared_ptr<Scene> load_scene(std::string const& file_path) {
std::shared_ptr<Scene> scene = std::make_shared<Scene>();
auto logger = Logger::instance();
logger->log("-- Start. Parsing scene: " + file_path);
std::string file_string = load_file(file_path);
sanitize_inputs(file_string);
std::vector<std::string> rule_vector = split(file_string, '\n');
order_rule_vector(rule_vector);
std::istringstream iss{ file_string };
for (auto&& rule : rule_vector) {
std::istringstream rule_stream{ rule };
std::string command;
rule_stream >> command;
if (command == "define") {
std::string define_target;
rule_stream >> define_target;
if (define_target == "material") {
std::string mat_name;
rule_stream >> mat_name;
if (scene->materials.find(mat_name) != scene->materials.end()) {
logger->log("Warning: Duplicate material '" + mat_name + "' was skipped.");
continue;
}
Color ambient, diffuse, specular;
double shininess;
rule_stream >> ambient.r;
rule_stream >> ambient.g;
rule_stream >> ambient.b;
rule_stream >> diffuse.r;
rule_stream >> diffuse.g;
rule_stream >> diffuse.b;
rule_stream >> specular.r;
rule_stream >> specular.g;
rule_stream >> specular.b;
rule_stream >> shininess;
logger->log("--- Adding material: " + mat_name); | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
c++, parsing, raytracing
logger->log("--- Adding material: " + mat_name);
auto material = std::make_shared<Material>(
mat_name, ambient, diffuse, specular, shininess
);
if (!scene->materials.insert({ mat_name, material }).second) {
logger->log("Error: Material '" + mat_name
+ "' wasn't added to the scene object.");
}
} else if (define_target == "shape") {
std::string shape_type, shape_name;
rule_stream >> shape_type;
rule_stream >> shape_name;
std::shared_ptr<Shape> shape;
if(shape_type == "sphere") {
glm::vec3 center;
double radius = 1.0;
rule_stream >> center.x;
rule_stream >> center.y;
rule_stream >> center.z;
rule_stream >> radius;
std::string mat_name;
rule_stream >> mat_name;
std::shared_ptr<Material> material;
if(scene->materials.find(mat_name) == scene->materials.end()) {
logger->log("--- Warning: Material '" + mat_name
+ "' not found. Using default material instead.");
material = std::make_shared<Material>();
} else {
material = scene->materials[mat_name];
}
shape = std::make_shared<Sphere>(shape_name, material, center, radius);
} else if(shape_type == "box") {
glm::vec3 min, max;
rule_stream >> min.x;
rule_stream >> min.y;
rule_stream >> min.z;
rule_stream >> max.x;
rule_stream >> max.y;
rule_stream >> max.z; | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
c++, parsing, raytracing
std::string mat_name;
rule_stream >> mat_name;
std::shared_ptr<Material> material;
if(scene->materials.find(mat_name) == scene->materials.end()) {
logger->log("--- Warning: Material '" + mat_name
+ "' not found. Using default material instead.");
material = std::make_shared<Material>();
} else {
material = scene->materials[mat_name];
}
shape = std::make_shared<Box>(shape_name, material, min, max);
} else if (shape_type == "composite") {
std::string child_token;
Composite comp{ shape_name };
while (std::getline(rule_stream, child_token, ' ')) {
// Leading/trailing spaces result in empty strings
// being part of the tokens
if (child_token == "") {
continue;
}
auto search_it = scene->shapes.find(child_token);
if (search_it == scene->shapes.end()) {
logger->log("Error: Shape '" + child_token + "' for composite "
+ comp.name() + " not found.");
continue;
}
if (!comp.add(search_it->second)) {
logger->log("Error: Shape '" + child_token
+ "' was not added to composite " + comp.name());
continue;
}
}
} else {
logger->log("--- Warning: Skipping unknown shape type " + shape_type);
continue;
} | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
c++, parsing, raytracing
logger->log("--- Adding shape " + shape_name);
if (!scene->shapes.insert({ shape_name, shape }).second) {
logger->log("Error: Shape " + shape_name
+ " wasn't added to the scene object.");
}
} else if (define_target == "light") {
// Parse lights
} else if (define_target == "camera") {
// Parse cameras
} else {
logger->log("--- Warning: Skipping unknown define target " + define_target);
continue;
}
} else if (command == "transform") {
// Parse transform commands
} else if (command == "render") {
// Parse render commands
} else {
logger->log("--- Skipping unknown command " + command);
continue;
}
}
logger->log("-- Success. Scene parsed completely.");
return scene;
}
I don’t like that code. It’s a branch nightmare. I write rule_stream >> a lot. Also there are especially redundant pieces in there which I have to refactor.
An example would be parsing the shapes, more precisely which materials they use. I check a map for the materials name and use the pointer that’s stored there. The same code appears twice (once for spheres, once for boxes). That’s bad. One idea to solve this is to put the material name right after the shapes name. Then I can check for existance of the material before branching into the sphere and box cases.
Are there better approaches to parse such simple, regular languages like our scene definition format? What else can I improve?
Answer: Getting rid of the branches
I don’t like that code. It’s a branch nightmare.
Yes, let's get rid of the branches. Consider that all the branches are in the form of:
if (command == "foo") {
// parse rule_stream further
…
} | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
c++, parsing, raytracing
When you have a sequence of homogenous if/else statements like that, there are alternatives to consider. One would be a switch-statement, but those unfortunately only work with integers and enums. Another option would be to create a map from strings to std::functions:
using ParseFunction = std::function<void(std::istream&, Scene*)>;
static const std::unordered_map<std::string, ParseFunction> commands = {
{"define", parse_define},
{"transform", parse_transform},
{"render", parse_render},
};
Then inside load_scene(), you would write something like:
std::string command;
rule_stream >> command;
auto it = commands.find(command);
if (it != commands.end()) {
auto parse_function = it->second;
parse_function(rule_stream, scene->get());
} else {
logger->log("--- Skipping unknown command " + command);
continue;
}
Then you can define a function for each command, for example:
void parse_define(std::istream& rule_stream, Scene* scene) {
std::string define_target;
rule_stream >> define_target;
…
scene->materials.insert(…);
…
}
That shows how to get rid of the outer ifs. You can also do the same for targets and shapes.
Avoiding writing rule_stream >>
I write rule_stream >> a lot.
This is because you are reading each individual value. You can write your own overloads of operator>>() for the types you are using. For example:
std::istream& operator>>(std::istream& is, glm::vec3 &v) {
return is >> v.x >> v.y >> v.z;
}
And then you can write:
glm::vec3 min, max;
rule_stream >> min >> max; | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
c++, parsing, raytracing
And then you can write:
glm::vec3 min, max;
rule_stream >> min >> max;
Split up large functions
Another reason your code looks bad is because everything is in one huge function. It is easy to lose overview. The techniques I've shown above already introduce new functions that in turn simplify your load_scene(). But even without those you could have split up the function yourself:
static void parse_define(std::istream& rule_stream, Scene* scene) {
…
}
…
static void parse_rule(const std::string& rule, Scene* scene) {
std::istringstream rule_stream{ rule };
std::string command;
rule_stream >> command;
if (command == "define") {
parse_define(rule_stream, scene):
} else if (command == "transform") {
…
} …
};
std::shared_ptr<Scene> load_scene(std::string const& file_path) {
…
for (auto&& rule : rule_vector) {
parse_rule(rule, scene->get());
}
return scene;
}
Are the std::shared_ptrs necessary?
I see you use std::shared_ptrs a lot. But are they really necessary? You could have load_scene() return a Scene directly; even without C++17's guaranteed copy elision, if Scene has a move constructor, it could move all its contents efficiently to the caller. If you do need a smart pointer because of polymorphism, consider whether you can just use astd::unique_ptr instead of the more expensive std::shared_ptr.
Let's have a look at scene->materials. This looks like a std::map or std::unordered_map. These containers will already do memory management for you, and pointers to values stored in the map are guaranteed to be stable. So if it was defined as:
struct Scene {
…
std::unordered_map<std::string, Material> materials;
…
};
The code in your parser could be simplified a lot:
std::string mat_name;
Color ambient, diffuse, specular;
float shininess;
rule_stream >> mat_name >> ambient >> diffuse >> specular >> shininess; | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
c++, parsing, raytracing
rule_stream >> mat_name >> ambient >> diffuse >> specular >> shininess;
auto result = scene->materials.try_emplace(
mat_name, mat_name, ambient, diffuse, specular, shininess
);
if (!result.second) {
logger->log("Error: Material '" + mat_name + "' wasn't added to the scene object.");
}
(I used C++17's try_emplace() here, you can achieve the same in other ways in earlier versions of C++, but less elegantly).
If you ensure any material used by shapes is in scene->materials before the shapes using them are added, then you can just store a reference to the Material in a Shape instead of using a std::shared_ptr.
If you have a default constructor and an operator>> overload for Material, then you could also consider writing:
Material mat;
rule_stream >> mat;
if (scene->materials.try_emplace(mat.name(), mat) {
logger->log("Error: Material '" + mat.name() + "' wasn't added to the scene object.");
}
Do you really need to order the rules first?
You are ordering the rules before parsing them. That means you have to read the whole file in memory first. But do you really need that? I see you are already handling missing materials, by assigning a default constructed Material to a Shape. But why not add that default Material under the given name to scene->materials, and then when you later do encounter the rule defining that Material, just update it in place?
if (define_target == "shape") {
if (shape_type == "sphere") {
…
auto& material = scene->materials[mat_name];
shape = std::make_unique<Sphere>(shape_name, material /* reference */, center, radius);
}
…
} else if (define_target == "material") {
…
auto& material = scene->materials[mat_name];
material = {mat_name, ambient, diffuse, specular, shininess};
} … | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
c++, parsing, raytracing
You can then do error checking afterwards: any material in scene->materials that is still just default constructed was added by a "shape" target, but there was never a matching "material" target.
About parser generators
Dan Oberlam suggested Boost Spirit. This allows defining a grammar for a language completely inside C++. There are also external tools that can generate a parser written in C++ for you, like GNU Bison. These can be very helpful, especially for more complex grammars. The one you are trying to parse looks simple enough though that it probably is easier to write your own parser in C++. | {
"domain": "codereview.stackexchange",
"id": 44471,
"lm_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++, parsing, raytracing",
"url": null
} |
python, design-patterns, pandas, vectorization
Title: Replace personal names and addresses with company ones
Question: The problem:
I am given a data frame. Somewhere in that dataframe there is 3*N
number of columns that I need to modify based on a condition. The
columns of interest look like this:
names_1
address_1
description_1
names_2
address_2
...
Joe
joe_address
...
George
...
...
Kate
kate_address
...
Daphne
...
...
Bob
bob_address
...
Jake
...
...
I can generate this with the following code:
import pandas as pd
names_dict = {'names_1':['Joe', 'Kate', 'Bob'],
'address_1':['a1', 'a2', 'a3'],
'description_1':['d1', 'd2', 'd3'],
'names_2':['George', 'Daphne', 'Jake'],
'address_2':['a4', 'a5', 'a6'],
'description_2':['d4', 'd5', 'd6']}
df = pd.DataFrame(data=names_dict)
There is also a dictionary that I need to use. The keys to that
dictionary are names of some companies. Each key has a list of names
attached. It looks like this:
companies_dict = {'company1': ['Kate', 'Mark', 'Ben'],
'company2':['Jacob', 'Michael', 'Ken'],
'company3':['Jake', 'Don', 'Joe']}
I need to go over all names_k columns. If I encounter a
name that is in one of the companies lists, I swap the name of that
person with the name of that company. Moreover, I swap the address
and description of that person with the address and the description of
that company.
Here are dictionaries to use for this purpose:
companies_descriptions = {'company1': 'company1_desc',
'company2': 'company2_desc',
'company3': 'company3_desc'}
companies_addresses = {'company1': 'company1_address',
'company2': 'company2_address',
'company3': 'company3_address'} | {
"domain": "codereview.stackexchange",
"id": 44472,
"lm_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, design-patterns, pandas, vectorization",
"url": null
} |
python, design-patterns, pandas, vectorization
Note: The columns are somewhere in the dataframe, but they are next
to each other. That is, the names_1 all the way to description_N
are next to each other.
My solution:
I wrote the following Python code.
N = 2
number_of_columns = N
for k in range(1, number_of_columns+1):
for index, name in enumerate(df[f'names_{k}']):
for company, name_list in companies_dict.items():
if name in name_list:
df.loc[index, f'names_{k}'] = company
df.loc[index, f'address_{k}'] = companies_descriptions.get(company)
df.loc[index, f'description_{k}'] = companies_addresses.get(company)
Note:
We can safely assume that each person's name is
unique. So no two companies have the same employee.
N = 2 is an arbitrary value. Should work for any int>=1. It dictates how many columns (named names_k) there are and is defined by a separate process. N = 2 is given here as an example.
My solution is ugly, but it solves the problem. How to write it better?
Here is the whole code to copy:
import pandas as pd
names_dict = {'names_1':['Joe', 'Kate', 'Bob'],
'address_1':['a1', 'a2', 'a3'],
'description_1':['d1', 'd2', 'd3'],
'names_2':['George', 'Daphne', 'Jake'],
'address_2':['a4', 'a5', 'a6'],
'description_2':['d4', 'd5', 'd6']}
df = pd.DataFrame(data=names_dict)
companies_dict = {'company1': ['Kate', 'Mark', 'Ben'],
'company2':['Jacob', 'Michael', 'Ken'],
'company3':['Jake', 'Don', 'Joe']}
companies_descriptions = {'company1': 'company1_desc',
'company2': 'company2_desc',
'company3': 'company3_desc'}
companies_addresses = {'company1': 'company1_address',
'company2': 'company2_address',
'company3': 'company3_address'} | {
"domain": "codereview.stackexchange",
"id": 44472,
"lm_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, design-patterns, pandas, vectorization",
"url": null
} |
python, design-patterns, pandas, vectorization
N = 2
number_of_columns = N
for k in range(1, number_of_columns+1):
for index, name in enumerate(df[f'names_{k}']):
for company, name_list in companies_dict.items():
if name in name_list:
df.loc[index, f'names_{k}'] = company
df.loc[index, f'address_{k}'] = companies_descriptions.get(company)
df.loc[index, f'description_{k}'] = companies_addresses.get(company)
Answer: The question
It's unhelpful, in a handful of ways:
It presents you data that are shaped in an unhelpful way
It implies the use of non-vectorised dictionary lookups
It implies the use of non-vectorised iteration
What you're really doing is building up a dataframe of merged contacts, but the question does not describe this
Since you claim this is not from a course, and from your own scenario, this is somewhat an x/y problem: you asked how to do x when you shouldn't do x at all, and should do y instead.
The existing code
Get rid of all of your for-loops. Get rid of all of your dictionary lookups. Get rid of element-wise reassignment.
Vectorised approach
You've tagged your question vectorization, but the language of the problem statement is not guiding you toward this, and your own solution (perhaps unsurprisingly) is not vectorised - but it should be.
This will be done in, roughly, the following steps:
Fix the broken column representation in the first dataframe
Load the other dictionaries into dataframes with sensible indices and columns
Left-merge to get a porous merged-dataframe
fillna to substite where possible
Suggested
import pandas as pd | {
"domain": "codereview.stackexchange",
"id": 44472,
"lm_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, design-patterns, pandas, vectorization",
"url": null
} |
python, design-patterns, pandas, vectorization
Suggested
import pandas as pd
# You are given a data frame. Somewhere in that dataframe there is 3*N number of columns
contacts: pd.DataFrame = pd.DataFrame({
'names_1': ('Joe', 'Kate', 'Bob'),
'address_1': ('a1', 'a2', 'a3'),
'description_1': ('d1', 'd2', 'd3'),
'names_2': ('George', 'Daphne', 'Jake'),
'address_2': ('a4', 'a5', 'a6'),
'description_2': ('d4', 'd5', 'd6'),
})
contacts.columns = pd.MultiIndex.from_frame(
contacts.columns.str.extract(r'(.+)_(\d+)$'),
names=('property', 'contact_group'),
)
contacts.index.name = 'contact'
# There is also a dictionary that you need to use. The keys to that dictionary
# are names of some companies. Each key has a list of names attached.
companies_dict = {
'company1': ('Kate', 'Mark', 'Ben'),
'company2': ('Jacob', 'Michael', 'Ken'),
'company3': ('Jake', 'Don', 'Joe'),
}
company_employees: pd.Series = pd.DataFrame(companies_dict).stack()
company_employees.index.names = 'employee', 'company_name'
company_employees.name = 'employee_name'
# you swap the address and description of that person with the address and the
# description of that company. Here are dictionaries to use for this purpose:
companies_descriptions = {
'company1': 'company1_desc',
'company2': 'company2_desc',
'company3': 'company3_desc',
}
companies_addresses = {
'company1': 'company1_address',
'company2': 'company2_address',
'company3': 'company3_address',
}
companies = pd.DataFrame.from_dict({
'description': companies_descriptions,
'address': companies_addresses,
})
companies.index.name = 'company_name'
# You need to iterate over all [employee] names_k columns. If you encounter an [employee] name that
# is in one of the companies lists, you swap the name of that person with the name of that company.
# Moreover, you swap the address and description of that person with the address and the description
# of that company. | {
"domain": "codereview.stackexchange",
"id": 44472,
"lm_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, design-patterns, pandas, vectorization",
"url": null
} |
python, design-patterns, pandas, vectorization
employees_with_company_properties = pd.merge(
left=company_employees, right=companies,
left_on='company_name', right_on='company_name'
)
contacts_long = contacts.stack(level='contact_group')
contacts_merged = pd.merge(
left=contacts_long, right=employees_with_company_properties.reset_index(),
left_on='names', right_on='employee_name',
suffixes=('_employee', '_company'),
how='left',
).set_index(contacts_long.index)
contacts_replaced = contacts_merged[[
'company_name', 'address_company', 'description_company'
]].rename(columns={
'company_name': 'names',
'address_company': 'address',
'description_company': 'description',
}).fillna(
contacts_merged[['names', 'address_employee', 'description_employee']]
.rename(columns={
'address_employee': 'address',
'description_employee': 'description',
})
).unstack(
level='contact_group'
).sort_values('contact_group', axis=1)
pd.set_option('display.max_columns', 10)
pd.set_option('display.width', 1000)
print(contacts_replaced)
Output
names address description names address description
contact_group 1 1 1 2 2 2
contact
0 company3 company3_address company3_desc George a4 d4
1 company1 company1_address company1_desc Daphne a5 d5
2 Bob a3 d3 company3 company3_address company3_desc | {
"domain": "codereview.stackexchange",
"id": 44472,
"lm_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, design-patterns, pandas, vectorization",
"url": null
} |
php, mysql, laravel
Title: Three way Eloquent relationship definition and saving in Laravel
Question: I'm building a Laravel app (with Vue3 and InertiaJS), and I'm attempting to create relationships between three models:
User
Area
WorkHours
where WorkHours is the primary model. In addition to the main data (date, hours, comments, reason), I need to create the following relationships:
User - the WorkHours entry is for work performed by the member (aka User), so I need to be able to see total hours for the user for the year. One user can have many WorkHours records.
Area - The part of the club that the work hours has been performed in/for. Each WorkHours entry has one approver, and one approver can be associated with many WorkHours entries.
Approver - Every Area has specific people that can approve WorkHours entries, and these are defined as approvers in the Area model related to the User model as approver_id (a belongstoMany() relationship both ways). Each WorkHours entry has one approver, but one approver can be associated with many WorkHours entries.
It seems then that the work_hours table should have _id values for each of the three relations (user_id, area_id, and approver_id). However, as I read the Eloquent docs, that means that WorkHours would be a child of both Area and Approver via belongsTo(), since the child gets the _id value of the parent.
So with all that here's the code:
work_hours migrations
public function up()
{
Schema::create('work_hours', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('area_id');
$table->unsignedBigInteger('approver_id');
$table->date('date');
$table->decimal('hours', 5, 2);
$table->string('reason')->nullable();
$table->string('comments')->nullable();
$table->timestamps();
$table->softDeletes(); | {
"domain": "codereview.stackexchange",
"id": 44473,
"lm_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, mysql, laravel",
"url": null
} |
php, mysql, laravel
$table->foreign('user_id')
->references('id')
->on('users');
$table->foreign('approver_id')
->references('id')
->on('users');
$table->foreign('area_id')
->references('id')
->on('areas');
});
}
WorkHours
class WorkHours extends Model
{
use HasFactory, SoftDeletes;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
'date',
'hours',
'reason',
'comments'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function approver()
{
return $this->belongsTo(User::class, 'approver_id');
}
public function area()
{
return $this->belongsTo(Area::class);
}
}
Area
class Area extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'name'
];
public function approvers()
{
return $this->belongsToMany(User::class, 'area_user', 'area_id', 'user_id');
}
public function workHours()
{
return $this->hasMany(WorkHours::class);
}
}
User
class User extends Authenticatable
{
public function workHours()
{
return $this->hasMany(WorkHours::class);
}
public function areas() {
return $this->belongsToMany(Area::class);
}
public function approval()
{
return $this->belongsTo(WorkHours::class, 'approver_id');
}
}
Now where I'm running into the problem is saving everything when I submit my form to my controller. From my form I have the following pieces of info
user_id
area_id
approver_id
date
hours
reason
comments
So based on the docs, I would think I would do something like this in WorkHoursController:
public function store(StoreWorkHoursRequest $request)
{
$validated = $request->validated(); | {
"domain": "codereview.stackexchange",
"id": 44473,
"lm_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, mysql, laravel",
"url": null
} |
php, mysql, laravel
$user = User::find($validated['user']);
$area = Area::find($validated['area']);
$approver = User::find($validated['approver']);
$wh = WorkHours::make([
'date' => $validated['date'],
'hours' => $validated['hours'],
'reason' => $validated['reason'],
'comments' => $validated['comments']
]);
$wh->user()->associate($user);
$wh->area()->associate($area);
$wh->approver()->associate($approver);
return Redirect::route('workHours.index')->with('success', 'Work Hours saved');
}
but I get an error about user_id not having a default value, which is true, since my understanding is that Eloquent handles assigning that. What I can do is make user_id, approver_id, and area_id fillable in the WorkHours model and save like this:
$wh = WorkHours::create([
'date' => $validated['date'],
'hours' => $validated['hours'],
'reason' => $validated['reason'],
'comments' => $validated['comments'],
'user_id' => $validated['user'],
'approver_id' => $validated['approver'],
'area_id' => $validated['area']
]);
and it works, but it is cloogy, and bypasses Eloquent.
Do I have my relationships set up properly for what I am trying to accomplish?
How do I need to store the records in my controller to properly use Eloquent?
Answer: My issue (as I suspected) was in a relationship definition. Once I changed the approval() definition in User from this
public function approval()
{
return $this->belongsTo(WorkHours::class, 'approver_id');
}
to this
public function approvals()
{
return $this->haMany(WorkHours::class, 'approver_id');
}
it worked fine. There was no user id value to write since the relationship for the approver was wrong, which was why it was looking for a default value. | {
"domain": "codereview.stackexchange",
"id": 44473,
"lm_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, mysql, laravel",
"url": null
} |
python, tkinter, canvas
Title: Python - Tkinter - Infinite Canvas World for drawing apps
Question: We have worked an idea out that seems to have a wide usecase and there seems to be no examples for it on the web for python tkinter. Having unlimited space to draw can be crucial and can be done wrong in many ways (trust me I tried I few before coming up with this example). However, I'm a hobby coder and just tried (the best of my knowledge) to solve this task for high performance and memory efficiency.
I would like you to review especially the performance and if possible provide solutions for it. Other constructive criticism of course is welcomed too.
It also would be interesting for what is a good use-case for this code or how you would improve the widget overall ?
Hope you have fun with it, like I had.
import tkinter as tk
class InfiniteCanvas(tk.Canvas):
'''
Initial idea by Nordine Lofti
https://stackoverflow.com/users/12349101/nordine-lotfi
written by Thingamabobs
https://stackoverflow.com/users/13629335/thingamabobs
The infinite canvas allows you to have infinite space to draw.
You can move around the world as follows:
- MouseWheel for Y movement.
- Shift-MouseWheel will perform X movement.
- Alt-Button-1-Motion will perform X and Y movement.
(pressing ctrl while moving will invoke a multiplier)
Additional features to the standard tk.Canvas:
- Keeps track of the viewable area
--> Acess via InfiniteCanvas().viewing_box()
- Keeps track of the visibile items
--> Acess via InfiniteCanvas().inview()
- Keeps track of the NOT visibile items
--> Acess via InfiniteCanvas().outofview()
Also a new standard tag is introduced to the Canvas.
All visible items will have the tag "inview"
''' | {
"domain": "codereview.stackexchange",
"id": 44474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, canvas",
"url": null
} |
python, tkinter, canvas
def __init__(self, master, **kwargs):
super().__init__(master, **kwargs)
self._xshifted = 0 #view moved in x direction
self._yshifted = 0 #view moved in y direction
self.configure(
confine=False, highlightthickness=0, bd=0)
self.bind('<MouseWheel>', self._vscroll)
self.bind('<Shift-MouseWheel>', self._hscroll)
self.winfo_toplevel().bind(
'<KeyPress-Alt_L>', self._alternate_cursor)
self.winfo_toplevel().bind(
'<KeyRelease-Alt_L>', self._alternate_cursor)
self.bind('<ButtonPress-1>', self._start_drag_scroll)
self.bind('<Alt-B1-Motion>', self._drag_scroll)
return None
def viewing_box(self) -> tuple:
'Returns a tuple of the form x1,y1,x2,y2 represents visible area'
x1 = 0 - self._xshifted
y1 = 0 - self._yshifted
x2 = self.winfo_reqwidth()-self._xshifted
y2 = self.winfo_reqheight()-self._yshifted
return x1,y1,x2,y2
def inview(self) -> set:
'Returns a set of identifiers that are currently viewed'
return set(self.find_overlapping(*self.viewing_box()))
def outofview(self) -> set:
'Returns a set of identifiers that are currently viewed'
all_ = set(self.find_all())
return all_ - self.inview()
def _alternate_cursor(self, event):
if (et:=event.type.name) == 'KeyPress':
self.configure(cursor='fleur')
elif et == 'KeyRelease':
self.configure(cursor='')
def _update_tags(self):
vbox = self.viewing_box()
self.addtag_overlapping('inview',*vbox)
inbox = set(self.find_overlapping(*vbox))
witag = set(self.find_withtag('inview'))
[self.dtag(i, 'inview') for i in witag-inbox]
self.viewing_box()
def _create(self, *args):
ident = super()._create(*args)
self._update_tags()
return ident | {
"domain": "codereview.stackexchange",
"id": 44474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, canvas",
"url": null
} |
python, tkinter, canvas
def _wheel_scroll(self, xy, amount):
cx,cy = self.winfo_rootx(), self.winfo_rooty()
self.scan_mark(cx, cy)
if xy == 'x': x,y = cx+amount, cy
elif xy == 'y': x,y = cx, cy+amount
name = f'_{xy}shifted'
setattr(self,name, getattr(self,name)+amount)
self.scan_dragto(x,y, gain=1)
self._update_tags()
def _drag_scroll(self,event):
xoff = event.x-self._start_drag_point_x
yoff = event.y-self._start_drag_point_y
self._xshifted += xoff
self._yshifted += yoff
gain = 1
if (event.state & 0x4) != 0: #if ctr/strg
gain = 2
self.scan_dragto(event.x, event.y, gain=gain)
self._start_drag_point_x = event.x
self._start_drag_point_y = event.y
self._update_tags()
def _start_drag_scroll(self,event):
self._start_drag_point_x = event.x
self._start_drag_point_y = event.y
self.scan_mark(event.x,event.y)
return
def _hscroll(self,event):
offset = int(event.delta/120)
if (event.state & 0x4) != 0: #if ctr/strg
offset = int(offset*10)
self._wheel_scroll('x', offset)
def _vscroll(self,event):
offset = int(event.delta/120)
if (event.state & 0x4) != 0:#if ctr/strg
offset = int(offset*10)
self._wheel_scroll('y', offset)
if __name__ == '__main__':
root = tk.Tk()
canvas = InfiniteCanvas(root)
canvas.pack(fill=tk.BOTH, expand=True)
size, offset, start = 100, 10, 0
canvas.create_rectangle(start,start, size,size, fill='green')
canvas.create_rectangle(
start+offset,start+offset, size+offset,size+offset, fill='darkgreen')
root.mainloop() | {
"domain": "codereview.stackexchange",
"id": 44474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, canvas",
"url": null
} |
python, tkinter, canvas
root.mainloop()
Answer: The code looks good and performance wise it is also pretty good, could handle about 1000 objects with relatively ease (of course depends on hardware and complexity of objects).
Some suggestions for improving the widget, avoid configuring the widget in __init__, since the user might want to add border, only configure options that may destroy the functionality of the widget. If you want another default value use setdefault on kwargs. For example:
kwargs.setdefault("highlightthickness", 0)
kwargs.setdefault("confine", False)
kwargs.setdefault("bd", 0)
super().__init__(master, **kwargs)
If the user want different scroll step sizes, add those as arguments when creating and configuring the InfiniteCanvas.
I tried adding a zoom functionality which worked great with the code you already have, first bind as usual self.bind('<Alt-MouseWheel>', self._zoom) then the function:
def _zoom(self, event: tk.Event):
zoom = self._zoom_step ** int(event.delta/120)
canvas.scale("all", self.canvasx(event.x), self.canvasy(event.y), zoom, zoom)
The self._zoom_step is just a user defined zooming speed, which in my case I used the default value of 1.2.
I see you have used type hints for all public functions, I would also suggest using type hints for all functions, both arguments and return type, if someone want to extend the widget. You could also be more precise on what is returned, e.g., tuple[int, int, int, int].
The bind on toplevel is a bit dangerous, for example if you want multiple InfiniteCanvas. You could use add=True to ensure it doesn't replace previous bindings, but then you need to remove them properly on destroy. Unfortunately I do not have any other ideas for handling this, but thought I could at least mention it.
I have before created map applications using e.g. https://www.openstreetmap.org/, and using the InfiniteCanvas with zoom would definitely be interesting. | {
"domain": "codereview.stackexchange",
"id": 44474,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, tkinter, canvas",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.