text stringlengths 1 2.12k | source dict |
|---|---|
c, networking, unix, posix
That makes it easier to temporarily change the flags used by commenting out lines.
We don't need a %.o: %.c rule, as Make already knows about that, and if we just call the executable selectserver then Make can infer that too.
log.o shouldn't depend on selectserver.h - instead of writing dependencies yourself, just ask GCC to do it as a side-effect of compilation, like this:
CFLAGS += -MD
-include $(wildcard *.d)
We're missing .PHONY and .DELETE_ON_ERROR targets, which makefiles always need.
A replacement makefile is a bit simpler:
# the compiler:
CC = gcc-10
# compiler flags:
CFLAGS += -std=c17
CFLAGS += -Wall
CFLAGS += -Wextra
CFLAGS += -Warray-bounds
CFLAGS += -Wconversion
CFLAGS += -Wmissing-braces
CFLAGS += -Wno-parentheses
CFLAGS += -Wpedantic
CFLAGS += -Wstrict-prototypes
CFLAGS += -Wwrite-strings
CFLAGS += -fanalyzer
CFLAGS += -fno-builtin
CFLAGS += -fno-common
CFLAGS += -fno-omit-frame-pointer
CFLAGS += -fsanitize=address
CFLAGS += -fsanitize=undefined
CFLAGS += -O2
CFLAGS += -MD
selectserver: selectserver.o log.o
clean:
$(RM) *.o *.d selectserver
-include $(wildcard *.d)
.PHONY: clean
.DELETE_ON_ERROR: | {
"domain": "codereview.stackexchange",
"id": 44377,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, networking, unix, posix",
"url": null
} |
c++, beginner
Title: Simple data processing program that performs a find and replace on a list of assembler macros | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner
Question: I'm a newb. I learned some C in high school, and using that to learn C++. I really didn't understand the use of OO, but I had a major enlightenment while working on this simple piece of code. I have refactored it in a more OO style and simplified it using C++ idioms to where it looks as clean as I can make it. I'm hoping for advice in terms of understanding basic C++/OO idioms that would be applicable to other projects. I'm not looking for advanced algorithm optimization. Also, I know well how to use sed and tr. :) This was a learning exercise.
This project operates on a struct containing a list of assembler commands and associated opcodes. The opcodes have shorthand characters, G through O which mark registers. The function of the program is to expand the list by replacing each of those shorthands with an expanded list of opcodes containing each valid register code. I replaced address codes with 0xAAAA as I didn't want to expand the entire address space many times over! The purpose was to build a fuzzer for a decompiler to ensure it processed all opcodes correctly. | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner
Initially, I wrote this more C style, passing a lot of references to functions for return values. I suddenly understood that by moving my functions and data into a class, I could simplify the code by not having to pass a bunch of extra references. So I built a class to contain a queue. Load an element into the queue, and read the data out. Reading the data out calls a method that performs the work by iterating over the internal queue buffer and pushing processed data back into queue until it's complete. I have a feeling recursion could also be used here, but it's not obvious to me how to make that work. I've tried to ensure const correctness, pass by reference to avoid copies where possible, and write in such a way as to get return value optimization. One thing I see now I could improve on is that I duplicated the push/pop mechanism of a std::vector. I probably could have used inheritance to implement that, but I don't quite understand how to do that yet.
#include <iostream>
#include <vector> | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner
const Instruction instructions[] = { // define each opcode instruction name pair.
{ "ANDC #xx:8,EXR", "014106MM"}
,{ "BAND #xx:3,@ERd", "7CG076P0"}
,{ "BAND #xx:3,@aa:8", "7ENN76P0"}
,{ "BAND #xx:3,@aa:16", "6A10NNNN76P0"}
,{ "BAND #xx:3,@aa:32", "6A30NNNNNNNN76P0"}
,{ "BCLR #xx:3,@aa:16", "6A18NNNN72P0"}
};
struct Instruction {
std::string name; //instruction name, longest I saw was 27 characters long.
std::string bytecode; //bytecode
};
class InstructionProcessQueue {
public:
void push(Instruction elementToAdd) {
processQueue.push_back(elementToAdd);
}
Instruction pop() {
if (empty()) exit(__LINE__); // Error check
currentInstruction = processQueue.back(); // Pull an element from the queue
processQueue.pop_back();
for (char& bytecodeElement : currentInstruction.bytecode) {
switch (bytecodeElement) {
case 'O': //ERn: 3 bits w preceding 1
case 'Q':
expandOpcode(bytecodeElement, 8, 15);
currentInstruction = processQueue.back();
processQueue.pop_back();
break;
case 'G': //ERn: 3 bits with preceding 0
case 'P': //3 bits with preceding 0
expandOpcode(bytecodeElement, 0, 7);
currentInstruction = processQueue.back();
processQueue.pop_back();
break;
case 'H': //Rn: 4 bits
expandOpcode(bytecodeElement, 0, 15);
currentInstruction = processQueue.back();
processQueue.pop_back();
break;
case 'L': //Address space, 8, 16, 32 bits.
case 'M':
case 'N':
expandOpcode(bytecodeElement, 10, 10); // Just insert 0xA
currentInstruction = processQueue.back();
processQueue.pop_back();
break;
}
}
return currentInstruction;
} | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner
const bool empty() const {
return processQueue.empty();
}
private:
const std::string Hex = "0123456789ABCDEF";
std::vector<Instruction> processQueue;
Instruction currentInstruction;
void expandOpcode(char& bytecodeElement, const int& begin, const int& end) {
for (int i = begin; i <= end; i++) {
bytecodeElement = Hex[i];
processQueue.push_back(currentInstruction);
}
}
};
int main() {
std::vector<Instruction> instrOutput;
InstructionProcessQueue queue;
for (const auto& i : instructions) { //Iterate over the const instruction list
queue.push(i); //Put the current element in the process queue
while (!queue.empty()) //Process the queue until empty
instrOutput.push_back(queue.pop());
for (auto& i : instrOutput) { //Iterate the output and clear it for the next loop
std::cout << i.name << ' ' << i.bytecode << std::endl;
}
instrOutput.clear();
}
} | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner
Answer: For a beginner in C++, your code is looking very good!
Define types before you use them
The code you posted doesn't compile because you are using the type Instruction before it is defined.
Consider throwing exceptions on errors
You call exit(__LINE__) if someone tries to pop from an empty queue, but that has several problems. First, you should #include <cstdlib> and call std::exit() instead, as otherwise the C++ standard does not guarantee that this function exists.
Second, return EXIT_FAILURE instead of __LINE__. Exit codes only have a limited range of possible values, but __LINE__ could be anything. If it has the wrong value it could potentially be truncated to zero, which would indicate success instead of failure.
Third, consider throwing an exception instead. If it is not handled, it will cause the program to terminate as well, potentially with a better error message if you use a standard exception type, like std::logic_error. It also gives the caller the opportunity to catch the exception, and potentially recover from the error.
Add a default case to your switch statement
You might want to add a default: break; to your switch statement to make it explicit that you want to ignore characters that don't match any case statement.
Note that some compilers might also warn if they see that you don't handle all possible values.
Don't store data unnecessarily
The variable currentInstruction is only used in pop() and in expandOpcode(), and the latter is only ever called from pop(). So outside of those functions, there is no need to store a currentInstruction. Make currentInstruction a local variable inside pop(), and also pass it as a parameter to expandOpcode().
Hex is only needed inside expandOpcode(), so move it into that function. Also make it static.
In main(), the vector instrOutput is not necessary. Instead you can just print the result from pulling from queue directly:
InstructionProcessQueue queue; | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner
for (const auto& instr_in : instructions) {
queue.push(instr_in);
while (!queue.empty()) {
auto instr_out = queue.pop();
std::cout << instr_out.name << ' ' << instr_out.bytecode << '\n';
}
}
Add commas after array items
When you define an array, it is more common to add the comma after each item. You are also allowed to add a comma after the last element. So:
const Instruction instructions[] = {
{ "ANDC #xx:8,EXR", "014106MM"},
{ "BAND #xx:3,@ERd", "7CG076P0"},
…
{ "BCLR #xx:3,@aa:16", "6A18NNNN72P0"},
};
Avoid unnecessary copies
Your code works fine, but in several places it is making copies of Instructions unnecessarily. Since Instruction is a "large" object, those copies can have a performance impact. You can avoid that and make your program more efficient. First, in push(), pass elementToAdd() as a const reference:
void push(const Instruction& elementToAdd) {
…
}
This avoids the caller having to make a copy, it will just pass a reference. Inside push(), it will still make a copy when adding the element to processQueue, but that is fine.
Each time you pop an item from the queue you are making a copy as well. Here we can use std::move(), like so:
currentInstruction = std::move(processQueue.back());
processQueue.pop_back();
Also, since you repeat this pattern 5 times, you might want to put this into a private member function.
Don't pass small values by reference
While copying large objects can be inefficient, and thus passing them by reference is generally better, you should not pass everything by reference. Small things like int and float are better passed by value. So in expandOpcode(), pass begin and end by value.
Of course, bytecodeElement should still be passed by reference because you want to mutate the value in the caller.
Inheriting from std::vector | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner
One thing I see now I could improve on is that I duplicated the push/pop mechanism of a std::vector. I probably could have used inheritance to implement that, but I don't quite understand how to do that yet.
It's probably better not to inherit from std::vector. This might expose all kinds of undesired functionality. So your current approach of having a private member variable is correct.
Consider using std::queue
Since you are using processQueue stricly as a queue, use std::queue instead of std::vector.
Expand on push or on pull?
Your example code always pushes one Instruction and then pulls from the queue until it is empty. But what if you would first push all elements of instructions[], and only then start pulling from the queue? The output would be different. I'm not sure that is what you want. Alternatively, you could expand the instructions inside push() instead of doing it inside pull().
If the idea is to only expand instructions one at a time, and not have the queue fill up with the expansion of multiple instructions, consider whether you need a class at all, and maybe you just should write a free function expand(), that basically combines your push() and the pop() loop into one:
static void expandOpcode(char& bytecodeElement, int begin, int
end, const Instruction& instruction, std::vector<Instruction>& result) {
static const std::string Hex = "…";
for (int i = begin; i <= end; i++) {
bytecodeElement = Hex[i];
result.push_back(instruction);
}
}
std::vector<Instruction> expand(Instruction instruction) {
std::vector<Instruction> result;
for (char& bytecodeElement : instruction.bytecode) {
switch (bytecodeElement) {
case 'O':
case 'Q':
expandOpcode(bytecodeElement, 8, 15, instruction, result);
break;
…
}
}
return result;
} | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner
return result;
}
And then your main() could look like:
int main() {
for (const auto& instr_in : instructions) {
for (const auto& instr_out : expand(instr_in)) {
std::cout << instr_out.name << ' ' << instr_out.bytecode << '\n';
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44378,
"lm_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",
"url": null
} |
c++, beginner, strings, qt
Title: Do a thing with a derived string for a number of strings | {
"domain": "codereview.stackexchange",
"id": 44379,
"lm_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, strings, qt",
"url": null
} |
c++, beginner, strings, qt
Question: I feel this should be possible more concisely, less code repetition, with a loop and a two-dimensional array or something. But not sure how exactly. Any best practice for review?
// Activate shortcuts for editor menu items like Ctrl+S for "Save Item" etc.
// Deactivate instead with optional "false" - to allow these for keybindings
void dlgTriggerEditor::setShortcuts(const bool active)
{
QList<QAction*> actionList = toolBar->actions();
QString actionText;
// 3/3 save button texts need to be kept in sync
const QStringList saveButtonNames = {qsl("Save Item"), tr("Save Trigger"), tr("Save Timer"), tr("Save Alias"), tr("Save Script"), tr("Save Button"), tr("Save Key"), tr("Save Variable")};
for (auto& action : actionList) {
actionText = action->text();
if (saveButtonNames.contains(actionText)) {
action->setShortcut((active) ? tr("Ctrl+S") : QString());
} else if (actionText == tr("Save Profile")) {
action->setShortcut((active) ? tr("Ctrl+Shift+S") : QString());
}
}
actionList = toolBar2->actions();
QString actionText;
for (auto& action : actionList) {
actionText = action->text();
if (actionText == tr("Triggers")) {
action->setShortcut((active) ? tr("Ctrl+1") : QString());
} else if (actionText == tr("Aliases")) {
action->setShortcut((active) ? tr("Ctrl+2") : QString());
} else if (actionText == tr("Scripts")) {
action->setShortcut((active) ? tr("Ctrl+3") : QString());
} else if (actionText == tr("Timers")) {
action->setShortcut((active) ? tr("Ctrl+4") : QString());
} else if (actionText == tr("Keys")) {
action->setShortcut((active) ? tr("Ctrl+5") : QString());
} else if (actionText == tr("Variables")) {
action->setShortcut((active) ? tr("Ctrl+6") : QString());
} else if (actionText == tr("Buttons")) { | {
"domain": "codereview.stackexchange",
"id": 44379,
"lm_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, strings, qt",
"url": null
} |
c++, beginner, strings, qt
} else if (actionText == tr("Buttons")) {
action->setShortcut((active) ? tr("Ctrl+7") : QString());
} else if (actionText == tr("Errors")) {
action->setShortcut((active) ? tr("Ctrl+8") : QString());
} else if (actionText == tr("Statistics")) {
action->setShortcut((active) ? tr("Ctrl+9") : QString());
} else if (actionText == tr("Debug")) {
action->setShortcut((active) ? tr("Ctrl+0") : QString());
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44379,
"lm_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, strings, qt",
"url": null
} |
c++, beginner, strings, qt
Here is a python mock-up of the bottom (not yet a) loop for comparison:
texts_and_actions = (
("Statistics", "Ctrl+9"),
("Debug", "Ctrl+0")
)
for text, action in texts_and_actions:
if actionText == text:
setShortcut(action)
Answer: Just try implementing your ideas
I feel this should be possible more concisely, less code repetition, with a loop and a two-dimensional array or something. But not sure how exactly.
You have the right idea. Now you have to find a way to turn it into C++ code. Even if you can't imagine the final code from the start, just start writing your idea and work on it until it works. Let's start with your Python code:
texts_and_actions = (
("Statistics", "Ctrl+9"),
("Debug", "Ctrl+0")
)
You can transform that into an array in C++. Of course, in C++ everything has to have a well-defined type. You could make an array of std::pair here, but even better is to create a struct that holds a text and an action:
struct TextAction {
std::string text;
std::string action;
};
And then create an array out of that:
TextAction texts_and_actions[] = {
{"Statistics", "Ctrl+9"},
{"Debug", "Ctrl+0"},
};
Notice how it's not so different from the Python code. Then we have your for-loop in Python:
for text, action in texts_and_actions:
if actionText == text:
setShortcut(action)
You can use the same in C++:
for (auto& [text, action]: texts_and_actions) {
if (actionText == text) {
something->setShortcut(action);
}
} | {
"domain": "codereview.stackexchange",
"id": 44379,
"lm_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, strings, qt",
"url": null
} |
c++, beginner, strings, qt
There are some issues with this (that are also in your example Python code), which we'll see below.
Naming things
Take a bit more time to give proper names to things. For example, in your question, "action" is used for two things: objects in actionList, and the name of the shortcut in texts_and_actions. Maybe the latter should be named "shortcut" instead? The word "text" is also very generic and can apply to anything that is a string, so you probably want to choose something more specific. Maybe "name", "label" or "description" are better choices?
Make looking up shortcuts faster
Going through the list of texts_and_actions each time to find the right element is going to be slow. In Python you would use a dict here, so you can write:
shortcuts = {
"Statistics": "Ctrl+9",
"Debug": "Ctrl+0",
}
…
if actionText in shortcuts:
setShortcut(shortcuts[actionText])
In C++ you can do something similar by using a std::unordered_map:
std::unordered_map<std::string, std::string> shortcuts = {
{"Statistics", "Ctrl+9"},
{"Debug", "Ctrl+0"},
};
…
if (auto it = shortcuts.find(actionText); it != shortcuts.end()) {
action->setShortcut(it->second);
}
Also, if active is false, you are going to set the shortcut to the empty string regardless of the actionText, so why bother doing a lookup at all? You can just put something like this at the start of each for-loop:
if (!active) {
action->setShortcut(QString());
continnue;
}
Avoid repeating yourself
If you find yourself repeating similar code, find ways to avoid it. You already had the idea of using arrays, that is one way. Putting code that is used multiple times into a separate function is also a way. If you have the same list of shortcuts, and want to apply it to several action lists, consider doing something like:
// Overload that sets shortcuts for one action list only
void dlgTriggerEditor::setShortcuts(QList<QAction*> actionList, const bool active)
{
for (auto& action : actionList) {
…
}
} | {
"domain": "codereview.stackexchange",
"id": 44379,
"lm_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, strings, qt",
"url": null
} |
c++, beginner, strings, qt
void dlgTriggerEditor::setShortcuts(const bool active)
{
setShortcuts(toolBar->actions(), active);
setShortcuts(toolBar2->actions(), active);
…
}
It might even be possible to make an array or tuple or references out of toolBar and toolBar2, but for something as simple as this I would not do that. | {
"domain": "codereview.stackexchange",
"id": 44379,
"lm_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, strings, qt",
"url": null
} |
php, strings, regex
Title: Clean regex matches with named matches
Question: I have a regex pattern that will match some elements from a string and give them a particular name. For example, #^(?<foo>.*)$# will match the whole string and name it foo.
My problem is that the matches also contain the "classic", numbered matches.
For example:
<?php
$pattern = '#^(?<foo>.*)$#';
$str = '123';
$matches = null;
preg_match($pattern, $str, $matches);
print_r($matches);
will print:
Array
(
[0] => 123
[foo] => 123
[1] => 123
)
As all the matches will always be named, I decided to manually remove the numbered indexes from $matches in order to clean things up:
<?php
$pattern = '#^(?<foo>.*)$#';
$str = '123';
$matches = null;
if (preg_match($pattern, $str, $matches))
{
foreach ($matches as $key => $value)
{
if (is_int($key))
unset($matches[$key]);
}
}
print_r($matches);
Which prints:
Array
(
[foo] => 123
)
It works, but I feel that it can be improved. Is there a better way to do this, especially without the foreach loop?
In practice, $pattern and $str can be much more complicated than the example I gave and I want this to be executed as fast as possible.
Answer: I've looking for the same solution as you. But after finding your solution and additional research I find this way to do it, which does not contain a loop.
$pattern = "#^/article/(?<id>\d+)-(?<slug>.+)$#";
$url = "/article/42-is-the-answer";
preg_match($pattern, $url, $args);
print_r($args);
$args = array_filter($args, 'is_string', ARRAY_FILTER_USE_KEY);
print_r($args);
Output :
Without array_filter() :
Array
(
[0] => /article/42-is-the-answer
[id] => 42
[1] => 42
[slug] => is-the-answer
[2] => is-the-answer
)
With array_filter() :
Array
(
[id] => 42
[slug] => is-the-answer
) | {
"domain": "codereview.stackexchange",
"id": 44380,
"lm_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, strings, regex",
"url": null
} |
c++, multithreading, c++20
Title: jthread drop-in replacement
Question: I have a couple of libraries that use jthread, but also are published via vcpkg. The problem I have is that both github and vcpkg's AzureDevOps CI have a version of clang that does not have jthread implemented on MacOS. I was hoping that abeil would have a jthread, but that is not the case.
To reduce the number files that require of #ifdef __cpp_lib_jthread I decided to implement a drop in replacement for these cases.
jthread.h
#ifndef _C9Y_JTHREAD_H_
#define _C9Y_JTHREAD_H_
#include <thread>
#include <memory>
#include <functional>
#include "defines.h"
namespace c9y
{
#ifdef __cpp_lib_jthread
using std::jthread;
using std::stop_token;
using std::stop_source;
using std::stop_callback;
using std::nostopstate;
#else
struct StopState;
struct nostopstate_t {};
constexpr auto nostopstate = nostopstate_t{};
class C9Y_EXPORT stop_token
{
public:
stop_token();
explicit stop_token(std::shared_ptr<StopState> state);
stop_token(const stop_token& other) noexcept;
stop_token(stop_token&& other) noexcept;
~stop_token();
stop_token& operator = (const stop_token& other) noexcept;
stop_token& operator = (stop_token&& other) noexcept;
[[nodiscard]] bool stop_requested() noexcept;
[[nodiscard]] bool stop_possible() const noexcept;
void swap(stop_token& other) noexcept;
private:
std::shared_ptr<StopState> state;
friend class stop_callback;
};
inline void swap(stop_token& lhs, stop_token& rhs) noexcept
{
lhs.swap(rhs);
}
class C9Y_EXPORT stop_source
{
public:
stop_source();
explicit stop_source(nostopstate_t nss) noexcept;
stop_source(const stop_source& other) noexcept;
stop_source(stop_source&& other) noexcept;
~stop_source(); | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
stop_source& operator = (const stop_source& other) noexcept;
stop_source& operator = (stop_source&& other) noexcept;
[[nodiscard]] stop_token get_token() const noexcept;
bool request_stop() noexcept;
[[nodiscard]] bool stop_possible() const noexcept;
void swap(stop_source& other) noexcept;
private:
std::shared_ptr<StopState> state;
};
inline void swap(stop_source& lhs, stop_source& rhs) noexcept
{
lhs.swap(rhs);
}
class C9Y_EXPORT stop_callback
{
public:
template<class C>
explicit stop_callback(const stop_token& st, C&& cb)
: token(st), callback(cb)
{
self_register();
}
template<class C>
explicit stop_callback(stop_token&& st, C&& cb )
: token(std::forward<stop_token>(st)), callback(cb)
{
self_register();
}
~stop_callback();
private:
stop_token token;
std::function<void ()> callback;
void self_register();
stop_callback(const stop_callback&) = delete;
stop_callback(stop_callback&&) = delete;
stop_callback& operator = (const stop_callback& other) noexcept = delete;
stop_callback& operator = (stop_callback&& other) noexcept = delete;
friend struct StopState;
};
//! Drop in replacement for all cases where std::jthread is not yet implemented.
//!
//! @see std::jthread
class C9Y_EXPORT jthread
{
public:
using id = std::thread::id;
jthread() noexcept;
jthread(jthread&& other) noexcept;
template<class Function, class... Args>
requires std::is_invocable_v<std::decay_t<Function>, std::decay_t<Args>...>
explicit jthread(Function&& f, Args&&... args)
: impl(std::forward<Function>(f), std::forward<Args>(args)...) {} | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
template<class Function, class... Args>
requires std::is_invocable_v<std::decay_t<Function>, stop_token, std::decay_t<Args>...>
explicit jthread(Function&& f, Args&&... args)
: impl(std::forward<Function>(f), stop.get_token(), std::forward<Args>(args)...) {}
~jthread();
jthread& operator = (jthread&& other) noexcept;
[[nodiscard]] id get_id() const noexcept;
[[nodiscard]] bool joinable() const noexcept;
void join();
void detach();
[[nodiscard]] stop_source get_stop_source() noexcept;
[[nodiscard]] stop_token get_stop_token() noexcept;
bool request_stop() noexcept;
void swap(jthread& other) noexcept;
private:
stop_source stop = {};
std::thread impl;
jthread(const jthread&) = delete;
jthread& operator = (const jthread& other) noexcept = delete;
};
inline void swap(jthread& lhs, jthread& rhs) noexcept
{
lhs.swap(rhs);
}
#endif
}
#endif
jthread.cpp
#include "jthread.h"
#ifndef __cpp_lib_jthread
#include <cassert>
#include <atomic>
#include <mutex>
#include <vector>
namespace c9y
{
struct StopState
{
std::atomic<bool> request_stop = false;
// this is not efficient, but it only needs to be correct
std::mutex callbacks_mutex;
std::vector<stop_callback*> callbacks;
void add_callback(stop_callback* callback)
{
auto lk = std::unique_lock<std::mutex>(callbacks_mutex);
if (!request_stop)
{
callbacks.push_back(callback);
}
else
{
callback->callback();
}
} | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
void remove_callback(stop_callback* callback)
{
auto lk = std::unique_lock<std::mutex>(callbacks_mutex);
auto i = std::find(begin(callbacks), end(callbacks), callback);
if (i != end(callbacks))
{
callbacks.erase(i);
}
}
void exec_callbacks()
{
auto lk = std::unique_lock<std::mutex>(callbacks_mutex);
for (const auto& cb : callbacks)
{
assert(cb->callback);
cb->callback();
}
callbacks.clear();
}
};
stop_token::stop_token() = default;
stop_token::stop_token(std::shared_ptr<StopState> s)
: state(s) {}
stop_token::stop_token(const stop_token& other) noexcept = default;
stop_token::stop_token(stop_token&& other) noexcept = default;
stop_token::~stop_token() = default;
stop_token& stop_token::operator = (const stop_token& other) noexcept = default;
stop_token& stop_token::operator = (stop_token&& other) noexcept = default;
bool stop_token::stop_requested() noexcept
{
if (state)
{
return state->request_stop;
}
return false;
}
bool stop_token::stop_possible() const noexcept
{
return static_cast<bool>(state);
}
void stop_token::swap(stop_token& other) noexcept
{
state.swap(other.state);
}
stop_source::stop_source()
: state(std::make_shared<StopState>()) {}
stop_source::stop_source(nostopstate_t nss) noexcept {}
stop_source::stop_source(const stop_source& other) noexcept = default;
stop_source::stop_source(stop_source&& other) noexcept = default;
stop_source::~stop_source() = default;
stop_source& stop_source::operator = (const stop_source& other) noexcept = default;
stop_source& stop_source::operator = (stop_source&& other) noexcept = default; | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
stop_token stop_source::get_token() const noexcept
{
return stop_token{state};
}
bool stop_source::request_stop() noexcept
{
if (state && (state->request_stop.exchange(true) == false))
{
state->exec_callbacks();
return true;
}
return false;
}
bool stop_source::stop_possible() const noexcept
{
return static_cast<bool>(state);
}
void stop_source::swap(stop_source& other) noexcept
{
state.swap(other.state);
}
stop_callback::~stop_callback()
{
if (token.state)
{
token.state->remove_callback(this);
}
}
void stop_callback::self_register()
{
if (token.state)
{
token.state->add_callback(this);
}
else
{
callback();
}
}
jthread::jthread() noexcept
: stop{nostopstate} {}
jthread::jthread(jthread&& other) noexcept = default;
jthread::~jthread()
{
if (joinable())
{
request_stop();
join();
}
}
jthread& jthread::operator = (jthread&& other) noexcept = default;
jthread::id jthread::get_id() const noexcept
{
return impl.get_id();
}
bool jthread::joinable() const noexcept
{
return impl.joinable();
}
void jthread::join()
{
impl.join();
}
void jthread::detach()
{
impl.detach();
}
stop_source jthread::get_stop_source() noexcept
{
if (joinable())
{
return stop;
}
else
{
return stop_source{nostopstate};
}
}
stop_token jthread::get_stop_token() noexcept
{
return get_stop_source().get_token();
}
bool jthread::request_stop() noexcept
{
return stop.request_stop();
} | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
bool jthread::request_stop() noexcept
{
return stop.request_stop();
}
void jthread::swap(jthread& other) noexcept
{
stop.swap(other.stop);
impl.swap(other.impl);
}
}
#endif
jthread_test.cpp
#include <c9y/c9y.h>
#include <gtest/gtest.h>
TEST(jthread, create_and_destroy)
{
auto thread = c9y::jthread{};
}
TEST(jthread, launch_thread)
{
auto tid = c9y::jthread::id{};
auto thread = c9y::jthread{[&] () {
tid = std::this_thread::get_id();
}};
thread.join();
EXPECT_NE(tid, std::this_thread::get_id());
}
TEST(jthread, launch_thread_with_args)
{
auto a = 0u;
auto thread = c9y::jthread{[&] (unsigned int awnser) {
a = awnser;
}, 42u};
thread.join();
EXPECT_EQ(a, 42u);
}
TEST(jthread, id)
{
auto latch = c9y::latch{1};
auto tid = c9y::jthread::id{};
auto thread = c9y::jthread{[&] () {
tid = std::this_thread::get_id();
latch.count_down();
}};
latch.wait();
EXPECT_EQ(thread.get_id(), tid);
thread.join();
}
TEST(jthread, empty_id)
{
auto thread = c9y::jthread{};
EXPECT_EQ(thread.get_id(), c9y::jthread::id{});
}
TEST(jthread, detach)
{
auto latch = c9y::latch{1};
{
auto thread = c9y::jthread{[&] () {
latch.wait();
}};
thread.detach();
}
latch.count_down();
}
TEST(jthread, move_assignment)
{
auto latch = c9y::latch{1};
auto outside = c9y::jthread{};
{
auto inside = c9y::jthread{[&] () {
latch.wait();
}};
outside = std::move(inside);
EXPECT_FALSE(inside.joinable());
}
EXPECT_TRUE(outside.joinable());
latch.count_down();
outside.join();
}
TEST(jthread, move_constructor)
{
auto latch = c9y::latch{1};
auto construct = [&] () {
auto inside = c9y::jthread{[&] () {
latch.wait();
}};
return inside;
};
auto outside = construct(); | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
EXPECT_TRUE(outside.joinable());
latch.count_down();
outside.join();
}
TEST(jthread, swap)
{
auto latch = c9y::latch{1};
auto a = c9y::jthread{};
auto b = c9y::jthread{[&] () {
latch.wait();
}};
EXPECT_FALSE(a.joinable());
EXPECT_TRUE(b.joinable());
a.swap(b);
EXPECT_TRUE(a.joinable());
EXPECT_FALSE(b.joinable());
latch.count_down();
a.join();
}
TEST(jthread, request_stop)
{
auto thread = c9y::jthread{[] (c9y::stop_token token) {
while (!token.stop_requested())
{
std::this_thread::yield();
}
}};
thread.request_stop();
thread.join();
}
TEST(jthread, automatic_stop_request)
{
auto thread = c9y::jthread{[] (c9y::stop_token token) {
while (!token.stop_requested())
{
std::this_thread::yield();
}
}};
}
TEST(jthread, stop_callback)
{
auto should_be_called = std::atomic<unsigned int>{0};
auto should_not_be_called = std::atomic<unsigned int>{0};
auto worker = c9y::jthread{[] (c9y::stop_token token) {
while (!token.stop_requested())
{
std::this_thread::yield();
}
}};
auto callback = c9y::stop_callback(worker.get_stop_token(), [&] {
should_be_called++;
});
{
auto scoped_callback = c9y::stop_callback(worker.get_stop_token(), [&] {
should_not_be_called++;
});
}
auto stopper_func = [&] {
worker.request_stop();
};
c9y::jthread stopper1(stopper_func);
c9y::jthread stopper2(stopper_func);
stopper1.join();
stopper2.join();
EXPECT_EQ(1, should_be_called);
EXPECT_EQ(0, should_not_be_called);
auto should_be_called_imediatly = std::atomic<unsigned int>{0};
auto callback2 = c9y::stop_callback(worker.get_stop_token(), [&] {
should_be_called_imediatly++;
}); | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
EXPECT_EQ(1, should_be_called);
EXPECT_EQ(0, should_not_be_called);
EXPECT_EQ(1, should_be_called_imediatly);
}
TEST(jthread, called_stop_callback)
{
auto worker = c9y::jthread{[] (c9y::stop_token token) {
while (!token.stop_requested())
{
std::this_thread::yield();
}
}};
worker.request_stop();
auto should_be_called_imediatly = std::atomic<unsigned int>{0};
auto callback2 = c9y::stop_callback(worker.get_stop_token(), [&] {
should_be_called_imediatly++;
});
EXPECT_EQ(1, should_be_called_imediatly);
}
TEST(jthread, expired_stop_callback)
{
auto worker = c9y::jthread{[] (c9y::stop_token token) {
while (!token.stop_requested())
{
std::this_thread::yield();
}
}};
worker.request_stop();
worker.join();
auto should_be_called_imediatly = std::atomic<unsigned int>{0};
auto callback2 = c9y::stop_callback(worker.get_stop_token(), [&] {
should_be_called_imediatly++;
});
EXPECT_EQ(1, should_be_called_imediatly);
}
defines.h
You also need this bit of code from defines.h:
#if defined(_WIN32)
#define C9Y_EXPORT __declspec(dllexport)
#else
#define C9Y_EXPORT
#endif
The code is targeting C++20; with the obviously missing jthread.
A few notes: | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
The code is targeting C++20; with the obviously missing jthread.
A few notes:
stop_source, stop_token and stop_callback are passed around by value and thus not accessed through multiple threads. This means that the shared_ptr does not need to be synchronized. The underlying reference count is safe, as guaranteed by the standard.
Any race conditions on jthread::joinable are IMHO imagined. I can imagine one in jthread::get_stop_source, but then other implementations would also be broken. It seems that I am missing an assumption the standard has on how you can use jthread::join and jthread::get_stop_source.
Getting stop_callback to work correctly and safely was quite a challenge. I am considering removing it, since I don't need it and the use is quite obscure.
Answer: To me it looks like a really good implementation!
About your notes
stop_source, stop_token and stop_callback are passed around by value and thus not accessed through multiple threads. This means that the shared_ptr does not need to be synchronized. The underlying reference count is safe, as guaranteed by the standard.
Correct.
Any race conditions on jthread::joinable are IMHO imagined. I can imagine one in jthread::get_stop_source, but then other implementations would also be broken. It seems that I am missing an assumption the standard has on how you can use jthread::join and jthread::get_stop_source.
std::jthread::join() just does exactly what std::thread::join() does, nothing more, nothing less. It does not interact with the stop source or token in any way. As far as I can tell, there is no race condition in std::jthread::joinable() itself. However, if you call std::jthread::join() from one thread and std::jthread::joinable() from another, by the time you get the result from std::jthread::joinable() the answer might no longer be true. But doing that would be silly anyway. Note that there is a race condition if you call std::jthread::join() from multiple threads. | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
Getting stop_callback to work correctly and safely was quite a challenge. I am considering removing it, since I don't need it and the use is quite obscure. | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
It can easily be made to work correctly and safely, but not the most efficient. You tried to add efficiency, and that might interfere with correctness, see below.
Don't expose more public API than the STL does
The constructor of c9y::stop_token that takes a std::shared_ptr<StopState> as an argument is public, but there is no counterpart in std::stop_token. While you don't define StopState in jthread.h, someone might define it in another source file and then call this constructor with a bogus state. It is easily preventable by making this particular constructor private, and adding stop_source as a friend.
Define trivial functions in the header file
You have a lot of trivial (copy, move) constructors and destructors. By only declaring them in the header file but defining them in jthread.cpp, code using these classes have to do a function call, which is often more expensive than clearing or copying a few variables if these functions were defined in jthread.hpp instead.
Don't mix atomics and mutexes
In StopState you have both an atomic variable request_stop and a mutex. The mutex is there to guard callbacks, but it does not cover request_stop, likely as intended for performance reasons. The problem now happens in add_callback(): the mutex only covers the atomicity of access to the vector callbacks, but reading request_stop is not part of that! So now you have to wonder if the compiler and/or the CPU are allowed to reorder reads or writes from/to request_stop to before/after locking callbacks_mutex. If it is, are you still sure your code is correct in all possible ways it can be called from multiple threads simultaneously?
If you are not 100% sure about this, just don't do it, and instead always take the mutex even if you are modifying request_stop, which then doesn't need to be made atomic anymore. | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
Note that mutexes themselves are quite efficient if there is no contention, and it is very likely there will not be any contention: almost all the time it's just one thread that is checking whether it needs to stop.
Make StopState a class with private member variables
Even if it's only used internally inside jthread.cpp, it's good practice to make StopState a proper class with private member variables, and expose all the logic to modify the state via public member functions. That will allow you to catch mistakes more easily, and if you have to refactor StopState, you don't have to hunt through the rest of the code to find out where its member variables are being modified. So consider adding two public functions: | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
c++, multithreading, c++20
bool is_stop_requested() const, which just returns the value of request_stop,
void stop(), which sets request_stop and runs all the callbacks registered so far.
The member function exec_callbacks() should be removed, or perhaps made private and called from stop().
Naming things
Use verbs for functions, but not for variables. In StopState, the variable request_stop is confusing, especially since there is a function request_stop() in stop_source. So it would be better to name it stop_requested, although unfortunately there is already the function stop_requested() in stop_token.
Fix compiler warnings
There is one warning generated by both GCC and Clang: the parameter nss in one of the constructors of stop_source is unused. The fixed is to simply remove the name of that parameter. | {
"domain": "codereview.stackexchange",
"id": 44381,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, multithreading, c++20",
"url": null
} |
beginner, rust
Title: Produce randomly-generated pronouncable names
Question: #[derive(Default)]
pub struct ResourceName {
chars: [u8; 9],
size: u8,
}
impl ResourceName {
pub fn to_str(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(&self.chars[0..usize::from(self.size)]) }
}
fn generate(&mut self, rng: &mut UnityRNG) {
const VOWELS: &[u8; 5] = b"AEIOU";
const CONSONANTS: &[u8; 21] = b"BCDFGHJKLMNPQRSTVWXYZ";
let pairs = rng.int_range(0, 3) + 2;
self.size = 0;
fn add_char(out: &mut ResourceName, rng: &mut UnityRNG, letters: &[u8]) {
out.chars[usize::from(out.size)] = letters[rng.int_range(0, letters.len() as i32) as usize];
out.size += 1;
}
for _ in 0..pairs {
if rng.next_float() < 0.1 {
add_char(self, rng, VOWELS);
add_char(self, rng, VOWELS);
} else {
if rng.next_float() < 0.5 {
add_char(self, rng, VOWELS);
add_char(self, rng, CONSONANTS);
} else {
add_char(self, rng, CONSONANTS);
add_char(self, rng, VOWELS);
}
}
}
if rng.next_float() < 0.5 {
if VOWELS.contains(&self.chars[usize::from(self.size) - 1]) {
add_char(self, rng, CONSONANTS);
} else {
add_char(self, rng, VOWELS);
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
The code generates a pronounceable (or pronounceable-ish) random name. I am re-implementing code that exists elsewhere, so it must perform this exact sequence of sequence of steps; I have no leeway in how the algorithm works. I chose a slightly unconventional representation (fixed-size [u8] and a u8 size) because I need to generate a lot of these, quickly: It's important that no heap allocation be on the hot path.
Aside from general style improvement, I'm particularly interested if there's a way to improve the situation with the add_char helper function. In C++ I would use a lambda and capture self (this) and rng, but that's not an option here because of the borrow checker. C++ also has macros as an option, and I looked into that but the different scopes of identifiers in macro_rules! foiled me.
Answer: I managed to speed up your code by 5-10% by unrolling the loop:
fn generate(&mut self, rng: &mut UnityRNG) {
const VOWELS: &[u8; 5] = b"AEIOU";
const CONSONANTS: &[u8; 21] = b"BCDFGHJKLMNPQRSTVWXYZ"; | {
"domain": "codereview.stackexchange",
"id": 44382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
let pairs = rng.int_range(0, 3) + 2;
self.size = 0;
#[inline]
fn add_char(out: &mut ResourceName, rng: &mut UnityRNG, letters: &[u8]) {
out.chars[usize::from(out.size)] = letters[rng.int_range(0, letters.len() as i32) as usize];
out.size += 1;
}
for _ in 0 .. pairs - 1 {
if rng.next_float() < 0.1 {
add_char(self, rng, VOWELS);
add_char(self, rng, VOWELS);
} else {
if rng.next_float() < 0.5 {
add_char(self, rng, VOWELS);
add_char(self, rng, CONSONANTS);
} else {
add_char(self, rng, CONSONANTS);
add_char(self, rng, VOWELS);
}
}
}
if rng.next_float() < 0.1 {
add_char(self, rng, VOWELS);
add_char(self, rng, VOWELS);
if rng.next_float() < 0.5 {
add_char(self, rng, CONSONANTS);
}
} else {
if rng.next_float() < 0.5 {
add_char(self, rng, VOWELS);
add_char(self, rng, CONSONANTS);
if rng.next_float() < 0.5 {
add_char(self, rng, VOWELS);
}
} else {
add_char(self, rng, CONSONANTS);
add_char(self, rng, VOWELS);
if rng.next_float() < 0.5 {
add_char(self, rng, CONSONANTS);
}
}
}
}
EDIT: Improved a bit the situation with add_char calls without any performance loss
impl ResourceName {
pub fn to_str(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(&self.chars[0..usize::from(self.size)]) }
} | {
"domain": "codereview.stackexchange",
"id": 44382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
#[inline]
fn add_chars<'a, T: AsRef<[&'a [u8]]>>(&mut self, rng: &mut UnityRNG, chars: T) {
for &letters in chars.as_ref() {
self.chars[usize::from(self.size)] = letters[rng.int_range(0, letters.len() as i32) as usize];
self.size += 1;
}
}
fn generate(&mut self, rng: &mut UnityRNG) {
const VOWELS: &[u8] = b"AEIOU";
const CONSONANTS: &[u8] = b"BCDFGHJKLMNPQRSTVWXYZ";
let pairs = rng.int_range(0, 3) + 2;
self.size = 0;
for _ in 0 .. pairs - 1 {
if rng.next_float() < 0.1 {
self.add_chars(rng, [VOWELS, VOWELS]);
} else {
if rng.next_float() < 0.5 {
self.add_chars(rng, [VOWELS, CONSONANTS]);
} else {
self.add_chars(rng, [CONSONANTS, VOWELS]);
}
}
}
if rng.next_float() < 0.1 {
self.add_chars(rng, [VOWELS, VOWELS]);
if rng.next_float() < 0.5 {
self.add_chars(rng, [CONSONANTS]);
}
} else {
if rng.next_float() < 0.5 {
self.add_chars(rng, [VOWELS, CONSONANTS]);
if rng.next_float() < 0.5 {
self.add_chars(rng, [VOWELS]);
}
} else {
self.add_chars(rng, [CONSONANTS, VOWELS]);
if rng.next_float() < 0.5 {
self.add_chars(rng, [CONSONANTS]);
}
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
A solution that further improves add_char calls. If you have to carry multiple pieces of state together for a while, like in your situation, it's best to add a record type rather than use anonymous functions. You may add methods on that type like I did below. This is probably what you were looking for. It is 10% slower. If you flatten the record, the performance might come back. That is left to check for you if you wish.
struct ResourceNameWithRng<'a, 'b> {
resource_name: &'a mut ResourceName,
rng: &'b mut UnityRNG,
}
impl<'a, 'b> ResourceNameWithRng<'a, 'b> {
#[inline]
fn add_chars<'c, T: AsRef<[&'c [u8]]>>(&mut self, chars: T) {
for &letters in chars.as_ref() {
self.resource_name.chars[usize::from(self.resource_name.size)] = letters[self.rng.int_range(0, letters.len() as i32) as usize];
self.resource_name.size += 1;
}
}
fn generate(&mut self) {
const VOWELS: &[u8] = b"AEIOU";
const CONSONANTS: &[u8] = b"BCDFGHJKLMNPQRSTVWXYZ"; | {
"domain": "codereview.stackexchange",
"id": 44382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
beginner, rust
let pairs = self.rng.int_range(0, 3) + 2;
self.resource_name.size = 0;
for _ in 0 .. pairs - 1 {
if self.rng.next_float() < 0.1 {
self.add_chars([VOWELS, VOWELS]);
} else {
if self.rng.next_float() < 0.5 {
self.add_chars([VOWELS, CONSONANTS]);
} else {
self.add_chars([CONSONANTS, VOWELS]);
}
}
}
if self.rng.next_float() < 0.1 {
self.add_chars([VOWELS, VOWELS]);
if self.rng.next_float() < 0.5 {
self.add_chars([CONSONANTS]);
}
} else {
if self.rng.next_float() < 0.5 {
self.add_chars([VOWELS, CONSONANTS]);
if self.rng.next_float() < 0.5 {
self.add_chars([VOWELS]);
}
} else {
self.add_chars([CONSONANTS, VOWELS]);
if self.rng.next_float() < 0.5 {
self.add_chars([CONSONANTS]);
}
}
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44382,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, rust",
"url": null
} |
javascript, beginner, html, svelte
Title: adding characters on mouseover using Svelte
Question: This is my first time using svelte. I am also using tailwind and astro but that is irrelevant. The following component prepends >> to my text when it is being hovered upon and takes the >> out when it is not.
Is this the typical way to use svelte? Am I doing something wrong? I feel I am.
<script>
let spanId = "selected";
let isMouseOver = false;
function handleMouseOver() {
if(!isMouseOver) {
this.innerHTML = `<span id="${spanId}">>> </span>` + this.innerHTML;
isMouseOver = true;
}
}
function handleMouseOut() {
let selectedSpan = document.getElementById(spanId);
selectedSpan.parentNode.removeChild(selectedSpan);
isMouseOver = false;
}
</script>
<p
class="hover:text-green-600 cursor-pointer whitespace-nowrap"
on:mouseover={handleMouseOver}
on:mouseout={handleMouseOut}
>
<slot />
</p>
Answer: As per some others in a community where I have asked:
A more idiomatic way of doing it in svelte would be to remove innerHTML completely. Svelte's declarative approach makes modifying the innerHTML property unnecessary.
function handleMouseOver() {
isMouseOver = true;
}
And later in the markup just set the markup declaratively
<p
class="hover:text-green-600 cursor-pointer whitespace-nowrap"
on:mouseover={handleMouseOver}
on:mouseout={handleMouseOut}
>
{#if isMouseOver}
<span id={spanId}>>></span>
{/if}
<slot />
</p>
Essentially the code turns to:
<script>
let isMouseOver = false;
</script>
<p
class="hover:text-green-600 cursor-pointer whitespace-nowrap"
on:mouseover={() => (isMouseOver = true)}
on:mouseout={() => (isMouseOver = false)}
>
{#if isMouseOver}
<span>>></span>
{/if}
<slot />
</p> | {
"domain": "codereview.stackexchange",
"id": 44383,
"lm_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, html, svelte",
"url": null
} |
javascript, beginner, html, svelte
<slot />
</p>
And also only CSS (tailwind in this case) could be used as so:
<p class="group hover:text-green-600 cursor-pointer whitespace-nowrap">
<span class="group-hover:inline hidden">>></span> <slot />
</p> | {
"domain": "codereview.stackexchange",
"id": 44383,
"lm_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, html, svelte",
"url": null
} |
beginner, c, event-handling, pthreads
Title: Event functionality in C
Question: I am beginner to intermediate and wanted to write a little event code in c.
It's one header file with 108 line pure code and it does what I was thinking it should be like for me.
EventListener.h
#ifndef EVENTLISTENER2_H
#define EVENTLISTENER2_H
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
struct Event;
struct EventListener {
pthread_t tid;
struct Event *event;
void *(*callback)(void*);
void *arg;
int trigger;
struct EventListener *next;
};
typedef struct EventListener EventListener;
struct Event{
pthread_mutex_t mtx;
EventListener *listeners;
};
typedef struct Event Event;
void malloc_exit_on_failure(void *p)
{
if(p == NULL)
{
perror("memory allocation failed");
exit(EXIT_FAILURE);
}
}
EventListener *EventListener_Create(void *(*callback)(void*), void *arg)
{
EventListener *listener = (EventListener *) malloc(sizeof(*listener));
malloc_exit_on_failure(listener);
listener->callback = callback;
listener->arg = arg;
listener->tid = 0;
listener->event = NULL;
listener->next = NULL;
listener->trigger = 0;
return listener;
}
void EventListenerWait(EventListener *listener)
{
while(listener->trigger == 0);
}
void EventListenerRun(EventListener *listener)
{
listener->callback(listener->arg);
listener->trigger = 0;
}
void *EventListenerThread(void *listener_arg)
{
EventListener *listener = (EventListener*) listener_arg;
while(1)
{
EventListenerWait(listener);
EventListenerRun(listener);
}
}
Event *Event_Create()
{
Event *event = (Event *) malloc(sizeof(Event));
malloc_exit_on_failure(event);
event->listeners = NULL;
pthread_mutex_init(&event->mtx, NULL);
return event;
}
void Event_RegisterRaw(Event *event, void *(*callback)(void *), void *arg); | {
"domain": "codereview.stackexchange",
"id": 44384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, event-handling, pthreads",
"url": null
} |
beginner, c, event-handling, pthreads
return event;
}
void Event_RegisterRaw(Event *event, void *(*callback)(void *), void *arg);
void Event_Register(Event *event, EventListener *listener)
{
if(event->listeners == NULL)
event->listeners = listener;
else
{
struct EventListener *current = event->listeners;
while(current->next != NULL)
current = current->next;
current->next = listener;
}
listener->event = event;
if(pthread_create(&listener->tid, NULL, EventListenerThread, listener) != 0)
{
perror("cannot create thread");
exit(EXIT_FAILURE);
}
}
void Event_Trigger(Event *event){
EventListener *current = event->listeners;
while(current != NULL){
pthread_mutex_lock(&event->mtx);
current->trigger = 1;
current = current->next;
pthread_mutex_unlock(&event->mtx);
}
}
void Event_memory_usage(Event *event)
{
size_t size;
int n_listeners = 0;
size = sizeof(*event);
EventListener *current = event->listeners;
while(current != NULL)
{
size = size + sizeof(*current);
current = current->next;
n_listeners++;
}
printf("Event size with %d listeners: %lu bytes.\n", n_listeners, size);
}
#endif
event_test.c
#include <stdio.h>
#include <unistd.h>
#include "EventListener.h"
void *event_trigger_test(void *arg)
{
printf("%s\n", (char *) arg);
}
char *arg = "Event triggered!";
char *arg2 = "Event 2 triggered!";
void *event_trigger_loop_test(void *arg)
{
printf("invoke\n");
while(1)
{
sleep(2);
printf("i am running\n");
}
}
int main(void)
{
EventListener *l = EventListener_Create(event_trigger_test, arg);
EventListener *l2 = EventListener_Create(event_trigger_test, arg2);
EventListener *l3 = EventListener_Create(event_trigger_loop_test, NULL);
Event *TEST_EVENT = Event_Create(); | {
"domain": "codereview.stackexchange",
"id": 44384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, event-handling, pthreads",
"url": null
} |
beginner, c, event-handling, pthreads
Event *TEST_EVENT = Event_Create();
Event_Register(TEST_EVENT, l);
Event_Register(TEST_EVENT, l2);
Event_Register(TEST_EVENT, l3);
printf("EventListener Size: %lu\n", sizeof(EventListener));
printf("Event Size: %lu\n", sizeof(Event));
Event_memory_usage(TEST_EVENT);
for(int i = 0; i < 5; i++) {
sleep(i);
Event_Trigger(TEST_EVENT);
printf("\n"); // debug
}
sleep(10);
}
What should happen to listeners from an event that are running in an infinite loop after the event is triggered?
Is it okay/normal/best practice to create one thread per listener?
I just want to hear what you think about it and I ask for constructive criticism like improvements, hint and so on what I missed, what I should do better and if there is a better approach.
For future questions of mine I just wanted to ask if it is okay to ask for review of a header file like this tiny one or where I should be looking for that? | {
"domain": "codereview.stackexchange",
"id": 44384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, event-handling, pthreads",
"url": null
} |
beginner, c, event-handling, pthreads
Answer: In addition to Toby's comments, here are two more issues that should be looked into.
trigger needs to be volatile
The trigger variable in your EventListener struct is currently declared without the volatile keyword. This means that the compiler is free to make assumptions about the variable when optimizations are enabled. For example, the compiler could notice that the while loop in EventListenerWait() only ever attempts to read from trigger and never writes to it, so it could incorrectly assume that it never changes.
Adding volatile instructs the compiler to always read from memory when accessing the variable, ensuring that if a different thread changes the value, the thread reading from it will get the updated value.
Also note that you really should be using a mutex lock whenever reading from or writing to any variable that is shared across threads.
EventListenerWait() blindly eats CPU time
The while loop which waits for trigger to change:
void EventListenerWait(EventListener *listener)
{
while(listener->trigger == 0);
} | {
"domain": "codereview.stackexchange",
"id": 44384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, event-handling, pthreads",
"url": null
} |
beginner, c, event-handling, pthreads
...will end up eating all of the CPU for that thread while waiting here, continuously reading the value of trigger as quickly as it can over and over again. With enough threads created, you can see how this won't scale well.
You can avoid this by adding a sleep() inside the while loop so that the thread releases time back to the OS. Sleeping one full second each iteration through the loop can begin to increase the latency before an event can start from the time it's triggered, so you might want to consider using something like nanosleep() and sleeping for 1/4th of a second or so.
Suggestion: Use pthread_cond
Ideally, you should be using the pthread_cond set of functions instead of trying to implement the event triggering yourself.
For example, calling pthread_cond_wait() is really all you would need to do inside of your EventListenerWait() function, and will automatically block your thread and release CPU time back to the OS until it is signalled. You can then trigger your event by calling pthread_cond_signal(). No trigger variable would be needed at all. | {
"domain": "codereview.stackexchange",
"id": 44384,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "beginner, c, event-handling, pthreads",
"url": null
} |
php, laravel
Title: Route protection with custom middleware in Laravel 8
Question: I am working on a blogging application in Laravel 8.
The application assigns users roles and permissions. There is a many-to-many relationship between roles and permissions.
I have created a custom middleware to give users access to routes based on their permissions:
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class CheckUserPermissions
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
// Permissions checker
public function hasPermissionTo($permission) {
return in_array($permission, Auth::user()->role->permissions->pluck('slug')->toArray());
}
public function handle(Request $request, Closure $next, ...$permissions)
{
// Check user permissions
foreach ($permissions as $permission) {
if (!$this->hasPermissionTo($permission)) {
$permission_label = join(' ', explode('-', $permission));
return redirect()->back()->with('error', 'You do not have permission to ' . $permission_label);
}
}
return $next($request);
}
}
In routes\web.php I have:
// Dashboard routes
Route::group(['prefix' => 'dashboard', 'middleware' => ['auth']], function() {
Route::get('/', [DashboardController::class, 'index'])->name('dashboard');
// Settings routes
Route::group(['prefix' => 'settings', 'middleware' => ['checkUserPermissions:edit-settings']], function() {
Route::get('/', [SettingsController::class, 'index'])->name('dashboard.settings');
Route::post('/update', [SettingsController::class, 'update'])->name('dashboard.settings.update');
}); | {
"domain": "codereview.stackexchange",
"id": 44385,
"lm_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, laravel",
"url": null
} |
php, laravel
// Pages routes
Route::group(['prefix' => 'pages'], function() {
Route::get('/', [PageController::class, 'index'])->name('dashboard.pages')->middleware('checkUserPermissions:view-pages');
Route::get('/new', [PageController::class, 'create'])->name('dashboard.pages.new')->middleware('checkUserPermissions:add-pages');
Route::post('/add', [PageController::class, 'save'])->name('dashboard.pages.add');
Route::get('/edit/{id}', [PageController::class, 'edit'])->name('dashboard.pages.edit')->middleware('checkUserPermissions:edit-pages');
Route::post('/update/{id}', [PageController::class, 'update'])->name('dashboard.pages.update');
Route::get('/delete/{id}', [PageController::class, 'delete'])->name('dashboard.pages.delete')->middleware('checkUserPermissions:delete-pages');
});
// Category routes
Route::group(['prefix' => 'categories'], function() {
Route::get('/', [ArticleCategoryController::class, 'index'])->name('dashboard.categories')->middleware('checkUserPermissions:view-categories');
Route::get('/new', [ArticleCategoryController::class, 'create'])->name('dashboard.categories.new')->middleware('checkUserPermissions:add-categories');
Route::post('/add', [ArticleCategoryController::class, 'save'])->name('dashboard.categories.add');
Route::get('/edit/{id}', [ArticleCategoryController::class, 'edit'])->name('dashboard.categories.edit')->middleware('checkUserPermissions:edit-categories');
Route::post('/update/{id}', [ArticleCategoryController::class, 'update'])->name('dashboard.categories.update');
Route::get('/delete/{id}', [ArticleCategoryController::class, 'delete'])->name('dashboard.categories.delete')->middleware('checkUserPermissions:delete-categories');
}); | {
"domain": "codereview.stackexchange",
"id": 44385,
"lm_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, laravel",
"url": null
} |
php, laravel
// Article routes
Route::group(['prefix' => 'articles'], function() {
Route::get('/', [ArticleController::class, 'index'])->name('dashboard.articles')->middleware('checkUserPermissions:view-articles');
Route::get('/new', [ArticleController::class, 'create'])->name('dashboard.articles.new')->middleware('checkUserPermissions:add-articles');
Route::post('/add', [ArticleController::class, 'save'])->name('dashboard.articles.add');
Route::get('/edit/{id}', [ArticleController::class, 'edit'])->name('dashboard.articles.edit')->middleware('checkUserPermissions:edit-articles');
Route::post('/update/{id}', [ArticleController::class, 'update'])->name('dashboard.articles.update');
Route::get('/delete/{id}', [ArticleController::class, 'delete'])->name('dashboard.articles.delete')->middleware('checkUserPermissions:delete-articles');
});
// Comments routes
Route::group(['prefix' => 'comments'], function() {
Route::get('/', [CommentController::class, 'index'])->name('dashboard.comments')->middleware('checkUserPermissions:view-comments');
Route::get('/delete/{id}', [CommentController::class, 'delete'])->name('dashboard.comments.delete')->middleware('checkUserPermissions:delete-comments');
Route::get('/approve/{id}', [CommentController::class, 'approve'])->name('dashboard.comments.approve')->middleware('checkUserPermissions:approve-comments');
Route::get('/unapprove/{id}', [CommentController::class, 'unapprove'])->name('dashboard.comments.unapprove')->middleware('checkUserPermissions:unapprove-comments');
}); | {
"domain": "codereview.stackexchange",
"id": 44385,
"lm_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, laravel",
"url": null
} |
php, laravel
// User management routes
Route::group(['prefix' => 'users'], function() {
Route::get('/rights', [UserRightsController::class, 'index'])->name('user-rights')->middleware('checkUserPermissions:manage-user-rights');;
Route::get('/rights/change-role/{id}', [UserRightsController::class, 'change_role'])->name('change-role')->middleware('checkUserPermissions:assign-user-roles');
Route::post('/rights/update-role/{id}', [UserRightsController::class, 'update_role'])->name('update-role');
Route::get('/rights/ban/{id}', [UserRightsController::class, 'ban_user'])->name('ban-user')->middleware('checkUserPermissions:ban-users');
Route::get('/rights/activate/{id}', [UserRightsController::class, 'activate_user'])->name('activate-user')->middleware('checkUserPermissions:activate-users');
});
});
The Super-admin has several abilities related to user management:
use App\Models\User;
use App\Models\Role;
class UserRightsController extends Controller
{
public function roles() {
return Role::all();
}
public function index() {
$users = User::paginate(10);
return view('dashboard/user-rights', ['users' => $users]);
}
public function change_role($id) {
$user = User::find($id);
return view('dashboard/change-role',['user' => $user, 'roles' => $this->roles()]);
}
public function update_role(Request $request, $id) {
$user = User::find($id);
$user->role_id = $request->get('role_id');
$user->save();
return redirect()->route('user-rights')->with('success', 'The role for ' . $user->first_name . ' ' . $user->last_name . ' was updated');
}
public function ban_user($id){
User::find($id)->update(['active' => 0]);
return redirect()->back()->with('success', 'The user is now banned');
}
public function activate_user($id){
User::find($id)->update(['active' => 1]);
return redirect()->back()->with('success', 'The user is now active');
}
}
Questions: | {
"domain": "codereview.stackexchange",
"id": 44385,
"lm_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, laravel",
"url": null
} |
php, laravel
Questions:
Do you see any security issues in the code above?
Are there ways to make it more DRY?
Do you see any architecture flaw?
Answer:
I see an avoidable single-use variable. And explode-join can be replaced with str_replace.
$permission_label = join(' ', explode('-', $permission));
return redirect()->back()->with('error', 'You do not have permission to ' . $permission_label);
Can be reduced to:
return redirect()->back()->with(
'error',
'You do not have permission to ' . str_replace('-', ' ', $permission)
);
I'd probably not declare $users in index() nor $user in change_role().
I recommend adding type declarations to all of the $id arguments in the UserRightsController() class as well as $permission in the hasPermissionTo() method. Even handle() can have string ...$permissions.
I do not have any insights regarding security; I have no experience with Laravel. | {
"domain": "codereview.stackexchange",
"id": 44385,
"lm_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, laravel",
"url": null
} |
c, c99
Title: Solution to Codejam 2019 1A (Pylons) in C
Question: The following is my solution to the Pylons problem from Codejam 2019: https://codingcompetitions.withgoogle.com/codejam/round/0000000000051635/0000000000104e03.
Our Battlestarcraft Algorithmica ship is being chased through space by persistent robots called Pylons! We have just teleported to a new galaxy to try to shake them off of our tail, and we want to stay here for as long as possible so we can buy time to plan our next move... but we do not want to get caught!
This galaxy is a flat grid of R rows and C columns; the rows are numbered from 1 to R from top to bottom, and the columns are numbered from 1 to C from left to right. We can choose which cell to start in, and we must continue to jump between cells until we have visited each cell in the galaxy exactly once. That is, we can never revisit a cell, including our starting cell.
We do not want to make it too easy for the Pylons to guess where we will go next. Each time we jump from our current cell, we must choose a destination cell that does not share a row, column, or diagonal with that current cell. Let (i, j) denote the cell in the i-th row and j-th column; then a jump from a current cell (r, c) to a destination cell (r', c') is invalid if and only if any of these is true:
r = r'
c = c'
r - c = r' - c'
r + c = r' + c'
Can you help us find an order in which to visit each of the R × C cells, such that the move between any pair of consecutive cells in the sequence is valid? Or is it impossible for us to escape from the Pylons? In summary, the task is to visit every cell in an RxC grid exactly once, without jumping to a cell that shares a row, column, or diagonal with the previous cell. If it is possible to visit every cell, the solution should print the sequence of steps.
This is a standard backtracking problem, but there is a caveat. We want to check cells in "random" order, or otherwise the solution will be too slow. | {
"domain": "codereview.stackexchange",
"id": 44386,
"lm_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, c99",
"url": null
} |
c, c99
The code is correct, i.e. it gets two green checkmarks. I'd appreciate any feedback!
#include <stdbool.h>
#include <stdio.h>
#define MAX_R 20
#define MAX_C 20
bool backtrack(bool visited_cells[][MAX_C], int sequence[][2], int R, int C, int visited_count, int r, int c) {
// Total number of cells
int N = R * C;
// Return true if we have visited every cell.
if (visited_count == N) {
return true;
}
// Otherwise, try every legal jump in "random" order.
visited_count++;
for (int i = 0; i < N; i++) {
// Next row and column to visit
// Note that checking cells in consecutive order will be very slow.
int nrc = i * 29 % N;
// Next row
int nr = nrc / C;
// Next column
int nc = nrc % C;
// Skip the cell if we have already visited it.
if (visited_cells[nr][nc]) {
continue;
}
// Skip any invalid jumps.
if (visited_count > 1 && (r == nr || c == nc || r - c == nr - nc || r + c == nr + nc)) {
continue;
}
// Record our chosen cell.
visited_cells[nr][nc] = true;
sequence[visited_count-1][0] = nr;
sequence[visited_count-1][1] = nc;
// Recurse and try to visit the rest of the cells.
if (backtrack(visited_cells, sequence, R, C, visited_count, nr, nc)) {
// We have found a solution.
return true;
}
// If we failed, undo our choice and try another cell.
visited_cells[nr][nc] = false;
}
// We haven't found a solution.
return false;
}
bool solve(int sequence[][2], int R, int C) {
// Array to keep track of visited cells.
bool visited_cells[MAX_R][MAX_C];
// Initially, we haven't visited any cells.
for (int r = 0; r < R; r++) {
for (int c = 0; c < C; c++) {
visited_cells[r][c] = false;
}
}
// Try to visit every cell using exhaustive search.
return backtrack(visited_cells, sequence, R, C, 0, -1, -1);
} | {
"domain": "codereview.stackexchange",
"id": 44386,
"lm_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, c99",
"url": null
} |
c, c99
int main(void) {
// Number of test cases
int T = 0;
scanf("%d", &T);
// Solve each test case.
for (int t = 1; t <= T; t++) {
// Number of rows
int R = 0;
// Number of columns
int C = 0;
scanf("%d %d", &R, &C);
// Array to keep track of a solution
int sequence[R * C][2];
// Solve the case.
bool possible = solve(sequence, R, C);
// Print our verdict.
printf("Case #%d: %s\n", t, possible ? "POSSIBLE" : "IMPOSSIBLE");
if (possible) {
// Print our solution sequence.
for (int i = 0; i < R * C; i++) {
printf("%d %d\n", sequence[i][0] + 1, sequence[i][1] + 1);
}
}
}
}
Example output:
$ cat tests.txt
2
2 2
2 5
$ ./solution < tests.txt
Case #1: IMPOSSIBLE
Case #2: POSSIBLE
1 1
2 4
1 2
2 5
1 3
2 1
1 4
2 2
1 5
2 3
Answer: These coding competition sites are great at teaching you tricks and algorithms, but they are terrible at teaching you to write readable and maintainable code. Let's see how we can improve the latter.
Naming things
Short variable names save some typing, but it is hard to read code that only contains abbreviations. Only use one-letter variable names if that letter is used in a very common way, like i as a loop iterator, or if its scope is very limited, so that you don't have to go searching through the code to find out where it is declared and what it means. Here are some suggestions for replacements:
R → n_rows. Now we no longer have to guess that r stands for row. The prefix n_ is commonly used to indicate "number of". You might also drop the prefix and just write rows, but see below about that.
C -> n_cols or n_columns
r -> row
c -> col or column
N -> n_cells. If you drop the prefix, it will be cells, but notice how you already have the array visible_cells: now cells might start to sound like an array as well. This is where n_ removes any doubt.
nr -> next_row
nc -> next_col or next_column
nrc -> next_cell | {
"domain": "codereview.stackexchange",
"id": 44386,
"lm_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, c99",
"url": null
} |
c, c99
Names like backtrack and solve are very generic. Backtrack what? Solve what and how? If you use them in a larger program where you need to solve different kinds of things, having these generic names in the global namespace will cause a problem when linking your code. So either give them more unique names, or make sure these names are not visible outside of the source file they are in, by making these functions static.
Don't hesitate to create structs
A great way to make your code easier to write, more maintainable and more self-documenting is by creating structs for things that always occur together. For example, you have a 2-dimensional array of integers named sequence, but actually it's just a 1-dimensional array of coordinates. You can make it look like the latter if you create a struct that describes a coordinate:
typedef struct {
int row;
int col;
} coordinate;
And then you can write:
static bool backtrack(…, coordinate sequence[], …) {
…
sequence[visited_count - 1].row = next_row;
sequence[visited_count - 1].col = next_col;
…
}
But it gets better if you make more use of coordinate. Use it everywhere you have a combination of row and column. For example:
static bool backtrack(…, coordinate sequence[], coordinate size,
int visited_count, coordinate pos) {
int n_cells = size.row * size.col;
…
coordinate next_pos = {next_cell / size.cols, next_cell % size.cols};
…
sequence[visited_count - 1] = next_pos;
if (backtrack(…, sequence, size, visited_count, next_pos)) {
…
}
…
}
Next, consider that your algorithm has some state that it has to pass to backtrack every time. This gets easier if you group all the state in a struct:
typedef struct {
coordinate *sequence;
coordinate size;
bool visited_cells[MAX_ROWS][MAX_COLS];
} backtrack_state; | {
"domain": "codereview.stackexchange",
"id": 44386,
"lm_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, c99",
"url": null
} |
c, c99
Note that this includes all the state that is shared by all invocations of backtrack(), it doesn't include the variables that are local to each invocation (visited_count, r and c). Now you can write:
static bool backtrack(backtrack_state *state, int visited_count,
coordinate pos) {
int n_cells = state->size.row * state->size.col;
…
coordinate next_pos = {next_cell / size.cols, next_cell % size.cols};
…
state->sequence[visited_count - 1] = next_pos;
if (backtrack(state, visited_count, next_pos)) {
…
}
…
}
static bool solve(coordinate sequence[], coordinate size) {
backtrack_state state = {sequence, size, {{0}}};
return backtrack(&state, 0, (coordinate){-1, -1});
}
Note how we can initialize the state, including the two-dimensional array visited_cells, all in one go.
Simplify functions
Try to keep functions simple and concise. If you find out you are doing a lot of things in one function, see if you can split it up in a meaningful way. For example, in main(), you read the number of test cases, and then proceed to process each test case in sequence. You can create a function that just does one test case, that way the code simplifies like so:
static void process_test_case(int case_nr) {
coordinate size;
scanf("%d %d", &size.row, &size.col);
int n_cells = size.row * size.col;
coordinate sequence[n_cells];
bool possible = solve(sequence, size);
printf("Case #%d: %s\n", case_nr, possible ? "POSSIBLE" : "IMPOSSIBLE");
if (possible) {
for (int i = 0; i < n_cells; i++) {
printf("%d %d\n", sequence[i].row + 1, sequence[i].col + 1);
}
}
}
int main(void) {
int n_cases;
scanf("%d", &n_cases);
for (int case_nr = 1; case_nr <= n_cases; case_nr++) {
process_test_case(case_nr);
}
} | {
"domain": "codereview.stackexchange",
"id": 44386,
"lm_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, c99",
"url": null
} |
c, c99
Note that this also automatically helps document the code: we now have a name for exactly that piece of code that processes a single test case, so you don't need a comment to explain that. That also brings me to:
Avoid unnecessary comments
You have added a lot of comments to your code, but some of them are not really necessary. If it is obvious from the code what is going on, you don't need a comment that says exactly the same thing. Of course, if you use cryptic variable and function names, you might need comments to decode what is going on, but if you have clear variable and function names, the need for comments often goes away. Consider:
// Total number of cells
int N = R * C;
Yes, N is so generic, it often means "number of things", but what things? Now consider:
int n_cells = size.row * size.col;
The name n_cells implies it is the number of cells, so now you no longer have to explain that. It is now also clear that it's the product of the size in rows and columns, instead of resistance times capacitance, or whatever R and C might mean if you don't already know the context.
If you have a complex expression and need to explain what it means, consider assigning it to a variable with a clear name first. Maybe split up very long expressions into smaller ones first. You can also create helper functions. For example:
static bool is_valid_jump(coordinate from, coordinate to) {
if (from.row == to.row) {
return false;
}
if (from.col == to.col) {
return false;
}
…
}
…
if (visited_count > 1 && !is_valid_jump(pos, next_pos)) {
continue;
}
Some comments are very necessary though. Consider the calculation of the next position. You are hinting that scanning sequentially is going to be to slow. But what about that % 29? Here a comment explaining in more detail what is going on would be very helpful. It's not really choosing a random position, but perhaps this very pseudo-random way is good enough? How was the constant 29 chosen? | {
"domain": "codereview.stackexchange",
"id": 44386,
"lm_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, c99",
"url": null
} |
python, performance, python-3.x, numpy
Title: Solve an option pricing PDE in Python - Part 1
Question: The Github repository NM-Heston solves call option prices under the Heston 2-factor model using ADI splitting schemes. I am adapting the code to price options under the 3-factor Heston-Hull-White model, also using ADI splitting schemes. While doing this, I became curious if it is possible to get rid of the nested for loops in the make_matrices() function, and instead create a vectorized version. Similar to my question posted here: Solving a 3D heat diffusion PDE.
The code within mat_factory.py is too long to post here and I have instead taken a snippet of the code, tweaked it, and added it below. I would like to understand how to convert it to a vectorized version. Once I understand, I will do it for the entire piece of code. The snippet is as follows:
import numpy as np
x = 5
y = 3
Vec_x = np.linspace(0, 1, x + 1)
Vec_y = np.linspace(0, 1, y + 1)
m = (x + 1) * (y + 1)
A_0 = np.zeros((m, m))
for i in range(1, x):
for j in range(1, y):
A_0[i + j * (x + 1), (i - 1) + (j + -1) * (x + 1)] += 2 * Vec_x[i] * Vec_y[j] * (Vec_x[i + 1] - Vec_x[i]) / (Vec_x[i] - Vec_x[i - 1]) / (Vec_x[i + 1] - Vec_x[i - 1]) * (Vec_y[j + 1] - Vec_y[j]) / (Vec_y[j] - Vec_y[j - 1]) / (Vec_y[j + 1] - Vec_y[j - 1])
print(sum(sum(A_0)))
>>15.0
I am therefore trying to get rid of the nested for loops in the code snippet above, and replace it with a vectorized version. I am doing this to see if I can cut down on execution time, while also shortening the code.
Answer: Step 1: don't linspace your sample data. This allows for a certain category of transposition error. Instead just use random data for more confidence in the regression tests.
Format
Step 2: your formatting is completely impenetrable, and in its current state masks the actual structure of the problem. Reformat to:
y = 3
x = 5
rand = default_rng(seed=0)
vec_y = rand.random(y + 1)
vec_x = rand.random(x + 1)
m = (y + 1)*(x + 1) | {
"domain": "codereview.stackexchange",
"id": 44387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy",
"url": null
} |
python, performance, python-3.x, numpy
m = (y + 1)*(x + 1)
def old() -> np.ndarray:
A_0 = np.zeros((m, m))
for i in range(1, y):
for j in range(1, x):
A_0[
j + (i )*(x + 1),
j + (i - 1)*(x + 1) - 1,
] += (
vec_y[i] * (vec_y[i + 1] - vec_y[i])
* vec_x[j] * (vec_x[j + 1] - vec_x[j])
/ (vec_y[i] - vec_y[i - 1]) / (vec_y[i + 1] - vec_y[i - 1])
/ (vec_x[j] - vec_x[j - 1]) / (vec_x[j + 1] - vec_x[j - 1])
)
return 2*A_0
While you do this, rearrange your loops and expressions to be in row-major order: \$y\$ and \$i\$ first, and by convention, \$i\$ being the vertical index.
Linear algebra
Now do your linear-algebraic analysis. Your problem has a high degree of symmetry - in fact, \$A_0\$ is symmetric about one diagonal, and all other diagonals are nothing but 0. This can be proven by the relation
$$
a_j = a_i - x - 2
$$
with \$a_i\$ and \$a_j\$ the indices into your matrix. Since \$a_i\$ has no duplicates and
$$
\frac {\partial a_i} {\partial a_j} = 1
$$
there must be unique indices on a single diagonal.
Now observe that there are two sub-expressions, one for each of \$\vec x\$ and \$\vec y\$, that are structurally identical, independent and evaluated in one dimension. This is due to your ADI construction. Get your offsets and define a common function via
def adi_shift(a: np.ndarray) -> np.ndarray:
a0, a1, a2 = sliding_window_view(a, a.size - 2)
return a1 * (a2 - a1) / (a1 - a0) / (a2 - a0)
In the main routine, the diagonal is now
2 * np.outer(adi_shift(vec_y), adi_shift(vec_x)) | {
"domain": "codereview.stackexchange",
"id": 44387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy",
"url": null
} |
python, performance, python-3.x, numpy
In the main routine, the diagonal is now
2 * np.outer(adi_shift(vec_y), adi_shift(vec_x))
In other words, with \$\vec y\$ as a vertical vector and \$\vec x\$ as a horizontal vector, find the matrix product. This will not yet be in dimensions suitable for \$A_0\$.
In the main routine, define your indices not as scalars but as vectors, and do not add 1 to your lengths:
y = len(vec_y)
x = len(vec_x)
i = np.arange(1, y-1)
j = np.arange(1, x-1)
ai = np.add.outer(i*x, j)
aj = ai - (x + 1)
Create \$A_0\$ as you were, but do not add to it. One error in the original implementation is that the individual elements were treated as a sum when they need to be an assignment. Assign by index:
A_0[ai, aj] = 2 * np.outer(adi_shift(vec_y), adi_shift(vec_x))
Move all code into functions and add PEP484 typehints.
Suggested
All together:
from typing import Callable
import numpy as np
from numpy.lib.stride_tricks import sliding_window_view
from numpy.random import default_rng
def old(vec_y: np.ndarray, vec_x: np.ndarray) -> np.ndarray:
y = len(vec_y) - 1
x = len(vec_x) - 1
m = (y + 1)*(x + 1)
A_0 = np.zeros((m, m))
for i in range(1, y):
for j in range(1, x):
A_0[
j + (i )*(x + 1),
j + (i - 1)*(x + 1) - 1,
] += (
vec_y[i] * (vec_y[i + 1] - vec_y[i])
* vec_x[j] * (vec_x[j + 1] - vec_x[j])
/ (vec_y[i] - vec_y[i - 1]) / (vec_y[i + 1] - vec_y[i - 1])
/ (vec_x[j] - vec_x[j - 1]) / (vec_x[j + 1] - vec_x[j - 1])
)
return 2*A_0
def adi_shift(a: np.ndarray) -> np.ndarray:
a0, a1, a2 = sliding_window_view(a, a.size - 2)
return a1 * (a2 - a1) / (a1 - a0) / (a2 - a0) | {
"domain": "codereview.stackexchange",
"id": 44387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy",
"url": null
} |
python, performance, python-3.x, numpy
def new(vec_y: np.ndarray, vec_x: np.ndarray) -> np.ndarray:
y = len(vec_y)
x = len(vec_x)
i = np.arange(1, y-1)
j = np.arange(1, x-1)
ai = np.add.outer(i*x, j)
aj = ai - (x + 1)
m = y*x
A_0 = np.zeros((m, m))
A_0[ai, aj] = 2 * np.outer(adi_shift(vec_y), adi_shift(vec_x))
return A_0
def test(
vec_y: np.ndarray,
vec_x: np.ndarray,
method: Callable[[np.ndarray, np.ndarray], np.ndarray],
) -> None:
A_0 = method(vec_y, vec_x)
assert 0 == np.count_nonzero(np.tril(A_0, k=-7 - 1))
assert 0 == np.count_nonzero(np.triu(A_0, k=-7 + 1))
assert np.allclose(
np.diag(A_0, -7),
[
-9.88163813, -0.60548181, -24.43299993, 3.96913142,
0. , 0. , 3.14201806, 0.19252221,
7.76884623, -1.26204607, 0. , 0. ,
0. , 0. , 0. , 0. ,
0. ,
]
)
def main() -> None:
rand = default_rng(seed=0)
vec_x = rand.random(6)
vec_y = rand.random(4)
test(vec_y, vec_x, old)
test(vec_y, vec_x, new)
if __name__ == '__main__':
main()
True diagonal initialisation
One potential optimisation is to make an actual diagonal vector first, and then call diagflat; this is equivalent and quite easier:
def new(vec_y: np.ndarray, vec_x: np.ndarray) -> np.ndarray:
y = len(vec_y)
x = len(vec_x)
diag = np.zeros((y-1, x))
diag[:-1, :-2] = 2 * np.outer(adi_shift(vec_y), adi_shift(vec_x))
return np.diagflat(diag.ravel()[:-1], k=-1 - x)
Sparse matrices
You have not offered any indication as to the true scale of your problem. Sparse matrices may be called-for. Read on scipy.sparse.diags. Past a certain point, \$A_0\$ is non-representable with a dense matrix, and only a sparse matrix is feasible:
from timeit import timeit
from typing import Callable | {
"domain": "codereview.stackexchange",
"id": 44387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy",
"url": null
} |
python, performance, python-3.x, numpy
import numpy as np
import scipy.sparse
from numpy.lib.stride_tricks import sliding_window_view
from numpy.random import default_rng
from scipy.sparse import spmatrix
def old(vec_y: np.ndarray, vec_x: np.ndarray) -> np.ndarray:
y = len(vec_y) - 1
x = len(vec_x) - 1
m = (y + 1)*(x + 1)
A_0 = np.zeros((m, m))
for i in range(1, y):
for j in range(1, x):
A_0[
j + (i )*(x + 1),
j + (i - 1)*(x + 1) - 1,
] += (
vec_y[i] * (vec_y[i + 1] - vec_y[i])
* vec_x[j] * (vec_x[j + 1] - vec_x[j])
/ (vec_y[i] - vec_y[i - 1]) / (vec_y[i + 1] - vec_y[i - 1])
/ (vec_x[j] - vec_x[j - 1]) / (vec_x[j + 1] - vec_x[j - 1])
)
return 2*A_0
def adi_shift(a: np.ndarray) -> np.ndarray:
a0, a1, a2 = sliding_window_view(a, a.size - 2)
return a1 * (a2 - a1) / (a1 - a0) / (a2 - a0)
def new(vec_y: np.ndarray, vec_x: np.ndarray) -> spmatrix:
y = len(vec_y)
x = len(vec_x)
diag = np.zeros((y-1, x))
diag[:-1, :-2] = 2 * np.outer(adi_shift(vec_y), adi_shift(vec_x))
return scipy.sparse.diags(diag.ravel()[:-1], offsets=-1 - x) | {
"domain": "codereview.stackexchange",
"id": 44387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy",
"url": null
} |
python, performance, python-3.x, numpy
def test(
vec_y: np.ndarray,
vec_x: np.ndarray,
method: Callable[[np.ndarray, np.ndarray], np.ndarray],
) -> None:
A_0 = method(vec_y, vec_x)
if scipy.sparse.issparse(A_0):
assert 0 == scipy.sparse.tril(A_0, k=-7 - 1).count_nonzero()
assert 0 == scipy.sparse.triu(A_0, k=-7 + 1).count_nonzero()
diag = A_0.diagonal(k=-7)
else:
assert 0 == np.count_nonzero(np.tril(A_0, k=-7 - 1))
assert 0 == np.count_nonzero(np.triu(A_0, k=-7 + 1))
diag = np.diag(A_0, -7)
assert np.allclose(
diag,
[
-9.88163813, -0.60548181, -24.43299993, 3.96913142,
0. , 0. , 3.14201806, 0.19252221,
7.76884623, -1.26204607, 0. , 0. ,
0. , 0. , 0. , 0. ,
0. ,
]
)
def main() -> None:
rand = default_rng(seed=0)
vec_x = rand.random(6)
vec_y = rand.random(4)
test(vec_y, vec_x, old)
test(vec_y, vec_x, new)
vec_y = rand.random(17)
vec_x = rand.random(26)
a0 = old(vec_y, vec_x)
a1 = new(vec_y, vec_x)
assert np.allclose(a0, a1.toarray())
vec_y = rand.random(30_000)
vec_x = rand.random(2_000)
def run():
return new(vec_y, vec_x)
print(
f'{len(vec_y)}x{len(vec_x)} '
f'in {timeit(run, number=1):.4f}'
)
if __name__ == '__main__':
main()
Performance
Using a test routine of
def main() -> None:
rand = default_rng(seed=0)
vec_x = rand.random(6)
vec_y = rand.random(4)
test(vec_y, vec_x, old)
test(vec_y, vec_x, new)
vec_y = rand.random(17)
vec_x = rand.random(26)
a0 = old(vec_y, vec_x)
a1 = new(vec_y, vec_x)
assert np.allclose(a0, a1)
vec_y = rand.random(250)
vec_x = rand.random(150)
def run():
return new(vec_y, vec_x)
print(
f'{len(vec_y)}x{len(vec_x)} '
f'in {timeit(run, number=1):.4f}'
) | {
"domain": "codereview.stackexchange",
"id": 44387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy",
"url": null
} |
python, performance, python-3.x, numpy
with the diagflat method, this executes quickly:
250x150 in 0.0691
I run out of memory before I run out of time.
With the sparse method this is vastly improved:
250x150 in 0.0005
30000x2000 in 0.5826
Comparing the original and sparse methods for size 200x100, there is a speedup multiple of about 270. | {
"domain": "codereview.stackexchange",
"id": 44387,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, python-3.x, numpy",
"url": null
} |
c#, .net, redis
Title: Redis Output Cache Store refactoring - IOutputCacheStore Redis Implementation
Question: This code incorporates the new .NET 7 Output Caching. I would like to get some refactoring tips on the RedisOutputCacheStore class.
How to use
// Redis Output Cache
builder.Services.AddStackExchangeRedisCache(options => options.ConfigurationOptions = new ConfigurationOptions
{
EndPoints = { "localhost:6379" },
Password = "my_master_password",
Ssl = false // false for development testing purposes
});
builder.Services.AddRedisOutputCache();
app.UseOutputCache();
app.MapGet("/cache", () =>
{
Log.Information("Cache 1 called");
return Task.FromResult(Results.Ok("This is the endpoint that gets cached for 30 seconds. It also gets categorised under the 'cache' tag"));
})
.CacheOutput(x => x
.Expire(TimeSpan.FromSeconds(30))
.Tag("cache"));
app.MapGet("/cache2", (ILoggerFactory loggerFactory) =>
{
Log.Information("Cache 2 called");
return Task.FromResult(Results.Ok("This is the secondary endpoint that gets cached for 20 seconds. It also gets categorised under the 'cache' tag"));
})
.CacheOutput(x => x
.Expire(TimeSpan.FromSeconds(20))
.Tag("cache"));
app.MapGet("/uncache",
async (IOutputCacheStore outputCacheStore, CancellationToken token) =>
{
await outputCacheStore.EvictByTagAsync("cache", token);
return Results.Ok("This endpoint removes all the values for the cached endpoints that are categorised under the 'cache' tag");
});
Code
public static class OutputCacheExtensions
{
/// <summary>
/// Add output caching services using Redis.
/// </summary>
/// <param name="services">The <see cref="IServiceCollection" /> for adding services.</param>
/// <returns></returns>
public static IServiceCollection AddRedisOutputCache(this IServiceCollection services)
{
ArgumentNullException.ThrowIfNull(services); | {
"domain": "codereview.stackexchange",
"id": 44388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, redis",
"url": null
} |
c#, .net, redis
services.AddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>();
services.AddSingleton<IOutputCacheStore>(sp =>
{
var distributedCache = sp.GetRequiredService<IDistributedCache>();
var redisCacheOptions = sp.GetRequiredService<IOptions<RedisCacheOptions>>();
return new RedisOutputCacheStore(distributedCache, redisCacheOptions);
});
return services;
}
}
public sealed class RedisOutputCacheStore : IOutputCacheStore
{
private const string SetScript = @"
redis.call('HSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
if ARGV[3] ~= '-1' then
redis.call('EXPIRE', KEYS[1], ARGV[3])
end
return 1";
private const string SetScriptPreExtendedSetCommand = @"
redis.call('HMSET', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
if ARGV[3] ~= '-1' then
redis.call('EXPIRE', KEYS[1], ARGV[3])
end
return 1";
private static readonly Version ServerVersionWithExtendedSetCommand = new(4, 0, 0);
private readonly IDistributedCache _distributedCache;
private readonly RedisCacheOptions _options;
private readonly SemaphoreSlim _connectionLock = new(1, 1);
private volatile IConnectionMultiplexer? _connection;
private IDatabase? _cache;
private string _setScript = SetScript;
public RedisOutputCacheStore(IDistributedCache distributedCache, IOptions<RedisCacheOptions> redisCacheOptions)
{
_distributedCache = distributedCache;
_options = redisCacheOptions.Value;
} | {
"domain": "codereview.stackexchange",
"id": 44388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, redis",
"url": null
} |
c#, .net, redis
public async ValueTask EvictByTagAsync(string tag, CancellationToken cancellationToken)
{
await ConnectAsync(cancellationToken).ConfigureAwait(false);
var memberKeys = _cache!.SetMembers($"tag_{tag}").Select(x => x.ToString());
var redisKeys = memberKeys.Select(x => new RedisKey(x)).ToArray();
await _cache.KeyDeleteAsync(redisKeys).ConfigureAwait(false);
}
public async ValueTask<byte[]?> GetAsync(string key, CancellationToken cancellationToken)
{
return await _distributedCache.GetAsync(key, cancellationToken).ConfigureAwait(false);
}
public async ValueTask SetAsync(string key, byte[] value, string[]? tags, TimeSpan validFor, CancellationToken cancellationToken)
{
var distributedCacheEntryOptions = new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = validFor };
await _distributedCache.SetAsync(key, value, distributedCacheEntryOptions, cancellationToken);
await AddKeyToTagSet(key, tags, cancellationToken).ConfigureAwait(false);
}
private async Task AddKeyToTagSet(string key, string[]? tags, CancellationToken cancellationToken)
{
if (tags == null)
{
return;
}
await ConnectAsync(cancellationToken).ConfigureAwait(false);
foreach (var tag in tags)
{
await _cache!.SetAddAsync($"tag_{tag}", key).ConfigureAwait(false);
}
}
private async Task ConnectAsync(CancellationToken token = default)
{
token.ThrowIfCancellationRequested();
if (_cache != null)
{
Debug.Assert(_connection != null);
return;
} | {
"domain": "codereview.stackexchange",
"id": 44388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, redis",
"url": null
} |
c#, .net, redis
await _connectionLock.WaitAsync(token).ConfigureAwait(false);
try
{
if (_cache == null)
{
if (_options.ConnectionMultiplexerFactory is null)
{
if (_options.ConfigurationOptions is not null)
{
_connection = await ConnectionMultiplexer.ConnectAsync(_options.ConfigurationOptions).ConfigureAwait(false);
}
else
{
_connection = await ConnectionMultiplexer.ConnectAsync(_options.Configuration).ConfigureAwait(false);
}
}
else
{
_connection = await _options.ConnectionMultiplexerFactory().ConfigureAwait(false);
}
PrepareConnection();
_cache = _connection.GetDatabase();
}
}
finally
{
_connectionLock.Release();
}
}
private void PrepareConnection()
{
ValidateServerFeatures();
TryRegisterProfiler();
}
private void ValidateServerFeatures()
{
_ = _connection ?? throw new InvalidOperationException($"{nameof(_connection)} cannot be null.");
try
{
foreach (var endPoint in _connection.GetEndPoints())
{
if (_connection.GetServer(endPoint).Version < ServerVersionWithExtendedSetCommand)
{
_setScript = SetScriptPreExtendedSetCommand;
return;
}
}
}
catch (NotSupportedException)
{
_setScript = SetScriptPreExtendedSetCommand;
}
}
private void TryRegisterProfiler()
{
_ = _connection ?? throw new InvalidOperationException($"{nameof(_connection)} cannot be null."); | {
"domain": "codereview.stackexchange",
"id": 44388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, redis",
"url": null
} |
c#, .net, redis
if (_options.ProfilingSession != null)
{
_connection.RegisterProfiler(_options.ProfilingSession);
}
}
}
```
Answer: It seems a fairly decent implement and easy to read code for me.
Here are some refactor ideas:
SetScript class members
As far as I can see the only difference is a single letter: HSET vs HMSET
In order to reduce the possibility of typo(s) I would suggest to use a template string and two string.Format calls
private const string ScriptTemplate = @"
redis.call('{0}', KEYS[1], 'absexp', ARGV[1], 'sldexp', ARGV[2], 'data', ARGV[4])
if ARGV[3] ~= '-1' then
redis.call('EXPIRE', KEYS[1], ARGV[3])
end
return 1";
private readonly string SetScript = string.Format(ScriptTemplate, "HSET");
private readonly string SetScriptPreExtendedSetCommand = string.Format(ScriptTemplate, "HMSET");
EvictByTagAsync
I don't see any reason why do you need the memberKeys variable
You could simply combine the two Linq queries into a single
var redisKeys = _cache!.SetMembers($"tag_{tag}")
.Select(value => new RedisKey(value.ToString()))
.ToArray();
SetAsync
It may or not may be a problem but the _distributedCache.SetAsync and AddKeyToTagSet are not treated atomically
It can happen that the first command succeeds but the second fails
It could cause inconsistency which could cause further problems later
AddKeyToTagSet
It might make sense to move the null check of the tags to the caller-side
await _distributedCache.SetAsync(key, value, distributedCacheEntryOptions, cancellationToken);
if(tags is not null)
await AddKeyToTagSet(key, tags, cancellationToken).ConfigureAwait(false);
It might also make sense to replace the sequential calls of SetAddAsync to parallel
var addTasks = tags.Select(tag => _cache!.SetAddAsync($"tag_{tag}", key));
await Task.WhenAll(addTasks).ConfigureAwait(false);
ConnectAsync
Personally I don't like multi-level if-else branching | {
"domain": "codereview.stackexchange",
"id": 44388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, redis",
"url": null
} |
c#, .net, redis
ConnectAsync
Personally I don't like multi-level if-else branching
The entire try block could be refactored like this:
if (_cache != null) return;
Func<Task<ConnectionMultiplexer>> connectVariant = _options.ConfigurationOptions is not null
? () => ConnectionMultiplexer.ConnectAsync(_options.ConfigurationOptions)
: () => ConnectionMultiplexer.ConnectAsync(_options.Configuration);
_connection = _options.ConnectionMultiplexerFactory is not null
? await _options.ConnectionMultiplexerFactory().ConfigureAwait(false)
: await connectVariant().ConfigureAwait(false);
//I've just inlined `PrepareConnection`
ValidateServerFeatures();
TryRegisterProfiler();
_cache = _connection.GetDatabase();
Unfortunately we can't combine all three options into single expression
Due to the incompatibility of Task<ConnectionMultiplexer> and Task<IConnectionMultiplexer>
ValidateServerFeatures
I've found quite confusing that
sometimes you use the null forgiving operator (so called damn-it operator)
other times null coalescing operator with throw expression
and you also have Debug.Assert calls
I think using a single option consistently helps the maintainability of your code
I would suggest to move the try-catch block inside the loop
bool shouldUpdateSetScript = false;
foreach (var endPoint in _connection.GetEndPoints())
{
try
{
var version = _connection.GetServer(endPoint).Version;
if (version < ServerVersionWithExtendedSetCommand)
shouldUpdateSetScript = true;
}
catch (NotSupportedException)
{
shouldUpdateSetScript = true;
}
if (shouldUpdateSetScript) break;
}
if(shouldUpdateSetScript)
_setScript = SetScriptPreExtendedSetCommand;
Or it might make sense to use a while loop instead of for | {
"domain": "codereview.stackexchange",
"id": 44388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, redis",
"url": null
} |
c#, .net, redis
Or it might make sense to use a while loop instead of for
bool shouldUpdateSetScript = false;
var endpointIterator = _connection.GetEndPoints().Cast<EndPoint>().GetEnumerator();
while (!shouldUpdateSetScript || endpointIterator.MoveNext())
{
try
{
var version = _connection.GetServer(endpointIterator.Current).Version;
if (version < ServerVersionWithExtendedSetCommand)
shouldUpdateSetScript = true;
}
catch (NotSupportedException)
{
shouldUpdateSetScript = true;
}
}
if(shouldUpdateSetScript)
_setScript = SetScriptPreExtendedSetCommand; | {
"domain": "codereview.stackexchange",
"id": 44388,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, redis",
"url": null
} |
c++, beginner, algorithm
Title: Bookstore program using standard algorithms
Question: This is the exercise, from C++ Primer 5th edition:
10.32: Rewrite the bookstore problem from § 1.6 (p. 24) using a vector to hold the transactions and various algorithms to do the
processing. Use sort with your compareIsbn function from § 10.3.1 (p.
387) to arrange the transactions in order, and then use find and
accumulate to do the sum."
Here's my code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <numeric>
#include "Sales_item.h"
bool compareIsbnv2(const Sales_item &sd1, const Sales_item &sd2)
{
return sd1.isbn() < sd2.isbn();
}
int main()
{
// get input from user
std::istream_iterator<Sales_item> item_iter(std::cin), eof;
std::ostream_iterator<Sales_item> out_iter(std::cout, "\n");
// make sure we have data to process
std::vector<Sales_item> trans(item_iter,eof);
if (item_iter == eof)
{
std::cerr << "no data to process!" << std::endl;
}
// sorting vector
std::sort(trans.begin(), trans.end(), compareIsbnv2);
std::cout << "Summing up data..\n";
for (auto& s : trans)
std::cout << s << "\n";
std::cout << "\n\n";
//Sales_item sum;
for (auto beg = trans.begin(); beg != trans.end(); beg++)
{
auto it = std::find_if_not(beg, trans.end(), [&](Sales_item& item)
{return item.isbn() == beg->isbn(); });
out_iter = std::accumulate(beg, it, Sales_item(beg->isbn()));
std::cout << "\n\n";
}
return 0;
}
For some reason that I didn't quite understand the original compare isbn function didn't work, so I'm not sure if the result I get is correct:
Input:
0-201-12345-X 3 20.00
0-205-12345-X 5 3.00
0-201-12345-X 2 20.00
0-202-12345-X 10 25.00
0-205-12345-X 10 5.00
0-202-12345-X 5 20.00
Output:
0-201-12345-X 5 100 20
0-201-12345-X 2 40 20
0-202-12345-X 15 350 23.3333
0-202-12345-X 5 100 20 | {
"domain": "codereview.stackexchange",
"id": 44389,
"lm_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, algorithm",
"url": null
} |
c++, beginner, algorithm
0-201-12345-X 2 40 20
0-202-12345-X 15 350 23.3333
0-202-12345-X 5 100 20
0-205-12345-X 15 65 4.33333
0-205-12345-X 10 50 5
Sales_item.h :
#ifndef SALESITEM_H
// we're here only if SALESITEM_H has not yet been defined
#define SALESITEM_H
// Definition of Sales_item class and related functions goes here
#include <iostream>
#include <string>
class Sales_item {
// these declarations are explained section 7.2.1, p. 270
// and in chapter 14, pages 557, 558, 561
friend std::istream& operator>>(std::istream&, Sales_item&);
friend std::ostream& operator<<(std::ostream&, const Sales_item&);
friend bool operator<(const Sales_item&, const Sales_item&);
friend bool
operator==(const Sales_item&, const Sales_item&);
public:
// constructors are explained in section 7.1.4, pages 262 - 265
// default constructor needed to initialize members of built-in type
Sales_item() = default;
Sales_item(const std::string& book) : bookNo(book) { }
Sales_item(std::istream& is) { is >> *this; }
public:
// operations on Sales_item objects
// member binary operator: left-hand operand bound to implicit this pointer
Sales_item& operator+=(const Sales_item&);
// operations on Sales_item objects
std::string isbn() const { return bookNo; }
double avg_price() const;
// private members as before
private:
std::string bookNo; // implicitly initialized to the empty string
unsigned units_sold = 0; // explicitly initialized
double revenue = 0.0;
};
// used in chapter 10
inline
bool compareIsbn(const Sales_item& lhs, const Sales_item& rhs)
{
return lhs.isbn() == rhs.isbn();
}
// nonmember binary operator: must declare a parameter for each operand
Sales_item operator+(const Sales_item&, const Sales_item&); | {
"domain": "codereview.stackexchange",
"id": 44389,
"lm_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, algorithm",
"url": null
} |
c++, beginner, algorithm
inline bool
operator==(const Sales_item& lhs, const Sales_item& rhs)
{
// must be made a friend of Sales_item
return lhs.units_sold == rhs.units_sold &&
lhs.revenue == rhs.revenue &&
lhs.isbn() == rhs.isbn();
}
inline bool
operator!=(const Sales_item& lhs, const Sales_item& rhs)
{
return !(lhs == rhs); // != defined in terms of operator==
}
// assumes that both objects refer to the same ISBN
Sales_item& Sales_item::operator+=(const Sales_item& rhs)
{
units_sold += rhs.units_sold;
revenue += rhs.revenue;
return *this;
}
// assumes that both objects refer to the same ISBN
Sales_item
operator+(const Sales_item& lhs, const Sales_item& rhs)
{
Sales_item ret(lhs); // copy (|lhs|) into a local object that we'll return
ret += rhs; // add in the contents of (|rhs|)
return ret; // return (|ret|) by value
}
std::istream&
operator>>(std::istream& in, Sales_item& s)
{
double price;
in >> s.bookNo >> s.units_sold >> price;
// check that the inputs succeeded
if (in)
s.revenue = s.units_sold * price;
else
s = Sales_item(); // input failed: reset object to default state
return in;
}
std::ostream&
operator<<(std::ostream& out, const Sales_item& s)
{
out << s.isbn() << " " << s.units_sold << " "
<< s.revenue << " " << s.avg_price();
return out;
}
double Sales_item::avg_price() const
{
if (units_sold)
return revenue / units_sold;
else
return 0;
}
#endif
Bookstore problem from § 1.6 (p. 24) : | {
"domain": "codereview.stackexchange",
"id": 44389,
"lm_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, algorithm",
"url": null
} |
c++, beginner, algorithm
Bookstore problem from § 1.6 (p. 24) :
We are now ready to solve our original bookstore problem. We need to read a file of
sales transactions and produce a report that shows, for each book, the total number
of copies sold, the total revenue, and the average sales price. We’ll assume that all
the transactions for each ISBN are grouped together in the input.
Our program will combine the data for each ISBN in a variable named total. We’ll
use a second variable named trans to hold each transaction we read. If trans and
total refer to the same ISBN , we’ll update total. Otherwise we’ll print total and
reset it using the transaction we just read:
#include <iostream>
#include "Sales_item.h"
int main()
{
Sales_item total; // variable to hold data for the next transaction
// read the first transaction and ensure that there are data to process
if (std::cin >> total) {
Sales_item trans; // variable to hold the running sum
// read and process the remaining transactions
while (std::cin >> trans) {
// if we're still processing the same book
if (total.isbn() == trans.isbn())
total += trans; // update the running total
else {
// print results for the previous book
std::cout << total << std::endl;
total = trans; // total now refers to the next book
}
}
std::cout << total << std::endl; // print the last transaction
} else {
// no input! warn the user
std::cerr << "No data?!" << std::endl;
return -1; // indicate failure
}
Answer: About the compare function
For some reason that I didn't quite understand the original compare isbn function didn't work | {
"domain": "codereview.stackexchange",
"id": 44389,
"lm_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, algorithm",
"url": null
} |
c++, beginner, algorithm
For some reason that I didn't quite understand the original compare isbn function didn't work
The compareIsbn() function I see in Sales_item.h compares two items for equality, however sort() has no use for that, it has to know in which order items have to be put. So it needs to be able to compare the order of two items.
I have no idea what you needed exactly in chapter 10, but consider that if you have a function that compares the order of two things, you can use that to get the equality as well, at least if there is a total order:
bool less(const auto& a, const auto& b) {
return a < b;
}
bool equal(const auto& a, const auto& b) {
return !less(a, b) && !less(b, a); // a >= b && b >= a → a == b
}
In any case, your compareIsbnv2() is a correct function for std::sort().
Your output contains the same book multiple times
I think the assignment is to have only one line of output for each unique ISBN number. When you have the start and end of a range of identical ISBNs, then you calculate the sum over that, and then skip to the item right after that range. This is simply:
for (auto beg = trans.begin(); beg != trans.end();)
{
auto it = std::find_if_not(…);
out_iter = std::accumulate(beg, it, Sales_item(beg->isbn()));
beg = it;
}
Naming
Make sure you give variables concise but meaningful names. Avoid abbreviations, unless they are very common ones, like i for a loop iterator. Also avoid naming variables after their type. Here is a list of suggested changes to names:
item_iter -> input
out_iter -> output
trans -> transactions
s -> transaction
beg -> begin or start
it -> end, or perhaps end_of_same to make it clear this is the end of the range of identical books. | {
"domain": "codereview.stackexchange",
"id": 44389,
"lm_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, algorithm",
"url": null
} |
c++, beginner, algorithm
Incorrect error checking
You are reading the input using std::istream_iterator, which is indeed very helpful here. However, the way you check for errors is not correct. Consider that an error might occur before reaching the end of the input, in which case item_iter might not be equal to eof. It is better to check that std::cin.eof() == true to see if the end of the input has been reached successfully.
What is important after that is that the vector holding the transactions is not empty, so instead of comparing the input iterators, write:
if (transactions.empty())
{
std::cerr << "No data to process!\n";
return EXIT_FAILURE;
} | {
"domain": "codereview.stackexchange",
"id": 44389,
"lm_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, algorithm",
"url": null
} |
c++, beginner, algorithm
Note also that if you encounter an error, it is usually a good idea to return an error or throw an exception. Luckily, the rest of your code still works fine if there were no transactions on the input. You might also consider this to be a valid input, in which case you shouldn't print an error message at all.
Note that an error can also happen on the output. What if the output is redirected to a file, but there is an error writing data to disk? If you ignore it and return 0, then it might look like your program finished successfully, which is not desirable. Check that std::cout.good() == true at the end of the program, and if not, write an error message to std::cerr and return EXIT_FAILURE.
How it would look in C++23
C++ is continuously evolving, and new features are added to make the life of programmers easier. It looks like the 5th edition of C++ Primer was released in 2012, and thus only covers the standard up to C++11. It's now more than a decade later, and we can do things differently now.
In particular, the ranges library allows us to avoid working with iterators, but operate on ranges instead. Effectively, most algorithms now take a reference to a container as a parameter. Also, there is an easy algorithm to group items in a container based on a predicate using std::views::chunk_by(). For some reason std::accumulate() was never made to work with ranges, but we now have std::ranges::fold_left() and related functions that can be used to do the same. Your code could look like:
#include <algorithm>
#include <iostream>
#include <ranges>
#include <stdexcept>
#include <vector>
…
int main()
{
std::istream_iterator<Sales_item> input(std::cin), eof;
std::ostream_iterator<Sales_item> output(std::cout, "\n");
std::vector transactions(input, eof);
if (!std::cin.eof())
throw std::runtime_error("Error reading input");
std::ranges::sort(transactions, compareIsbnv2); | {
"domain": "codereview.stackexchange",
"id": 44389,
"lm_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, algorithm",
"url": null
} |
c++, beginner, algorithm
std::ranges::sort(transactions, compareIsbnv2);
for (auto chunk: transactions | std::views::chunk_by(compareIsbn))
out_iter = std::ranges::fold_left_first(chunk, std::plus<>());
if (!std::cout.good())
throw std::runtime_error("Error writing output");
}
Note that it's currently hard to find compilers and standard libraries that have full C++23 support, so the above will probably not compile for you yet. | {
"domain": "codereview.stackexchange",
"id": 44389,
"lm_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, algorithm",
"url": null
} |
c#, performance, hash-map, console, csv
Title: Calculate average values for each day of the week for each Meter
Question: I have a program with these two methods. One method to import a set of data from a CSV within the given time period and store them in a dictionary. Here the data in CSV file is stored in following format with meter Id, Timestamp in UTC and value. For each meter there's approximately 2000 values.
"MeterId","Ts","Value"
10411,"2022-10-31T16:00:00.000Z","null"
10411,"2022-10-31T16:30:00.000Z",5150
My Read CSV method loads each line to a dictionary and loads each meter ID to a separate list. I passed the dictionary and list as reference since I'm using them for second method.
public static void ReadCSVData(DateTime mFromTime, DateTime mToTime, ref Dictionary<Tuple<string, DateTime>, float> mDictLines, ref List<string> mUniqueList)
{
Console.WriteLine(DateTime.Now.ToString() + " Reading CSV...");
List<string> lstMeters = new List<string>();
using (var reader = new StreamReader(gSourceFile))
{
while (!reader.EndOfStream)
{
//read single line
var line = reader.ReadLine();
var values = line.Split(',');
DateTime timeValue;
if (DateTime.TryParse(values[1].Trim('"'), out timeValue))
{
if (timeValue >= mFromTime && timeValue < mToTime)
{
if (values[2].Trim('"') != "null")
{
float meterValue = float.Parse(values[2].Trim('"'), CultureInfo.InvariantCulture.NumberFormat);
DateTime meterDate = DateTime.Parse(values[1].Trim('"')).AddHours(8); | {
"domain": "codereview.stackexchange",
"id": 44390,
"lm_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, hash-map, console, csv",
"url": null
} |
c#, performance, hash-map, console, csv
mDictLines.Add(Tuple.Create(values[0], meterDate), meterValue);
lstMeters.Add(values[0].Trim('"'));
}
}
}
}
}
mUniqueList.AddRange(lstMeters.Distinct());
}
My second method get the dictionary and list as arguments and calculate average values for each day of the week for each meter.
public static void CalculateAverageValues(Dictionary<Tuple<string, DateTime>, float> mDictLines, List<string> mUniqueList)
{
List<object> arrDoc = new List<object>();
IEnumerable<string> ieUnique = from itemUnique in mUniqueList select itemUnique;
foreach (string meterIdUnique in ieUnique)
{
float mondayTot = 0;
float tuesdayTot = 0;
float wednesdayTot = 0;
float thursdayTot = 0;
float fridayTot = 0;
float saturdayTot = 0;
float sundayTot = 0;
int mondayCount = 0;
int tuesdayCount = 0;
int wednesdayCount = 0;
int thursdayCount = 0;
int fridayCount = 0;
int saturdayCount = 0;
int sundayCount = 0;
foreach (KeyValuePair<Tuple<string, DateTime>, float> dictItem in mDictLines)
{
Tuple<string, DateTime> lineId = dictItem.Key;
if (meterIdUnique == lineId.Item1)
{ | {
"domain": "codereview.stackexchange",
"id": 44390,
"lm_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, hash-map, console, csv",
"url": null
} |
c#, performance, hash-map, console, csv
if (meterIdUnique == lineId.Item1)
{
switch (lineId.Item2.DayOfWeek)
{
case DayOfWeek.Monday:
mondayTot += dictItem.Value;
mondayCount++;
break;
case DayOfWeek.Tuesday:
tuesdayTot += dictItem.Value;
tuesdayCount++;
break;
case DayOfWeek.Wednesday:
wednesdayTot += dictItem.Value;
wednesdayCount++;
break;
case DayOfWeek.Thursday:
thursdayTot += dictItem.Value;
thursdayCount++;
break;
case DayOfWeek.Friday:
fridayTot += dictItem.Value;
fridayCount++;
break;
case DayOfWeek.Saturday:
saturdayTot += dictItem.Value;
saturdayCount++;
break;
case DayOfWeek.Sunday:
sundayTot += dictItem.Value;
sundayCount++;
break;
}
}
}
float avgMonday = (mondayTot / mondayCount);
float avgTuesday = (tuesdayTot / tuesdayCount);
float avgWednesday = (wednesdayTot / wednesdayCount);
float avgThursday = (thursdayTot / thursdayCount);
float avgFriday = (fridayTot / fridayCount);
float avgSaturday = (saturdayTot / saturdayCount);
float avgSunday = (sundayTot / sundayCount); | {
"domain": "codereview.stackexchange",
"id": 44390,
"lm_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, hash-map, console, csv",
"url": null
} |
c#, performance, hash-map, console, csv
Console.WriteLine(DateTime.Now.ToString() + " Processed data for meter " + meterIdUnique);
InsertDataToCSV(csv, meterIdUnique, avgMonday, avgTuesday, avgWednesday, avgThursday, avgFriday, avgSaturday, avgSunday);
}
File.WriteAllText(gResultFile, csv.ToString());
Console.WriteLine(DateTime.Now.ToString() + " Process over");
}
This code works fine but it takes approximately one minute to process data for 1500 meters. Is there a way I could speed it up?
Answer: Please note: the code has been reviewed in two parts.
Some modifications about the first part can be found under update #1 .
As I suggested in the comments you can take advantage of CsvHelper to parse csv for you.
I would suggest to split your ReadCSVData into two methods to embrace reusability:
The first method (ReadCSV) should read and parse the csv.
The second (FilterMeters) should perform the necessary filtering.
ReadCSV
The Meter class
class Meter
{
public int MeterId { get; set; }
public DateTime TimeStamp { get; set; }
public int? MeterValue { get; set; }
}
You might need to adjust the names of the fields and their data types for your needs
The ReadCSV method
static List<Meter> ReadCSV()
{
using var fileReader = new StreamReader("sample.csv");
using var csvReader = new CsvReader(fileReader, CultureInfo.InvariantCulture);
csvReader.Context.RegisterClassMap<MeterMap>();
csvReader.Context.TypeConverterOptionsCache.GetOptions<int?>().NullValues.Add("null");
return csvReader.GetRecords<Meter>().ToList();
}
It reads all the lines and try to parse them as Meter objects
The field mapping is defined inside MeterMap (see next section)
The null value handling for the MeterValue property is done via TypeConverterOptions | {
"domain": "codereview.stackexchange",
"id": 44390,
"lm_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, hash-map, console, csv",
"url": null
} |
c#, performance, hash-map, console, csv
The MeterMap class
sealed class MeterMap : ClassMap<Meter>
{
public MeterMap()
{
Map(m => m.MeterId).Name("MeterId");
Map(m => m.TimeStamp).Name("Ts");
Map(m => m.MeterValue).Name("Value");
}
}
This separation allows you to use different property names than the csv's column names
FilterMeters
static (Dictionary<(int, DateTime), int> groupedMeterValues, List<int> meterIds) FilterMeters(List<Meter> meters, DateTime fromTime, DateTime toTime)
{
var filteredMeters = meters.Where(m => m.TimeStamp >= fromTime && m.TimeStamp < toTime && m.MeterValue.HasValue);
return (filteredMeters.ToDictionary(m => (m.MeterId, m.TimeStamp), m => m.MeterValue.Value),
filteredMeters.Select(m => m.MeterId).Distinct().ToList());
}
You could use Tuples (as well as ValueTuples) as a return value as well
So, you don't need to pass parameters via ref
The filtering can be easily done via Linq's Where
The ToDictionary allows you to transform your data for your needs
BTW for this particular example we could also use here the Linq's GroupBy
Linq's Distinct allows you to select only once the duplicate values
UPDATE #1: Suggestions for CalculateAverageValues
After started working with the CalculateAverageValues method I've just realized that we don't need the unique meter ids collection.
So, the above FilterMeters could be rewritten like this:
static Dictionary<(int, DateTime), int> FilterMeters(IEnumerable<Meter> meters, DateTime fromTime, DateTime toTime)
{
return meters.Where(m => m.TimeStamp >= fromTime && m.TimeStamp < toTime && m.MeterValue.HasValue)
.ToDictionary(m => (m.MeterId, m.TimeStamp), m => m.MeterValue.Value);
}
If you would define a helper class/struct/record like bellow:
class AveragedMeter
{
public int MeterId { get; set; }
public DayOfWeek DayOfWeek { get; set; }
public double AverageMeterValue { get; set; }
} | {
"domain": "codereview.stackexchange",
"id": 44390,
"lm_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, hash-map, console, csv",
"url": null
} |
c#, performance, hash-map, console, csv
then the whole CalculateAverageValues could be as simple as this
public static List<AveragedMeter> CalculateAverageValues(Dictionary<(int MeterId, DateTime TimeStamp), int> groupedMeterValues)
{
return groupedMeterValues
.GroupBy(m => new { m.Key.MeterId, m.Key.TimeStamp.DayOfWeek })
.Select(g => new AveragedMeter {
MeterId = g.Key.MeterId,
DayOfWeek = g.Key.DayOfWeek,
AverageMeterValue = g.Average(m => m.Value) })
.ToList();
}
As you can see here I removed those lines that are responsible for writing to csv.
Finally, let's connect the dots
var meters = ReadCSV();
var groupedMeterValues = FilterMeters(meters, from, till);
var averagedMeterValues = CalculateAverageValues(groupedMeterValues);
WriteAverageCSV(averagedMeterValues); | {
"domain": "codereview.stackexchange",
"id": 44390,
"lm_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, hash-map, console, csv",
"url": null
} |
javascript, jquery
Title: Clone Div and change input control
Question: I am using keypress to get all the events of a input control. Once the user hits the enter button after I am then clone a div and update the ids. One project I am having is that I only want to do this one time for each control. Meaning if a user changes row 1 two times I dont want to do this logic. I have set this data field to 0 then change it to 1 but that is not working.
Any suggestions/comments are greatly appreciated to improve the code further. Thanks.
$("[id^='fieldrowItem_']").on('keypress', function (e) {
if (e.which === 13) {
let rowDataChanged = $(this).data();
//if (rowDataChanged === "0")
//{
let rowCount = $('[id^=newrowItem_]').length
let newrowCount = rowCount + 1;
let rowField = $("[id='newrowItem_" + rowCount + "']").clone(true,true);
let rowInput = "input[id='fieldrowItem_" + rowCount + "']";
let newrowInput = "fieldrowItem_" + newrowCount;
let placeholder = "Row " + newrowCount;
rowField = rowField.attr("id", "newrowItem_" + newrowCount + "");
rowField.find(rowInput)
.attr("id", newrowInput)
.attr("placeholder", placeholder)
.val('');
$("[id='newrowItem_" + rowCount + "']").after(rowField);
$(this).attr('data', "1");
// } | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
$(this).attr('data', "1");
// }
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class='form-group'>
<div class="col-sm-6 row">
<label>Rows</label>
<div class="input-group" id=newrowItem_1>
<input type='text' id='fieldrowItem_1' class='form-control fieldrowItem' placeholder="Row 1" data-value="0">
<div class="input-group-addon">
<span class="input-group-addon" style="display: none;cursor:pointer;" data-section="admin" onclick="RemoveRow_1()">
<i class="fa fa-times"></i>
</span>
</div>
</div>
</div>
What I am trying to replicate.
Answer: I'm not going to lie: the code is quite messy, and really hard to read.
The indentation is all over the place, and the way the JavaScript is written is extremely confusing.
I will split this review by language, to make it easier to follow.
However, first, I need to talk about ...
Hidden broken functionality
You have hidden code that isn't functional.
There's this block of HTML:
<div class="input-group-addon">
<span class="input-group-addon" style="display: none;cursor:pointer;" data-section="admin" onclick="RemoveRow_1()">
<i class="fa fa-times"></i>
</span>
</div>
But, the code doesn't work or do anything at all.
Your way to make it just functional enough for a review was to hide the ✕ button.
A code review is supposed to review all the code, as such, I will review everything.
I'll talk about the JavaScript code, because it's a different beast... | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
CSS
In the previous block of HTML, you have inline CSS.
Please avoid it.
More often than not, you can just move those changes to a different class.
However, in this case, you don't even need that inline CSS at all, and can just discard it, since Bootstrap already has everything you need for this.
If you want to hide the element, just use the d-none class, and remove it if you need to show the element.
I won't go much further because you didn't provide the Bootstrap version and the font-awesome version.
For the cursor, I will talk about it in the HTML section.
Also, you do have extra classes that have absolutely no styles at all, like the class fieldrowItem.
HTML
The HTML has absolutely no indentation at all.
Besides making it really hard to read, also makes it really hard to follow what's what.
Also, the code is all glued together, making it look like a giant blob of text - very hard to read.
Not to mention the mix of quotes, between double-quotes, single-quotes and *gasp* no quotes :O.
Please, be consistent with the quotes (preferring the double-quotes), and ALWAYS have quotes.
If you don't use quotes, you can have lots of nasty surprises.
Here's how the HTML code could look like:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<div class="form-group">
<div class="col-sm-6 row">
<label>Rows</label>
<div class="input-group" id="newrowItem_1">
<input type="text" id="fieldrowItem_1" class="form-control fieldrowItem" placeholder="Row 1" data-value="0">
<div class="input-group-addon">
<span class="input-group-addon" style="display: none;cursor:pointer;" data-section="admin" onclick="RemoveRow_1()">
<i class="fa fa-times"></i>
</span>
</div>
</div>
</div> | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
Now, we can dig deeper, and ... notice the missing closing </div>.
Count it in your code: you open 4 <div> but only have 3 </div>.
Regarding the hidden button, you have this code:
<div class="input-group-addon">
<span class="input-group-addon" style="display: none;cursor:pointer;" data-section="admin" onclick="RemoveRow_1()">
<i class="fa fa-times"></i>
</span>
</div>
Instead of having this wrapped around a <span>, just use a button, like this:
<!-- Bootstrap 5.x -->
<div class="input-group">
<input type="text" id="fieldrowItem_1" class="form-control fieldrowItem" placeholder="Row 1" data-value="0">
<button class="btn btn-outline-secondary" type="button">
<i class="fa fa-times"></i>
</button>
</div>
<!-- Bootstrap 4.x -->
<div class="input-group">
<input type="text" id="fieldrowItem_1" class="form-control fieldrowItem" placeholder="Row 1" data-value="0">
<div class="input-group-append">
<button class="btn btn-outline-secondary" type="button">
<i class="fa fa-times"></i>
</button>
</div>
</div>
<!-- Bootstrap 3.x -->
<div class="input-group">
<input type="text" id="fieldrowItem_1" class="form-control fieldrowItem" placeholder="Row 1" data-value="0">
<div class="input-group-btn">
<button class="btn btn-outline-secondary" type="button">
<i class="fa fa-times"></i>
</button>
</div>
</div>
I don't know which version you're aiming for, so, here's for all versions.
I haven't tested this, but the functionality should be almost there.
And yes, I removed the old-school inline onclick event handler: we're in 2023, and that function doesn't even exist. | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
JavaScript and jQuery
This code is an absolute mess and very sub-optimal.
Did I mention that the indentation is a nightmare?
You're also using jQuery 3.3.0, instead of using jQuery 3.6.3 - the latest version.
There were some potentially serious vulnerabilities in jQuery 3.3.0, some of them being fixed in jQuery 3.5 and newer: https://www.cvedetails.com/product/11031/Jquery-Jquery.html?vendor_id=6538
One big mistake (that may or may not be slightly mitigated depending on where the code is included) is to do not run this code on a ready event.
Just simply wrapping your code in something like this:
jQuery(function($){
// Your code comes here...
});
This will solve any possible issue.
If you hate using braces, you can have the JavaScript at the end of the <body> element, but this code does more than you see...
In case someone/something runs jQuery.noConflict(), your code is perfectly safe and can continue using the $ "shortcut" for jQuery.
You have absolutely useless comments, like this one: //if (rowDataChanged === "0").
If you want to remove the code, please just remove it, instead of having it dangling there doing nothing.
And your code is in need of comments: the duality of coding.
Your code is void of any explanation as to why you decide to do what you're doing.
Important stuff like:
Why do you have the ids based in a counter, based on the length?
Why are you cloning a <div> instead of using a template?
What's that $(this).attr('data', "1"); doing there?
Why did you decide to check for keypresses, instead of using the input event?
This is the type of stuff that would really help in being added to the code. | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
This is the type of stuff that would really help in being added to the code.
How I would implement this?
Yeah, I've been "bashing" your code for a while, instead of giving an example of how I would implement this.
I've implemented some basic functionality for the delete button - as you deserve it for paying attention.
I've changed the functionality on how you add the rows, to make it more obvious to the user, as pressing "enter" isn't something that obvious.
In fact, can you even press "enter" on a mobile device, on a single-line input?
If I'm not mistaken, it is just replaced by an emoji button, for those fields...
This isn't very accessible for assistive technologies, and I didn't make an effort for that (I leave it as an exercise for you, since I'm too lazy).
Despite being A LOT longer than your code, I'm sure it is infinitely easier to read and understand what's going on. | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
jQuery(function($){
var $container = $('#field-container');
// To work with <template>, you can't use jQuery's API
var template = $('#template-input-group').get(0);
// Easy access to selectors that are repeated - in case we need to change them
const INPUT_SEL = 'input[type="text"][name="name[]"]';
const ROW_SEL = '.row';
const DELETE_SEL = '.btn.delete';
// Creates the first row, since $container starts empty
addRow();
function addRow(){
// Must use .cloneNode(true) for a deep clone
var $input_group = $(template.content.cloneNode(true));
$container.append($input_group);
}
// My best interpretation of what the hidden remove button is supposed to do
function removeRow($row){
// In case something goes wrong, don't remove the last row
if($row.is(':last-child'))
{
// Set the input to have an empty value - removes undo/redo as well
$row.find(INPUT_SEL).val('');
return;
}
// Can't move this to the top because the code needs to check if it is the last element before removing
$row.remove();
}
// Handles changes in the input, and add a row if appropriate
$container.on('input', INPUT_SEL, function(){
var $this = $(this);
var $row = $this.closest(ROW_SEL);
var $btn_delete = $row.find(DELETE_SEL);
// Enable the button, just in case it is still disabled
$btn_delete.removeAttr('disabled');
/*
Only add a new row if the user is in the last row.
Also check if the value is empty, just to prevent bugs.
This check isn't really necessary, but prevents weird edge cases I couldn't predict.
*/
if($row.is(':last-child') && $this.val() !== '')
{
addRow();
}
});
// Handles the delete button - to remove a row
$container.on('click', DELETE_SEL, function(){
var $this = $(this);
var $row = $this.closest(ROW_SEL);
removeRow($row);
});
}); | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
var $this = $(this);
var $row = $this.closest(ROW_SEL);
removeRow($row);
});
});
/* Adds a counter to the rows - matches the example image */
#field-container {
/* Guarantees that the counter exists */
counter-reset: rows;
} | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
#field-container .input-group::before {
/* Shows the counter - no JS required */
counter-increment: rows;
content: counter(rows) ".";
align-self: center;
/*
The baseline width is 3 characters.
This should be fine up to 99 rows.
*/
width: 3ch;
}
#field-container input {
/* Remove the border radius, to make it look closer to the example image */
border-radius: 0;
}
#field-container .btn.delete {
/* Ridiculous padding was removed */
padding: 0 0.375rem;
/* Make sure the delete button is always gray */
--bs-btn-color: var(--bs-gray);
--bs-btn-hover-color: var(--bs-gray);
--bs-btn-active-color: var(--bs-gray);
}
#field-container .btn.delete:disabled {
/* Make it more obvious that the button is disabled */
opacity: 0.5;
}
#field-container .btn.delete > svg {
/* The SVG icons should always follow the .btn font-size */
width: 2.5em;
height: 2.5em;
}
<!-- Hide the SVG, since it doesn't need to be visible -->
<svg xmlns="http://www.w3.org/2000/svg" class="d-none" fill="currentColor">
<!-- Modified version of: https://icons.getbootstrap.com/icons/x/ -->
<symbol id="icon-close" fill="currentColor" viewBox="0 0 16 16">
<path d="M4.646 4.646a.5.5 0 0 1 .708 0L8 7.293l2.646-2.647a.5.5 0 0 1 .708.708L8.707 8l2.647 2.646a.5.5 0 0 1-.708.708L8 8.707l-2.646 2.647a.5.5 0 0 1-.708-.708L7.293 8 4.646 5.354a.5.5 0 0 1 0-.708z"/>
</symbol>
</svg>
<!-- The template with the basic HTML to use -->
<template id="template-input-group">
<!-- mb-3 = margin bottom -->
<div class="row mb-3">
<div class="input-group">
<!-- To be useful, server-side, must have a name -->
<input type="text" name="name[]" class="form-control" placeholder="Row name" /> | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
javascript, jquery
<!-- Must be disabled by default, to prevent deleting the last row by mistake -->
<button class="btn btn-link delete" type="button" disabled>
<!-- Icon from the SVG on top -->
<svg role="img" aria-label="Remove">
<use href="#icon-close"></use>
</svg>
</button>
</div>
</div>
</template>
<!-- Stops the user from selecting everything if the user double-clicks the disabled button -->
<div class="container user-select-none">
<div class="form-group col-6">
<p>Rows</p>
<div id="field-container"></div>
</div>
</div>
<!-- Use CDNJS instead of code.jquery.com because I'm lazy and it comes with all the hashes and stuff -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="sha512-STof4xm1wgkfm7heWqFJVn58Hm3EtS31XFaagaa8VMReCXAkQnJZ+jEy8PCC/iT18dFy95WcExNHFTqLyp72eQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!-- Using the latest stable version -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
This code relies in the jQuery.closest function, to find the parent .row element.
This makes it possible to find the row without having to fiddle around with ids and stuff like that.
The name on the inputs looks strange, if it is your first time seeing it (E.g.: name[]).
The idea is, in case you submit it (or serialize it), you get an array with all the values.
On the server-side, you will have an array with all the values.
The disadvantage on how I have this implemented is that the last item is always empty.
You should filter these out server-side anyway, as you can have any field being empty anywhere...
If you have any questions, just send a comment and I will explain everything, and even add an explanation to this answer. | {
"domain": "codereview.stackexchange",
"id": 44391,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, jquery",
"url": null
} |
go, utf-8
Title: Determining if a file is UTF-8 text by looking at its first n bytes
Question: I'm trying to find out whether a particular file is UTF-8 encoded readable text, by which I mean printable symbols, whitespaces, \n, \r\n and \t (think: source code). As speed is of importance, this has to be determined from just the first few dozen or so bytes of the file.
I've tried my luck using an io.RuneReader, implementing the core logic around it. This io.RuneReader can then be implemented by either a bufio.Reader for reading from a file or by a strings.Reader if I wanted to write some tests without creating dedicated files. The logic itself is simple enough, utf8.IsGraphic covers almost everything I need.
Here's the source code (or go playground), followed by my actual questions, which are also contained within the code sample.
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
"unicode"
"unicode/utf8"
)
func IsReadableTextRunes(r io.RuneReader, max int) (bool, error) {
for i := 0; i < max; i++ {
rn, sz, err := r.ReadRune()
switch {
// Can I rely on io.RuneReader to always behave like
// utf8.DecodeRune() with respect to erroneous encodings?
// I.e. will io.RuneReader::ReadRune() always return
// (utf8.RuneError, 1, nil) where an invalid encoding is
// encountered?
case rn == utf8.RuneError && sz == 1:
return false, nil
case unicode.IsGraphic(rn) || rn == '\n' || rn == '\t':
continue
case rn == '\r':
rn2, _, err2 := r.ReadRune()
if rn2 != '\n' || err2 != nil {
return false, nil
}
i++
// Do we have an prior information about which particular
// errors may be returned by io.RuneReader::ReadRune()?
case err != nil:
if errors.Is(err, io.EOF) {
return true, nil
}
return false, err | {
"domain": "codereview.stackexchange",
"id": 44392,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, utf-8",
"url": null
} |
go, utf-8
default:
return false, nil
}
}
return true, nil
}
func IsUtf8ReadableTextFile(filepath string) (bool, error) {
f, err := os.Open(filepath)
if err != nil {
return false, err
}
defer f.Close()
// Is this buffer size the smallest possible
// to guarantee that valid UTF-8 read into the
// the buffer is never truncated?
max := 32
bufSz := max * utf8.UTFMax
return IsReadableTextRunes(bufio.NewReaderSize(f, bufSz), max)
}
func main() {
data := []string{
"Is this\nthe\r\nreal\tlife?", // valid
"\ra", // invalid: \r outside of \r\n
"\xffa", // invalid: invalid UTF-8
"\x1b123", // invalid: contains non-graphical rune
}
for _, d := range data {
fmt.Printf("%q\n", d)
r := strings.NewReader(d)
valid, err := IsReadableTextRunes(r, 12)
switch {
case err != nil:
fmt.Println(" -> error")
case valid:
fmt.Println(" -> valid UTF-8 readable text")
default:
fmt.Println(" -> invalid UTF-8 readable text")
}
}
} | {
"domain": "codereview.stackexchange",
"id": 44392,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, utf-8",
"url": null
} |
go, utf-8
What do you think about this approach in general? I'm a go novice and would appreciate any kind of feedback, meta or specific. Is this a viable method to quickly scan many, possibly thousands of files? Is it idiomatic go?
io.RuneReader does not specify how ReadRune() handles erroneous encodings. I found out that strings.Reader::ReadRune() as well as bufio.Reader::ReadRune() use utf.DecodeRune() under the hood, which, upon encountering invalid UTF-8, will return (RuneError, 1). Can I rely on all io.RuneReaders to behave this way? My implementation of IsReadableTextRunes implicitly depends on it.
io.RuneReader is also unclear about which errors I can expect under which conditions. Can I at least count upon an io.EOF to signal the end of the data stream? Again, the above implementation assumes so.
Does IsUtf8ReadableTextFile correctly wrap IsReadableTextRunes, choosing the smallest possible buffer size?
Thank you.
Answer: Thank you for offering this.
It's some nice source code.
Bonus points for the playground!
This is a good approach,
a viable method to quickly scan many files.
The style matches the idioms found in the underlying utf8 library.
The underlying error handling happens here:
https://github.com/golang/go/blob/1e12c6/src/unicode/utf8/utf8.go#L151
So you're good as long as we stick with utf8 encoding.
I have seen astonishing things checked into source control,
such as a utf16-encoded Makefile.
I believe you would view such an artifact as "binary"
for the present use case.
Add some unit tests to verify behavior.
Be sure to include LE + BE encodings,
with good + bad (mismatched) BOM.
Can you depend on EOF behavior? Yes,
as long as we stick with utf8 encoding
the above mentioned DecodeRune() will properly report EOF.
Your unit test should include a 4-glyph input file,
that has glyphs of lengths 1, 2, 3, 4.
Truncate the file repeatedly, and verify
correct behavior at each length. | {
"domain": "codereview.stackexchange",
"id": 44392,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, utf-8",
"url": null
} |
go, utf-8
Yes, the buffer is correctly allocated.
However, iterating to max is on the conservative side.
You might consider iterating until EOF,
which on some input files would let you
examine four times as much of the file, at the expense of needing to track the index or to disregard final error due to truncation.
And no matter which way you go on that,
I definitely recommend you do some
single-core and multi-core timings.
If you can scan a bigger file prefix
with minimal cost, it's worth doing.
Do we have [any] prior information about which particular errors may be returned by io.RuneReader::ReadRune()?
It looks like general I/O errors can come back,
perhaps including "NFS read timeout" errors.
Write a unit test if you wish to demonstrate
particular errors.
The usual
idiom
for reading in utf16 format is
bufio.NewScanner(transform.NewReader(file, unicode.UTF16(unicode.LittleEndian, unicode.UseBOM).NewDecoder()))
and there's no trace of such code here,
so I suppose we're safe from accidentally
using an inappropriate decoder.
I am reading IsReadableTextRunes().
The value of max, 32, seems like it's on the
short side if you want to assess line terminators
within the file prefix, since some input lines will be
longer than that.
This function determines
three
different things:
is file well-formed utf8?
is its prefix printable characters + whitespace?
does it contain CR-delimited lines?
Those last two were kind of shoe-horned in.
Consider breaking out helpers, then
verify you still get good timings.
Or maybe expand "Text" to something
like IsReadablePlainTextRunes(),
emphasizing that we enforce rules about
what valid text looks like.
We do not attempt to verify canonical forms
or combining mark craziness, and that is fine.
Let's take a step back.
Here's a pair of alternate / complementary approaches. | {
"domain": "codereview.stackexchange",
"id": 44392,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, utf-8",
"url": null
} |
go, utf-8
Let's take a step back.
Here's a pair of alternate / complementary approaches.
Many of your input files will have just \t, SPACE, \n,
and ASCII printable characters. Create a boolean vector and use it
when scanning the prefix bytes. On some files this will
let you declare victory early, so there's no need to fall
back to the full-blown utf8 decoding.
Many of your input files will start with GIF89a,
\x89PNG\r\n, or other well known file
signatures
that fit nicely in a
hash table.
Again, there is an opportunity to declare victory early
upon seeing certain prefixes.
I will offer an even more radical suggestion.
Ask stat() for file length.
Pick a random offset, not "too close" to the end.
At this point there's an excellent chance you're pointing
at the middle of some multi-byte glyph.
So read a few runes.
If you manage to at last read without error,
you are now in sync, and can read max runes
if it's well-formed utf8.
Alternatively, use a constant starting offset,
to let you examine the final portion of a 4-KiB
file buffer that the OS already had to read in anyway.
Overall, this code achieves its design goals.
It would benefit from timing figures and from more extensive unit tests. | {
"domain": "codereview.stackexchange",
"id": 44392,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "go, utf-8",
"url": null
} |
php, validation, laravel
Title: Theme picker for Laravel 8 blogging application
Question: I am working on a blogging application in Laravel 8.
The application supports themes. In a nutshell, theme support works like this:
In the views directory, I have the directory containing the views of every theme.
In public\themes I keep the assets (CSS, Javascript) of every theme.
In the SettingsController controller I have, among others, a variable named $theme_directory, which contains the name of the directory of the current theme. I use this variable in the theme view, like this, for instance:
<link href="{{ asset('themes/' . $theme_directory . '/css/clean-blog.min.css') }}" rel="stylesheet">
From the "Settings" section I can set the current theme.
I have added a "theme picker": a select-box containing all the available themes to pick from.
In the controller, I have a themes() method that reads the names of the themes directories in the views and displays them:
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Models\Settings;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\File;
class SettingsController extends Controller {
private $rules = [
'site_name' => 'required|string|max:190',
'tagline' => 'required|string|max:190',
'owner_name' => 'required|string|max:190',
'owner_email' => 'required|email|max:190',
'twitter' => 'required|string|max:190',
'facebook' => 'required|string|max:190',
'instagram' => 'required|string|max:190',
'theme_directory' => 'required',
]; | {
"domain": "codereview.stackexchange",
"id": 44393,
"lm_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, validation, laravel",
"url": null
} |
php, validation, laravel
private $messages = [
'site_name.required' => 'A site title is required',
'tagline.required' => 'A site tag line is required',
'owner_name.required' => 'Please provide a site owner/company name',
'owner_email.required' => 'A valid email is required',
'owner_email.email' => 'The email you provided is not valid',
'twitter.required' => 'Please provide a Twitter account',
'facebook.required' => 'Please provide a Facebook account',
'instagram.required' => 'Please provide an Instagram account',
'theme_directory.required' => 'Please pick a theme',
];
public function themes() {
$themes = [];
$themes_path = Config::get('view.paths')[0] . '\themes';
foreach(File::directories($themes_path) as $theme) {
$slug = array_reverse(explode('\\', $theme))[0];
$name = ucwords(str_replace('-', ' ', $slug));
$themes[] = (object)compact('slug', 'name');
}
return $themes;
}
public function index() {
$settings = Settings::first();
return view('dashboard/settings', [
'settings' => $settings,
'themes' => $this->themes()
]);
}
public function update(Request $request) {
$validator = Validator::make($request->all(), $this->rules, $this->messages); | {
"domain": "codereview.stackexchange",
"id": 44393,
"lm_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, validation, laravel",
"url": null
} |
php, validation, laravel
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
} else {
$settings = Settings::first();
$settings->site_name = $request->get('site_name');
$settings->tagline = $request->get('tagline');
$settings->owner_name = $request->get('owner_name');
$settings->owner_email = $request->get('owner_email');
$settings->twitter = $request->get('twitter');
$settings->facebook = $request->get('facebook');
$settings->instagram = $request->get('instagram');
$settings->theme_directory = $request->get('theme_directory');
$settings->is_cookieconsent = $request->get('is_cookieconsent') == 'on' ? 1 : 0;
$settings->is_infinitescroll = $request->get('is_infinitescroll') == 'on' ? 1 : 0;
$settings->save();
return redirect()->route('dashboard.settings')->with('success', 'The settings were updated!');
}
}
}
In the view (form), I have:
<div class="row mb-2">
<label for="theme" class="col-md-12">{{ __('Theme directory') }}</label>
<div class="col-md-12 @error('theme_directory') has-error @enderror">
<select name="theme_directory" id="theme" class="form-control @error('theme_directory') is-invalid @enderror">
<option value="">Pick a theme</option>
@foreach($themes as $theme)
<option value="{{ $theme->slug }}" {{ $theme->slug == $settings->theme_directory ? 'selected' : '' }}>{{ $theme->name }}</option>
@endforeach
</select>
@error('theme_directory')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
</div>
Questions:
Is there any redundancy in my code?
Do you see any security issues? | {
"domain": "codereview.stackexchange",
"id": 44393,
"lm_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, validation, laravel",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.