text
stringlengths
1
2.12k
source
dict
php, html, file-system, bootstrap www/Libarys/bootstrap/bootstrap_loader.php: The bootstrap_loader.php searches and includes the CSS and JS files from the BootStrap Framework to the www/index.php file. I tested those scripts in more than 4 sub directories with sub directories and they worked well. <?php class BootStrap { function loadFileGeter($param, $direct) { switch ($param) { case "CSS": $this->getFileList($direct."/".strtolower($param), $param); break; case "JS": $this->getFileList($direct."/".strtolower($param), $param); break; } } function getFileList($dir, $param) { $dir = $dir; $files = scandir($dir, 1); sort($files); foreach ($files as &$value) { if (str_ends_with($value,".".strtolower($param))) { switch ($param) { case "CSS": $string = '<link rel="stylesheet" type="text/css" href="'.$dir.'/'.$value.'" />'."\n"; ECHO($string); break; case "JS": $string = '<script async="" src="'.$dir.'/'.$value.'"></script>'."\n"; ECHO($string); break; } } } } } ?> Answer: Spacing could be better Overall the code isn't difficult to read. Idiomatic PHP has spacing conventions, mainly outlined in the PHP Standards Recommendations - e.g. PSR-12: Extended Coding Style. There is one convention for spacing not followed by the code - and that is spacing around binary operators like . - e.g. $dir = $dir."./Libarys/bootstrap"; For readability, it is better to have a space around all binary operators including the concatenation operator: $dir = $dir . "./Libarys/bootstrap";
{ "domain": "codereview.stackexchange", "id": 44202, "lm_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, html, file-system, bootstrap", "url": null }
php, html, file-system, bootstrap That way it is easier to see the placement of the operators and operands. Naming can be confusing The class Initialisation has a property $direct. In English direct is a verb or adverb but not really a noun, though it seems for the purposes of the code it stores a directory path. Perhaps a better name might be directory or else abbreviated as dir. Some variable declarations become superfluous when overwritten Looking at the first method in the class Initialisation - i.e. getFileLocation() I see: function getFileLocation() { $value = ""; $value = $_SERVER["REQUEST_URI"]; return($value); } The first line assigns an empty string to $value. The second line re-writes that variable with the request URI from the superglobal. Thus the first line becomes useless and it can be removed. Furthermore, $value is never altered or used in-between that last assignment and when it is returned, so it can be eliminated. The method can simply return $_SERVER["REQUEST_URI"]. In a previous review Dharman stated: Don't put parentheses after echo. It's not a function and these parentheses are extremely confusing. Same applies to require The same applies to return - parentheses are not needed for language constructs. As the documentation states: These words have special meaning in PHP. Some of them represent things which look like functions, some look like constants, and so on - but they're not, really: they are language constructs. 1 The List of Keywords also includes the include_once statement and that statement appears in the loadBS() method with parentheses- those can be removed there as well. Use String Concatenation assignment operators In the next method of class Initialisation - i.e. getCurrentDirectory() the variable $dir is assigned to multiple times, often with a string literal appended to it - e.g. $dir = $dir."../"; and $dir = $dir."./Libarys/bootstrap";
{ "domain": "codereview.stackexchange", "id": 44202, "lm_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, html, file-system, bootstrap", "url": null }
php, html, file-system, bootstrap $dir = $dir."../"; and $dir = $dir."./Libarys/bootstrap"; Many high-level programming languages, including PHP, offer a string concatenation assignment operator. For PHP it is .=. The two lines cited above can be re-written as: $dir .= "../"; and $dir .= "./Libarys/bootstrap"; Loop can be replaced with function call PHP offers the built-in function str_repeat() which can be used to replace the for loop within Initialisation::getCurrentDirectory() repeated $countetSlashes - 1 times. Redundant switch cases can be consolidated The method Bootstrap::loadFileGeter() (which likely has a typo - typically it is written getter) has two case statements inside the switch: class BootStrap { function loadFileGeter($param, $direct) { switch ($param) { case "CSS": $this->getFileList($direct."/".strtolower($param), $param); break; case "JS": $this->getFileList($direct."/".strtolower($param), $param); break; } } In both cases the same method is called with the same arguments. Those can be consolidated: switch ($param) { case "CSS": case "JS": $this->getFileList($direct."/".strtolower($param), $param); break; } Going a step further, the switch statement could be replaced by a conditional block utilizing the PHP function in_array(): if (in_array($param, ['CSS', 'JS'])) { $this->getFileList($direct."/".strtolower($param), $param); }
{ "domain": "codereview.stackexchange", "id": 44202, "lm_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, html, file-system, bootstrap", "url": null }
php, html, file-system, bootstrap Then there is no need to add the case and break lines. The method getFileList() also has a similar switch statement though the generated HTML tags are different. One could simplify that slightly by using a method to get the tag based on the value of $param. The method would be more granular, allowing for the code to be more in line with the Single Responsibility Principle. Reference operator in loop In that method getFileList() the foreach loop has a by-reference operator before $value which means it will be assigned by reference. 3 foreach ($files as &$value) { However, it doesn't appear that there is a need to assign that variable by reference. Closing tags can be omitted PSR-12 also mentions: The closing ?> tag MUST be omitted from files containing only PHP. Per the PHP documentation for PHP tags: If a file contains only PHP code, it is preferable to omit the PHP closing tag at the end of the file. This prevents accidental whitespace or new lines being added after the PHP closing tag, which may cause unwanted effects because PHP will start output buffering when there is no intention from the programmer to send any output at that point in the script. Sorting may not be necessary In the method BootStrap:: getFileList() there is a call to sort($files). Maybe you prefer to have the files sorted in the HTML output but that doesn't appear to be a requirement. It could be removed, though if it is preferable to have them sorted by name then consider using natsort() for "natural order" sorting - e.g. for sheet2.css after sheet12.css. Files could be filtered to certain extensions One could use the [glob()] function to find files with a pattern - e.g. *.css, *.js - then the amount of code to filter files could be decreased.
{ "domain": "codereview.stackexchange", "id": 44202, "lm_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, html, file-system, bootstrap", "url": null }
c#, .net, binary-search Title: Find closest value in a big list Question: There are solutions e.g. list.OrderBy(item => Math.Abs(number - item)).First() or list.Aggregate((x,y) => Math.Abs(x-number) < Math.Abs(y-number) ? x : y); which are O(N) at best. The solution bellow should be faster than a sequential scan on a large list. It is more performant to sort the list first (O(NlogN)) and then use List<T>.BinarySearch for each query. The performance for k queries is O((k+N)logN), in comparison to O(kN) of the previous methods. The question is did I implement it correctly? private decimal FindClosestLevel(IReadOnlyCollection<decimal> collection, decimal value) { var list = collection.ToList(); list.Sort(); var index = list.BinarySearch(value); if (index > 0) { return list[index]; } index = ~index; if (index >= list.Count) { return list[list.Count - 1]; } if (index <= 0) { return list[0]; } var val1 = list[index - 1]; var val2 = list[index]; return val2 - value > value - val1 ? val1 : val2; } Answer: The question is did I implement it correctly? Do you have any test cases? Anyway: The algorithm It is more performant to sort the list first (O(NlogN)) and then use List.BinarySearch for each query.
{ "domain": "codereview.stackexchange", "id": 44203, "lm_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, binary-search", "url": null }
c#, .net, binary-search I would agree with that, it's a good approach, but it's not what the code does. What it actually does is for each query, sort the list and then binary search in it. There is no advantage then, each query would take O(N log N) that way, O(kN log N) for k queries, so worse than the O(kN) approach. The interface That also means that the interface should be different. You cannot do this in the way you planned to it through the interface decimal FindClosestLevel(IReadOnlyCollection<decimal> collection, decimal value). Even if you put a precondition on this that the collection must have been sorted already, you cannot binary search an IReadOnlyCollection directly (copying it into a list would make the query O(N) again, so that's a dead end). You need all queries in one place, to handle them all in one go after sorting the collection once, only then does the approach actually reach the O((k+N) log N) that you mentioned.
{ "domain": "codereview.stackexchange", "id": 44203, "lm_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, binary-search", "url": null }
c++, algorithm, graph Title: Node graph implementation for a material system Question: I'm working on a material/shader graph system. I came up with a simple solution, but nodes that weren't connected were used in some situations. So, I thought of using Kahn's algorithm to execute nodes' tasks. I'm not quite sure if it's a proper implementation. I've only played with it, so it's a single file to avoid jumping between many files. https://godbolt.org/z/8hYEWbGsv includes #include <iostream> #include <ranges> #include <vector> #include <cinttypes> #include <memory_resource> There is a generic DAG class that references Nodes and Edges. It also sorts and executes nodes' code - DAG::Execute() function struct DAG { DAG() { nodes.reserve(16); edges.reserve(32); } ~DAG() = default; DAG(const DAG&) = delete; DAG& operator=(const DAG&) = delete; struct Node { Node(DAG& dag) : id(dag.AddNode(this)) { } virtual ~Node() = default; Node(const Node&) = delete; Node& operator=(const Node&) = delete; virtual void Execute() = 0; [[nodiscard]] inline std::size_t getID() const { return id; } [[nodiscard]] inline std::uint32_t getRefCount() const { return refCount; } inline void MakeTarget() { target = true; } [[nodiscard]] inline bool isTarget() const { return target; } private: friend struct DAG; std::uint32_t refCount = 0; const std::size_t id = 0; bool target = false; }; struct Edge { Edge(DAG& dag, const std::size_t fromNode, const std::size_t toNode) : fromNode(fromNode), toNode(toNode) { dag.AddEdge(this); } Edge(const Edge&) = delete; Edge& operator=(const Edge& rhs) = delete; const std::size_t fromNode = 0; const std::size_t toNode = 0; };
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph const std::size_t fromNode = 0; const std::size_t toNode = 0; }; [[nodiscard]] inline auto getOutgoingEdges(const Node* const node) { return edges | std::views::filter([node](const Edge* const edge) { return edge->fromNode == node->getID(); }); } [[nodiscard]] inline auto getIncomingEdges(const Node* const node) { return edges | std::views::filter([node](const Edge* const edge) { return edge->toNode == node->getID(); }); } void Execute(); private: [[nodiscard]] inline std::size_t AddNode(Node* node) { std::size_t id = nodes.size(); nodes.push_back(node); return id; } inline void AddEdge(Edge* edge) { edges.push_back(edge); } std::vector<Node*> nodes; std::vector<Edge*> edges; }; void DAG::Execute() { //Reset nodes refCount before sorting for (Node* const node : nodes) { node->refCount = 0; } for (const Edge* const edge : edges) { Node* const node = nodes[edge->fromNode]; node->refCount++; } std::vector<Node*> stack; for (Node* const node : nodes) { if (node->getRefCount() == 0) { stack.push_back(node); } } while (!stack.empty()) { Node* const node = stack.back(); stack.pop_back(); //If the current node is not a target //and if it hasn't got out edges //don't execute the Node::Execute() function //and don't process it's incoming edges auto&& outEdges = getOutgoingEdges(node); if (outEdges.empty() && !node->isTarget()) { continue; } node->Execute(); auto&& edges = getIncomingEdges(node); for (const Edge* const edge : edges) { Node* const linkedNode = nodes[edge->fromNode]; if (--linkedNode->refCount == 0) { stack.push_back(linkedNode); } } } }
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph What I'm not sure in DAG::Execute() function is this part: auto&& outEdges = getOutgoingEdges(node); if (outEdges.empty() && !node->isTarget()) { continue; } I don't even know why, but it just feels not right. It's not a standard Kahn algorithm, but I need it to cull not connected nodes. See the results at the end of this question. The final Node, Edge and Pin look like this: struct Graph; struct Node : DAG::Node { Node(Graph& g, const std::string_view name); void Execute() override; inline void AddInput(const std::size_t pinID) { inputs.push_back(pinID); } inline void AddOuput(const std::size_t outputID) { outputs.push_back(outputID); } [[nodiscard]] inline const std::string& getName() const { return name; } [[nodiscard]] inline const std::vector<size_t>& getInputs() const { return inputs; } [[nodiscard]] inline const std::vector<size_t>& getOutputs() const { return outputs; } [[nodiscard]] inline bool hasInputs() const { return !inputs.empty(); } [[nodiscard]] inline bool hasOutputs() const { return !outputs.empty(); } private: std::vector<std::size_t> inputs; std::vector<std::size_t> outputs; Graph& g; const std::string name; }; struct Pin { Pin(const std::string_view name, const std::size_t id, const std::size_t nodeID) : name(name), id(id), nodeID(nodeID) { } [[nodiscard]] inline std::size_t getID() const { return id; } [[nodiscard]] inline std::size_t getNodeID() const { return nodeID; } [[nodiscard]] inline std::uint32_t getRefCount() const { return refCount; } [[nodiscard]] inline bool isCulled() const { return refCount == 0; } [[nodiscard]] inline const std::string& getName() const { return name; } inline void IncrementRefCount() { refCount++; } inline void Reset() { refCount = 0; } inline void AddOutputEdge(const std::size_t id) { outputEdges.push_back(id); } inline void setInputEdge(const std::size_t id) { inputEdge = id; }
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph [[nodiscard]] inline const std::vector<std::size_t>& getOutputEdges() const { return outputEdges; } [[nodiscard]] inline const std::optional<std::size_t>& getInputEdge() const { return inputEdge; } private: std::vector<std::size_t> outputEdges; std::optional<std::size_t> inputEdge = std::nullopt; std::string name; std::uint32_t refCount = 0; const std::size_t id = 0; const std::size_t nodeID = 0; }; struct Edge : DAG::Edge { Edge(Graph& g, const std::size_t fromPin, const std::size_t toPin, const std::size_t fromNode, const std::size_t toNode); const std::size_t fromPin = 0; const std::size_t toPin = 0; }; Note that Pin is not a part of DAG. I wanted to implement some abstraction like struct PinNode : DAG::Node - holds connections struct VirtualPin - actual pin type, has a reference/id to PinNode but after a while it didn't seem like a good idea Also, I'm not sure how I should return std::optional<std::size_t> inputEdge in getInputEdge() function. const & is ok or should I just return a copy? Node and Edge constructors will be defined after Graph implementation Here it is: struct Graph { Graph(std::pmr::monotonic_buffer_resource& linearArena) : linearArena(linearArena) { nodes.reserve(16); edges.reserve(32); pins.reserve(64); } Graph(const Graph&) = delete; Graph& operator=(const Graph&) = delete; ~Graph() = default; [[nodiscard]] Node* AddNode(const std::string_view name); [[nodiscard]] Pin* AddInput(const std::string_view name, Node* const owner); [[nodiscard]] Pin* AddOutput(const std::string_view name, Node* const owner); bool Connect(Pin* const from, Pin* const to); void Execute();
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph bool Connect(Pin* const from, Pin* const to); void Execute(); [[nodiscard]] inline const Node* getNode(const std::size_t id) const { return nodes[id]; } [[nodiscard]] inline const Pin* getPin(const std::size_t id) const { return pins[id]; } [[nodiscard]] inline const DAG& getDag() const { return dag; } [[nodiscard]] inline DAG& getDag() { return dag; } [[nodiscard]] inline const std::pmr::vector<Pin*>& getPins() const { return pins; } private: [[nodiscard]] Pin* AddPin(const std::string_view name, Node* const owner); template<typename T, size_t alignment = alignof(T), typename ... Args> [[nodiscard]] T* ArenaAllocate(Args&& ... args) { void* const p = linearArena.allocate(sizeof(T), alignment); return p ? new(p) T(std::forward<Args>(args)...) : nullptr; } std::pmr::monotonic_buffer_resource& linearArena; DAG dag; std::pmr::vector<Node*> nodes{&linearArena}; std::pmr::vector<Edge*> edges{&linearArena}; std::pmr::vector<Pin*> pins{&linearArena}; }; Node* Graph::AddNode(const std::string_view name) { auto node = ArenaAllocate<Node>(*this, name); nodes.push_back(node); return node; } Pin* Graph::AddInput(const std::string_view name, Node* const owner) { auto pin = AddPin(name, owner); owner->AddInput(pin->getID()); return pin; } Pin* Graph::AddOutput(const std::string_view name, Node* const owner) { auto pin = AddPin(name, owner); owner->AddOuput(pin->getID()); return pin; } Pin* Graph::AddPin(const std::string_view name, Node* const owner) { std::size_t id = pins.size(); auto pin = ArenaAllocate<Pin>(name, id, owner->getID()); pins.push_back(pin); return pin; } bool Graph::Connect(Pin* const from, Pin* const to) { if (to->getInputEdge().has_value()) { return false; } const std::size_t id = edges.size();
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph const std::size_t id = edges.size(); auto edge = ArenaAllocate<Edge>( *this, from->getID(), to->getID(), from->getNodeID(), to->getNodeID() ); edges.push_back(edge); from->AddOutputEdge(id); to->setInputEdge(id); return true; } void Graph::Execute() { //Reset pins refCount before each DAG::Execute() call for(auto pin : pins) { pin->Reset(); } //Calculate pins refCount for (const Edge* const edge : edges) { Pin& pin = *pins[edge->fromPin]; pin.IncrementRefCount(); } dag.Execute(); } Node::Node(Graph& g, const std::string_view name) : DAG::Node(g.getDag()), g(g), name(name) { } Edge::Edge(Graph& g, const std::size_t fromPin, const std::size_t toPin, const std::size_t fromNode, const std::size_t toNode) : DAG::Edge(g.getDag(), fromNode, toNode), fromPin(fromPin), toPin(toPin) { } right now Node::Execute() simply prints inputs and outputs void Node::Execute() { std::cout << "\nNode: " << name << "\n"; std::cout << " Inputs:\n"; if(inputs.empty()) { std::cout << " empty \n"; } else { for (auto inputID : inputs) { auto input = g.getPin(inputID); std::cout << " " << input->getName() << "\n"; } } std::cout << " Outputs:\n"; auto unculledOutputs = getOutputs() | std::views::filter([&pins = g.getPins()](auto pinID) { return !pins[pinID]->isCulled(); }); for (auto outputID : unculledOutputs) { auto output = g.getPin(outputID); std::cout << " " << output->getName() << "\n"; } } but in a future it'll convert outputs into some variables. I haven't fully written it yet. main function: int main() { std::pmr::monotonic_buffer_resource arena{1024 * 1024}; Graph sg{arena};
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph auto lit = sg.AddNode("Lit"); [[maybe_unused]] auto basePin = sg.AddInput("material.baseColor", lit); [[maybe_unused]] auto normalPin = sg.AddInput("material.normal", lit); [[maybe_unused]] auto materialAlphaPin = sg.AddInput("material.alpha", lit); [[maybe_unused]] auto metallicPin = sg.AddInput("material.metallic", lit); [[maybe_unused]] auto roughnessPin = sg.AddInput("material.roughness", lit); lit->MakeTarget(); auto alphaNode = sg.AddNode("Alpha"); auto alphaPin = sg.AddOutput("alpha", alphaNode); auto multiplierNode = sg.AddNode("Multiplier"); auto multiplierPin = sg.AddOutput("multiplier", multiplierNode); auto addNode = sg.AddNode("AddNode"); auto a = sg.AddInput("a", addNode); auto b = sg.AddInput("b", addNode); auto out = sg.AddOutput("out", addNode); sg.Connect(alphaPin, a); sg.Connect(multiplierPin, b); sg.Connect(out, materialAlphaPin); sg.Execute(); return 0; } Output of this program: Node: Lit Inputs: material.baseColor material.normal material.alpha material.metallic material.roughness Outputs: Node: AddNode Inputs: a b Outputs: out Node: Multiplier Inputs: empty Outputs: multiplier Node: Alpha Inputs: empty Outputs: alpha It looks good. Now let's disconnect alphaPin from a pin, just comment out this line in the main function: sg.Connect(alphaPin, a); and run again: Node: Lit Inputs: material.baseColor material.normal material.alpha material.metallic material.roughness Outputs: Node: AddNode Inputs: a b Outputs: out Node: Multiplier Inputs: empty Outputs: multiplier Also looks good. Alpha Node hasn't been printed since its pin is not connected. If DAG::Execute wouldn't have: auto&& outEdges = getOutgoingEdges(node); if (outEdges.empty() && !node->isTarget()) { continue; } the it would look like this: Node: Alpha Inputs: empty Outputs:
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph the it would look like this: Node: Alpha Inputs: empty Outputs: Node: Lit Inputs: material.baseColor material.normal material.alpha material.metallic material.roughness Outputs: Node: AddNode Inputs: a b Outputs: out Node: Multiplier Inputs: empty Outputs: multiplier which is not correct, because Alpha node is processed. Could you do a review of this code and say if this code in DAG::Execute(): auto&& outEdges = getOutgoingEdges(node); if (outEdges.empty() && !node->isTarget()) { continue; } is corrected and I'm just freaking out? Answer: Make better use of polymorphic allocators The whole point of polymorphic allocators is so that containers that use those can transparently use that allocator to allocate memory for the objects they store. Of course, if you want stable pointers to elements stored in a container, you cannot use std::vector, however you can use std::deque or std::list instead. So instead of doing: std::pmr::vector<Node*> nodes{&linearArena}; … auto node = ArenaAllocate<Node>(*this, name); nodes.push_back(node); return node; You want to do this: std::pmr::deque<Node> nodes{&linearArena}; … return &nodes.emplace_back(name); Once you store everything by value, copying graphs also becomes safe, and you no longer need to delete the copy constructors. Prefer passing references where appropriate You pass pointers everywhere, but especially if you store items in PMR containers by value, then it makes sense to pass references instead, so for example: Pin& Graph::AddPin(std::string_view name, Node& owner) { std::size_t id = pins.size(); return pins.emplace_back(name, id, owner.getID()); }
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph References must always be non-null, so the compiler and/or static analyzers could spot bugs more easily, they also cannot be changed to point to another object, so const is not necessary anymore. Note that whereever you used auto variables to hold a pointer, now you should use auto& to hold a reference, otherwise a copy will be made. Avoid double bookkeeping There seems to be some double bookkeeping going on. Graph owns the nodes, edges and pins, but then in also has a DAG that stores pointers to exactly the same nodes and edges. This is all done seemingly to make Execute() a bit simpler to implement. I see two ways around this. One is to make DAG a base class of Graph, and add virtual functions to DAG that allow Execute access to the nodes and edges without having to store pointers to them itself. Another way is to do away with DAG entirely, and instead make a templated free function that can work on any kind of graph. For example: template<typename Nodes, typename Edges, typename Executor> void execute_dag(Nodes& nodes, Edges& edges, Executor&& executor) { for (auto& node: nodes) { node.refCount = 0; } … std::stack<Nodes::pointer> stack; for (auto& node: nodes) { if (node.getRefCount() == 0) { stack.push(&node); } } while (!stack.empty()) { auto& node = *stack.back(); stack.pop(); … std::invoke(std::forward<Executor>(executor), node); … } } The above function takes a reference to the lists of nodes and edges, so that these can stay private inside Graph. And Graph::Execute() just becomes: void Graph::Execute() { for (auto& pin : pins) { pin.Reset(); } for (auto Edge& edge : edges) { pins[edge->fromPin].IncrementRefCount(); } execute_dag(nodes, edges, [](Node& node){ node.Execute(); }); }
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c++, algorithm, graph execute_dag(nodes, edges, [](Node& node){ node.Execute(); }); } The above assumes that Node still has a refCount and isTarget(). Since refCount is only needed during the DAG traversal, you could instead create a temporary vector holding the reference counts inside execute_dag(). For isTarget(), you could consider having the executor return a bool to indicate whether to process the incoming edges or not, so the executor can return false if node.isTarget() == false. This decouples knowledge of isTarget() from the DAG algorithm. Finally, getOutgoingEdges() and getIncomingEdges() are quite simple and can be inlined into execute_dag().
{ "domain": "codereview.stackexchange", "id": 44204, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c++, algorithm, graph", "url": null }
c#, object-oriented, game, console, sliding-tile-puzzle Title: Simple N Puzzle console game Question: I am completely new to object oriented programing (OOP). I have also never worked with C# before. The exercise from my book had some requirements that should be followed to complete the exercise. Use of at least two classes (not counting the main class), one of which should be a Tile class, representing the tiles No public fields with the exception of the field representing the value of Tiles. The value field of Tiles must be readonly This are the problems I am currently facing. I dont know what the tile class should do or how it should be implemented. I am almost 100% sure I am not following the guidelines (tried my best) I think my shuffle method and detection if the puzzle is solvable is wrong Program.cs class Program { static void Main(string[] args) { Board board = new Board(); board.StartGame(); } } Tile.cs class Tile { readonly public int Value; } Board.cs class Board { private int[,] Arr2d { get; set; } private int Size { get; set; } public void StartGame() { Size = 3; Arr2d = new int[Size, Size]; FillTiles(); ShuffleTiles(); if (IsSolvable() == true) { PrintArr(); } else { StartGame(); } SwapTiles(); Console.WriteLine("Finished the game"); } private void FillTiles() { int k = 0; for (int i = 0; i < Size; i++) { for (int j = 0; j < Size; j++) { Arr2d[i, j] = k++; } } } private void ShuffleTiles() { Random random = new Random(); int n = Arr2d.GetLength(1);
{ "domain": "codereview.stackexchange", "id": 44205, "lm_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#, object-oriented, game, console, sliding-tile-puzzle", "url": null }
c#, object-oriented, game, console, sliding-tile-puzzle for (int i = Arr2d.Length - 1; i > 0; i--) { int i0 = i / n; int i1 = i % n; int j = random.Next(i + 1); int j0 = j / n; int j1 = j % n; int temp = Arr2d[i0, i1]; Arr2d[i0, i1] = Arr2d[j0, j1]; Arr2d[j0, j1] = temp; } } private int GetInvCount() { //List<int> flattedList = new List<int> { 1, 20, 6, 4, 5 }; var flattedList = Arr2d.OfType<int>().ToList(); int inv_count = 0; for (int i = 0; i < flattedList.Count - 1; i++) { for (int j = i + 1; j < flattedList.Count; j++) { if (flattedList[i] > flattedList[j]) { inv_count++; } } } return inv_count+1; } private int GetRowNumberFromBelow(int emptyTilePosition) { var row = emptyTilePosition / Size; return Size - row; } private bool IsSolvable() { int numberOfInversions = GetInvCount(); if (Size % 2 != 0) { return (numberOfInversions % 2 == 0); } int pos = GetRowNumberFromBelow(IndexZeroPos()); if (pos % 2 != 0) { return (numberOfInversions % 2 == 0); } else { return (numberOfInversions % 2 != 0); } } private void PrintArr() { for (int i = 0; i < Size; i++) { for (int j = 0; j < Size; j++) { Console.Write(Arr2d[i, j] + " "); } Console.WriteLine(); } }
{ "domain": "codereview.stackexchange", "id": 44205, "lm_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#, object-oriented, game, console, sliding-tile-puzzle", "url": null }
c#, object-oriented, game, console, sliding-tile-puzzle Console.WriteLine(); } } private bool ArrSorted() { var flattedList = Arr2d.OfType<int>().ToList(); var result = flattedList.OrderByDescending(x => x !=0).ThenBy(x => x).SequenceEqual(flattedList); return result; } private int IndexZeroPos() { var flattedList = Arr2d.OfType<int>().ToList(); int i = flattedList.IndexOf(0); return i; } private void SwapTiles() { int y = IndexZeroPos() % Size; int x = IndexZeroPos() / Size; var isSorted = ArrSorted(); while (isSorted != true) { ConsoleKeyInfo info = Console.ReadKey(); Console.WriteLine(); if (info.Key == ConsoleKey.RightArrow) { if (y >= (Size - 1)) { continue; } int temp = Arr2d[x, y]; Arr2d[x, y] = Arr2d[x, (y + 1)]; Arr2d[x, (y + 1)] = temp; if (isSorted != ArrSorted()) { break; } else { y = IndexZeroPos() % Size; x = IndexZeroPos() / Size; PrintArr(); } } if (info.Key == ConsoleKey.LeftArrow) { if (y <= 0) { continue; } int temp = Arr2d[x, y]; Arr2d[x, y] = Arr2d[x, (y - 1)]; Arr2d[x, (y - 1)] = temp;
{ "domain": "codereview.stackexchange", "id": 44205, "lm_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#, object-oriented, game, console, sliding-tile-puzzle", "url": null }
c#, object-oriented, game, console, sliding-tile-puzzle if (isSorted != ArrSorted()) { break; } else { y = IndexZeroPos() % Size; x = IndexZeroPos() / Size; PrintArr(); } } if (info.Key == ConsoleKey.UpArrow) { if (x <= 0) { continue; } int temp = Arr2d[x, y]; Arr2d[x, y] = Arr2d[(x - 1), y]; Arr2d[(x - 1), y] = temp; if (isSorted != ArrSorted()) { break; } else { y = IndexZeroPos() % Size; x = IndexZeroPos() / Size; PrintArr(); } } if (info.Key == ConsoleKey.DownArrow) { if (x >= (Size - 1)) { continue; } int temp = Arr2d[x, y]; Arr2d[x, y] = Arr2d[(x + 1), y]; Arr2d[(x + 1), y] = temp; if (isSorted != ArrSorted()) { break; } else { y = IndexZeroPos() % Size; x = IndexZeroPos() / Size; PrintArr(); } } } } }
{ "domain": "codereview.stackexchange", "id": 44205, "lm_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#, object-oriented, game, console, sliding-tile-puzzle", "url": null }
c#, object-oriented, game, console, sliding-tile-puzzle } } } As this is my first small project I feel like any feedback will do me good and I would really appreciate any feedback of any sort to become better. The code above works, as in the user can move and it will complete when the puzzle is in this state 1 2 3 4 5 6 7 8 0. I have tested some puzzles that where generated with Puzzle solver From the testing it seems a lot of the puzzle states are not solvable which shouldn't be the case. My method IsSolvable seem flawed. Answer: I think you're real close to the ask of the problem. I have two main bits for you to change up: Your Tile class has no way of setting the tile value. Change so that it does. I think immutability is useful here, so note the fact that the property is get-only and the class is sealed (to be honest, I'd implement it as a struct rather than a class, but that would not honor the letter of your requirements): public sealed class Tile : IComparable<Tile> { public Tile(int value) => this.Value = value; public int Value { get; } public int CompareTo(Tile? other) => other?.Value.CompareTo(this.Value) ?? -1; public override string ToString() => this.Value.ToString(); } Change the type of Arr2d from int[,] to Tile[,] (you'll also have to change various int declarations in the rest of the class to Tile). Also change the name of the member variable from Arr2d to Tiles and change the visibility as such: public Tile[,] Tiles { get; private set; } Now there are a few other issues with the code to be sure, and I think it may be broke enough to violate the rule of only working code be posted. But I think you can find those through debugging.
{ "domain": "codereview.stackexchange", "id": 44205, "lm_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#, object-oriented, game, console, sliding-tile-puzzle", "url": null }
kotlin Title: Splitting a list in Kotlin Question: I want to split a list (as if splitting a string by a delimiter), ideally in a functional style, and was surprised how hard it seems to be. Or maybe my code is just unnecessarily complicated? fun <ElemType : Comparable<ElemType>> Iterable<ElemType>.split(delim: ElemType): List<List<ElemType>> { return this.fold(emptyList<List<ElemType>>()) { acc: List<List<ElemType>>, elem: ElemType -> if (elem == delim) acc + listOf(emptyList<ElemType>()) else if (acc.isEmpty()) listOf<List<ElemType>>(listOf<ElemType>(elem)) else acc.take(acc.size - 1) + listOf(acc.last() + elem) } } fun main() { val l = listOf("1", "", "2", "3", "", "", "4") println(l.split("")) val l2 = listOf(1, 0, 2, 3, 0, 0, 4) println(l2.split(0)) } The result for both cases is [[1], [2, 3], [], [4]]. Kotlin Playground Answer: It's complicated because you are making it unnecessarily complicated. I wouldn't use .fold to accomplish this. Think about how many list operations this line does: acc.take(acc.size - 1) + listOf(acc.last() + elem) acc.take(acc.size - 1) copies the current list of sublists except the last. listOf(acc.last() + elem) (I believe this could be just acc.last() + elem?) creates a new list with one element appended to the last list.
{ "domain": "codereview.stackexchange", "id": 44206, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "kotlin", "url": null }
kotlin We know that once we've seen a delimiter, we don't need to touch any previous lists, we can just continue looking at what's ahead of us. This makes it a perfect choice for a sequence builder. fun <ElemType> Iterable<ElemType>.split(delim: ElemType): List<List<ElemType>> { return sequence { val currentList = mutableListOf<ElemType>() for (elem in this@split) { if (elem == delim) { yield(currentList.toList()) currentList.clear() } else { currentList.add(elem) } } yield(currentList.toList()) }.toList() } Other notes: Your function requires ElemType to extend Comparable<ElemType>. I do not see any reason for this. You can remove that restriction.
{ "domain": "codereview.stackexchange", "id": 44206, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "kotlin", "url": null }
c++, object-oriented Title: Hospital appointments registry Question: #ifndef REGISTRY_REGISTRY_H #define REGISTRY_REGISTRY_H #include <vector> #include "patient.h" #include "doctor.h" #include "appointment.h" class Registry { public: Registry(); ~Registry(); std::vector<std::pair<std::string, Patient>> GetPatients() const; std::vector<std::pair<std::string, Doctor>> GetDoctors() const; std::vector<std::pair<std::string, Appointment>> GetAppointments() const; void SetPatients(std::vector<std::pair<std::string, Patient>> patients); void SetDoctors(std::vector<std::pair<std::string, Doctor>> doctors); void SetAppointments(std::vector<std::pair<std::string, Appointment>> appointments); void Add(Doctor doctor); void Add(Patient patient); void Add(DoctorID doctorId, PatientID patientId, Date date); void Remove(PatientID id); void Remove(DoctorID id); void Remove(AppointmentID id); std::vector<std::pair<std::string, Appointment>> FindAppointments(DoctorID id); std::vector<std::pair<std::string, Appointment>> FindAppointments(PatientID id); void ShowAll(const std::vector<std::pair<std::string, Patient>> &patients) const; void ShowAll(const std::vector<std::pair<std::string, Doctor>> &doctors) const; void ShowAll(const std::vector<std::pair<std::string, Appointment>> &appointments, const std::vector<std::pair<std::string, Patient>> &patients) const; void ShowAll(const std::vector<std::pair<std::string, Appointment>> &appointments, const std::vector<std::pair<std::string, Doctor>> &doctors) const; void ShowAll(const std::vector<std::pair<std::string, Appointment>> &appointments, const std::vector<std::pair<std::string, Patient>> &patients, const std::vector<std::pair<std::string, Doctor>> &doctors) const; private:
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, object-oriented private: std::vector<std::pair<std::string, Patient>> patients_; std::vector<std::pair<std::string, Doctor>> doctors_; std::vector<std::pair<std::string, Appointment>> appointments_; void Remove(std::vector<std::pair<std::string, Doctor>>::iterator itDoctor); void Remove(std::vector<std::pair<std::string, Patient>>::iterator itPatient); void Remove(std::vector<std::pair<std::string, Appointment>>::iterator itAppointment); std::vector<std::pair<std::string, Patient>>::iterator Find(PatientID id); std::vector<std::pair<std::string, Doctor>>::iterator Find(DoctorID id); std::vector<std::pair<std::string, Appointment>>::iterator Find(AppointmentID id); }; #endif //REGISTRY_REGISTRY_H #include "../include/registry.h" #include "../include/idgenerator.h" #include <iostream> using namespace std; Registry::Registry() { } Registry::~Registry() { } vector<pair<string, Patient>> Registry::GetPatients() const { return patients_; } vector<pair<string, Doctor>> Registry::GetDoctors() const { return doctors_; } vector<pair<string, Appointment>> Registry::GetAppointments() const { return appointments_; } void Registry::SetPatients(vector<pair<string, Patient>> patients) { patients_ = patients; } void Registry::SetDoctors(vector<pair<string, Doctor>> doctors) { doctors_ = doctors; } void Registry::SetAppointments(vector<pair<string, Appointment>> appointments) { appointments_ = appointments; } void Registry::Add(Doctor doctor) { doctors_.emplace_back(IdGenerator::Generate(), doctor); } void Registry::Add(Patient patient) { patients_.emplace_back(IdGenerator::Generate(), patient); } void Registry::Add(DoctorID doctorId, PatientID patientId, Date date) { auto itDoctor = Find(doctorId); if (itDoctor == doctors_.end()) { throw invalid_argument("Лікаря з таким кодом не існує"); } auto itPatient = Find(patientId); if (itPatient == patients_.end()) {
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, object-oriented auto itPatient = Find(patientId); if (itPatient == patients_.end()) { throw invalid_argument("Пацієнта з таким кодом не існує"); } Appointment newAppointment(itPatient->first, itDoctor->first, date); // emplace_back - вместо того, чтобы принимать value_type, он принимает вариативный список аргументов, так что это означает, // что теперь вы можете идеально пересылать аргументы и напрямую создавать объект в контейнере без временного хранения. appointments_.emplace_back(IdGenerator::Generate(), newAppointment); } void Registry::Remove(PatientID id) { auto it = Find(id); if (it == patients_.end()) { throw invalid_argument("Пацієнта з таким кодом не існує"); } Remove(it); } void Registry::Remove(DoctorID id) { auto it = Find(id); if (it == doctors_.end()) { throw invalid_argument("Лікаря з таким кодом не існує"); } Remove(it); } void Registry::Remove(AppointmentID id) { auto it = Find(id); if (it == appointments_.end()) { throw invalid_argument("Прийому пацієнта до лікаря з таким кодом не існує"); } Remove(it); } vector<pair<string, Appointment>> Registry::FindAppointments(DoctorID id) { auto it = Find(id); if (it == doctors_.end()) { throw invalid_argument("Лікаря з таким кодом не існує"); } vector<pair<string, Appointment>> doctorAppointments; string doctorKey = it->first; copy_if(appointments_.begin(), appointments_.end(), back_inserter(doctorAppointments), [&doctorKey](const pair<string, Appointment> &appointment) { return appointment.second.GetDoctorKey() == doctorKey; }); return doctorAppointments; } vector<pair<string, Appointment>> Registry::FindAppointments(PatientID id) { auto it = Find(id); if (it == patients_.end()) { throw invalid_argument("Пацієнта з таким кодом не існує"); }
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, object-oriented throw invalid_argument("Пацієнта з таким кодом не існує"); } vector<pair<string, Appointment>> patientAppointments; string patientKey = it->first; copy_if(appointments_.begin(), appointments_.end(), back_inserter(patientAppointments), [&patientKey](const pair<string, Appointment> &appointment) { return appointment.second.GetPatientKey() == patientKey; }); return patientAppointments; } void Registry::Remove(vector<pair<string, Patient>>::iterator itPatient) { string patientKey = itPatient->first; patients_.erase(itPatient); // Удаляю все приемы в которых удаленный пациент // erase - удаляет из вектора один элемент (позицию), либо диапазон элементов. appointments_.erase( // remove_if - элементы удовлетворяющие условию записывает в конец вектора, и возвращает итератор на начало элементов на удаление remove_if(appointments_.begin(), appointments_.end(), [&patientKey](const pair<string, Appointment> &appointment) { return appointment.second.GetPatientKey() == patientKey; }), appointments_.end()); } void Registry::Remove(vector<pair<string, Doctor>>::iterator itDoctor) { string doctorKey = itDoctor->first; doctors_.erase(itDoctor); appointments_.erase( remove_if(appointments_.begin(), appointments_.end(), [&doctorKey](const pair<string, Appointment> &appointment) { return appointment.second.GetDoctorKey() == doctorKey; }), appointments_.end()); } void Registry::Remove(vector<pair<string, Appointment>>::iterator itAppointment) { appointments_.erase(itAppointment); } vector<pair<string, Patient>>::iterator Registry::Find(PatientID id) {
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, object-oriented vector<pair<string, Patient>>::iterator Registry::Find(PatientID id) { // find_if - возвращает итератор к первому элементу в диапазоне [first, last], для которого предикат возвращает true. // Если такой элемент не найден, функция возвращает last. auto it = find_if(patients_.begin(), patients_.end(), [&id](const pair<string, Patient> &patient) { return patient.second.GetID() == id; }); return it; } vector<pair<string, Doctor>>::iterator Registry::Find(DoctorID id) { auto it = find_if(doctors_.begin(), doctors_.end(), [&id](const pair<string, Doctor> &doctor) { return doctor.second.GetID() == id; }); return it; } vector<pair<string, Appointment>>::iterator Registry::Find(AppointmentID id) { auto it = find_if(appointments_.begin(), appointments_.end(), [&id](const pair<string, Appointment> &appointment) { return appointment.second.GetID() == id; }); return it; } void Registry::ShowAll(const vector<pair<string, Patient>> &patients) const { for (int i = 0; i < patients.size(); i++) { patients[i].second.Show(); cout << endl; } } void Registry::ShowAll(const vector<pair<string, Doctor>> &doctors) const { for (int i = 0; i < doctors.size(); i++) { doctors[i].second.Show(); cout << endl; } } void Registry::ShowAll(const vector<pair<string, Appointment>> &appointments, const vector<pair<string, Patient>> &patients) const { for (int i = 0; i < appointments.size(); i++) { cout << endl; AppointmentID appointmentId = appointments[i].second.GetID(); cout << "Номер прийому: " << appointmentId << endl << endl; string patientKey = appointments[i].second.GetPatientKey();
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, object-oriented string patientKey = appointments[i].second.GetPatientKey(); auto patientIt = find_if(patients.begin(), patients.end(), [&patientKey](const pair<string, Patient> &patient) { return patient.first == patientKey; }); patientIt->second.Show(); cout << endl; Date date = appointments[i].second.GetDate(); cout << "Дата прийому: "; date.Show(); cout << endl; } } void Registry::ShowAll(const vector<pair<string, Appointment>> &appointments, const vector<pair<string, Doctor>> &doctors) const { for (int i = 0; i < appointments.size(); i++) { cout << endl; AppointmentID appointmentId = appointments[i].second.GetID(); cout << "Номер прийому: " << appointmentId << endl << endl; string doctorKey = appointments[i].second.GetDoctorKey(); auto doctorIt = find_if(doctors.begin(), doctors.end(), [&doctorKey](const pair<string, Doctor> &doctor) { return doctor.first == doctorKey; }); doctorIt->second.Show(); cout << endl; Date date = appointments[i].second.GetDate(); cout << "Дата прийому: "; date.Show(); cout << endl; } } void Registry::ShowAll(const vector<pair<string, Appointment>> &appointments, const vector<pair<string, Patient>> &patients, const vector<pair<string, Doctor>> &doctors) const { for (int i = 0; i < appointments.size(); i++) { cout << endl; AppointmentID appointmentId = appointments[i].second.GetID(); cout << "Номер прийому: " << appointmentId << endl << endl; string patientKey = appointments[i].second.GetPatientKey(); auto patientIt = find_if(patients.begin(), patients.end(), [&patientKey](const pair<string, Patient> &patient) { return patient.first == patientKey; }); patientIt->second.Show();
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, object-oriented return patient.first == patientKey; }); patientIt->second.Show(); cout << endl; string doctorKey = appointments[i].second.GetDoctorKey(); auto doctorIt = find_if(doctors.begin(), doctors.end(), [&doctorKey](const pair<string, Doctor> &doctor) { return doctor.first == doctorKey; }); doctorIt->second.Show(); Date date = appointments[i].second.GetDate(); cout << endl; cout << "Дата прийому: "; date.Show(); cout << endl; } }
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, object-oriented } } Hi all, I want to implement a hospital Registry class. But I don't know how to do it properly. It should contain vectors of patients, doctors and appointments of patients to doctors. It should have functionality to add, delete patients, doctors and appointments of patients to doctors, etc. For correct deletion of objects, there should be a search method for these objects. I also want to make a functionality, for example, to search for patients' appointments with certain doctors. Objects, for example Patient has structure field PatientID and these IDs are generated in constructor at object creation and have number form (0, 1, 2...). I did it as a structure to do overloading in Remove() methods for example. In class, I plan to store objects in pairs, the first element of the pair - string (object key, something like UUID), the second element of the pair - the object itself. These keys will be generated in Add() methods. I can not use ID objects which are generated in object constructors, because after restarting the program they can be different each time, and it's not allowed to bind patients and doctors in Appointment object, so I plan to keep patient and doctor keys in Appointment objects for binding them, because the keys are generated only once and never change. I think that my implementation is not very good, because right now it's just focused on object IDs, but what if I want to search for objects by name? I don't know how to make overloaded methods in this case. What are your recommendations? What is the right way to do it?
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, object-oriented Answer: using namespace std; can lead to surprises when standard library functions (including template functions) better match that the functions we think we're calling. Namespaces exist to help us separate similar-named functions and throwing that away by pulling the entirety of std into the global namespace is quite harmful. If you really feel unable to use the five characters std::, then consider importing specific names into the global namespace - even then, I'd advise keeping their scope small (at least you didn't do it in the header, where it would harm every program using it!). It's not clear why we have so many vectors of pairs - most of those look like they would be better as std::map objects, especially as we have written a lot of linear searches over them. I'm surprised you need six overloads of Remove() - the private ones are called once each, so just inline those at their call sites. You could make Remove() and FindAppointments() much simpler (and faster) by maintaining back-references from each doctor and patient to their appointment objects (probably as a collection of std::reference_wrapper objects). You'll need to make sure these are updated correctly when appointments are changed (added, modified or deleted) of course. There's a lot of searching that matches on the second element of a pair, using std::find_if. We could write a convenience function to generate all those similar functors: auto match_id(auto const& id) { return [&id](auto const& pair){ return pair.second.GetID == id; }; } So we could write auto Registry::Find(const PatientID& id) { return std::ranges::find_if(patients_, match_id(id)); } and similar. But it might be more productive to consider supplying a projection argument to the find algorithm, and avoid the need for a predicate function. E.g. auto Registry::Find(const PatientID& id) { using PatientPair = std::pair<std::string, Patient>; return std::ranges::find(patients, id, &PatientPair::second); }
{ "domain": "codereview.stackexchange", "id": 44207, "lm_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++, object-oriented", "url": null }
c++, tree Title: Converting String to Binary Hash Tree Question: I've written a pretty basic algorithm to convert a string to a binary hash tree of its characters, where each character represents a leaf node. The hash tree itself is being stored in a vector. If the number of leaf nodes is not a power of 2, I'm padding the number leaf nodes with empty substrings until the number of leaves is a power of 2. I know there's likely a much better way to achieve this, but I'm having trouble picturing what that would look like. What are some alternate, potentially more performant approaches I may have overlooked? Please disregard the chosen hash function (DJB2()). #include <iostream> #include <fstream> #include <string> #include <vector> #include <math.h> #include "../code/hash.h" using namespace std; struct Node { unsigned int hash; }; bool IsPowerOfTwo(int c) { int a = ceil(log2(c)); int b = floor(log2(c)); return a == b; } int NextPowerOfTwo(int c) { int a = ceil(log2(c)); return pow(2, a); } int main(int argc, char* argv[]) { string str = "abc34"; vector<shared_ptr<Node>> nodes; int leaves = IsPowerOfTwo(str.length()) ? str.length() : NextPowerOfTwo(str.length()); int total_nodes = 2 * leaves - 1; int non_leaves = total_nodes - leaves; // Add root + internal nodes to vector for(int i = 0; i < non_leaves; i++) { shared_ptr<Node> new_node(new Node); nodes.push_back(new_node); } // Generate the hash for leaf nodes + add to vector for (int i = 0; i < leaves; i++) { shared_ptr<Node> new_node(new Node); string substr = (i >= str.length()) ? "" : string (1, str[i]); new_node->hash = DJB2(substr); nodes.push_back(new_node); } // Generate the hash for internal and root nodes for (int i = non_leaves - 1; i >= 0; i--) { int left_child_index = 2 * i + 1; int right_child_index = 2 * i + 2;
{ "domain": "codereview.stackexchange", "id": 44208, "lm_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++, tree", "url": null }
c++, tree int left_child_index = 2 * i + 1; int right_child_index = 2 * i + 2; string left_child_hash = to_string(nodes[left_child_index]->hash); string right_child_hash = to_string(nodes[right_child_index]->hash); string child_hashes = left_child_hash + right_child_hash; nodes[i]->hash = DJB2(child_hashes); } // Output index of node in vector/tree and its corresponding hash value for (int i = 0; i < nodes.size(); i++) { cout << i << " : " << nodes[i]->hash << endl; } return 0; } Answer: Use the C++ version of standard C header files You are including <math.h>, but you should include <cmath>. Especially for the math functions, using the versions from std:: will make sure they automatically deduce whether they should return float or double. Avoid unnecessary use of floating point arithmetic Converting an integer to floating point, doing some operation, and then converting back is going to be slow. Floating point math is also not always exact, and this can cause problems if you assume it is. If possible, do everything using integer arithmetic where possible. To see what you can do with just integers, look at Sean Eron Anderson's bit twiddling hacks, it includes how to check if an integer is a power of two and how to round up to the next power of two. Even better, if you can use C++20, use std::has_single_bit() to check if something is a power of two, and std::bit_ceil() to round up to the nearest power of two. Unnecessary use of std::shared_ptr I don't see any reason to use std::shared_ptr for storing Nodes. You should be able to just write: … int non_leaves = total_nodes - leaves; std::vector<Node> nodes(non_leaves); This creates a vector of non_leaves Nodes. Then to add the leaf nodes: for (int i = 0; i < leaves; ++i) { std::string substr = (i >= str.length()) ? "" : std::string(1, str[i]); nodes.emplace_back(DJB2(substr)); }
{ "domain": "codereview.stackexchange", "id": 44208, "lm_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++, tree", "url": null }
c++, tree In the rest of the code, you can replace ->hash with .hash, since the elements of nodes` are no longer pointers. Use .reserve() Since STL containers do not know up front how many elements you are going to place in them, they start out small and allocate more memory later, and for std::vector is also has to move elements from the old to the new memory region each time it grows. But if you know up front how many elements you are going to store, you can call .reserve() so it can do one big allocation up front: std::vector<Node> nodes(…); nodes.reserve(total_nodes); Use '\n' instead of std::endl Prefer to use '\n' instead of std::endl; the are mostly equivalent, but the latter also forces the output to be flushed, which is often unnecessary and can be bad for performance. Suboptimal calculation of internal node hash values Regardless of the performance of DJB2() itself, one issue is that for the internal nodes, you are converting indices to strings, concatenating those strings, and then hashing the result of that. That is not efficient, and it also has some issues. For example, consider these scenarios: `left_child_hash = "123"; right_child_hash = "45"; `left_child_hash = "12"; right_child_hash = "345"; The child hashes in the second case are clearly different from the first case, but the concatenation is the same. While hash functions don't guarantee uniqueness, so it's probably not a big problem, you are actually providing less information to the hash function than you could, so it's going to perform slightly worse. One solution would be to do a bitwise copy of the integers into a std::string and hash that. Making use of the fact that the two child hash values are already consecutive inside nodes: std::string child_hashes(2 * sizeof(Node)); for (int i = non_leaves - 1; i >= 0; --i) { std::copy_n(reinterpret_cast<char*>(&nodes[2 * i + 1]), 2 * sizeof(Node), child_hashes.data()); nodes[i].hash = DJB2(child_hashes); }
{ "domain": "codereview.stackexchange", "id": 44208, "lm_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++, tree", "url": null }
c++, tree Make use of std::string_view if possible It would be nice if DJB2() would take a std::string_view as an argument. This would avoid some copies that your code is currently making, like substr, and even the std::copy_n() into child_hashes in the example above. Pre-compute commonly used hash values While the compiler might be able to optimize this for you if it can inline DJB2(), you can help it yourself by pre-computing the hash of the empty string: Node empty_node{DJB2("")}; for (int i = 0; i < leaves; ++i) { if (i >= str.length()) { nodes.push_back(empty_node); } else { nodes.emplace_back(DJB2(str.substr(i, 1))); } } Or even better, remove the if entirely and just loop up to str.length() and pad the vector afterwards: for (int i = 0; i < str.length(); ++i) { nodes.emplace_back(DJB2(str.substr(i, 1))); } nodes.insert(nodes.back(), leaves - str.length(), DJB2("")); Also note that if str is very large, you will likely calculate the hash of the same character multiple times. You could then speed up this part by pre-computing all possible hashes of a char, or by creating a simple cache.
{ "domain": "codereview.stackexchange", "id": 44208, "lm_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++, tree", "url": null }
python, strings, file Title: SImple Inverted Index Question: This is a simple inverted index I made. The goal is to: Read set of text files from a directory, docs Tokenize them Normalize the tokens by removing punctuation and lowercasing them create an index of words to doc name, count of docs that that word appears in Everything works as expected. I'm just curious what improvements there are to make. import os import re import fileinput punctuation_regex = r"[^\w\s]" def normalize_tokens(tokens): """Remove all non-alphanumeric characters and convert to lower case""" tokens = [re.sub(punctuation_regex, "", str.lower()) for str in tokens] return tokens def tokenize_input(input): """Split string on whitespace and return unique tokens""" tokens = normalize_tokens(input.split()) return set(tokens) def read_docs(): """Read files in docs directory and return map of filename -> tokens in file""" docs_to_tokens = {} for filename in os.listdir("docs"): with open(os.path.join("docs", filename), 'r') as f: docs_to_tokens[filename] = tokenize_input(f.read()) return docs_to_tokens def make_index(): """Make inverted index of token -> docs containing token, number of docs containing token""" index = {} docs = read_docs() for doc in docs: for str in docs[doc]: if not str in index: index[str] = {} index[str]['count'] = 0 index[str]['docs'] = [] index[str]['count'] += 1 index[str]['docs'].append(doc) return index def query_index(key, index): """Return docs that contain key""" if key not in index: return None return index[key]['docs'] def main(): index = make_index() for line in fileinput.input(): print(query_index(line.rstrip(), index)) if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 44209, "lm_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, strings, file", "url": null }
python, strings, file if __name__ == "__main__": main() Answer: Nice, readable code, and well laid out. I don't like the hardcoded pathname in read_docs() - surely that should be an argument? Similarly, I would pass the result of read_docs() as argument to make_index() so it can be tested separately. Here, we have dicts that we access by exactly two fixed keys: if not str in index: index[str] = {} index[str]['count'] = 0 index[str]['docs'] = [] index[str]['count'] += 1 index[str]['docs'].append(doc) Perhaps we should be using a (named) tuple instead of a dict? And perhaps index should be a defaultdict, so we don't need the str in index test? Perhaps normalize_tokens() should return a set, rather than creating a list which we then deduplicate in tokenize_input()? Alternatively, make it a generator, which also avoids constructing the list.
{ "domain": "codereview.stackexchange", "id": 44209, "lm_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, strings, file", "url": null }
python, programming-challenge Title: Permutations CodeWars problem solved! Question: i have solved a question in codewars: https://www.codewars.com/kata/5254ca2719453dcc0b00027d/python , here's my solution is it unefficient to use itertools because people are blaming that is cheating using libraries should i try to solve it on other ways and is it this bad way to implement the question this is my first time to solve kata 4kuy a months ago it wasn't possible today is my first one to be solved because of difficulty of the questions.Can you tell me is using libraries considered as a cheating because a lot of people say that is and as a begginer programmer i don't know if i am begginer i am one year into this should i try to focus more on not using libraries? Thank you. import itertools def permutations(s): result = itertools.permutations(s,len(s)) new_list = [] for item in result: new_list.append("".join(item)) return sorted(set(new_list)) Answer: As to whether or not you should use libraries - depends entirely on what you want to achieve. Perhaps briefly put, if you enjoy the algorithmic challenge of essentially building the algorithm behind itertools.permutations, then do it. If you want to build efficient software and reuse good work other people have already done, do use libraries. Libraries exist because well-crafted and well-tested solutions for general problems are obviously very useful. As for your solution, it's usually a good idea to use list (or set) comprehension and to avoid explicit for loops. This is usually considered more Pythonic, and can often be more efficient. So we could just do: import itertools def permutations(s: str) -> list: return list({''.join(p) for p in itertools.permutations(s)})
{ "domain": "codereview.stackexchange", "id": 44210, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, programming-challenge", "url": null }
c++, performance, game Title: C++ Resource Manager base for game application Question: I'm writing a Resource Manager for my small but scalable future project. The main target of this is to get best speed of access, be flexible and avoid memory leaks. Enumerations enum class ResourceType { None = 0, Script, Texture, Mesh, Shader, Sound, }; enum ResourceDictionary : uint64_t { // Sound R_Sound_Click1, R_Sound_Click2, R_Sound_Click3, // Mesh R_Mesh_Monster1, R_Mesh_Monster2, R_Mesh_Monster3, // Shader R_Shader_Vertex1, R_Shader_Vertex2, // ... }; Resource base class Resource { ResourceType m_Type = ResourceType::None; std::string m_Name = "Empty"; std::filesystem::path m_Path; protected: bool m_Loaded = false; public: Resource() = default; Resource(ResourceType type, const std::string_view name, const std::filesystem::path& path) : m_Type(type), m_Name(name), m_Path(path) { } virtual ~Resource() = default; public: virtual bool Load() { return false; } virtual bool Unload() { return false; } public: ResourceType GetType() const { return m_Type; } const std::string_view GetName() const { return m_Name; } const std::filesystem::path& GetPath() const { return m_Path; } bool GetLoaded() const { return m_Loaded; } }; template<typename T> concept ResourceComponent = std::derived_from<T, Resource>; Concrete Resource class Sound final : public Resource { public: Sound() = default; Sound(const std::string_view name, const std::filesystem::path& path) : Resource(ResourceType::Sound, name, path) { } ~Sound() { if (m_Loaded) { Unload(); } } public: bool Load() override { m_Loaded = true; return true; } bool Unload() override { m_Loaded = false; return true; } };
{ "domain": "codereview.stackexchange", "id": 44211, "lm_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, game", "url": null }
c++, performance, game bool Unload() override { m_Loaded = false; return true; } }; Resource Manager class ResourceManager { using ResourceKey = ResourceDictionary; using ResourcePtr = std::unique_ptr<Resource>; using ResourceContainer = std::unordered_map<ResourceKey, ResourcePtr>; using ResourceContainerPair = std::pair<ResourceKey, const ResourcePtr&>; ResourceContainer m_Resources; private: template<ResourceComponent T> constexpr ResourceType EnumResourceType() { if (std::is_same_v<T, Resource>) return ResourceType::None; else if (std::is_same_v<T, Sound>) return ResourceType::Sound; else if (std::is_same_v<T, Mesh>) return ResourceType::Mesh; else if (std::is_same_v<T, Shader>) return ResourceType::Shader; } public: ResourceManager() = default; ~ResourceManager() = default; public: template<ResourceComponent T> void Register(ResourceKey key, T* resource) { m_Resources.insert_or_assign(key, ResourcePtr(resource)); } void Release(ResourceKey key) { if (!m_Resources.contains(key)) { return; } m_Resources.erase(key); } template<ResourceComponent T = Resource> void Release() { const ResourceType type = EnumResourceType<T>(); std::erase_if(m_Resources, [this, type](const ResourceContainerPair& pair) { if (type == ResourceType::None || pair.second->GetType() == type) { return true; } return false; }); } void Load(ResourceKey key) { const auto it = m_Resources.find(key); if (it != m_Resources.end()) { const auto& resource = it->second; if (resource->GetLoaded()) { // notify rewrite resource->Unload(); }
{ "domain": "codereview.stackexchange", "id": 44211, "lm_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, game", "url": null }
c++, performance, game if (resource->Load()) { // notify success } else { // notify failure } } } template<ResourceComponent T = Resource> void Load() { const ResourceType type = EnumResourceType<T>(); auto container_view = m_Resources | std::views::filter([type](const ResourceContainerPair& pair) { if (type == ResourceType::None) return true; return pair.second->GetType() == type; }); for (const auto& [key, resource] : container_view) { if (resource->GetLoaded()) { // notify rewrite resource->Unload(); } if (resource->Load()) { // notify success } else { // notify failure } } } void Unload(ResourceKey key) { const auto it = m_Resources.find(key); if (it != m_Resources.end()) { const auto& resource = it->second; if (resource->Unload()) { // notify success } else { // notify failure } } } template<ResourceComponent T = Resource> void Unload() { const ResourceType type = EnumResourceType<T>(); auto container_view = m_Resources | std::views::filter([type](const ResourceContainerPair& pair) { if (type == ResourceType::None) return true; return pair.second->GetType() == type; }); for (const auto& [key, resource] : container_view) { if (resource->Unload()) { // notify success } else { // notify failure } } }
{ "domain": "codereview.stackexchange", "id": 44211, "lm_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, game", "url": null }
c++, performance, game public: template<ResourceComponent T> T* Get(ResourceKey key) const { static T null_resource; const auto it = m_Resources.find(key); if (it != m_Resources.end()) { return dynamic_cast<T*>(m_Resources.at(key).get()); } // notify failure return &null_resource; } }; Example of usage int main() { ResourceManager manager; manager.Register(R_Sound_Click1, new Sound("Sound 0", "Sound/Sound0.wav")); manager.Register(R_Mesh_Monster1, new Mesh("Mesh 0", "Model/Mesh0.3d")); manager.Register(R_Sound_Click2, new Sound("Sound 1", "Sound/Sound1.wav")); manager.Register(R_Mesh_Monster2, new Mesh("Mesh 1", "Model/Mesh1.3d")); manager.Register(R_Sound_Click3, new Sound("Sound 2", "Sound/Sound2.wav")); manager.Register(R_Mesh_Monster3, new Mesh("Mesh 2", "Model/Mesh2.3d")); manager.Register(R_Shader_Vertex1, new Shader("Shader 1", "Shader/Shader0.3d")); // get concrete resource auto sound = manager.Get<Sound>(R_Sound_Click1); // load all resources manager.Load(); // load concrete resource manager.Load(R_Shader_Vertex1); // release concrete resource manager.Release(R_Shader_Vertex1); // release sound resources manager.Release<Sound>(); // release all resources manager.Release(); } Answer: Alternative ways to manage resources Looking at your code, I think it's a bit complicated, not very flexible, and ResourceManager isn't much more than a glorified wrapper around a std::unordered_map<Key, std::unique_ptr<Resource>>. Do you need a resource manager class at all? Consider that instead of having the indirection via the key, you could create resources as global variables: Sound soundClick1("Sound 0", "Sound/Sound0.wav"); Mesh meshMonster1("Mesh 0", "Model/Mesh0.3d"); …
{ "domain": "codereview.stackexchange", "id": 44211, "lm_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, game", "url": null }
c++, performance, game You can create a header file that exports these global variables so they can be used in other source files as well. The only advantage I currently see is that you can (un)load groups of resources in one go. You could create an array or vector of pointers to resources if you need to group them: std::vector<Resource*> sounds = {&soundClick1, &soundClick2, …}; And for example load all resources in one go with: std::ranges::for_each(sounds, [](auto& sound){ sound.Load(); }); While that's a bit more manual work, it is also more flexible: you can group resources however you like now, and are not confined to whatever grouping the resource manager supports. This way for example you can unload all sounds used by a game level, but not those used for the UI. Another issue is that you still have to manually add entries to enum ResourceDictionary and construct resource objects. Consider making your resource manager more data driven, so it can manage resources without hardcoding anything. What if you could write this? ResourceManager manager; manager.Register("resources.txt"); Sound& soundClick1 = manager.Get<Sound>("Sound 0"); Avoid passing raw pointers It's good that you use std::unique_ptr to store resources, but if you want to add a resource using Register(), also use a std::unique_ptr to pass the resources. This avoids the possibility of bugs like: auto soundClick1 = new Sound("Sound 0", "Sound/Sound0.wav"); manager.register(R_Sound_Click1, soundClick1); manager.register(R_Sound_Click2, soundClick1); You can change Register() like so: template<ResourceComponent T> void Register(ResourceKey key, ResourcePtr&& resource) { m_Resources.insert_or_assign(key, std::move(resource)); } And call it like so: manager.Register(R_Sound_Click1, std::make_unique<Sound>("Sound 0", "Sound/Sound0.wav"));
{ "domain": "codereview.stackexchange", "id": 44211, "lm_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, game", "url": null }
c++, performance, game Or you can make it even more convenient by having Register() construct the resource itself: template<ResourceComponent T, typename... Args> void Register(ResourceKey key, Args&&... args) { m_Resources.insert_or_assign(key, std::make_unique<T>(std::forward<Args>(args)...)); } And then call it like so: manager.Register<Sound>(R_Sound_Click1, "Sound 0", "Sound/Sound0.wav"); Make one map per resource type Instead of having one big std::unordered_map storing pointers to base class, consider having multiple maps, one per resource type. This way you can store concrete types in each map. There are several ways to do this. If you already know the exact set of types you are going to support, you can make a std::tuple: template<typename T> using ResourceContainer = std::unordered_map<ResourceKey, T>; std::tuple< ResourceContainer<Sound>, ResourceContainer<Mesh>, ResourceContainer<Shader> > m_Resources; … template<ResourceComponent T, typename... Args> void Register(ResourceKey key, Args&&... args) { std::get<ResourceContainer<T>>(m_Resources).try_emplace(key, std::forward<Args>(args)...); } … template<ResourceComponent T> T& Get(ResourceKey key) const { return std::get<ResourceContainer<T>>(m_Resources).at(key); } If you don't mind having ResourceManager be a singleton, you can simplify things by making an inline static template member variable: template<typename T> using ResourceContainer = std::unordered_map<ResourceKey, T>; template<typename T> inline static ResourceContainer<T> m_Resources; … template<ResourceComponent T, typename... Args> void Register(ResourceKey key, Args&&... args) { m_Resources<T>.try_emplace(key, std::forward<Args>(args)...); } … template<ResourceComponent T> T& Get(ResourceKey key) const { return m_Resources<T>.at(key); }
{ "domain": "codereview.stackexchange", "id": 44211, "lm_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, game", "url": null }
c++, performance, game Note how we didn't have to make m_Resources a tuple, and we didn't specify in any way which types it should support. So you can add new resource types without having to modify ResourceManager, the drawback is that it only works if m_Resources is a static member variable, so you can't have two different instances of a ResourceManager manager different sets of resources.
{ "domain": "codereview.stackexchange", "id": 44211, "lm_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, game", "url": null }
rust, iterator, trait Title: Extend iterators with until() function Question: I want to extend generic iterators with a convenience function until() that works like an inversion of take_while(). Here is the code: Cargo.toml: [package] name = "until" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] src/lib.rs: use std::iter::TakeWhile; pub trait Until<T, P>: Iterator<Item = T> + Sized where P: Fn(&Self::Item) -> bool + 'static, { fn until(&mut self, f: P) -> TakeWhile<&mut Self, Box<dyn Fn(&T) -> bool>> { self.take_while(Box::new(move |item| !f(item))) } } impl<T, P, I> Until<T, P> for I where P: Fn(&Self::Item) -> bool + 'static, I: Iterator<Item = T>, { } src/main.rs: use until::Until; fn main() { let items = vec![1, 2, 3, 4, 5]; for item in items.into_iter().until(|item| *item > 3) { println!("{}", item); } } What I don't like about this implementation are The use of a Box to wrap the function pointer The thus resulting complex return type of until() The fact that I explicitly need to implement the trait for all iterators in an empty impl block How can I address these three issues (and possibly others)? Answer: My first thought: why? If all you are going to do is invert the logic of take_while, why don't I just call take_while with an extra ! The use of a Box to wrap the function pointer The thus resulting complex return type of until() Typically, what's done is that the iterator is implemented as a struct generic over the internal iterator type. So you'd implement a: struct TakeUntil<I, P> {iterator: I, predicate: P); impl <I:Iterator, P: FnMut(&I::Item) -> bool> Iterator for TakeUntil<I> { ... } Then your until function would return this type: fn until(&mut self, f: P) -> TakeUntil<Self, P>
{ "domain": "codereview.stackexchange", "id": 44212, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, iterator, trait", "url": null }
rust, iterator, trait Then your until function would return this type: fn until(&mut self, f: P) -> TakeUntil<Self, P> That makes the return type simpler and avoid allocation and dynamic dispatch, but does require additional ceremony. However, its also odd here because iterators typically take self not &mut self. Put another way, they consume the iterator they don't modify it. The fact that I explicitly need to implement the trait for all iterators in an empty impl block I don't believe you can avoid this. What you can do is move the implementation to the impl block and remove much of what is currently on the trait: pub trait Until<T, P> { fn until(&mut self, f: P) -> TakeWhile<&mut Self, Box<dyn Fn(&T) -> bool>>; } impl<T, P, I> Until<T, P> for I where P: Fn(&I::Item) -> bool + 'static, I: Iterator<Item = T>, { fn until(&mut self, f: P) -> TakeWhile<&mut Self, Box<dyn Fn(&T) -> bool>> { self.take_while(Box::new(move |item| !f(item))) } } This is what I typically see for iterator extensions.
{ "domain": "codereview.stackexchange", "id": 44212, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust, iterator, trait", "url": null }
python, python-3.x, game Title: Simple text-game navigation system Question: I am a total newbie when it comes to coding in general, let alone Python. After following a few tutorials, I decided to try making my own little navigation system for simple maps, sort of drawing from what I know about how old MUD games like Achaea work. It works, but I have no idea how robust or expandable it will be. Code here: def r0_0(): print("You are in room 0,0") while True: a = input("You can move North or East.\n>") if a == "n": r1_0() elif a == "e": r0_1() else: print("You can't go that way.") def r0_1(): print("You are in room 0,1") while True: a = input("You can move North or West.\n>") if a == "n": r1_1() elif a == "w": r0_0() else: print("You can't go that way.") def r1_0(): print("You are in room 1,0") while True: a = input("You can move South or East.\n>") if a == "s": r0_0() elif a == "e": r1_1() else: print("You can't go that way.") def r1_1(): print("You are in room 1,1") while True: a = input("You can move South, West, Up, or Down.\n>") if a == "s": r0_1() elif a == "w": r1_0() elif a == "u": r1_1_1() elif a == "d": r1_1_b1() else: print("You can't go that way.") def r1_1_1(): print("You are in room 1,1,1") a = input("You can move Down.\n>") if a == "d": r1_1() else: print("You can't go that way.") def r1_1_b1(): print("You are in room 1,1,-1") a = input("You can move Up.\n>") if a == "u": r1_1() else: print("You can't go that way.") r0_0() I'm mainly looking for feedback on how to improve this system, or if it will even be reliable. Should I continue with this system, or is it going to cause problems later on?
{ "domain": "codereview.stackexchange", "id": 44213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game", "url": null }
python, python-3.x, game Answer: A UX problem in this app is there's no easy way to quit. A design problem is the call stack size. Each call spawns another call that never returns, slowly eating up the call stack. After 1000 or so calls on CPython, the program crashes. A bug seems to be that r1_1_1 and r1_1_b1 don't have while True: loops, so if the player gives bad input, the player pops back to the previous room. Conceptually, you're making a state machine. The player moves from the current state to the next state based on an input. The code in general is pretty WET. Sometimes this is OK, but in this case it'd benefit from identifying and extracting common patterns into a data structure that encodes the state machine logic along with a little engine that runs the state machine. A dictionary is a good data structure for a state machine. The keys represent the state names and values are nested dictionaries mapping decisions/inputs to next state names. Here's an example rewrite that illustrates how you could go about setting this up: from types import MappingProxyType def imm_dict(*args, **kwargs): return MappingProxyType(dict(*args, **kwargs)) states = imm_dict({ "0,0": imm_dict( n="1,0", e="0,1", ), "0,1": imm_dict( n="1,1", w="0,0", ), "1,0": imm_dict( s="0,0", e="1,1", ), "1,1": imm_dict( s="0,1", w="1,0", u="1,1,1", d="1,1,-1", ), "1,1,1": imm_dict( d="1,1", ), "1,1,-1": imm_dict( u="1,1", ), }) directions = imm_dict( n="North", s="South", e="East", w="West", u="Up", d="Down", ) def humanize(lst): if not lst: return "" elif len(lst) == 1: return lst[0] return ", ".join(lst[:-1]) + f" or {lst[-1]}" def explore(): current_room = "0,0"
{ "domain": "codereview.stackexchange", "id": 44213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game", "url": null }
python, python-3.x, game def explore(): current_room = "0,0" while True: print(f"You are in room {current_room}") movements = list(states[current_room].keys()) humanized_directions = humanize([directions[x] for x in movements]) while True: print(f"You can move {humanized_directions}") response = input("> ").lower().strip() if response == "exit" or (response and response[0] == "q"): print("Goodbye.") return elif response not in movements: print("You can't go that way.") else: current_room = states[current_room][response] break if __name__ == "__main__": explore() A few advantages: no stack overflows separates engine from the raw state transition/movement data (easy to move to a config/JSON file if desired) easy to extend (plug in a different set of rooms or make adjustments to the current room map without changing the engine code) Interaction was left pretty direct without much abstraction, but I didn't want to be too premature about that. In a larger app, you might want to move the inner while loop out to a generic function that asks for input until a valid response is given. For some text interaction applications like this, the logic per room isn't so regular and you'll need custom classes or functions to handle the logic for each state, so this app is a rather "easy" case because it's highly regular. Taking that idea a step further, your particular room structure is a 3d grid, so if it's not too sparse, you might consider using a 3d list to store it. A step in that direction might be to switch from strings to tuples, possibly keeping all of them the same length. For example: states = imm_dict({ (0, 0, 0): imm_dict( n=(1, 0, 0), e=(0, 1, 0), ), (0, 1, 0): imm_dict( n=(1, 1, 0), w=(0, 0, 0), ), # ... })
{ "domain": "codereview.stackexchange", "id": 44213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game", "url": null }
python, python-3.x, game You don't have to use the immutable dictionary here, but I'm a fan of immutability and I don't want to accidentally mutate the state machine. Python doesn't have a native Object.freeze() (JS) or .freeze (Ruby) at the time of writing. As a final node, always use 4 space indentation in Python. 2 space indentation only seems to be readable in languages that have braces (most languages) or at least an end keyword (Ruby, Lua, Bash). In Python, small indents make it difficult to determine which nesting level code belongs to.
{ "domain": "codereview.stackexchange", "id": 44213, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "python, python-3.x, game", "url": null }
c, error-handling Title: A stripped-down version of UNIX sort utility Question: Usage: ./usort <options> <filename> Name: ./usort - sort lines of text. Description: Write sorted concatenation of FILE to standard output. In the absence of options, lexicographical order is taken as default. Ordering Options: -n, --numeric sorts by numeric order. -r, --reverse sorts in reverse order. -h, --help displays this message and exits. -o, --output=FILE writes result to FILE instead of standard output. Review Goals: I would like some feedback regarding: Non-idiomatic code Style Error-Checking Bad practices Further improvements Code: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <stdbool.h> #include <string.h> #include <getopt.h> #include <stddef.h> #define MAX 1000 #define MAXLINES 50000 #define OP_LIST "nrho:" FILE *fp; struct flags { bool nflag ; /* Numeric flag */ bool rflag ; /* Reverse flag */ bool oflag ; /* Output to FILE flag */ }; static void parse_options (struct option long_options[], struct flags *opt_ptr, int argc, char *argv[], char *out_file); static void usage(size_t status); static int read_file(char *lines[], char *filename); static void write_to_stdout(char *lines[], int num_lines, struct flags *opt_ptr); static void write_to_FILE (char *lines[], int num_lines, char *optarg, struct flags *opt_ptr); static int scmp(const void *s1, const void *s2); static int numcmp(const void *s1, const void *s2); static void *xcalloc(size_t size); static void free_allocs(char *lines[], char *out_file, char *in_file); int main(int argc, char *argv[]) {
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling int main(int argc, char *argv[]) { static struct option long_options[] = { {"numeric", no_argument, NULL, 'n'}, {"reverse", no_argument, NULL , 'r'}, {"output", required_argument, NULL, 'o'}, {"help", no_argument, NULL , 'h'}, {NULL, 0, NULL, 0} }; char *in_file = xcalloc(256); char *out_file = xcalloc(256); struct flags options = {false, false, false}; struct flags *opt_ptr = &options; parse_options(long_options, opt_ptr, argc, argv, out_file); /* If there is no file argument, call usage */ if (optind >= argc) { usage(EXIT_FAILURE); } /* If there is more or less than 1 argument, call usage */ else if ((optind + 1) != argc) { usage(EXIT_FAILURE); } strcpy(in_file, argv[optind]); char *lines[MAXLINES]; size_t i; for (i = 0; i < MAXLINES; i++) { lines[i] = xcalloc(MAX); } size_t num_lines; num_lines = read_file(lines, in_file); qsort(lines, num_lines, sizeof *lines, opt_ptr->nflag? numcmp: scmp); opt_ptr->oflag ? write_to_FILE(lines, num_lines, out_file, opt_ptr) : write_to_stdout(lines, num_lines, opt_ptr); free_allocs(lines, out_file, in_file); return EXIT_SUCCESS; } /* ====================================================================================================================================================================================================== */ static void usage(size_t status) { if (status != EXIT_FAILURE) { fprintf(stderr, "\nUSAGE\n\tusort <options> <filename>\n\n"); fputs("NAME\n\tusort - sort lines of text.\n\n\ DESCRIPTION\n\tWrite sorted concatenation of FILE to standard output.\n\ In the absence of options, lexicographical order is taken as default.\n\n", stdout);
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling fputs("ORDERING OPTIONS:\n\n\ -n, --numeric sorts by numeric order.\n\n\ -r, --reverse sorts in reverse order.\n\n\ -h, --help displays this message and exits.\n\n\ -o, --output=FILE writes result to FILE instead of standard output.\n\n", stdout); exit(status); } else { fprintf(stderr, "The syntax of the command is incorrect.\n\ Try %s: -h for more information.\n", "usort"); exit(status); } } /* ======================================================================================================================================================================================================*/ static void parse_options (struct option long_options[], struct flags *opt_ptr, int argc, char *argv[], char *out_file) { int c; while ((c = getopt_long(argc, argv, OP_LIST, long_options, NULL)) != -1) { switch(c) { case 'n': opt_ptr->nflag = true; break; case 'r': opt_ptr->rflag = true; break; case 'h': usage(EXIT_SUCCESS); break; case 'o': opt_ptr->oflag = true; strcpy(out_file, optarg); break; /* case '?' */ default: usage(EXIT_FAILURE); break; } } } /* ====================================================================================================================================================================================================== */ static int read_file(char *lines[], char *filename) { fp = fopen(filename, "r"); if (!fp) { perror("fopen"); usage(EXIT_FAILURE); } char buffer[MAX]; size_t i = 0;
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling char buffer[MAX]; size_t i = 0; while (fgets(buffer, sizeof(buffer), fp)) { buffer[strcspn(buffer, "\n")] = 0; strcpy(lines[i], buffer); i++; } fclose(fp); return i; } /* ====================================================================================================================================================================================================== */ static void write_to_stdout(char *lines[], int num_lines, struct flags *opt_ptr) { int i; if (opt_ptr->rflag) { for (i = num_lines - 1; i >= 0; i--) { fprintf(stdout, "%s\n", lines[i]); } } else { for (i = 0; i < num_lines; i++) { fprintf(stdout, "%s\n", lines[i]); } } } /* ====================================================================================================================================================================================================== */ static void write_to_FILE (char *lines[], int num_lines, char *out_file, struct flags *opt_ptr) { int i; fp = fopen(out_file, "w"); if (!fp) { perror("fopen"); exit(EXIT_FAILURE); } if (opt_ptr->rflag) { for (i = num_lines - 1; i >= 0; i--) { fprintf(fp, "%s\n", lines[i]); } } else { for (i = 0; i < num_lines; i++) { fprintf(fp, "%s\n", lines[i]); } fclose(fp); } } /* ============================================================================================================================================================== */ /* Compares s1 and s2 lexicographically */ static int scmp(const void *s1, const void *s2) { const char *v1, *v2; v1 = *(char **)s1; v2 = *(char **)s2; //the comparison method gets passed 'pointers to pointers' (char**) by qsort... return strcmp(v1, v2); }
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling return strcmp(v1, v2); } /* =============================================================================================================================================================== */ /* Compares s1 and s2 numerically */ static int numcmp(const void *s1, const void *s2) { long *v1 = *(long * const *)s1; long *v2 = *(long * const *)s2; return (*v1 > *v2) - (*v1 < *v2); } /* =============================================================================================================================================================== */ /* A wrapper function for calloc, returns a void ptr on success, exits on failure */ static void *xcalloc(size_t size) { if (size == 0) { exit(EXIT_FAILURE); } void *ptr = calloc(1, size); if (!ptr) { perror("calloc "); exit(EXIT_FAILURE); } return ptr; } /* ================================================================================================================================================================ */ static void free_allocs(char *lines[], char *out_file, char *in_file) { size_t i; for (i = 0; i < MAXLINES; i++) { free(lines[i]); } free(in_file); free(out_file); } How do I go about dealing with the magic numbers? What options are there to deduce the file size and the number of lines beforehand? Is allocating storage for 50000 lines beforehand a waste? Edit: The deletion of the post was due to a bug @Martin found, after which I deemed the post off-topic for the site and self-deleted it. The question may remain closed until it's fixed.
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling Answer: Compiler warnings GCC reports some dodgy type conversions: gcc-12 -std=c17 -fPIC -gdwarf-4 -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes -fanalyzer 281850.c -o 281850 281850.c: In function ‘main’: 281850.c:69:17: warning: conversion to ‘size_t’ {aka ‘long unsigned int’} from ‘int’ may change the sign of the result [-Wsign-conversion] 69 | num_lines = read_file(lines, in_file); | ^~~~~~~~~ 281850.c:73:43: warning: conversion from ‘size_t’ {aka ‘long unsigned int’} to ‘int’ may change value [-Wconversion] 73 | opt_ptr->oflag ? write_to_FILE(lines, num_lines, out_file, opt_ptr) : write_to_stdout(lines, num_lines, opt_ptr); | ^~~~~~~~~ 281850.c:73:98: warning: conversion from ‘size_t’ {aka ‘long unsigned int’} to ‘int’ may change value [-Wconversion] 73 | opt_ptr->oflag ? write_to_FILE(lines, num_lines, out_file, opt_ptr) : write_to_stdout(lines, num_lines, opt_ptr); | ^~~~~~~~~ 281850.c: In function ‘usage’: 281850.c:94:18: warning: conversion from ‘size_t’ {aka ‘long unsigned int’} to ‘int’ may change value [-Wconversion] 94 | exit(status); | ^~~~~~ 281850.c:101:14: warning: conversion from ‘size_t’ {aka ‘long unsigned int’} to ‘int’ may change value [-Wconversion] 101 | exit(status); | ^~~~~~ 281850.c: In function ‘read_file’: 281850.c:158:12: warning: conversion from ‘size_t’ {aka ‘long unsigned int’} to ‘int’ may change value [-Wconversion] 158 | return i; | ^ These are all avoidable. Forward declarations It shouldn't be necessary to declare all our functions twice. If we write them in bottom-up order, we can make all the declarations be definitions.
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling usage() should be two functions Since we only ever call usage() with literal argument to switch between two behaviours, it looks like we ought to have two functions. And it doesn't make sense that the help message is split across two different streams - I think it should all go to stdout. static void help(void) { puts("\nUSAGE\n\tusort <options> <filename>\n\n" "NAME\n\tusort - sort lines of text.\n\n" "DESCRIPTION\n\tWrite sorted concatenation of FILE to standard output.\n" " In the absence of options, lexicographical order is taken as default.\n\n" "ORDERING OPTIONS:\n\n" " -n, --numeric sorts by numeric order.\n\n" " -r, --reverse sorts in reverse order.\n\n" " -h, --help displays this message and exits.\n\n" " -o, --output=FILE writes result to FILE instead of standard output.\n\n"); exit(EXIT_SUCCESS); } static void usage_err(void) { fputs("The syntax of the command is incorrect.\n" "Try usort -h for more information.\n", stderr); exit(EXIT_FAILURE); } I'm not a big fan of the extra blank lines in the help output, but I left them as is. Writing should be one function Conversely, the two functions write_to_stdout() and write_to_FILE() should be a single function that takes a FILE* argument to determine where to write to: static void write_to(FILE *f, char *lines[], size_t num_lines, const struct flags *opt_ptr) { if (opt_ptr->rflag) { for (size_t i = num_lines; i > 0; i--) { fprintf(f, "%s\n", lines[i-1]); } } else { for (size_t i = 0; i < num_lines; i++) { fprintf(f, "%s\n", lines[i]); } } } In any case, when writing to a file, we should call fclose() regardless of whether -r flag was given.
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling Open the output file early Don't wait until we've done all the processing before discovering that the output file isn't writeable - do this first, before reading input. It also allows us to discard the name of the output file straight away, and just keep its FILE pointer. Similarly, if we represent input by its file-pointer, we can read from standard input as easily as from a file. Check for errors when performing I/O When fgets() returns a null pointer, we should check whether it's because we have reached the end of input or we have an error. When we write to and close our output stream, we need to check whether these operations were successful. Numeric sorting is broken You can't sort numerically just by reinterpreting character sequences as if they were integers: ./281850 -n <(seq 99999995 100000005) 100000000 100000001 100000002 100000003 100000004 100000005 99999995 99999996 99999997 99999998 99999999 We need to convert to integer, perhaps like this: static int numcmp(const void *s1, const void *s2) { const char *v1 = s1; const char *v2 = s2; long long a1 = atoll(v1); long long a2 = atoll(v2); return (a1 > a2) - (a2 < a1); } This can be improved further by using strtoll() (which "saturates" out of range values). Instead of using long long, we could use the platform's widest integer type and the corresponding strtoimax() (from <inttypes.h>). We could also consider falling back to the string comparison if lines are numerically equal. Reduce copying strcpy(out_file, optarg); If we made out_file a plain pointer, we could just assign it from optarg, which points to the argv array we never modify. while (fgets(buffer, sizeof(buffer), fp)) { buffer[strcspn(buffer, "\n")] = 0; strcpy(lines[i], buffer); No reason to bounce through buffer - just input directly into the lines array.
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling No reason to bounce through buffer - just input directly into the lines array. Get rid of the arbitrary limits We create storage of MAX * MAXLINES characters, which in many cases is far more than we need (e.g. Valgrind reports total heap usage: 50,002 allocs, 50,002 frees, 50,004,568 bytes allocated when I sort an empty input!), and for some cases is not nearly enough (and when it's not enough, we overrun the storage - that's very bad). Instead, we could read all the input into storage, then count the newlines and allocate the right amount of storage to hold them (or reallocate as we encounter newlines). Modified code With the above fixes applied (but still won't handle files containing \0, though one could argue that those aren't text files) #include <errno.h> #include <inttypes.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <getopt.h> #include <unistd.h> struct flags { bool nflag; /* Numeric flag */ bool rflag; /* Reverse flag */ FILE *output; /* Output to FILE */ }; static void help(void) { puts("\nUSAGE\n\tusort <options> <filename>\n\n" "NAME\n\tusort - sort lines of text.\n\n" "DESCRIPTION\n\tWrite sorted concatenation of FILE to standard output.\n" " In the absence of options, lexicographical order is taken as default.\n\n" "ORDERING OPTIONS:\n\n" " -n, --numeric sort in numeric order.\n\n" " -r, --reverse sort in reverse order.\n\n" " -h, --help display this message and exits.\n\n" " -o, --output=FILE write result to FILE instead of standard output.\n\n"); exit(EXIT_SUCCESS); } static void usage_err(void) { fputs("The syntax of the command is incorrect.\n" "Try usort -h for more information.\n", stderr); exit(EXIT_FAILURE); }
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling static void parse_options(const struct option long_options[], struct flags *opt_ptr, int argc, char *argv[]) { int c; while ((c = getopt_long(argc, argv, "nrho:", long_options, NULL)) != -1) { switch (c) { case 'n': opt_ptr->nflag = true; break; case 'r': opt_ptr->rflag = true; break; case 'h': help(); break; case 'o': /* We'll seek to beginning once we've read input, in case it's the same file. */ opt_ptr->output = fopen(optarg, "a"); if (!opt_ptr->output) { perror(optarg); exit(EXIT_FAILURE); } break; /* case '?' */ default: usage_err(); break; } } } /* Return an array of lines in the file, or a null pointer on failure. * Caller must free the zeroth element and the lines array. */ static char *read_file(FILE *fp) { static const size_t page_size = 4096; char *content = 0; size_t len = 0; for (size_t rcount = 1; rcount; len += rcount) { char *new = realloc(content, len + page_size); if (!new) { free(content); errno = ENOMEM; return 0; } content = new; rcount = fread(content + len, 1, page_size - 1, fp); if (ferror(fp)) { free(content); errno = ENOMEM; return 0; } } content[len] = '\0'; return content; } size_t split_lines(char *s, char ***lines) { static const size_t chunk_size = 1000; size_t capacity = 0; size_t line_count = 0;
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling while (s && *s) { if (line_count >= capacity) { char **new = realloc(*lines, sizeof **lines * (capacity += chunk_size)); if (!new) { free(*lines); *lines = NULL; errno = ENOMEM; return 0; } *lines = new; } (*lines)[line_count++] = s; s = strchr(s, '\n'); if (s) { *s++ = '\0'; } } return line_count; } static bool write_to(char *lines[], size_t num_lines, const struct flags *opt_ptr) { FILE *const f = opt_ptr->output; bool reverse = opt_ptr->rflag; if (f != stdout && ftruncate(fileno(f), 0)) { perror("seek"); return false; } for (size_t i = 0; i < num_lines; i++) { size_t n = reverse ? num_lines - 1 - i : i; if (fprintf(f, "%s\n", lines[n]) < 0) { perror("write"); return false; } } return f == stdout || !fclose(f); } /* Compare s1 and s2 lexicographically */ static int scmp(const void *s1, const void *s2) { const char *const *v1 = s1; const char *const *v2 = s2; return strcmp(*v1, *v2); } /* Compare s1 and s2 numerically */ static int numcmp(const void *s1, const void *s2) { const char *const *v1 = s1; const char *const *v2 = s2; char *p1; char *p2; intmax_t a1 = strtoimax(*v1, &p1, 10); intmax_t a2 = strtoimax(*v2, &p2, 10); return a1 > a2 ? 1 : a1 < a2 ? -1 : scmp(&p1, &p2); /* sort by rest of line as a string */ } int main(int argc, char *argv[]) { static const struct option long_options[] = { {"numeric", no_argument, NULL, 'n'}, {"reverse", no_argument, NULL, 'r'}, {"output", required_argument, NULL, 'o'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0} }; FILE *in_file = stdin;
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
c, error-handling FILE *in_file = stdin; struct flags options = {false, false, stdout}; parse_options(long_options, &options, argc, argv); if ((optind + 1) == argc) { in_file = fopen(argv[optind], "r"); if (!in_file) { perror(argv[optind]); return EXIT_FAILURE; } } else if (optind > argc) { usage_err(); } char *content = read_file(in_file); char **lines = NULL; size_t num_lines = split_lines(content, &lines); if (!lines) { free(content); perror("read"); return EXIT_FAILURE; } qsort(lines, num_lines, sizeof *lines, options.nflag ? numcmp : scmp); if (!write_to(lines, num_lines, &options)) { free(content); free(lines); return EXIT_FAILURE; } free(content); free(lines); return EXIT_SUCCESS; }
{ "domain": "codereview.stackexchange", "id": 44214, "lm_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, error-handling", "url": null }
beginner, c Title: Print vertical histogram of inputted words… Question: From The C Programming Language, by Kernighan and Ritchie: Exercise 1-13. Write a program to print a histogram of the lengths of words in its input. It is easy to draw the histogram with the bars horizontal; a vertical orientation is more challenging. (Kernighan, 24) This is my first time learning C seriously. I've started the few first pages over a thousand times, but now I've decided to get down to it and do the book from A to Z. My code for Exercise 1-13 is as follows: #include<stdio.h> #define MAXWLENGTH 20 #define MAXWNO 20 #define OUT 0 #define IN 1 #define NONBLANK '-' int main(void){ int wrdlength[MAXWNO], wrdid, longestwrd, wrdno; int current, last; // current and before-current characters being processed int i, ii; // for loop counters int state; // determines whether inside or outside of current word for(i = 0; i < MAXWNO; i++) wrdlength[i] = 0; // (tested and works) last = NONBLANK; state = OUT; wrdid = 0; // range 0–19 i = 0; longestwrd = 0; // collect data from input // tested and works while(((current = getchar()) != EOF) && (wrdid < MAXWNO)){ if(current == ' ' || current == '\n' || current == '\t'){ if(last == ' ' || last == '\n' || last == '\t'){ ; // STATE is already OUT } else{ state = OUT; wrdid++; // jump to next word } } else{ // if nonblank character… if(state == OUT) state = IN; wrdlength[wrdid] = wrdlength[wrdid] + 1; // add letter to current word } last = current; } wrdno = wrdid; // get # of non-void words // find greatest array element (longest word) // tested and works for(i = 0, wrdid = 0; i < MAXWNO; i++) if(longestwrd < wrdlength[wrdid]) longestwrd = wrdlength[wrdid];
{ "domain": "codereview.stackexchange", "id": 44215, "lm_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", "url": null }
beginner, c printf("\n\n\n\n--- Word Histogram ---\n\n"); for(i = longestwrd; i > 0; i--){ for(ii = 0; ii < wrdno; ii++) if(wrdlength[ii] >= i) printf("*"); // Unicode 25A0 else // -> if(wrdlength[ii] < i) putchar(' '); // put space if(i != 1) // -> if(i > 1) printf("\n"); } /* // this for loop simply prints out ALL the word lengths (even when zero) for(i = 0; i < MAXWNO; i++) printf("%d\n", wrdlength[i]); */ } The comments are my personal remarks, and aren't aimed at flagging anything to seize a reviewer's attention. They were simply used to help me in the process of making the code. My specific expectations from anyone who'd have the kindness to review my code: I'm looking for efficiency, readability, shortness (I know short is not necessarily efficient, and that's why I'm putting it after efficiency), and simply handling the problem in a way that is considered natural and intelligent to an experienced programmer's eyes. I feel like this code could be shorter and more concise, but I'm stuck as to how I should do that. Again, I'm very new to C, and have never programed seriously in another language before. Here's a demo output for my program: INPUT: Hello, world! How are you, today? Since I have just come to birth, I know nothing. And since I can learn nothing, I will know nothing more. OUTPUT: --- Word Histogram --- ** * * * ** ** * * * ** *** *** * ** * ******* *** * **** * ******* ***** **** * ******************** Please take into account that anything that wasn't mentioned in the book up to page 24, I most likely do not know. Also, I'm aware the book I'm using is somewhat dated, so don't hesitate in suggesting techniques that might apply to more recent standards of C. I'm compiling my code using the GCC, which was installed on Debian GNU/Linux 11 (bullseye) x86_64 via the official Debian repos. References:
{ "domain": "codereview.stackexchange", "id": 44215, "lm_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", "url": null }
beginner, c Kernighan, B.W. and Ritchie, D.M. (1988). The C programming language / ANSI C Version. Englewood Cliffs, N.J.: Prentice Hall. Answer: Initialize at declaration Rather than later zero the array, do so at declaration time. //int wrdlength[MAXWNO]; ... //for(i = 0; i < MAXWNO; i++) // wrdlength[i] = 0; // (tested and works) int wrdlength[MAXWNO] = { 0 }; Use isspace() to test for white-space Instead of testing of some of the possible white-spaces, test for all of them. See <ctype.h>. // if(current == ' ' || current == '\n' || current == '\t'){ if (isspace(current)) { Style: Use {} Even for one-liners, IMO, use {}. //if(state == OUT) // state = IN; if(state == OUT) { state = IN; } ++ // wrdlength[wrdid] = wrdlength[wrdid] + 1; wrdlength[wrdid]++; // or ++wrdlength[wrdid]; Bug Loop body never uses i. Certainly incorrect. for(i = 0, wrdid = 0; i < MAXWNO; i++) if(longestwrd < wrdlength[wrdid]) longestwrd = wrdlength[wrdid]; Why is "*" commented as Unicode 25A0? // ???? printf("*"); // Unicode 25A0 Test limit first In this code, it makes no difference, yet in general, don't read from stdin unless code intends to do something with the input. // while(((current = getchar()) != EOF) && (wrdid < MAXWNO)){ while((wrdid < MAXWNO) && ((current = getchar()) != EOF)){ Correct word ID count?? wrdid++; increments after a "blank" is found. If the entire input was "test", wrdid would remain at 0 whereas 1 is expected. Instead I recommend incrementing wrdid when the first letter of a word is found.
{ "domain": "codereview.stackexchange", "id": 44215, "lm_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", "url": null }
python Title: Extract section from URL path Question: Any comments / improvements welcome on this simple function. tests.py @pytest.mark.parametrize([ # path '/c/target-uri', '/c/uk/indiana/target-uri', '/c/uk/indiana/target-uri/persons', '/c/uk/florida/target-uri/persons', ]) def test_extract_uri(self, path): assert extract_uri(path) == 'target-uri' main.py from states import state_names def extract_uri(path: str): exclude_path_snippets = ['persons'] def filter_fn(element: str): return all([ element.lower() not in state_names, element.lower() not in exclude_path_snippets, len(element) > 2, # exclude 'c' or 'uk' ]) path_snippets: List[str] = path.split('/') filtered = list(filter(filter_fn, path_snippets)) if len(filtered) != 1: raise Exception(f"Failed to extract uri from {path}") return filtered[0] Answer: filter_fn should probably be moved to a global because it does not need closure. Combine state_names and exclude_path_snippets to one set via |, and then reduce to a single not in. all is not called-for; use a single boolean expression. Once you have only one set comparison, you will only need one and. Don't raise a bare Exception. Raise a ValueError, or an application-specific exception. Consider a tuple-unpack, potentially with a rethrow; and don't cast to a list: try: filtered, = filter(filter_fn, path_snippets) except ValueError as e: raise ValueError(f'Failed to extract URI from {path}') from e return filtered filter_fn deserves a better name like is_snippet_valid.
{ "domain": "codereview.stackexchange", "id": 44216, "lm_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", "url": null }
c++, multithreading Title: Wait for all threads in a pool to complete their work Question: I am trying to replace in an adapted code from internet, a thread pooling class, named ThreadPool: void ThreadPool::Wait() { // we're done waiting once all threads are waiting while (m_threads_waiting != m_threads.size()) { ; } } where m_threads_waiting is defined as: std::atomic<size_t> m_threads_waiting{ 0 }; and m_threads is defined as: std::vector<std::thread> m_threads; The replacing code is: void ThreadPool::Wait() { std::unique_lock<std::mutex> lock{ m_wait_mutex }; m_threads_done.wait(lock, [&]() { return m_threads_waiting != m_threads.size(); }); lock.unlock(); } where m_wait_mutex is defined as: std::mutex m_wait_mutex; and m_threads_done is defined as: std::condition_variable m_threads_done; The code is self-explanatory: the Wait() method should "wait" until all threads are done. And this method is called on main thread. Please tell me the the replaced code is correct and it is better than the old one. I put here the header of the source code: class ThreadPool { public: ThreadPool(); ThreadPool(const ThreadPool& rhs) = delete; ThreadPool& operator=(const ThreadPool& rhs) = delete; ThreadPool(ThreadPool&& rhs) = default; ThreadPool& operator=(ThreadPool&& rhs) = default; ~ThreadPool(); template<typename Func, typename... Args> auto Add(Func&& func, Args&&... args) -> std::future<typename std::result_of<Func(Args...)>::type>; size_t GetWaitingJobs() const; void Clear(); void Pause(const bool& state); // blocks calling thread until job queue is empty void Wait(); bool IsPaused() const { return m_paused; } bool IsTerminate() const { return m_terminate; } bool IsJobsEmpty() const { return m_jobs.empty(); }
{ "domain": "codereview.stackexchange", "id": 44217, "lm_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", "url": null }
c++, multithreading private: using Job = std::function<void()>; // variables std::queue<Job> m_jobs; std::mutex m_wait_mutex; mutable std::mutex m_jobs_mutex; std::condition_variable m_threads_done; std::condition_variable m_jobs_available; // notification variable for waiting threads std::vector<std::thread> m_threads; std::atomic<size_t> m_threads_waiting{ 0 }; std::atomic<bool> m_terminate{ false }; std::atomic<bool> m_paused{ false }; // methods static void ThreadTask(ThreadPool* pPool); // function each thread performs }; and the implementation: ThreadPool::ThreadPool() { const size_t threadCount = std::thread::hardware_concurrency(); m_threads.reserve(threadCount); std::generate_n( std::back_inserter(m_threads), threadCount, [this]() { return std::thread{ ThreadPool::ThreadTask, this }; }); } ThreadPool::~ThreadPool() { Clear(); m_terminate.store(true); m_jobs_available.notify_all(); for (auto& t : m_threads) { if (t.joinable()) t.join(); } } size_t ThreadPool::GetWaitingJobs() const { std::lock_guard<std::mutex> lock{ m_jobs_mutex }; return m_jobs.size(); } void ThreadPool::Clear() { std::lock_guard<std::mutex> lock{ m_jobs_mutex }; while (! m_jobs.empty()) m_jobs.pop(); } void ThreadPool::Pause(const bool& state) { m_paused = state;
{ "domain": "codereview.stackexchange", "id": 44217, "lm_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", "url": null }
c++, multithreading void ThreadPool::Pause(const bool& state) { m_paused = state; if (! m_paused) m_jobs_available.notify_all(); } #include <iostream> void ThreadPool::Wait() { // we're done waiting once all threads are waiting /*////////////////////////////////////////////////////////////// while (m_threads_waiting != m_threads.size()); /*////////////////////////////////////////////////////////////// std::cout << "\nbefore lock\n"; std::unique_lock<std::mutex> lock{ m_wait_mutex }; std::cout << "\nafter lock\n"; m_threads_done.wait(lock, [&, this]() { return m_threads_waiting <= m_threads.size(); }); lock.unlock(); ///*////////////////////////////////////////////////////////////// std::cout << "\nafter un-lock\n"; } // function each thread performs void ThreadPool::ThreadTask(ThreadPool* pPool) { // loop until we break (to keep thread alive) while (true) { if (pPool->m_terminate) break; std::unique_lock<std::mutex> lock{ pPool->m_jobs_mutex }; // if there are no more jobs, or we're paused, go into waiting mode if (pPool->m_jobs.empty() || pPool->m_paused) { ++pPool->m_threads_waiting; pPool->m_jobs_available.wait(lock, [&]() { return pPool->IsTerminate() || ! (pPool->IsJobsEmpty() || pPool->IsPaused()); }); --pPool->m_threads_waiting; } if (pPool->m_terminate) break; auto job = std::move(pPool->m_jobs.front()); pPool->m_jobs.pop(); lock.unlock(); job(); } } The point is ThreadPool::Wait() method.
{ "domain": "codereview.stackexchange", "id": 44217, "lm_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", "url": null }
c++, multithreading The point is ThreadPool::Wait() method. Answer: Missing definitions The header needs quite a few standard library types: #include <atomic> #include <condition_variable> #include <functional> #include <future> #include <mutex> #include <queue> #include <thread> #include <type_traits> #include <vector> using std::size_t; I wouldn't recommend polluting the global namespace like that in the header, though - that's quite rude to the client code. Instead, write std::size_t in full. Using std::jthread instead of std::thread would let us remove the join() loop from the destructor. We can simplify emptying the queue. Instead of this loop: while (! m_jobs.empty()) m_jobs.pop(); we can simply assign an empty queue: m_jobs = {}; ThreadPool::Wait() shouldn't be printing to the output stream - that will likely corrupt the program output. If we need some diagnostics, use std::clog instead. But really, just remove that because it will annoy users. The lambda passed to wait() doesn't need a default capture ([&, this]). Reduce it to just [this] so that it's clearer to readers. ThreadPool::ThreadTask() is given a pointer; I think that would be clearer if it were a reference (construct the thread with std::ref(*this) as argument). while (true) can be while (!pPool->m_terminate). Consider using a std::stop_token rather than separately testing m_terminate. All our atomic accesses use the default, strongest memory order, std::memory_order_seq_cst. Consider whether this is always appropriate; I believe we can use weaker ordering in most places.
{ "domain": "codereview.stackexchange", "id": 44217, "lm_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", "url": null }
c, regex Title: Doing a re.findall with pcre library Question: I am trying to get an array of all regex matches. For example, something like this: PATTERN: (\d+)[a-z]+ STRING: 123asd RESULT: ["123asd", "123"] ^ ^ full capture group 1 Additionally, if there are multiple matches, it should continue matching, for example: 123asd 123asd [ ["123asd", "123"], ["123asd", "123"] ] ^ ^ match 1 match 2 Here is what I came up with, where I try and create functions to do each of the items (though I haven't yet added a fetch_all() function): // pcretest.c #include <stdio.h> #include <string.h> #include <errno.h> #define PCRE2_CODE_UNIT_WIDTH 8 #include <pcre2.h> pcre2_code* pcre_compile_pattern(PCRE2_SPTR pattern, uint32_t options) { PCRE2_SIZE error_offset; int error_number; pcre2_code *re_compiled = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, options, &error_number, &error_offset, NULL); if (re_compiled == NULL) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(error_number, buffer, sizeof(buffer)); printf("Error: Compiling of pattern '%s' failed at offset %d: %s\n", pattern, (int)error_offset, buffer); } return re_compiled; } struct match_obj { int size; char** matches; }; // will return the offset of the full-match (or an error-code), and populate the struct match_obj int get_next_match(pcre2_code *re_compiled, PCRE2_SPTR8 string, struct match_obj *matches, int max_matches) { #define MAX_MATCHES_EXCEEDED (-99) pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(re_compiled, NULL); int return_code = pcre2_match(re_compiled, string, strlen((char*)string), 0, 0, match_data, NULL);
{ "domain": "codereview.stackexchange", "id": 44218, "lm_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, regex", "url": null }
c, regex // Error codes: https://code.woboq.org/qt5/qtbase/src/3rdparty/pcre2/src/pcre2.h.html#313 if (return_code < 0) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(return_code, buffer, sizeof(buffer)); if (return_code != PCRE2_ERROR_NOMATCH) printf("Error trying to match against '%s': %s\n", string, buffer); return return_code; } // Make sure no buffer overflow if (return_code > max_matches) { printf("Input buffer is too small.\n"); return MAX_MATCHES_EXCEEDED; } PCRE2_SIZE *offset_vector = pcre2_get_ovector_pointer(match_data); matches->size = return_code; for (int i=0; i < return_code; i++) { PCRE2_SPTR substring_start = string + offset_vector[2*i]; size_t substring_length = offset_vector[2*i+1] - offset_vector[2*i]; char* string = malloc(sizeof *string * substring_length); strncpy(string, (const char*) substring_start, substring_length); matches->matches[i] = string; } // (start, end) of the full match is the zero'th entry int end_position = offset_vector[1]; return end_position; } int main(void) { PCRE2_SPTR8 pattern = (const unsigned char*) "he[al](lo)"; PCRE2_SPTR8 string = (const unsigned char*) "add ello a healo b hello c"; // 1. Compile the pattern /* uint32_t re_options=0; */ pcre2_code *re_compiled = pcre_compile_pattern(pattern, 0); // 2. grab matches until expired #define MAX_MATCH_COMPONENTS 10 #define MAX_TOTAL_MATCHES 10 struct match_obj all_matches[MAX_TOTAL_MATCHES];
{ "domain": "codereview.stackexchange", "id": 44218, "lm_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, regex", "url": null }
c, regex int advance_by, total_matches=0; for (; total_matches < MAX_TOTAL_MATCHES; total_matches++) { struct match_obj *match_ptr = &all_matches[total_matches]; match_ptr->matches = malloc(sizeof (char*) * MAX_MATCH_COMPONENTS); advance_by = get_next_match(re_compiled, string, match_ptr, MAX_MATCH_COMPONENTS); if (advance_by < 0) break; string += advance_by; } // 3. Display them (or do whatever we want with them) for (int match_num=0; match_num < total_matches; match_num++) { struct match_obj match = all_matches[match_num]; for (int i=0; i<match.size; i++) printf("Match %d.%d: %s\n", match_num, i, match.matches[i]); } // 4. Free the allocations - array of string-pointers here, created-strings in get_next_match() for (int match_num=0; match_num < total_matches; match_num++) { for (int i=0; i < all_matches[match_num].size; i++) free(all_matches[match_num].matches[i]); // free the string free(all_matches[match_num].matches); // and the array of string pointers } } If helpful, here is the code on OnlineGDB. Note, however, I wasn't able to compile with extra compiler flags to work with #include <pcre2.h>. Here are a few specific questions about this: Figuring out allocations are hard! Does the above look like a sensible approach? I couldn't figure out which function should do what. My first thought was to do everything 'on the stack' in main but then the string-pointer array started acting up and so I moved to malloc's in main. Is there something like a good rule of thumb for where to do mallocs or how to split them up?
{ "domain": "codereview.stackexchange", "id": 44218, "lm_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, regex", "url": null }
c, regex Does the data structure look up for returning the matches? I thought an array-of-char* 's would work, though I ended up creating a struct as there were some other things I needed to keep track of (how far it advances, what the matches are, how many matches there are -- though this last item is I think always the same if it's using the same pattern). Answer: Looks generally good, and compiles almost cleanly. The "almost" is because we return int from get_next_match, but try to shoehorn negative error numbers and positive size_t into it. I'd at least change to return long long; it's probably better to return the length separately from the status. We fail to free the pcre2_code and pcre2_match_data objects that we get from the PCRE library. We fail to check the return value where we use malloc(). Not doing so risks Undefined Behaviour when we dereference it. Easily fixed: char* string = malloc(substring_length); /* sizeof (char) is necessarily 1 */ if (!string) { return PCRE2_ERROR_NOMEMORY; } match_ptr->matches = malloc(sizeof *match_ptr->matches * MAX_MATCH_COMPONENTS); if (!match_ptr->matches) { fprintf(stderr, strerror(ENOMEM)); return EXIT_FAILURE; } (We'll need to include <stdlib.h> to get a definition of EXIT_FAILURE) Really, we should clean up properly even if we fail. This will make it easier to re-use this code in a program that can't just exit in this case. As you say, memory management is hard in C! It's easiest if we define functions to initialise and release our structures: The other problem we have with memory handling is here: strncpy(string, (const char*) substring_start, substring_length);
{ "domain": "codereview.stackexchange", "id": 44218, "lm_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, regex", "url": null }
c, regex strncpy(string, (const char*) substring_start, substring_length); Do you see what's missing there? If not, then run Valgrind again, and look what happens when we print it. We've copied the strings characters, but haven't provided a terminating \0, leading to more UB. char* string = malloc(substring_length + 1); if (!string) { return PCRE2_ERROR_NOMEMORY; } memcpy(string, substring_start, substring_length); string[substring_length + 1] = '\0'; I don't like this macro definition buried halfway through a function: #define MAX_MATCHES_EXCEEDED (-99) Instead of a macro, define an integer at global scope: static const int MAX_MATCHES_EXCEEDED = -99; It's probably better to just allocate the size of results we need, in get_next_match() where the number is known, instead of having a fixed limit here. The URL in comment is dead (404). It's confusing to have a local variable string that shadows the function argument string in get_next_match. Modified code This compiles without warnings using gcc -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes, and runs clean under Valgrind. #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define PCRE2_CODE_UNIT_WIDTH 8 #include <pcre2.h> struct match_obj { int count; char** matches; }; static void match_obj_init(struct match_obj *p) { p->count = 0; p->matches = NULL; } static void match_obj_free(struct match_obj *p) { if (p) { for (int i = 0; i < p->count; ++i) { free(p->matches[i]); } free(p->matches); } } pcre2_code* pcre_compile_pattern(PCRE2_SPTR pattern, uint32_t options) { PCRE2_SIZE error_offset; int error_number;
{ "domain": "codereview.stackexchange", "id": 44218, "lm_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, regex", "url": null }
c, regex pcre2_code *re_compiled = pcre2_compile(pattern, PCRE2_ZERO_TERMINATED, options, &error_number, &error_offset, NULL); if (re_compiled == NULL) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(error_number, buffer, sizeof buffer); fprintf(stderr, "Error: Compiling of pattern '%s' failed at offset %zd: %s\n", pattern, error_offset, buffer); } return re_compiled; } // will return the offset of the full-match (or an error-code), and populate the struct match_obj int get_next_match(pcre2_code *re_compiled, PCRE2_SPTR8 string, struct match_obj *matches, size_t *advance) { pcre2_match_data *match_data = pcre2_match_data_create_from_pattern(re_compiled, NULL); int return_code = pcre2_match(re_compiled, string, strlen((char*)string), 0, 0, match_data, NULL); // Error codes: https://codebrowser.dev/qt5/include/pcre2.h.html#313 if (return_code == PCRE2_ERROR_NOMATCH) { /* normal */ free(match_data); return 0; } if (return_code < 0) { free(match_data); return return_code; } PCRE2_SIZE *offset_vector = pcre2_get_ovector_pointer(match_data); matches->matches = malloc(sizeof *matches->matches * (size_t)return_code); matches->count = return_code; if (!matches->matches) { free(match_data); return PCRE2_ERROR_NOMEMORY; } for (int i = 0; i < matches->count; ++i) { matches->matches[i] = NULL; } for (int i = 0; i < return_code; ++i) { PCRE2_SPTR substring_start = string + offset_vector[2*i]; size_t substring_length = offset_vector[2*i+1] - offset_vector[2*i]; char *const s = malloc(substring_length + 1); if (!s) { free(match_data); return PCRE2_ERROR_NOMEMORY; } memcpy(s, substring_start, substring_length); s[substring_length] = '\0'; matches->matches[i] = s; }
{ "domain": "codereview.stackexchange", "id": 44218, "lm_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, regex", "url": null }
c, regex // (start, end) of the full match is the zero'th entry *advance = offset_vector[1]; pcre2_match_data_free(match_data); return 0; } #define MAX_TOTAL_MATCHES 10 int main(void) { PCRE2_SPTR8 pattern = (const unsigned char*) "he[al](lo)"; PCRE2_SPTR8 string = (const unsigned char*) "add ello a healo b hello c"; // 1. Compile the pattern /* uint32_t re_options=0; */ pcre2_code *re_compiled = pcre_compile_pattern(pattern, 0); if (!re_compiled) { return EXIT_FAILURE; } // 2. grab matches until expired struct match_obj all_matches[MAX_TOTAL_MATCHES]; for (int i = 0; i < MAX_TOTAL_MATCHES; ++i) { match_obj_init(all_matches + i); } int total_matches=0; for (; total_matches < MAX_TOTAL_MATCHES; ++total_matches) { struct match_obj *match_ptr = &all_matches[total_matches]; size_t advance_by; int errcode = get_next_match(re_compiled, string, match_ptr, &advance_by); if (errcode) { PCRE2_UCHAR buffer[256]; pcre2_get_error_message(errcode, buffer, sizeof buffer); fprintf(stderr, "Error: Search failed: %s\n", buffer); return EXIT_FAILURE; } string += advance_by; } pcre2_code_free(re_compiled); // 3. Display them (or do whatever we want with them) for (int match_num = 0; match_num < total_matches; ++match_num) { struct match_obj match = all_matches[match_num]; for (int i = 0; i < match.count; ++i) { printf("Match %d.%d: %s\n", match_num, i, match.matches[i]); } } // 4. Free the allocations - array of string-pointers here, created-strings in get_next_match() for (int match_num = 0; match_num < MAX_TOTAL_MATCHES; ++match_num) { match_obj_free(all_matches + match_num); } }
{ "domain": "codereview.stackexchange", "id": 44218, "lm_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, regex", "url": null }
php, html, laravel, laravel-blade Title: Setting default of in Laravel with PHP Match Question: I have a filter component that lets a user filter for events on a website. The user needs to see which category is currently selected in the filter. For this there is a URL with parameters. e.g. /events?category=1 The code will match the category to the <option> in the <select>. The code: <?php $selected = 'selected'; if (Request::is('courses')) { $category = '0'; if (request()->get('category')) { [$selected, $category] = match (request()->get('category')) { '0' => [$selected, '0'], '1' => [$selected, '1'], '2' => [$selected, '2'], '3' => [$selected, '3'], '4' => [$selected, '4'], '5' => [$selected, '5'], '6' => [$selected, '6'], '7' => [$selected, '7'], '8' => [$selected, '8'], }; } } if (Request::is('events')) { $category = '1'; if (request()->get('category')) { [$selected, $category] = match (request()->get('category')) { '0' => [$selected, '0'], '1' => [$selected, '1'], '2' => [$selected, '2'], '3' => [$selected, '3'], '4' => [$selected, '4'], '5' => [$selected, '5'], '6' => [$selected, '6'], '7' => [$selected, '7'], '8' => [$selected, '8'], }; } } ?>
{ "domain": "codereview.stackexchange", "id": 44219, "lm_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, html, laravel, laravel-blade", "url": null }
php, html, laravel, laravel-blade ?> <form class="container"> <div class="bg-white p-6 rounded-lg"> <div class="grid grid-cols-1 md:grid-cols-2 gap-6"> <div> <label class="mb-3 inline-block">Category</label> <select aria-label="Category" name="category" class="w-full bg-gray-200 p-3 rounded-lg"> <option value="0" @if ($category === '0') Selected @endif>All</option> <option value="1" @if ($category === '1') Selected @endif>Selected Events 1</option> <option value="2" @if ($category === '2') Selected @endif>Selected Events 2</option> <option value="3" @if ($category === '3') Selected @endif>Selected Events 3</option> <option value="4" @if ($category === '4') Selected @endif>Selected Events 4</option> <option value="5" @if ($category === '5') Selected @endif>Selected Events 5</option> <option value="6" @if ($category === '6') Selected @endif>Selected Events 6</option> <option value="7" @if ($category === '7') Selected @endif>Selected Events 7</option> <option value="8" @if ($category === '8') Selected @endif>Selected Events 8</option> </select> </div> <div class="flex items-end"> <x-button type="submit" class="w-full">Search</x-button> </div> </div> </div> </form> is there any way to simplify this code? I could only think of this way, but I am still a beginner with PHP. The Categories are not stored in a DB table, so getting it from the DB is not possible. Answer: Some variable assignments are excessive Let's look at what $selected is set to: $selected = 'selected'; Then in both of the match statements $selected is always assigned to $selected so the return expressions from the match statements can simply return the value for $category - i.e.
{ "domain": "codereview.stackexchange", "id": 44219, "lm_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, html, laravel, laravel-blade", "url": null }
php, html, laravel, laravel-blade [$selected, $category] = match (request()->get('category')) { '0' => [$selected, '0'], '1' => [$selected, '1'], '2' => [$selected, '2'], '3' => [$selected, '3'], '4' => [$selected, '4'], '5' => [$selected, '5'], '6' => [$selected, '6'], '7' => [$selected, '7'], '8' => [$selected, '8'], }; can be simplified to the following: $category = match (request()->get('category')) { '0' => '0', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', }; Simplify assigning category variable A simpler way of assigning $category would be to check if request()->get('category') has an integer value between 0 and 8. That could be achieved using intval(), in_array() and range() $requestCategory = request()->get('category'); if (in_array(intval($requestCategory), range(0, 8))) { $category = $requestCategory } Set category default before checking request value Removing the match statements above could lead to these first two conditions: if (Request::is('courses')) { $category = '0'; } else if (Request::is('events')) { $category = '1'; } Then the isset() function can be used to check if either of those conditions were true and that variable was set: if (isset($category)) { $requestCategory = request()->get('category'); if (in_array(intval($requestCategory), range(0, 8))) { $category = $requestCategory; } }
{ "domain": "codereview.stackexchange", "id": 44219, "lm_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, html, laravel, laravel-blade", "url": null }
php, html, laravel, laravel-blade Edit: I saw in your suggested edit that you proposed simply checking if there is a value in request()->get('category') instead of using isset($category) - while it would technically be different functionality than the original code, that could be done instead. In that case $requestCategory could be assigned within the conditional statement, though some argue it is less readable. I will leave it up to you to decide whether to use that or not. if ($requestCategory = request()->get('category')) { if (in_array(intval($requestCategory), range(0, 8))) { $category = $requestCategory; } } With the assignment moved out of the conditional it could allow for the two conditionals to be combined, allowing for the indentation levels to be decreased: $requestCategory = request()->get('category') if ($requestCategory && in_array(intval($requestCategory), range(0, 8))) { $category = $requestCategory; } The template can have a loop Blade templates support loops. So these repeated lines: <option value="0" @if ($category === '0') Selected @endif>All</option> <option value="1" @if ($category === '1') Selected @endif>Selected Events 1</option> <option value="2" @if ($category === '2') Selected @endif>Selected Events 2</option> <option value="3" @if ($category === '3') Selected @endif>Selected Events 3</option> <option value="4" @if ($category === '4') Selected @endif>Selected Events 4</option> <option value="5" @if ($category === '5') Selected @endif>Selected Events 5</option> <option value="6" @if ($category === '6') Selected @endif>Selected Events 6</option> <option value="7" @if ($category === '7') Selected @endif>Selected Events 7</option> <option value="8" @if ($category === '8') Selected @endif>Selected Events 8</option>
{ "domain": "codereview.stackexchange", "id": 44219, "lm_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, html, laravel, laravel-blade", "url": null }
php, html, laravel, laravel-blade Could be simplified to the following. Note it uses the @selected directive mentioned in the Additional Attributes section. This allows for $selected to be eliminated. <option value="0" @selected($category === '0')>All</option> @for ($i = 1; $i < 9; $i++) <option value="{{ $i }}" @selected($category == $i)>Selected Events {{ $i }}</option> @endfor The range() function could also be used with a @foreach loop: <option value="0" @selected($category === '0')>All</option> @foreach (range(1, 8) as $i) <option value="{{ $i }}" @selected($category == $i)>Selected Events {{ $i }}</option> @endfor
{ "domain": "codereview.stackexchange", "id": 44219, "lm_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, html, laravel, laravel-blade", "url": null }
rust Title: Deserializing JSON data with flexible key and type into structures Question: I need to parse JSON data that's got a... unique structure. It either looks like this: {"ok": true, "<key>": .... } or this {"ok": false, "error": "reason" } Where <key> and the shape of the data depends on the API call. The following code accomplishes this task, assuming that T derives Deserialize from serde. However, it does not use serde to accomplish this. How might you alter this code to make it more idiomatic? Whilst you are free to review any part of the code as per your remit, please note that the name RawResponse2 originates because I was hacking this together to identify a solution; it's not reflective of an actual name I would use, although, regardless, this name would not be exposed to any caller. #[derive(Debug)] enum Error { MalformedResponse, Serde(serde_json::Error), Slack(Reason), } #[derive(Debug, Eq, PartialEq)] struct RawResponse2<T> { ok: bool, err: Option<Reason>, val: Option<T>, } impl<T> From<RawResponse2<T>> for Result<T, Error> { // We cannot have OK=false, Err=None, or OK=true and Err=Some|Data=None. // If any of these things happen, we have a malformed response fn from(val: RawResponse2<T>) -> Self { match val { RawResponse2 { ok: true, val: Some(v), .. } => Ok(v), RawResponse2 { ok: false, err: Some(reason), .. } => Err(Error::Slack(reason)), _ => Err(Error::MalformedResponse), } } } trait DeserializableValue<'a>: DeserializeOwned { fn tag_name() -> &'a str; }
{ "domain": "codereview.stackexchange", "id": 44220, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust trait DeserializableValue<'a>: DeserializeOwned { fn tag_name() -> &'a str; } fn from_json<'a, T>(value: &Value) -> Result<T, Error> where T: DeserializableValue<'a>, { // We need to exchange res for a value. This _should_ be an object with up to three keys: // * ok (bool) // * error (optional, string) // * <indeterminate key name> (optional, <interdeterminate type>) let (ok, err, val) = match value { Value::Object(map) => { let ok = map.get("ok").and_then(|v| v.as_bool()); let err = map .get("error") .map(|e| Reason::deserialize(e).map_err(Error::Serde)); let tag = T::tag_name(); let val = map .get(tag) .map(|v| T::deserialize(v).map_err(Error::Serde)); Ok((ok, err, val)) } _ => Err(Error::MalformedResponse), }?; // Now we can convert this into the intermediate representation, which is converted // to a Result via From RawResponse2 { // ok can never be absent - if it is, something has gone wrong, and it should be considered an error. ok: ok.ok_or(Error::MalformedResponse)?, // val can be absent (None), present but parsed incorrectly (Some(Err(_)), or present and parsed correctly (Some(Ok(_))). val: match val { None => None, Some(Ok(val)) => Some(val), Some(Err(e)) => return Err(e), }, // Similarly, err has the same branches.. err: match err { None => None, Some(Ok(val)) => Some(val), Some(Err(e)) => return Err(e), }, } .into() }
{ "domain": "codereview.stackexchange", "id": 44220, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
rust How would you approach this problem? As best I can tell, I cannot use #[serde(untagged)] to solve this, so I wrote the deserialization code myself. Here's a test which demonstrates that this code works: #[derive(Debug, Deserialize, Eq, PartialEq)] struct TestWebSocketInfo(String); impl<'a> DeserializableValue<'a> for TestWebSocketInfo { fn tag_name() -> &'a str { "url" } } fn typeck<'a, T>(blob: &'a &str) -> Result<T, Error> where T: DeserializableValue<'a> + std::fmt::Debug, { let res = serde_json::from_str::<Value>(blob)?; let t: T = from_json(&res)?; Ok(t) } #[test] fn derives_slack_response_correctly() { let ok_blob = r#"{"ok": true, "url": "wss://example.com/socket"}"#; assert_eq!( TestWebSocketInfo("wss://example.com/socket".to_string()), typeck(ok_blob).unwrap() ); } Answer: let err = map .get("error") .map(|e| Reason::deserialize(e).map_err(Error::Serde)); You have an Option<Error<...>> and end up with fairly complicated logic to handle it later. Instead, I'd just using the transpose() method which converts Option<Error<..>> into Error<Option<...>> let err = map.get("error").map(Reason::deserialize).transpose()?; Then you can just deal with an option later. Your whole intermediate representation is kinda pointless. Just convert directly to the desired form. Something like: match (ok, val, err) { (Some(true), Some(val), None) => Ok(val), (Some(false), None, Some(error)) => Err(Error::Slack(error)), _ => Err(Error::MalformedResponse) } But there is bit of an inefficiency in your code: fn from_json<'a, T>(value: &Value) -> Result<T, Error> With this implementation, the complete JSON has to be deserialized into a Value before being redeserialized into the target type. It'd be nice to skip that. You by implementing custom deserialization logic as explained here: https://serde.rs/deserialize-struct.html
{ "domain": "codereview.stackexchange", "id": 44220, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "rust", "url": null }
python, algorithm Title: Calculate result of an election using the D'Hondt method Question: I have learned about list comprehensions a week or so ago and understood that they can save a lot of screen space. Though, I have been told that this is bad practice only to use them, even if it brings tremendous benefits. Where is the line? The version with no nested comprehensions is at least three times longer. This function takes a dictionary like this and a number of seats in the council. "Name": "Votes for 1st candidate","Votes for 2nd candidate",... parties = {"020": [550,198,52,57], "De Vrie": [364,45,58,95,101,10,41,101,92,66,18,35,20,47,19,10,20,15,32,40,15,26,8,16,8,41,13,19,119,10,6,6,18,29,12,28,133,3,15,22], "inter": [299,85,26,34,29,15,18,38,27,16,18,9,8,13,17], "activisten": [161,44,139,155,25,53,58,61], "newdems": [78,77,52,35,59,20,21,6,11,8,11,23,7,28,32,19]} election_result(parties, 7) It prints how many seats each party is assigned according to the D'Hondt method: 020 - 1 seat(s) De Vrie - 3 seat(s) inter - 1 seat(s) activisten - 1 seat(s) newdems - 1 seat(s) Function itself: def election_results(parties: dict, seats: int) -> dict: """Looks cool""" assigned_seats = {p: sum(all_votes) // (sum([sum(all_votes) for all_votes in parties.values()]) // seats) for p, all_votes in parties.items()} while sum([seats_ for seats_ in assigned_seats.values()]) < seats: assigned_seats[[p for p in parties if (sum(parties[p]) // (assigned_seats[p] + 1)) == max([sum(all_votes) // (assigned_seats[p] + 1) for p, all_votes in parties.items()])][0]] += 1 [print(f"\r{k} - {v} seat(s)") for k, v in assigned_seats.items()] return assigned_seats P.S. Converting the while loop is definitely too much Answer: Short answer: Here are the rules of thumb with list comprehensions:
{ "domain": "codereview.stackexchange", "id": 44221, "lm_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, algorithm", "url": null }
python, algorithm Answer: Short answer: Here are the rules of thumb with list comprehensions: don't nest them don't use them for side effects don't use them if they require more than ~70 characters width, or have longwinded conditions don't use them to build a big list if you're just going to take one element don't use them if they in any way make the code harder to understand than a traditional loop--never try to be clever or write code because it "looks cool" (unless you're code golfing). This code breaks all of the rules. Long answer: Yes, this is definitely a misuse of list comprehensions. Frankly, it's an unreadable mess. Where is the line?
{ "domain": "codereview.stackexchange", "id": 44221, "lm_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, algorithm", "url": null }
python, algorithm Where is the line? The line is the same as any code feature/tool: use it if it benefits the code in terms of some metric(s) (performance, readability, maintainability, etc) and don't use it if it doesn't. Software engineering is basically a long series of judgement calls like this, analyzing tradeoffs and picking the solution that makes the most sense for whatever goals you might have. In almost any non-competitive, non-code golf context, the goals are speed of development versus maintainability, with performance occasionally an important factor. If all things seem equal, lean towards maintainability while keeping a reasonable pace and avoiding premature optimizations. As a rule of thumb, lines should never be longer than 80 characters in any language. Putting your code into Black gives immediate improvements in this regard: def election_results(parties: dict, seats: int) -> dict: """Looks cool""" assigned_seats = { p: sum(all_votes) // (sum([sum(all_votes) for all_votes in parties.values()]) // seats) for p, all_votes in parties.items() } while sum([seats_ for seats_ in assigned_seats.values()]) < seats: assigned_seats[ [ p for p in parties if (sum(parties[p]) // (assigned_seats[p] + 1)) == max( [ sum(all_votes) // (assigned_seats[p] + 1) for p, all_votes in parties.items() ] ) ][0] ] += 1 [print(f"\r{k} - {v} seat(s)") for k, v in assigned_seats.items()] return assigned_seats
{ "domain": "codereview.stackexchange", "id": 44221, "lm_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, algorithm", "url": null }
python, algorithm A rule of thumb with list comprehensions is to avoid nesting them. This code would be a terrible chore to safely modify without introducing bugs. One would need to de-obfuscate the code just to figure out what it even does, much less go about modifying it. Nested list comprehensions often hide unnecessary repeated work. Another rule of thumb with list comprehensions is to avoid using them for side effects, like printing. List comprehensions allocate memory, so using them to print involves expensive work that just gets thrown away to the garbage collector. Worse, it's not idiomatic and hides the intent of the code. Functions that perform logic shouldn't print to begin with. They should silently return results and let the caller decide what to do. """Looks cool""" is pretty much an insult to the reader. Imagine there's a bug in the company's code and the developer that was hired to replace you has to deal with this function. I'd vouch they'll see it as extremely uncool. Be nice to that person because you may find yourself in the same position. A good point is that you've added some type hints. However, the dict hint doesn't contain key and value types. Another good point is that your variable names are generally pretty clear. But the inner list comprehensions have no names, so it's unclear what they represent. Intermediate variables and functions would de-anonymize them and make their purpose clear. One list comprehension achieves nothing except a wasted allocation and loop: while sum([seats_ for seats_ in assigned_seats.values()]) < seats: can be while sum(assigned_seats.values()) < seats: Here's a first pass at a rewrite. I haven't looked at the algorithm, so there are probably other optimizations available. I didn't bother ensuring that I haven't broken something. If I did regress functionality, my point is proven. from typing import Any, Dict, Iterable, List Parties = Dict[str, List[int]] Result = Dict[str, int]
{ "domain": "codereview.stackexchange", "id": 44221, "lm_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, algorithm", "url": null }
python, algorithm Parties = Dict[str, List[int]] Result = Dict[str, int] def flatten(lst: Iterable) -> List: return [x for y in lst for x in y] def sum_dict_values(dct: Dict[Any, List[int]]) -> int: return sum(flatten(dct.values())) def find_best_party(parties: Parties, assigned_seats: Result) -> str: return max(parties, key=lambda p: sum(parties[p]) // (assigned_seats[p] + 1)) def determine_election_results(parties: Parties, seats: int) -> Result: total_votes = sum_dict_values(parties) assigned_seats = { p: sum(votes) // (total_votes // seats) for p, votes in parties.items() } while sum(assigned_seats.values()) < seats: best_party = find_best_party(parties, assigned_seats) assigned_seats[best_party] += 1 return assigned_seats def main(): parties = { "020": [550, 198, 52, 57], "De Vrie": [364, 45, 58, 95, 101, 10, 41, 101, 92, 66, 18, 35, 20, 47, 19, 10, 20, 15, 32, 40, 15, 26, 8, 16, 8, 41, 13, 19, 119, 10, 6, 6, 18, 29, 12, 28, 133, 3, 15, 22], "inter": [299, 85, 26, 34, 29, 15, 18, 38, 27, 16, 18, 9, 8, 13, 17], "activisten": [161, 44, 139, 155, 25, 53, 58, 61], "newdems": [78, 77, 52, 35, 59, 20, 21, 6, 11, 8, 11, 23, 7, 28, 32, 19], } assigned_seats = determine_election_results(parties, 7) for k, v in assigned_seats.items(): print(f"\r{k} - {v} seat(s)") if __name__ == "__main__": main()
{ "domain": "codereview.stackexchange", "id": 44221, "lm_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, algorithm", "url": null }
sql, sql-server, t-sql Title: Optimizing a TRANSACT SQL statement Question: I'm in need to optimize the following TRANSACT SQL statement : SELECT Id, Type, StartTime, Amount, CurrencyCode, CorrelationStatus, ProviderId FROM ( SELECT UserId, Id, {=charge} Type, StartTime, Amount, CurrencyCode, CorrelationStatus, ProviderId FROM charge WHERE (@Type IS NULL OR @Type = {=charge}) UNION ALL SELECT UserId, Id, {=recharge} Type, StartTime, Amount, CurrencyCode, CorrelationStatus, ProviderId FROM recharges WHERE (@Type IS NULL OR @Type = {=recharge}) ) AS T WHERE UserId = @UserId AND StartTime BETWEEN @StartDate AND @EndDate AND (@ProviderId IS NULL OR ProviderId = @ProviderId) AND (@FilterCorrelationStatus = 0 OR CorrelationStatus IN @CorrelationStatuses) ORDER BY StartTime DESC OFFSET (@PageIndex - 1) * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY; Can you give me some suggestions? Thanks, Simone
{ "domain": "codereview.stackexchange", "id": 44222, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, sql-server, t-sql", "url": null }
sql, sql-server, t-sql Can you give me some suggestions? Thanks, Simone Answer: As this is a application SQL (executed by stored proc?) returning DBSet (or similar) your choices are limited. I'd start by looking at the execution plans - look out for "Scans" - this would indicate a missing index. use SET STATISTICS IO ON to see how many reads are being undertaken. I would also look for the order of execution, you might be better off including the filter criteria in each of the unions, rather than having an outer At a guess, though each of the UNION clauses is returning a large set of data, before then applying the filter. Try something like this: SELECT Id, Type, StartTime, Amount, CurrencyCode, CorrelationStatus, ProviderId FROM ( SELECT UserId, Id, {=charge} Type, StartTime, Amount, CurrencyCode, CorrelationStatus, ProviderId FROM charge WHERE UserId = @UserId AND StartTime BETWEEN @StartDate AND @EndDate AND (@ProviderId IS NULL OR ProviderId = @ProviderId) AND (@FilterCorrelationStatus = 0 OR CorrelationStatus IN @CorrelationStatuses) AND (@Type IS NULL OR @Type = {=charge}) UNION ALL SELECT UserId, Id, {=recharge} Type, StartTime, Amount, CurrencyCode, CorrelationStatus, ProviderId FROM recharges WHERE UserId = @UserId AND StartTime BETWEEN @StartDate AND @EndDate AND (@ProviderId IS NULL OR ProviderId = @ProviderId) AND (@FilterCorrelationStatus = 0 OR CorrelationStatus IN @CorrelationStatuses) AND (@Type IS NULL OR @Type = {=recharge}) ) AS T ORDER BY StartTime DESC OFFSET (@PageIndex - 1) * @PageSize ROWS FETCH NEXT @PageSize ROWS ONLY; An alternate approach (last resort?!) is to create a schema bound indexed view. In other words create a schema bound view of CREATE VIEW xxx WITH SCHEMABINDING AS SELECT fields FROM charge UNION ALL SELECT fields recharges. You can then add indexes to the view.
{ "domain": "codereview.stackexchange", "id": 44222, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "sql, sql-server, t-sql", "url": null }
python, performance, pandas, database Title: Efficient way to read files python - 10 folders with 100k txt files in each one Question: i am looking for an efficient way to read and append texts of .txt files to a dataframe. I currently have 10 folders with 100k documents each. What i specifically need to do is: getting the names of the files inside one folder (filenames contain important information like a unique ID for each company that issue the document and the date when the document was published, like this: "CIK_000000_DATE_14_12_2022.txt") extract from the name of the files the unique ID (CIK) and the date take the text related to the file append this 3 pieces of informations in a dataset so that the dataset appear like: CIK date text serial 000000 11/12/2012 some text here... 1 000001 14/11/2019 some other text here... 2 the folders are individually made like this: TXT_01 |_ CIK__000000__DATE__14-12-2012__serial__0.txt |_ CIK__000001__DATE__12-11-2019__serial__1.txt |_ CIK__000001__DATE__11-12-2014__serial__2.txt |_ CIK__000175__DATE__11-04-2011__serial__3.txt |_ ... TXT_02 |_ CIK__000135__DATE__11-04-2001__serial__100.txt |_ CIK__000115__DATE__11-04-2001__serial__101.txt |_ CIK__000145__DATE__11-04-2001__serial__103.txt |_ CIK__000155__DATE__11-04-2001__serial__104.txt |_ ... ... They get the job done, but the time they take to finish a test folder with 4000 documents is way too much considering that i need to do this for 100k files folders. i can provide more informations if needed. I'm open to any advice, even learning faster programming languages in order to get this done. thank you all here the code i'm currently executing (consider that it comes from a collab notebook) folders = [] names = os.listdir() for i in names: if i.startswith('TXT'): folders.append(i) def get_file_names(folder): return os.listdir(folder)
{ "domain": "codereview.stackexchange", "id": 44223, "lm_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, pandas, database", "url": null }
python, performance, pandas, database def get_file_names(folder): return os.listdir(folder) def get_cik_date(file): cik = re.findall(r"CIK__([0-9]*)", file)[0].zfill(10) date = re.findall(r"date__(([0-9]*)-([0-9]*)-([0-9]*))", file)[0][0] serial = re.findall(r"serial__([0-9]*)", file)[0] return (cik, date, serial) def get_text(file): get_text.counter +=1 print(get_text.counter) with open(file) as f: lines = f.readlines() return lines get_text.counter = 0 file_names = list(map(get_file_names,folders)) folder_names = list(zip(folders,file_names)) cik_date_folder = [[get_cik_date(i) for i in j] for k,j in folder_names] texts = [[get_text(f"{k}/{i}") for i in j] for k,j in folder_names] test = [dict(zip(cik_date_folder[i], texts[i])) for i,n in enumerate(folders)] df = pd.DataFrame.from_dict(test) df = df.ffill().bfill().head(1).T df_reset = df.reset_index() df_reset = df_reset.rename({"index": "cik_date", 0:"text"}, axis = 1) df_reset[['cik','dates', 'serial']] = pd.DataFrame(df_reset['cik_date'].tolist(),index=df_reset.index) df_complete = df_reset.drop("cik_date", axis = 1) def concat_list(text_as_list): return " ".join(text_as_list) df_complete["text"] = df_complete["text"].apply(concat_list) ``` Answer: I created a few functions for quickly setting up a "test environment" of N folders each with M files: import random import re import os from pathlib import Path from string import ascii_letters import itertools from time import time import pandas as pd BASE = "C:\\some\\path\\" DATE_POOL = pd.date_range(start="01-01-2000", end="01-01-2022") FILE_LEN = 64 def create_filename(serial: int): identifier = str(random.randint(0, 999999)).zfill(6) stamp = random.choice(DATE_POOL).strftime("%m_%d_%Y") return f"CIK__{identifier}__DATE__{stamp}__serial__{serial}.txt"
{ "domain": "codereview.stackexchange", "id": 44223, "lm_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, pandas, database", "url": null }
python, performance, pandas, database def create_file_setup(num_folders: int, num_files: int): serial = 0 for i in range(num_folders): subpath = os.path.join(BASE, f"TXT_{i}") os.mkdir(subpath) for j in range(num_files): txt_file = os.path.join(subpath, create_filename(serial)) serial += 1 content = ''.join(random.choices(ascii_letters + ' ', k=FILE_LEN)) Path(txt_file).write_text(content) So by running create_file_setup(10, 100_000) I create 10 folders each with 100k files, each following the naming scheme you described (or, at least, I deduced as well as I could). I don't know how large your files are, but I entered 64 characters into each. Maybe this can vary too, but you don't specify. Now, just cleaning up your code slightly gives me: def get_cik_date(filename: str): _, identifier, _, date, _, serial = filename.split("__") serial, _ = serial.split('.') return identifier, date, serial def build_dataframe(): folders = [os.path.join(BASE, p) for p in os.listdir(BASE)] file_names = list(map(os.listdir, folders)) folder_names = list(zip(folders, file_names)) cik_date_folder = [[get_cik_date(i) for i in j] for _, j in folder_names] texts = [[Path(f"{k}/{i}").read_text() for i in j] for k, j in folder_names] df = pd.DataFrame(itertools.chain(*cik_date_folder), columns=["id", "date", "serial"]) df["text"] = list(itertools.chain(*texts)) return df If I now run df = build_dataframe() on my machine, the wall clock time is around 40 minutes. If you just need to do this processing once, this is probably much faster than spending time on learning to program in another language or spending time on optimizing your code. Just run it, do something else in the meantime, and come back to your freshly processed data.
{ "domain": "codereview.stackexchange", "id": 44223, "lm_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, pandas, database", "url": null }
c, array, memory-management Title: Implementation of a two-dimensional array in C Question: I implemented a two-dimensional array in C and would like to know if the implementation is sound in terms of Memory management Potential bugs and other side effects that I missed Code style (readability, naming conventions, etc...) Clean code Efficiency The code compiles and runs without any error: gcc -O -Wall main.c #include <assert.h> #include <stdio.h> #include <stdlib.h> struct Array { double **data; size_t rows; size_t cols; }; struct Array *NewArray(const size_t rows, const size_t cols){ if (rows <= 0 || cols <= 0){ return NULL; } struct Array *array = (struct Array *)malloc(sizeof(struct Array *)); array->rows = rows; array->cols = cols; array->data = (double **) malloc(rows * sizeof(double *)); for (size_t i = 0; i < rows; ++i) { array->data[i] = (double *) malloc(cols * sizeof(double)); } return array; } int FreeArray(struct Array *array){ if (array != NULL) { return -1; } assert (array->data); for (size_t i = 0; i < array->rows; ++i) { free(array->data[i]); } free(array->data); free(array); return 0; } void PrintArray(const struct Array *array) { for (int i=0; i<array->rows; ++i) { for (int j=0; j<array->cols; ++j) { printf("%.2lf ", array->data[i][j]); } printf("\n"); } return; } int main(){ size_t rows = 2; size_t cols = 4; struct Array *M = NewArray(2, 4); PrintArray(M); FreeArray(M); }
{ "domain": "codereview.stackexchange", "id": 44224, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, memory-management", "url": null }
c, array, memory-management Answer: Enable more warnings, and use a memory checker: gcc-12 -std=c17 -g -Wall -Wextra -Wwrite-strings -Wno-parentheses -Wpedantic -Warray-bounds -Wconversion -Wstrict-prototypes -fanalyzer 281916.c -o 281916 281916.c: In function ‘PrintArray’: 281916.c:43:20: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare] 43 | for (int i=0; i<array->rows; ++i) { | ^ 281916.c:44:24: warning: comparison of integer expressions of different signedness: ‘int’ and ‘size_t’ {aka ‘long unsigned int’} [-Wsign-compare] 44 | for (int j=0; j<array->cols; ++j) { | ^ 281916.c: At top level: 281916.c:52:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes] 52 | int main(){ | ^~~~ 281916.c: In function ‘main’: 281916.c:54:12: warning: unused variable ‘cols’ [-Wunused-variable] 54 | size_t cols = 4; | ^~~~ 281916.c:53:12: warning: unused variable ‘rows’ [-Wunused-variable] 53 | size_t rows = 2; | ^~~~ 281916.c: In function ‘NewArray’: 281916.c:17:17: warning: dereference of possibly-NULL ‘array’ [CWE-690] [-Wanalyzer-possible-null-dereference] 17 | array->rows = rows; | ~~~~~~~~~~~~^~~~~~ ‘NewArray’: events 1-4 | | 12 | if (rows <= 0 || cols <= 0){ | | ^ | | | | | (1) following ‘false’ branch... |...... | 15 | struct Array *array = (struct Array *)malloc(sizeof(struct Array *)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (2) ...to here | | (3) this call could return NULL | 16 | | 17 | array->rows = rows; | | ~~~~~~~~~~~~~~~~~~
{ "domain": "codereview.stackexchange", "id": 44224, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, memory-management", "url": null }
c, array, memory-management | 16 | | 17 | array->rows = rows; | | ~~~~~~~~~~~~~~~~~~ | | | | | (4) ‘array’ could be NULL: unchecked value from (3) | 281916.c: In function ‘PrintArray’: 281916.c:45:13: warning: use of uninitialized value ‘*_5 + _7’ [CWE-457] [-Wanalyzer-use-of-uninitialized-value] 45 | printf("%.2lf ", array->data[i][j]); | ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ‘main’: events 1-2 | | 52 | int main(){ | | ^~~~ | | | | | (1) entry to ‘main’ |...... | 55 | struct Array *M = NewArray(2, 4); | | ~~~~~~~~~~~~~~ | | | | | (2) calling ‘NewArray’ from ‘main’ | +--> ‘NewArray’: events 3-12 | | 11 | struct Array *NewArray(const size_t rows, const size_t cols){ | | ^~~~~~~~ | | | | | (3) entry to ‘NewArray’ | 12 | if (rows <= 0 || cols <= 0){ | | ~ | | | | | (4) following ‘false’ branch... |...... | 15 | struct Array *array = (struct Array *)malloc(sizeof(struct Array *)); | | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | | | | | (5) ...to here |...... | 21 | for (size_t i = 0; i < rows; ++i) { | | ~~~~~~~~ | | | | | (6) following ‘true’ branch (when ‘i < rows’)... | | (9) following ‘true’ branch (when ‘i < rows’)...
{ "domain": "codereview.stackexchange", "id": 44224, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c, array, memory-management", "url": null }