body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>As I was writing, I realized I have multiple classes polling for file descriptors in its own thread - lots of duplicate code like, synchronization, creating array of pollfds etc.</p> <p>I've decided to remove the duplicate code by writing the following class, which takes care of polling fds in the background. Any thoughts?</p> <pre><code>template&lt;typename Callback, typename ReadFn&gt; class Poller { public: using storage_type = std::vector&lt;struct pollfd&gt;; using callbacks_type = std::map&lt;int, Callback&gt;; explicit Poller(ReadFn&amp;&amp; readFn) : readFn(std::forward(readFn)) {} ~Poller() { if (worker.joinable()) { executeInContext([](storage_type&amp; storage, callbacks_type&amp; callbacks){ storage.erase(storage.begin()+1, storage.end()); callbacks.clear(); }); worker.join(); close(_fd[0]); close(_fd[1]); } } void addDescriptor(int fd, Callback cb) { if (!worker.joinable()) { pipe(_fd); _storage.push_back({_fd[0], POLLPRI | POLLIN, 0}); _storage.push_back({fd, POLLPRI | POLLIN, 0}); _callbacks[fd] = cb; worker = std::thread([this]{threadFunc();}); } else { executeInContext([fd, cb](storage_type&amp; storage, callbacks_type&amp; callbacks){ auto it = std::find_if(storage.begin(), storage.end(), [fd](struct pollfd i){ return fd == i.fd; }); if (it == storage.end()) { storage.push_back({fd, POLLPRI | POLLIN, 0}); } callbacks[fd] = cb; }); } } void removeDescriptor(int fd) { executeInContext([fd](storage_type&amp; storage, callbacks_type&amp; callbacks){ if (auto it = std::find_if(storage.begin(), storage.end(), [fd](struct pollfd i){ return i.fd == fd; }); it != storage.end()) { callbacks.erase(it-&gt;fd); storage.erase(it); } }); if (_storage.size() == 1 &amp;&amp; worker.joinable()) { worker.join(); close(_fd[0]); close(_fd[1]); _storage.clear(); } } template&lt;typename Callable&gt; void executeInContext(Callable&amp;&amp; func) { ::write(_fd[1], &quot;suse\0&quot;, 5); { std::unique_lock lock(mutex); std::invoke(std::forward(func), std::ref(_storage), std::ref(_callbacks)); } cv.notify_all(); } protected: void threadFunc() { std::unique_lock lock(mutex); while (true) { if (int rv = poll(_storage.data(), _storage.size(), -1); rv &gt; 0) { /* Pipe sync request */ if (_storage.begin()-&gt;revents) { char buff[0x10]; ::read(_fd[0], buff, sizeof(buff)); /* Wait for main thread to execute its stuff */ cv.wait(lock); if (_storage.size() == 1) { /* All fds have been removed except the pipe, exit */ break; } } for (auto&amp; pfd : _storage) { if (pfd.revents) { std::invoke(readFn, pfd.fd, _callbacks.at(pfd.fd)); } } } else if (errno == EINTR) { continue; } else { /* Debug trace breakpoint */ } } } private: std::thread worker{}; std::vector&lt;struct pollfd&gt; _storage{}; std::map&lt;int, Callback&gt; _callbacks{}; std::condition_variable cv{}; std::mutex mutex{}; int _fd[2]{}; ReadFn readFn; }; </code></pre> <p>Example usage:</p> <pre><code>using callback_type = std::function&lt;void(int)&gt;; auto readfn = [](int fd, callback_type cb){ struct event_structure ev{}; ::read(fd, &amp;ev, sizeof(ev)); std::invoke(cb, ev.property); }; Poller&lt;callback_type, decltype(readfn)&gt; poller(readfn); int fd = /* open FD */; poller.addDescriptor(fd, [](int){/* Handle property change */}); /* More descriptors with unique callbacks added/removed during program execution */ </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T08:40:57.203", "Id": "527830", "Score": "1", "body": "@TobySpeight I've updated the question with example usage. Please note I've just written it from top of my head - might not compile." } ]
[ { "body": "<h1>Start the thread in the constructor</h1>\n<p>Starting and stopping the thread on demand requires being very careful not to trigger any race conditions. But there is no reason not to have the thread running all the time, if it's just blocked waiting on a command on the sync fd, it doesn't use any CPU time. So I recommend you start the thread in the constructor, and stop it in the destructor.</p>\n<h1>Missing error handling</h1>\n<p>The calls to <code>::read()</code> and <code>::write()</code> can fail; be sure to handle failures correctly.</p>\n<h1>Use a <code>std::vector</code> for <code>_callbacks</code></h1>\n<p>It should be possible to store the callbacks in a <code>std::vector</code>, that matches its order with that of <code>_storage</code>. That way, you don't have to do a rather expensive lookup to get the callback; you just iterate over <code>_storage</code> and <code>_callbacks</code> simultaneously in <code>threadFunc()</code>.</p>\n<h1>Thread safety</h1>\n<p>The code you have might work for your application, but it is quite fragile. You've written it in such a way that it's only safe to add and remove descriptors to a <code>Poller</code> in the same thread where you instantiated it. Most importantly, a callback cannot remove itself safely. It would be possible to make it more robust at the cost of adding a bit more complexity.</p>\n<p>One reason for this is that adding items to or removing items from <code>_storage</code> will invalidate any iterators, including the ones used behind the scenes by the <code>for</code>-loop in <code>threadFunc()</code>. A possible solution is to set a flag when adding or removing items from the loop, and after invoking the callback, immediately exit the loop if the flag is set.</p>\n<p>Another issue is that calling <code>executeInContext()</code> from inside the polling thread will result in a deadlock. A potential solution is to let detect if <code>executeInContext()</code> detect if it is called from the same thread as <code>threadFunc()</code>, and if so not try to lock the mutex.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T19:11:32.760", "Id": "527853", "Score": "0", "body": "I do agree callback cannot remove itself, but how come I can only add items from the thread that instantiated it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T20:32:36.983", "Id": "527856", "Score": "0", "body": "The reason is that iterators that are still in use are being invalidated that way, and there's a deadlock situation. I've updated the answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T15:11:38.873", "Id": "527904", "Score": "0", "body": "I don't agree about invalidating the iterators. If we take into account that we are not able to add/remove elements from the callback, the iterators are not used during modify operation on vector/map. Only after this function has taken place, the for loop will begin to execute. Although I still like your answer as it made me think of these scenarios. Which brings me to the last question. Is there any error (besides EINTR), which might be set during write on pipes (when both ends are still valid)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T15:46:58.387", "Id": "527906", "Score": "0", "body": "If it's done outside the callback, it's indeed fine, as long as adding/removing items is all done from the same thread, or you have some way to ensure no two threads can add/remove at the same time. This might be a reasonable assumption to make. If you [document your code](https://www.doxygen.nl/index.html), be sure to include a note about the thread safety of your functions. As for pipe errors: if you make them non-blocking, `EAGAIN` or `EWOULDBLOCK` can happen. Apart from that not much. `EPIPE` when one end closes the pipe, which you could make use of in your code." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T14:41:06.770", "Id": "267686", "ParentId": "267668", "Score": "2" } } ]
{ "AcceptedAnswerId": "267686", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T06:55:04.327", "Id": "267668", "Score": "2", "Tags": [ "c++", "linux" ], "Title": "Polling FDs in a helper thread, dynamically adding/removing the descriptors" }
267668
<p>The class in this post returns a directed cycle in a <em><strong>financial loan graph</strong></em>. A financial loan graph consists of nodes and directed arcs. If there is an arc <span class="math-container">\$(u, v)\$</span> with weight <span class="math-container">\$w = w(u, v)\$</span>, then we interpret it as that <span class="math-container">\$u\$</span> has lent <span class="math-container">\$w\$</span> number of resources to <span class="math-container">\$v\$</span>.</p> <p>Since in a dense directed graph with <span class="math-container">\$n\$</span> nodes there may be up to <span class="math-container">\$n^2 - n = \Theta(n^2)\$</span> arcs, we might be interested in minimizing the number of arcs in the loan graph such that debt information is preserved. (See <a href="https://coderodde.wordpress.com/2015/07/20/minimizing-the-amount-of-bank-transactions-in-a-static-loan-graph/" rel="nofollow noreferrer">this Wordpress post</a> for more thourough discussion.) (The project repository is <a href="https://github.com/coderodde/lgs" rel="nofollow noreferrer">here</a>.)</p> <p>Please note that without modifying the graph, the method will return always the same cycle. It is used in a setting where at least one arc of a cycle is removed from the graph, which, in turn, will result obtaining another cycles.</p> <p><strong><code>net.coderodde.loan.model.support.RecursiveDepthFirstSearch</code>:</strong></p> <pre><code>package net.coderodde.loan.model.support; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import net.coderodde.loan.model.Graph; import net.coderodde.loan.model.Node; /** * This class implements a recursive depth-first search variant returning a * directed cycle. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 4, 2021) * @since 1.6 (Sep 4, 2021) */ public class RecursiveDepthFirstSearch { private final Set&lt;Node&gt; marked = new HashSet&lt;&gt;(); private final Set&lt;Node&gt; stack = new HashSet&lt;&gt;(); private final Map&lt;Node, Node&gt; parents = new HashMap&lt;&gt;(); public List&lt;Node&gt; findCycle(Graph graph) { for (Node root : graph) { if (!marked.contains(root)) { parents.put(root, null); List&lt;Node&gt; cycle = findCycleImpl(root); if (cycle != null) { clearDataStructures(); return cycle; } } } clearDataStructures(); return null; } private void clearDataStructures() { marked.clear(); stack.clear(); parents.clear(); } private List&lt;Node&gt; findCycleImpl(Node root) { if (marked.contains(root)) { return null; } if (stack.contains(root)) { List&lt;Node&gt; cycle = new ArrayList&lt;&gt;(); Node currentNode = parents.get(root); while (currentNode != root) { cycle.add(currentNode); currentNode = parents.get(currentNode); } cycle.add(root); Collections.&lt;Node&gt;reverse(cycle); return cycle; } stack.add(root); for (Node child : root) { parents.put(child, root); List&lt;Node&gt; cycleCandidate = findCycleImpl(child); if (cycleCandidate != null) { return cycleCandidate; } } stack.remove(root); marked.add(root); return null; } } </code></pre> <h3>Related posts:</h3> <ol> <li><a href="https://codereview.stackexchange.com/questions/267671/loan-graph-simplification-in-java-an-arc-minimization-algorithm">Loan graph simplification in Java: an arc minimization algorithm</a></li> <li><a href="https://codereview.stackexchange.com/questions/267670/loan-graph-simplification-in-java-the-graph-data-structures">Loan graph simplification in Java: the graph data structures</a></li> </ol> <h2>Critique request</h2> <p>Please, tell me anything that comes to mind. ^^</p>
[]
[ { "body": "<p>Couldn't this class just have static methods and members? You wouldn't need to create an instance every time you want to DFS and you reset the internal sets/maps after each search anyways. I'm not sure about how you plan on using this class later on or if it still works if everything is static, so it might be fine as-is.</p>\n<p>Also, consider renaming the class to just <code>DFS</code>. You don't have any other <code>...DepthFirstSearch</code> classes, so you could drop the <code>Recursive</code> part. Also, it might sound like the class is trying to distinguish itself from a <code>IterativeDFS</code> and both classes are extensions of an <code>AbstractDFS / DFS</code>. DFS seems to be a common enough shorthand to use and someone using an IDE will also see your doc comments.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T13:39:52.287", "Id": "267732", "ParentId": "267669", "Score": "1" } } ]
{ "AcceptedAnswerId": "267732", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T07:35:11.090", "Id": "267669", "Score": "1", "Tags": [ "java", "algorithm", "graph", "depth-first-search" ], "Title": "Loan graph simplification in Java: the recursive DFS for searching for directed cycles" }
267669
<p>This post presents the loan graph implementation. The class belongs to <a href="https://github.com/coderodde/lgs" rel="nofollow noreferrer">this GitHub repository</a>.</p> <p><strong><code>net.coderodde.loan.model.Node</code>:</strong></p> <pre><code>package net.coderodde.loan.model; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; /** * This class implements a loan graph node. * * @author Rodion &quot;coderodde&quot; Efremov * @version 1.61 (Sep 2, 2021) * @since 1.6 */ public class Node implements Iterable&lt;Node&gt; { /** * This is the name of a node. Also, this is treated as the ID of a * node. (Two nodes &lt;code&gt;u&lt;/code&gt;, &lt;code&gt;v&lt;/code&gt; are considered as * equal if and only if &lt;code&gt;u.name.equals(v.name)&lt;/code&gt;. */ private final String name; /** * This is the map from lender to loan amount. */ private final Map&lt;Node, Long&gt; in = new HashMap&lt;&gt;(); /** * This is the map from borrower to resources lent. */ private final Map&lt;Node, Long&gt; out = new HashMap&lt;&gt;(); /** * The graph owning this node, if any. */ protected Graph ownerGraph; /** * If equity is below 0, this node owes, and, vice versa, if positive, * is eligible to receive cash. */ private long equity; /** * Constructs a new node. * * @param name the name of the new node. */ public Node(String name) { this.name = name; } /** * Copy-constructs a node. * * @param copy the node to share the identity with. */ public Node(Node copy) { this(copy.name); } /** * Gets the name of this node. * * @return the name of this node. */ public String getName() { return name; } /** * Returns the number of borrowers. * * @return the number of borrowers. */ public int getNumberOfBorrowers() { return this.out.size(); } /** * Returns the number of lenders. * * @return the number of lenders. */ public int getNumberOfLenders() { return this.in.size(); } /** * Returns the weight of the directed arc {@code (this, borrower)}. * * @param borrower the head node of the arc. * @return the arc weight. */ public long getWeightTo(Node borrower) { checkBorrowerNotNull(borrower); checkBorrowerBelongsToThisGraph(borrower); checkBorrowerExists(borrower); return this.out.get(borrower); } /** * Sets the weight of the directed arc {@code (this, borrower)}. * * @param borrower the head node of the arc. * @param weight the arc weight. */ public void setWeightTo(Node borrower, long weight) { checkBorrowerNotNull(borrower); checkBorrowerBelongsToThisGraph(borrower); checkBorrowerExists(borrower); long oldWeight = this.out.get(borrower); this.out.put(borrower, weight); borrower.in.put(this, weight); // 50 = 100 - 50 long weightDelta = weight - oldWeight; ownerGraph.flow += weightDelta; equity += weightDelta; borrower.equity -= weightDelta; } /** * Connects this node to a borrower. * * @param borrower the borrower. */ public void connectToBorrower(Node borrower) { checkBorrowerNotNull(borrower); checkBorrowerBelongsToThisGraph(borrower); if (out.containsKey(borrower)) { return; } if (borrower.ownerGraph != this.ownerGraph) { borrower.ownerGraph = this.ownerGraph; borrower.clear(); } out.put(borrower, 0L); borrower.in.put(this, 0L); ownerGraph.edgeAmount++; } public boolean isConnectedTo(Node borrower) { return out.containsKey(borrower); } /** * Remove the borrower of this node. * * @param borrower the borrower to remove. */ public void removeBorrower(final Node borrower) { checkBorrowerNotNull(borrower); if (borrower.ownerGraph != this.ownerGraph) { return; } if (out.containsKey(borrower)) { long w = out.get(borrower); out.remove(borrower); borrower.in.remove(this); this.equity -= w; borrower.equity += w; ownerGraph.edgeAmount--; ownerGraph.flow -= w; } } /** * Clear this node from all loans coming in and out. */ public void clear() { Iterator&lt;Node&gt; iterator = iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } iterator = parentIterable().iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } } public boolean isOrphan() { return ownerGraph == null; } private void checkBorrowerBelongsToThisGraph(final Node borrower) { if (borrower.ownerGraph != this.ownerGraph) { throw new IllegalStateException(&quot;The input borrower node &quot; + borrower + &quot; does not belong to this graph.&quot;); } } /** * Returns the string representation of this node. * @return */ @Override public String toString() { return &quot;[Node &quot; + name + &quot;; equity: &quot; + getEquity() + &quot;]&quot;; } /** * Returns the hash code of this node. Depends only on the name of * the node. * * @return the hash code of this node. */ @Override public int hashCode() { return name.hashCode(); } /** * Returns &lt;code&gt;true&lt;/code&gt; if and only if the two nodes have the * same name (identity). * * @param o the object to test against. * @return &lt;code&gt;true&lt;/code&gt; if and only if &lt;code&gt;o&lt;/code&gt; is a node * and has the same name. */ @Override public boolean equals(Object o) { return ((Node) o).name.equals(this.name); } /** * Returns the iterator over this node's borrowers. * * @return the iterator over this node's borrowers. */ @Override public Iterator&lt;Node&gt; iterator() { return new ChildIterator(); } /** * Returns the iterable over this nodes lenders. * * @return the iterable over this nodes lenders. */ public Iterable&lt;Node&gt; parentIterable() { return new ParentIterable(); } /** * Return the equity of this node. * * @return the equity of this node. */ public long getEquity() { return this.equity; } /** * Checks that borrower is not null and not this. * * @param borrower the borrower to check. */ private void checkBorrowerNotNull(final Node borrower) { if (borrower == null) { throw new NullPointerException(&quot;Borrower is null.&quot;); } } /** * This class implements the iterator over this node's borrowers. */ private class ChildIterator implements Iterator&lt;Node&gt; { /** * The actual iterator. */ private Iterator&lt;Node&gt; iterator = Node.this.out.keySet().iterator(); /** * Holds the node last returned by &lt;code&gt;next&lt;/code&gt;. */ private Node lastReturned; /** * Returns &lt;code&gt;true&lt;/code&gt; if and only if there is more * nodes to iterate. * * @return &lt;code&gt;true&lt;/code&gt; if and only if there is more nodes * to iterate. */ @Override public boolean hasNext() { return iterator.hasNext(); } /** * Returns the next node. * * @return the next node. */ @Override public Node next() { return (lastReturned = iterator.next()); } /** * Removes the node from this node's borrowers. */ @Override public void remove() { if (lastReturned == null) { throw new NoSuchElementException( &quot;There is no current element to remove.&quot;); } final long weight = Node.this.getWeightTo(lastReturned); iterator.remove(); lastReturned.in.remove(Node.this); lastReturned = null; if (ownerGraph != null) { ownerGraph.edgeAmount--; ownerGraph.flow -= weight; } } } /** * Returns the iterable over this node's lenders. */ private class ParentIterable implements Iterable&lt;Node&gt; { /** * Returns the iterator over this node's lenders. * * @return the iterator over this node's lenders. */ @Override public Iterator&lt;Node&gt; iterator() { return new ParentIterator(); } } /** * This class implements the iterator over this node's lenders. */ private class ParentIterator implements Iterator&lt;Node&gt; { /** * The actual iterator. */ private Iterator&lt;Node&gt; iterator = Node.this.in.keySet().iterator(); /** * The node last returned. */ private Node lastReturned; /** * Return &lt;code&gt;true&lt;/code&gt; if this iterator has more nodes * to iterate. * * @return &lt;code&gt;true&lt;/code&gt; if this iterator has more nodes to * iterate. */ @Override public boolean hasNext() { return iterator.hasNext(); } /** * Returns the next node or throws * &lt;code&gt;NoSuchElementException&lt;/code&gt; if there is no more * nodes. * * @return the next element. */ @Override public Node next() { return (lastReturned = iterator.next()); } /** * Removes this lender from this node's lender list. */ @Override public void remove() { if (lastReturned == null) { throw new NoSuchElementException( &quot;There is no current element to remove.&quot;); } final long weight = lastReturned.getWeightTo(Node.this); iterator.remove(); lastReturned.out.remove(Node.this); lastReturned = null; if (ownerGraph != null) { ownerGraph.edgeAmount--; ownerGraph.flow -= weight; } } } private void checkBorrowerExists(Node borrower) { if (!out.containsKey(borrower)) { throw new IllegalArgumentException( &quot;No arc (&quot; + this + &quot;, &quot; + borrower + &quot;).&quot;); } } private void checkWeightDelta(final Node borrower, final long weightDelta) { if (out.get(borrower) + weightDelta &lt; 0L) { throw new IllegalArgumentException( &quot;The weight delta (&quot; + weightDelta + &quot;) exceeds the arc weight (&quot; + out.get(borrower) + &quot;).&quot;); } } } </code></pre> <p><strong><code>net.coderodde.loan.model.Graph</code>:</strong></p> <pre><code>package net.coderodde.loan.model; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.Objects; /** * This class models a loan graph. * * @author coderodde * @version 1.6 */ public class Graph implements Iterable&lt;Node&gt; { /** * This map maps name of the nodes to respective node objects. */ private final Map&lt;String, Node&gt; nodeMap = new HashMap&lt;&gt;(); /** * This list contains all the nodes currently stored in this graph. */ private final List&lt;Node&gt; nodeList = new ArrayList&lt;&gt;(); /** * This variable caches the amount of edges in this graph. */ protected int edgeAmount; /** * This variable caches the total flow of this graph * (sum of edge weights). */ protected long flow; /** * Constructs an empty graph. */ public Graph() {} /** * Constructs a graph with the same amount of nodes as in * &lt;code&gt;copy&lt;/code&gt; with the same node names. Edges are copied as well, * and their respective arc weights are set correspondingly. * * @param copy the graph to copy. */ public Graph(Graph copy) { Map&lt;Node, Node&gt; map = new HashMap&lt;&gt;(nodeList.size()); for (Node node : copy) { Node newNode = new Node(node); map.put(node, newNode); add(newNode); } for (Node node : copy) { Node tail = map.get(node); for (Node borrower : node) { Node head = map.get(borrower); tail.connectToBorrower(head); tail.setWeightTo(head, node.getWeightTo(borrower)); } } this.edgeAmount = copy.edgeAmount; } public Graph copyWithoutArcs() { Graph result = new Graph(); for (Node node : this) { result.add(new Node(node)); } return result; } @Override public String toString() { return &quot;[&quot; + nodeList.size() + &quot; nodes, &quot; + edgeAmount + &quot; edges, &quot; + flow + &quot; flow]&quot;; } public String toDetailedString() { StringBuilder stringBuilder = new StringBuilder(); for (Node node : this) { Graph.this.toDetailedString(node, stringBuilder); } return stringBuilder.toString(); } private static void toDetailedString( Node node, StringBuilder stringBuilder) { stringBuilder.append(node).append(&quot;\n&quot;); for (Node child : node) { stringBuilder.append(&quot; Node &quot;) .append(child.getName()) .append(&quot;, w = &quot;) .append(node.getWeightTo(child)) .append(&quot;\n&quot;); } } /** * Adds a node to this graph if not already in this graph. * * @param node the node to add. */ public void add(Node node) { Objects.requireNonNull(node, &quot;The input node is null.&quot;); if (node.ownerGraph != this &amp;&amp; node.ownerGraph != null) { throw new IllegalArgumentException( &quot;The input node belongs to some another graph.&quot;); } if (nodeMap.containsKey(node.getName())) { // Already in this graph. return; } node.clear(); node.ownerGraph = this; nodeMap.put(node.getName(), node); nodeList.add(node); } /** * Checks whether a node is included in this graph. * * @param node the node to query. * @return &lt;code&gt;true&lt;/code&gt; if this graph contains the query node; * &lt;code&gt;false&lt;/code&gt; otherwise. */ public boolean contains(Node node) { Objects.requireNonNull(node, &quot;The input node is null.&quot;); if (node.ownerGraph != this) { return false; } return nodeMap.containsKey(node.getName()); } /** * Returns a node with index &lt;code&gt;index&lt;/code&gt;. * * @param index the node index. * @return the node at index &lt;code&gt;index&lt;/code&gt;. */ public Node get(int index) { return nodeList.get(index); } /** * Returns a node with name &lt;code&gt;name&lt;/code&gt;. * * @param name the name of the query node. * @return the node with name &lt;code&gt;name&lt;/code&gt;; &lt;code&gt;null&lt;/code&gt; * otherwise. */ public Node get(String name) { return nodeMap.get(name); } /** * Removes a node from this graph if present. * * @param node the node to remove. */ public void remove(Node node) { if (node.ownerGraph != this) { throw new IllegalArgumentException( &quot;The input node does not belong to this graph.&quot;); } if (nodeMap.containsKey(node.getName())) { nodeMap.remove(node.getName()); nodeList.remove(node); node.clear(); node.ownerGraph = null; } } /** * Returns the amount of nodes in this graph. * * @return the amount of nodes in this graph. */ public int size() { return nodeList.size(); } /** * Returns the amount of edges in this graph. * * @return the amount of edges in this graph. */ public int getEdgeAmount() { return edgeAmount; } /** * Returns the total flow (sum of all edge weights) of this graph. * * @return the total flow of this graph. */ public long getTotalFlow() { return flow; } /** * Returns an iterator over this graph's nodes. * * @return an iterator over this graph's nodes. */ @Override public Iterator&lt;Node&gt; iterator() { return new NodeIterator(); } public boolean isEquivalentTo(Graph g) { if (this.size() != g.size()) { return false; } for (Node node : this) { Node tmp = g.get(node.getName()); if (tmp == null) { return false; } if (node.getEquity() != tmp.getEquity()) { return false; } } return true; } /** * This class implements the iterators over this graph's nodes. */ private class NodeIterator implements Iterator&lt;Node&gt; { /** * The actual iterator. */ private Iterator&lt;Node&gt; iterator = nodeList.iterator(); /** * The last returned node. */ private Node lastReturned; /** * Returns &lt;code&gt;true&lt;/code&gt; if and only if there is more * nodes to iterate. * * @return &lt;code&gt;true&lt;/code&gt; if and only if there is more nodes to * iterate. */ @Override public boolean hasNext() { return iterator.hasNext(); } /** * Returns the next node or throws * &lt;code&gt;NoSuchElementException&lt;/code&gt; if there is no more * nodes to iterate. * * @return the next node. */ @Override public Node next() { return (lastReturned = iterator.next()); } /** * Removes the current node from this graph. */ @Override public void remove() { if (lastReturned == null) { throw new NoSuchElementException( &quot;There is no current node to remove.&quot;); } iterator.remove(); nodeMap.remove(lastReturned.getName()); lastReturned.clear(); lastReturned = null; } } private void checkNodeBelongsToThisGraph(Node node) { if (node.ownerGraph != this) { throw new IllegalArgumentException( &quot;The input node &quot; + node + &quot; does not belong to this graph.&quot;); } } } </code></pre> <p>(This class resides <a href="https://github.com/coderodde/lgs" rel="nofollow noreferrer">in GitHub</a>.)</p> <h3>Related posts:</h3> <ol> <li><a href="https://codereview.stackexchange.com/questions/267669/loan-graph-simplification-in-java-the-recursive-dfs-for-searching-for-directed">Loan graph simplification in Java: the recursive DFS for searching for directed cycles</a></li> <li><a href="https://codereview.stackexchange.com/questions/267671/loan-graph-simplification-in-java-an-arc-minimization-algorithm">Loan graph simplification in Java: an arc minimization algorithm</a></li> </ol> <h2>Critique request</h2> <p>As always, I am eager to hear any comments from you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T08:18:27.863", "Id": "527829", "Score": "0", "body": "(How about an `interface Node` covering \"just the graph side\"?)" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T07:39:57.360", "Id": "267670", "Score": "0", "Tags": [ "java", "graph" ], "Title": "Loan graph simplification in Java: the graph data structures" }
267670
<p>In this post, I will present an interesting (to me) algorithm for reducing the number of arcs in a <a href="https://coderodde.wordpress.com/2015/07/20/minimizing-the-amount-of-bank-transactions-in-a-static-loan-graph/" rel="nofollow noreferrer">financial loan graphs</a>. (The class belongs to <a href="https://github.com/coderodde/lgs" rel="nofollow noreferrer">this GitHub repository</a>.)</p> <p><strong><code>net.coderodde.loan.model.support.CyclePurgeBypassSimplifier</code>:</strong></p> <pre><code>package net.coderodde.loan.model.support; import java.util.List; import net.coderodde.loan.model.Algorithm; import net.coderodde.loan.model.Graph; import net.coderodde.loan.model.Node; import net.coderodde.loan.model.support.Utils.Triple; /** * This class implements the cycle purge/bypass simplifier. In cycle purge * technique, we search for directed cycles, choose the minimum weight * {@code w}, subtract {@code w} from the weight of each arc in the cycle, and, * finally, remove all those arcs whose weight becomes zero. * &lt;p&gt; * In bypass technique, in order to lower the total flow, we choose two * connected arcs {@code a_1 = (n_1, n_2), a_2 = (n_2, n_3)}, then we choose * the minimum weight {@code w} of the {@code a_1} and {@code a_2}, subtract * {@code w} from both the arcs, and rearrange the arcs such that the total flow * is lowered. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 2, 2021) * @since 1.6 (Sep 2, 2021) */ public final class CyclePurgeBypassSimplifier implements Algorithm { @Override public Graph simplify(Graph g) { Graph resultGraph = new Graph(g); if (g.size() &lt; 2) { return resultGraph; } RecursiveDepthFirstSearch rdfs = new RecursiveDepthFirstSearch(); List&lt;Node&gt; cycle; while ((cycle = rdfs.findCycle(resultGraph)) != null) { resolveCycle(cycle); } Triple&lt;Node, Node, Node&gt; arcChainToBypass; while ((arcChainToBypass = findArcChain(resultGraph)) != null) { resolveArcChain(arcChainToBypass.first, arcChainToBypass.second, arcChainToBypass.third); } return resultGraph; } private static void resolveCycle(List&lt;Node&gt; cycle) { long minimumWeight = Long.MAX_VALUE; for (int i = 0; i &lt; cycle.size(); i++) { Node lender = cycle.get(i); Node borrower = cycle.get((i + 1) % cycle.size()); long arcWeight = lender.getWeightTo(borrower); minimumWeight = Math.min(minimumWeight, arcWeight); } for (int i = 0; i &lt; cycle.size(); i++) { Node lender = cycle.get(i); Node borrower = cycle.get((i + 1) % cycle.size()); long arcWeight = lender.getWeightTo(borrower); if (arcWeight == minimumWeight) { // Remove the minimum weight arc: lender.removeBorrower(borrower); } else { // Subtract 'minimumWeight' from the '(lender, borrower)' arc // weight: lender.setWeightTo(borrower, lender.getWeightTo(borrower) - minimumWeight); } } } private static Triple&lt;Node, Node, Node&gt; findArcChain(Graph graph) { for (Node root : graph) { return findArcChainImpl(root); } return null; } private static Triple&lt;Node, Node, Node&gt; findArcChainImpl(Node root) { for (Node child : root) { for (Node grandChild : child) { return new Triple&lt;&gt;(root, child, grandChild); } } return null; } private static void resolveArcChain(Node n1, Node n2, Node n3) { long weightN1N2 = n1.getWeightTo(n2); long weightN2N3 = n2.getWeightTo(n3); long minimumWeight = Math.min(weightN1N2, weightN2N3); n1.setWeightTo(n2, n1.getWeightTo(n2) - minimumWeight); n2.setWeightTo(n3, n2.getWeightTo(n3) - minimumWeight); if (n1.getWeightTo(n2) == 0L) { n1.removeBorrower(n2); } if (n2.getWeightTo(n3) == 0L) { n2.removeBorrower(n3); } if (n1.isConnectedTo(n3)) { n1.setWeightTo(n3, n1.getWeightTo(n3) + minimumWeight); } else { n1.connectToBorrower(n3); n1.setWeightTo(n3, minimumWeight); } } } </code></pre> <p>(This class resides <a href="https://github.com/coderodde/lgs" rel="nofollow noreferrer">in GitHub</a>.)</p> <h3>Related posts:</h3> <ol> <li><a href="https://codereview.stackexchange.com/questions/267669/loan-graph-simplification-in-java-the-recursive-dfs-for-searching-for-directed">Loan graph simplification in Java: the recursive DFS for searching for directed cycles</a></li> <li><a href="https://codereview.stackexchange.com/questions/267670/loan-graph-simplification-in-java-the-graph-data-structures">Loan graph simplification in Java: the graph data structures</a></li> </ol> <h2>Critique request</h2> <p>Please, tell me anything that comes to mind. ^^</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T07:45:19.740", "Id": "267671", "Score": "0", "Tags": [ "java", "algorithm", "graph" ], "Title": "Loan graph simplification in Java: an arc minimization algorithm" }
267671
<p>I've started learning Python several months ago. This code uses Google API to send URLs to Googlebot.</p> <p>I appreciate it if someone can review my code, and advice better practices in classes/method structure, sending requests and logging responses.</p> <p>How to start the program (<a href="https://github.com/drkwng/google-indexing-api" rel="nofollow noreferrer">link GiHub</a>)</p> <pre><code>import json import re import httplib2 from oauth2client.service_account import ServiceAccountCredentials class GoogleIndexationAPI: def __init__(self, key_file, urls_list): &quot;&quot;&quot; :param key_file: .json key Google API filename :param urls_list: .txt urls list filename &quot;&quot;&quot; self.key_file = key_file self.urls_list = urls_list def parse_json_key(self): &quot;&quot;&quot; Hello msg. Parses and validates JSON &quot;&quot;&quot; with open(self.key_file, 'r') as f: key_data = json.load(f) try: input(f'Please add OWNER rights in GSC resource to: {key_data[&quot;client_email&quot;]} \nand press Enter') except Exception as e: print(e, type(e)) exit() @staticmethod def get_domain(): &quot;&quot;&quot; Input URL and strips it to a domain name :return stripped_domain: &quot;&quot;&quot; domain = input('Enter domain you are going to work with: ') stripped_domain = re.sub('(https://)|(http://)|(www.)|/(.*)', '', domain) return stripped_domain @staticmethod def choose_method(): &quot;&quot;&quot; Choosing a method for Google Indexing API request :return method: method name &quot;&quot;&quot; while True: choose_msg = input('Choose one of methods (print number) and press Enter \n' '1 - URL_UPDATED\n' '2 - URL_DELETED:\n') if '1' in choose_msg: method = 'URL_UPDATED' break elif '2' in choose_msg: method = 'URL_DELETED' break else: print('Please enter correct number') print('You chose method: ', method) return method def get_urls(self): &quot;&quot;&quot; Gets URL list from a file and clean from not unique and not valid data :return final_urls: &quot;&quot;&quot; urls = [] domain = self.get_domain() try: with open(self.urls_list, 'r', encoding='utf-8') as f: for line in f: urls.append(line.strip()) # Clean not unique urs urls = list(set(urls)) # Delete urls without ^http or which don't contain our domain name for url in urls.copy(): if ('http' not in url) or (domain not in url): urls.pop(urls.index(url)) # 200 requests a day quota :( if len(urls) &gt; 200: print(f'You have a 200 request per day quota. You are trying to index {len(urls)}. ') len_answer = input(f'I will make requests only for the first 200 urls containing {domain}. ' f'Continue (YES/NO) ???\n') if 'yes' in len_answer.lower(): final_urls = urls[0:199] left_urls = urls[200:] # Write urls over quota limit in file with open('not_send_urls.txt', 'w', encoding='utf-8') as log: for item in left_urls: log.write(f'{item}\n') print(f'There are {len(left_urls)} not send to Googlebot. \n' f'Check not_send_urls.txt file in the script folder') elif 'no' in len_answer.lower(): exit() else: print('Please enter correct answer (YES / NO)') else: final_urls = urls if len(final_urls) &lt; 1: assert print('There are no urls in your file') exit() return final_urls except Exception as e: print(e, type(e)) exit() def single_request_index(self, __url, __method): &quot;&quot;&quot; Makes a request to Google Indexing API with a selected method :param __url: :param __method: :return content: &quot;&quot;&quot; api_scopes = [&quot;https://www.googleapis.com/auth/indexing&quot;] api_endpoint = &quot;https://indexing.googleapis.com/v3/urlNotifications:publish&quot; credentials = ServiceAccountCredentials.from_json_keyfile_name(self.key_file, scopes=api_scopes) try: http = credentials.authorize(httplib2.Http()) r_content = &quot;&quot;&quot;{&quot;&quot;&quot; + f&quot;'url': '{__url}', 'type': '{__method}'&quot; + &quot;&quot;&quot;}&quot;&quot;&quot; response, content = http.request(api_endpoint, method=&quot;POST&quot;, body=r_content) return content except Exception as e: print(e, type(e)) def indexation_worker(self): &quot;&quot;&quot; Run this method after class instance creating. Gets an URL list, parses JSON key file, chooses API method, then sends a request for an each URL and logs responses. &quot;&quot;&quot; self.parse_json_key() urls = self.get_urls() method = self.choose_method() with open('logs.txt', 'w', encoding='utf-8') as f: for url in urls: result = self.single_request_index(url, method) f.write(f'{result}\n') print(f'Done! We\'ve sent {len(urls)} URLs to Googlebot.\n' f'You can check responses in logs.txt') if __name__ == '__main__': g_index = GoogleIndexationAPI('cred.json', 'urls.txt') g_index.indexation_worker() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T11:47:19.033", "Id": "527836", "Score": "0", "body": "Welcome to the Code Review Community. The title should be a brief introduction into what the code does rather than your concerns about the code. Please read [How do I ask a good question](https://codereview.stackexchange.com/help/how-to-ask)." } ]
[ { "body": "<ul>\n<li>Add PEP484 type hints, such as <code>get_domain() -&gt; str</code></li>\n<li>The exception handling here:</li>\n</ul>\n<pre><code> try:\n input(f'Please add OWNER rights in GSC resource to: {key_data[&quot;client_email&quot;]} \\nand press Enter')\n\n except Exception as e:\n print(e, type(e))\n exit()\n</code></pre>\n<p>is a little odd. Do you expect for the exception to come from the fact that <code>client_email</code> is missing as a key? If so, it's best to check for that directly rather than rely on an exception. Even if you were to rely on the exception, you should narrow the caught type. Finally: this <code>input</code> doesn't look to belong in this method, and is an interaction that should appear in an area of the code dedicated to user interface.</p>\n<ul>\n<li>Your regular expression</li>\n</ul>\n<pre><code> '(https://)|(http://)|(www.)|/(.*)'\n</code></pre>\n<p>doesn't look strict enough; you should probably match on <code>^http</code> to make sure you're looking at the beginning of the string. However, I think the <code>sub()</code> is at odds with what you're asking the user. You're asking for the <em>domain</em> and not a URL, so why bother stripping off the protocol? I'd just let it fail at the network level if they give you something that isn't a domain. Better yet, rather than attempting to be clever and strip off substrings, just loop-validate that it's a valid domain by passing it to <code>socket.gethostbyname</code>.</p>\n<p>Along the same lines,</p>\n<pre><code> urls = list(set(urls))\n # Delete urls without ^http or which don't contain our domain name\n for url in urls.copy():\n if ('http' not in url) or (domain not in url):\n urls.pop(urls.index(url))\n</code></pre>\n<p>doesn't <em>actually</em> check for <code>^http</code> as you've commented, so either you need to use a regex, or use <code>startswith</code>. Consider running the urls through <code>urllib.parse.urlparse</code> and verifying that the scheme is either <code>http</code> or <code>https</code>, and that the netloc is equal to the given domain.</p>\n<p>Also, this block can be replaced with</p>\n<pre class=\"lang-py prettyprint-override\"><code>url = [u for u in set(urls)\n if u.startswith('http') and domain in u]\n</code></pre>\n<p>Consider representing the return value of <code>choose_method</code> as an enum rather than an unconstrained string.</p>\n<p>What's this? <code>&quot;&quot;&quot;{&quot;&quot;&quot;</code> You don't need a triple-quoted string for one brace. Is <code>r_content</code> supposed to be JSON? If so, you need to replace your single quotes with double quotes. You should also enclose this literal string in double quotes:</p>\n<pre><code> print(f'Done! We\\'ve sent {len(urls)} URLs to Googlebot.\\n'\n f'You can check responses in logs.txt')\n</code></pre>\n<p>so that you don't have to escape your apostrophes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-07T09:10:07.930", "Id": "530074", "Score": "0", "body": "Thank you for your answer. Very helpful" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-18T15:17:12.137", "Id": "268119", "ParentId": "267674", "Score": "0" } } ]
{ "AcceptedAnswerId": "268119", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T08:54:02.190", "Id": "267674", "Score": "1", "Tags": [ "performance", "python-3.x", "google-api" ], "Title": "Sending requests via Google Indexing API (Python)" }
267674
<p>I have User entity that has relationship to other entities(Order,Profile) When I assemble entity from dto and back I need assemble order and profile entity too.</p> <p>User entity:</p> <pre><code>@Table(name = &quot;user_info&quot;) @Entity @Getter @Setter public class User implements Serializable { private static final long serialVersionUID = 1789771068899105277L; @Id @GeneratedValue @Column(name = &quot;userId&quot;,columnDefinition = &quot;BINARY(16)&quot;) private UUID userId ; @Column(name = &quot;login&quot;, unique = true, length = 20) private String login; @Column(name = &quot;userPassword&quot;, length = 100) private String password; @Column(name = &quot;userEmail&quot;, unique = true, length = 320) private String userEmail; @OneToOne(mappedBy = &quot;user&quot;, cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false) private Profile profile; @OneToMany(mappedBy = &quot;user&quot;, cascade = CascadeType.ALL, orphanRemoval = true) private Set&lt;Role&gt; roles = new HashSet&lt;&gt;(); @OneToMany(mappedBy = &quot;user&quot;, cascade = CascadeType.ALL, orphanRemoval = true) private List&lt;Order&gt; orders = new ArrayList&lt;&gt;(); @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return Objects.equals(getUserId(), user.getUserId()); } @Override public int hashCode() { return Objects.hash(getUserId()); } @Override public String toString() { final StringBuilder sb = new StringBuilder(&quot;User{&quot;); sb.append(&quot;userId=&quot;).append(userId); sb.append(&quot;, login='&quot;).append(login).append('\''); sb.append(&quot;, password='&quot;).append(password).append('\''); sb.append(&quot;, userEmail='&quot;).append(userEmail).append('\''); sb.append('}'); return sb.toString(); } } @Override public int hashCode() { return Objects.hash(getId(), getUserAuthority()); } @Override public String toString() { final StringBuilder sb = new StringBuilder(&quot;Role{&quot;); sb.append(&quot;id=&quot;).append(id); sb.append(&quot;, userAuthority='&quot;).append(userAuthority).append('\''); sb.append(&quot;, user=&quot;).append(user); sb.append('}'); return sb.toString(); } } </code></pre> <p>For example If I need transform User entity to Dto I need assembler:</p> <pre><code>public interface Assembler &lt;E,D&gt;{ D mergeAggregateIntoDto(E entity); E mergeDtoIntoAggregate(D dto); } @Service public class UserAssembler implements Assembler&lt;User, UserDto&gt;{ @Autowired private CarDao carDao; @Override public UserDto mergeAggregateIntoDto(User entity) { UserDto userDto = new UserDto(); userDto.setUserId(entity.getUserId()); userDto.setUserEmail(entity.getUserEmail()); userDto.setLogin(entity.getLogin()); userDto.setPassword(entity.getPassword()); userDto.setProfile(mergeAggregateIntoDto(entity.getProfile())); userDto.setRoles(entity.getRoles().stream().map(this::mergeAggregateIntoDto).collect(Collectors.toSet())); userDto.setOrders(entity.getOrders().stream().map(this::mergeAggregateIntoDto).collect(Collectors.toList())); return userDto; } @Override public User mergeDtoIntoAggregate(UserDto dto) { User user = new User(); Map&lt;UUID,Car&gt; uuidCarMap = getCars(dto); Profile profile = mergeDtoIntoAggregate(dto.getProfile()); profile.setUser(user); user.setUserId(dto.getUserId()); user.setUserEmail(dto.getUserEmail()); user.setLogin(dto.getLogin()); user.setPassword(dto.getPassword()); user.setProfile(profile); user.setRoles(dto.getRoles().stream().map(roleDto-&gt;{ Role role = mergeDtoIntoAggregate(roleDto); role.setUser(user); return role; }).collect(Collectors.toSet())); user.setOrders(dto.getOrders().stream().map(orderDto -&gt; { Order order = mergeDtoIntoAggregate(orderDto); order.setUser(user); order.setCar(uuidCarMap.get(orderDto.getCarId())); return order; }).collect(Collectors.toList())); return user; } private Map&lt;UUID, Car&gt; getCars(UserDto userDto){ List&lt;UUID&gt; carIds = userDto.getOrders().stream().map(OrderDto::getCarId).collect(Collectors.toList()); List&lt;Car&gt; cars = carDao.findByIds(carIds); return cars.stream().collect(Collectors.toMap(Car::getCarId, Function.identity())); } private ProfileDto mergeAggregateIntoDto(Profile profile){ ProfileDto profileDto = new ProfileDto(); profileDto.setProfileId(profile.getProfileId()); profileDto.setUserId(profile.getUser().getUserId()); profileDto.setAccountBalance(profile.getAccountBalance()); profileDto.setUserFirstName(profile.getUserFirstName()); profileDto.setUserSurName(profile.getUserSurName()); profileDto.setUserRegistrationDate(profile.getUserRegistrationDate()); return profileDto; } private Profile mergeDtoIntoAggregate(ProfileDto profileDto){ Profile profile = new Profile(); profile.setProfileId(profileDto.getProfileId()); profile.setAccountBalance(profileDto.getAccountBalance()); profile.setUserFirstName(profileDto.getUserFirstName()); profile.setUserSurName(profileDto.getUserSurName()); profile.setUserRegistrationDate(profileDto.getUserRegistrationDate()); return profile; } private RoleDto mergeAggregateIntoDto(Role role){ RoleDto roleDto = new RoleDto(); roleDto.setId(role.getId()); roleDto.setUserAuthority(role.getUserAuthority()); roleDto.setUserId(role.getUser().getUserId()); return roleDto; } private Role mergeDtoIntoAggregate(RoleDto roleDto){ Role role = new Role(); role.setUserAuthority(roleDto.getUserAuthority()); role.setId(roleDto.getId()); return role; } private OrderDto mergeAggregateIntoDto(Order order){ OrderDto orderDto = new OrderDto(); orderDto.setOrderCost(order.getOrderCost()); orderDto.setOrderDate(order.getOrderDate()); orderDto.setOrderId(order.getOrderId()); orderDto.setUserAddress(order.getUserAddress()); orderDto.setUserDestination(order.getUserDestination()); orderDto.setUserId(order.getUser().getUserId()); orderDto.setCarId(order.getCar().getCarId()); return orderDto; } private Order mergeDtoIntoAggregate(OrderDto orderDto){ Order order = new Order(); order.setOrderId(orderDto.getOrderId()); order.setOrderCost(orderDto.getOrderCost()); order.setUserAddress(orderDto.getUserAddress()); order.setUserDestination(orderDto.getUserDestination()); order.setOrderDate(orderDto.getOrderDate()); return order; } } </code></pre> <p>So I used dao in assembler and I want to know can I do that? Thanks.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T01:19:01.763", "Id": "527870", "Score": "0", "body": "This question actually reads like it should belong to stackoverflow rather than codereview." } ]
[ { "body": "<h3>Entity Relationships</h3>\n<p>First you could draw the ER diagram to visualize entity-relations.\nAn UML class-diagram for <code>Order</code> could do, like this:</p>\n<pre><code>,----------------.\n|Order |\n|----------------|\n|customer: User |\n|orderedAt : Date|\n|items: Car[] |\n`----------------'\n</code></pre>\n<p>Relations:</p>\n<ul>\n<li>an order has exactly a single customer of type <code>User</code> (is ordered by)</li>\n<li>an order is submitted at a specific date of type <code>Date</code> (is ordered at)</li>\n<li>an order can have zero, one or many items of type <code>Car</code> (has order line items)</li>\n</ul>\n<h3>Class Design</h3>\n<p>A valid order must at least fulfill the two <em>is</em>-relationships.</p>\n<pre class=\"lang-java prettyprint-override\"><code>class Order {\n final Date orderedAt;\n final User customer;\n final List&lt;Car&gt; lineItems = new ArrayList&lt;Car&gt;();\n\n public Order(User customer, Date orderedAt) {\n this.orderedAt = orderedAt;\n this.customer = customer;\n }\n\n public Order(User customer) {\n this(customer, new Date()); // default: ordered today\n }\n\n public Address getInvoiceAddress() {\n return this.customer.getUserAddress(); // delegate to customer (user)\n }\n\n public Address getDeliveryAddress() {\n return this.customer.getDestinationAddress(); // delegate to customer (user)\n }\n\n public void addItem(Car item) {\n this.lineItems.add(item);\n }\n}\n</code></pre>\n<p>This shows, that you can simply construct an order by passing a <code>User</code> object. The other attributes (e.g. addresses) can be derived from the customer or user (delegation).</p>\n<h3>Mapping: from DTO to Entity and vice-versa</h3>\n<p>For this <em>mapping</em> there are plenty of <a href=\"https://www.baeldung.com/java-performance-mapping-frameworks\" rel=\"nofollow noreferrer\">mapping frameworks</a> like <em>MapStruct</em>, <em>Dozer</em> etc.</p>\n<p>You can also implement the <a href=\"https://en.wikipedia.org/wiki/Adapter_pattern#Java\" rel=\"nofollow noreferrer\">Adapter Pattern</a> yourself, which fits pretty well here.</p>\n<h3>Hibernate: is an OR-mapper already!</h3>\n<p><em>Hiberernate</em> is often described as <strong>object-relational mapper</strong> (OR-mapper).</p>\n<p>Because it maps from object-oriented structures (expressed in Java classes) to relational data structures (expressed in database tables) and back.</p>\n<p>The fact, that you are using the JPA-annotations <code>@Entity</code> and <code>@Table</code> on the class describes exactly this mapping.</p>\n<p>When properly using <em>Hibernate</em> and <em>JPA</em> (and their annotations), then you don't need further mapping frameworks or assembly-services.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T10:20:26.453", "Id": "267706", "ParentId": "267675", "Score": "1" } } ]
{ "AcceptedAnswerId": "267706", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T09:23:34.153", "Id": "267675", "Score": "2", "Tags": [ "java", "converting", "repository", "hibernate", "dto" ], "Title": "Is it good way to user dao when assembling dto to entity or not?" }
267675
<p>I recently got fascinated by the world of micro controllers, and chose to do a simple clock project to see what is what. First attempt I used .Net nanoframework since I'm a C# coder by day, but I haven't been able to figure out how to make it execute fast enough.</p> <p>I ported my code to C++ and used PlatformIO to build and deploy. It works and I completely eliminated the flickering problem I had, but as I haven't used C for over a decade and never really sunk my teeth into C++, <strong>I could really use some input on best practices</strong> and similar.</p> <p>As my project grows I'll need to put my classes into separate .hpp files (Google suggests C++ continues C's tradition of putting the interface in a header file and the implementation in a .cpp file -- I am a little bit miffed VSCode doesn't offer me this simple refactoring, so I feel I'm missing something obvious). But apart from that, what else am I missing?</p> <p>Enums felt a bit off to me. In C# I'd do a <code>myEnum++</code>. Porting <code>foreach</code> caused me some headache. I found <code>std::for_each()</code> but in the end I decided <code>for</code>'s syntax was actually more readable. My <code>std::array</code> initialization is probably also a bit wonky.</p> <p>To run this in its full glory: an ESP32 controller is required, a TI CD74HC4511E BCD decoder and a LiteOn LTC-2723Y 4 digit 7 segment display. Probably good to include seven resistors for good measure.</p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;stdio.h&gt; #include &quot;freertos/FreeRTOS.h&quot; #include &quot;freertos/task.h&quot; #include &quot;esp_system.h&quot; #include &quot;esp_spi_flash.h&quot; #include &quot;driver/gpio.h&quot; #include &lt;array&gt; #include &lt;algorithm&gt; extern &quot;C&quot; { void app_main(void); } // Outputs a 4-bit value to a BCD decoder class BCDWriter { public: BCDWriter(gpio_num_t d0, gpio_num_t d1, gpio_num_t d2, gpio_num_t d3) { _bits = {d0, d1, d2, d3}; for (auto pin = _bits.begin(); pin != _bits.end(); pin++) { gpio_pad_select_gpio(*pin); gpio_set_direction(*pin, GPIO_MODE_OUTPUT); } } void Write(short value) { for (auto pin = _bits.begin(); pin != _bits.end(); pin++) { gpio_set_level(*pin, (value &amp; 1) &gt; 0 ? 1 : 0); value &gt;&gt;= 1; } } private: std::array&lt;gpio_num_t, 4&gt; _bits; }; // Controls a four digit 7 segment display (e.g. LiteOn LTC-2723Y) // Assumes common cathode (set digit pin low to activate that digit's display) class QuadDigitDisplay { public: enum QuadDigit { First, Second, Third, Fourth, Indicators }; QuadDigitDisplay(gpio_num_t cc1, gpio_num_t cc2, gpio_num_t cc3, gpio_num_t cc4, gpio_num_t l) { _pins = {cc1, cc2, cc3, cc4, l}; for (auto pin = _pins.begin(); pin != _pins.end(); pin++) { gpio_pad_select_gpio(*pin); gpio_set_direction(*pin, GPIO_MODE_OUTPUT); }; } void SetHigh(QuadDigit quadDigit) { gpio_set_level(_pins[quadDigit], 1); } void SetLow(QuadDigit quadDigit) { gpio_set_level(_pins[quadDigit], 0); } private: std::array&lt;gpio_num_t, 5&gt; _pins; }; // Display &quot;12:34&quot; test output on the display void app_main() { printf(&quot;Hello PlatformIO!\n&quot;); QuadDigitDisplay quadDisp(GPIO_NUM_26, GPIO_NUM_22, GPIO_NUM_18, GPIO_NUM_27, GPIO_NUM_19); BCDWriter bcd(GPIO_NUM_0, GPIO_NUM_17, GPIO_NUM_2, GPIO_NUM_5); QuadDigitDisplay::QuadDigit quadDigit = QuadDigitDisplay::QuadDigit::First; while (true) { uint8_t number = quadDigit == QuadDigitDisplay::QuadDigit::Indicators ? (uint8_t)2 : (uint8_t)quadDigit; bcd.Write(number); quadDisp.SetLow(quadDigit); vTaskDelay(5 / portTICK_PERIOD_MS); quadDisp.SetHigh(quadDigit); if (quadDigit == QuadDigitDisplay::QuadDigit::Indicators) { quadDigit = QuadDigitDisplay::QuadDigit::First; } else { quadDigit = QuadDigitDisplay::QuadDigit(quadDigit + 1); } } } </code></pre>
[]
[ { "body": "<h1>Make <code>class QuadDigitDisplay</code> do what it says</h1>\n<p>The <code>QuadDigitDisplay</code> class doesn't actually handle displaying four digits, it only sets the pins that enable each digit. It would be nice if this class actually handled everything necessary to drive the quad digit display.</p>\n<p>Ideally, your main function looks like this:</p>\n<pre><code>void app_main()\n{\n QuadDigitDisplay quadDisp(GPIO_NUM_26, ...);\n\n // Display 11:11, 22:22 and so on in a loop\n while (true) {\n for (int i = 0; i &lt; 10; i++)\n quadDisp.setDigits({i, i, i, i});\n vTaskDelay(1000 / portTICK_PERIOD_MS);\n }\n }\n}\n</code></pre>\n<p>The <code>QuadDigitDisplay</code> class should create a new task in its constructor which takes care of displaying the digits. So it should look something like:</p>\n<pre><code>class QuadDigitDisplay\n{\npublic:\n QuadDigitDisplay(gpio_num_t cc1, ...): _pins{cc1, ...}, _bcd{d0, ...} {\n // Set pins to output\n for (auto pin: _pins) {\n gpio_pad_select_gpio(pin);\n gpio_set_direction(pin, GPIO_MODE_OUTPUT);\n };\n\n // Create the display task\n xTaskCreate(DisplayDigits, &quot;display digits&quot;, 100, this, 1, &amp;_task);\n }\n\n ~QuadDigitDisplay() {\n // Stop the display task\n vTaskDelete(_task);\n\n // Set pins to input\n for (auto pin: _pins) {\n gpio_set_direction(pin, GPIO_MODE_INPUT);\n };\n }\n\n void SetDigits(const std::array&lt;int, 4&gt; &amp;digits) {\n _digits = digits;\n }\n\nprivate:\n static void DisplayDigits(void *arg) {\n QuadDigitDisplay *self = arg;\n\n while (true) {\n for (auto digit = 0; digit &lt; 4; ++digit) {\n self-&gt;_bcd.Write(self-&gt;_digits[digit]);\n gpio_set_level(self-&gt;_pins[digit], 0);\n vTaskDelay(5 / portTICK_PERIOD_MS);\n gpio_set_level(self-&gt;_pins[digit], 1);\n }\n }\n }\n\n TaskHandle_t _task{};\n std::array&lt;int, 4&gt; _digits;\n std::array&lt;gpio_num_t, 5&gt; _pins;\n BCDWriter _bcd;\n};\n</code></pre>\n<p>You could move the original functionality of <code>QuadDigitDisplay</code> into a new class with a name that better describes what it does, perhaps <code>DigitSelector</code>. Then you can use that class inside <code>QuadDigitDisplay</code> to abstract away the digit selection, just like it uses <code>BCDWriter</code>.</p>\n<h1>Consider removing the <code>enum</code></h1>\n<p>An enum whose values are mostly just <code>ONE</code>, <code>TWO</code>, <code>THREE</code> or <code>FIRST</code>, <code>SECOND</code>, <code>THIRD</code> is not very useful. Just use a regular integer for this, they are great for counting! Also consider using a separate variable to hold the pin number for the indicators, as its purpose is really different from those of the digits themselves.</p>\n<h1>Use range-for</h1>\n<blockquote>\n<p>Porting foreach caused me some headache. I found <code>std::for_each()</code> but in the end I decided for's syntax was actually more readable.</p>\n</blockquote>\n<p>Since C++11 you can do &quot;foreach&quot; with a regular <code>for</code> statement, like I already showed in the code above. This is called a <a href=\"https://en.cppreference.com/w/cpp/language/range-for\" rel=\"nofollow noreferrer\">range-based for loop</a>, and you use it like so:</p>\n<pre><code>std::array&lt;gpu_num_t, 5&gt; _pins;\n...\nfor (auto pin: _pins) {\n gpio_pad_select_gpio(pin);\n gpio_set_direction(pin, GPIO_MODE_OUTPUT);\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T13:26:33.057", "Id": "527840", "Score": "0", "body": "For me the enum is a constraint. Note that it contains a member called \"Indicator\". It isn't just a number. Ideally I would want to say \"initialize to the first member of my enum\" and ask \"is the current value equal to the last member of the enum?\". Of course an int would work, but there are only five valid numbers. It would be neat if the language/compiler would help me guard this automatically. In Pascal I'd use Low() and High() (with a set) IIRC." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T13:27:16.260", "Id": "527841", "Score": "0", "body": "I love the for btw. Much better. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T13:32:08.550", "Id": "527842", "Score": "0", "body": "Setting pins to input in the destructor -- is that to help the board function a bit better when it is being programmed? I've experienced some problems with the nano framework as I've been forced to disconnect the ground pins when programming my board using USB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T20:27:13.337", "Id": "527855", "Score": "1", "body": "It's good practice in general to set the pins to a high impedance mode when you are no longer needing them, and if you can choose whether a pin has a pull-up or pull-down resister, set it to the one that causes the device to go idle. It might not be relevant though if your program runs in an infinite loop and never quits, as the destructors are then never called." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T12:29:54.393", "Id": "267682", "ParentId": "267679", "Score": "4" } }, { "body": "<p>Here are some things that may help you improve your program.</p>\n<h2>Prefer modern initializers for constructors</h2>\n<p>The constructors can both be slightly rewritten to use a more modern style:</p>\n<pre><code>BCDWriter(gpio_num_t d0, gpio_num_t d1, gpio_num_t d2, gpio_num_t d3)\n: _bits{d0, d1, d2, d3}\n{ /* the rest of the constructor */ }\n</code></pre>\n<h2>Use &quot;range <code>for</code>&quot; and simplify your code</h2>\n<p>The code includes a number of lines like this:</p>\n<pre><code>for (auto pin = _bits.begin(); pin != _bits.end(); pin++)\n</code></pre>\n<p>The much simpler way to express that in modern C++ is this:</p>\n<pre><code>for (auto pin : _bits)\n</code></pre>\n<h2>Use logical expressions logically</h2>\n<p>The code for <code>Write</code> contains this line:</p>\n<pre><code>gpio_set_level(*pin, (value &amp; 1) &gt; 0 ? 1 : 0);\n</code></pre>\n<p>This could be much, much simpler:</p>\n<pre><code>gpio_set_level(pin, value &amp; 1);\n</code></pre>\n<h2>Rethink the interface</h2>\n<p>These classes aren't really doing much except acting as placeholders for pin numbers. It would be much nicer if we could use a more user-friendly interface. I'd suggest it would make sense for the <code>QuadDigitDisplay</code> to contain both the cathodes and the digits and the currently displayed digit. Then it could have a method <code>diplay</code> which would take the digit and the value as arguments. With such a class, we could rewrite <code>app_main</code>:</p>\n<pre><code>void app_main()\n{\n printf(&quot;Hello PlatformIO!\\n&quot;);\n QuadDigitDisplay quadDisp({GPIO_NUM_26, GPIO_NUM_22, GPIO_NUM_18, GPIO_NUM_27, GPIO_NUM_19}, {GPIO_NUM_0, GPIO_NUM_17, GPIO_NUM_2, GPIO_NUM_5});\n std::array&lt;short, 5&gt; values{0, 1, 2, 3, 2 /* colon indicator */};\n\n while (true)\n {\n for (short i = 0; i &lt; 5; ++i) {\n quadDisp.display(i, values[i]);\n vTaskDelay(5 / portTICK_PERIOD_MS);\n }\n }\n}\n</code></pre>\n<p>The class could be written like this:</p>\n<pre><code>class QuadDigitDisplay\n{\npublic:\n QuadDigitDisplay(std::array&lt;gpio_num_t, 5&gt; cathodes, std::array&lt;gpio_num_t, 4&gt; digits)\n : cathodes{cathodes}\n , digits{digits}\n {\n for (auto pin : cathodes) {\n gpio_pad_select_gpio(pin);\n gpio_set_direction(pin, GPIO_MODE_OUTPUT);\n }\n for (auto pin : digits) {\n gpio_pad_select_gpio(pin);\n gpio_set_direction(pin, GPIO_MODE_OUTPUT);\n }\n }\n \n void display(unsigned short digit, short value) {\n // undisplay currently active digit\n gpio_set_level(cathodes[active_digit], 1);\n // set new active digit\n active_digit = digit;\n // set digit outputs\n for (auto pin : digits) {\n gpio_set_level(pin, value &amp; 1);\n value &gt;&gt;= 1;\n }\n // now display new active digit\n gpio_set_level(cathodes[active_digit], 0);\n }\n\nprivate:\n std::array&lt;gpio_num_t, 5&gt; cathodes;\n std::array&lt;gpio_num_t, 4&gt; digits;\n unsigned short active_digit = 0;\n}\n</code></pre>\n<p>Note that <code>digit</code> and <code>value</code> would both need range checking in real code. This is just a sample.</p>\n<h2>Consider further abstraction</h2>\n<p>Even as refactored above, there is some duplication. One could create a <code>GPIO_Outpin</code> class that would handle the setup, store the pin number and provide an <code>operator=</code> to set the value of the pin.</p>\n<p>Here's how that might look:</p>\n<pre><code>class GPIO_Outpin {\npublic:\n GPIO_Outpin(gpio_num_t pin) : pin{pin} {\n gpio_pad_select_gpio(pin);\n gpio_set_direction(pin, GPIO_MODE_OUTPUT);\n }\n void operator=(bool value) {\n gpio_set_level(pin, value);\n }\nprivate:\n gpio_num_t pin; \n};\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T15:13:26.253", "Id": "267688", "ParentId": "267679", "Score": "4" } } ]
{ "AcceptedAnswerId": "267682", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T09:56:30.090", "Id": "267679", "Score": "4", "Tags": [ "c++", "embedded" ], "Title": "Clock display controlled by esp32" }
267679
<p>Any sequence of characters starting with a non-whitespace character and ending with any of the following is considered to be a sentence by this program :-</p> <ol> <li>a full stop <code>'.'</code> followed by whitespace</li> <li>an exclamation mark <code>'!'</code> followed by whitespace</li> <li>a question mark <code>'?'</code> followed by whitespace</li> <li>end-of-file</li> </ol> <p>Also, any sequence of non-whitespace characters is considered to be a word by this program.</p> <hr /> <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdbool.h&gt; #include &lt;ctype.h&gt; char * get_string_from_user(void); void count_and_print_units(char *, bool); int main(void) { printf(&quot;Enter a string (EOF to stop):-\n&quot;); char * string = get_string_from_user(); count_and_print_units(string, true); count_and_print_units(string, false); free(string); return 0; } char * get_string_from_user(void) { // string is freed in main(). size_t assumed_size_of_string_array = 100; char * string = (char *) malloc(assumed_size_of_string_array); if (string == NULL) exit(EXIT_FAILURE); size_t i = 0; int c; while ((c = getchar()) != EOF) { string[i] = c; i++; if (i == assumed_size_of_string_array) { assumed_size_of_string_array *= 2; char * temp = realloc(string, assumed_size_of_string_array); if (temp == NULL) exit(EXIT_FAILURE); string = temp; } } string[i] = '\0'; size_t actual_size_of_string_array = i+1; char * temp = realloc(string, actual_size_of_string_array); if (temp == NULL) exit(EXIT_FAILURE); string = temp; return string; } void count_and_print_units(char * string, bool flag) { // If (flag == true), then 'units' means 'sentences'. Else, 'units' means 'words'. // Any sequence of characters starting with a non-whitespace character and ending with either // (1) a full stop followed by whitespace, or // (2) an exclamation mark followed by whitespace, or // (3) a question mark followed by whitespace, or // (4) End-of-file // is considered to be a sentence by this function. // Any sequence of non-whitespace characters is considered to be a word by this function. size_t assumed_number_of_units = (flag ? 10 : 100); char ** starting_addresses_of_units = (char **) malloc(assumed_number_of_units * sizeof(char *)); if (starting_addresses_of_units == NULL) exit(EXIT_FAILURE); size_t * lengths_of_units = (size_t *) calloc(assumed_number_of_units, sizeof(size_t)); if (lengths_of_units == NULL) exit(EXIT_FAILURE); size_t i = 0, j = 0; while (true) { while (isspace(string[j])) j++; if (string[j] == '\0') break; if (i == assumed_number_of_units) { assumed_number_of_units *= 2; char ** temp1 = realloc(starting_addresses_of_units, assumed_number_of_units * sizeof(char *)); if (temp1 == NULL) exit(EXIT_FAILURE); starting_addresses_of_units = temp1; size_t * temp2 = realloc(lengths_of_units, assumed_number_of_units * sizeof(size_t)); if (temp2 == NULL) exit(EXIT_FAILURE); lengths_of_units = temp2; } starting_addresses_of_units[i] = &amp;string[j]; while (string[j] != '\0') { if (flag) { if (isspace(string[j])) if ((string[j-1] == '.') || (string[j-1] == '!') || (string[j-1] == '?')) break; } else { if (isspace(string[j])) break; } (lengths_of_units[i])++; j++; } i++; } size_t actual_number_of_units = i; if (actual_number_of_units) { char ** temp1 = realloc(starting_addresses_of_units, actual_number_of_units * sizeof(char *)); if (temp1 == NULL) exit(EXIT_FAILURE); starting_addresses_of_units = temp1; size_t * temp2 = realloc(lengths_of_units, actual_number_of_units * sizeof(size_t)); if (temp2 == NULL) exit(EXIT_FAILURE); lengths_of_units = temp2; } else { free(starting_addresses_of_units); starting_addresses_of_units = NULL; free(lengths_of_units); lengths_of_units = NULL; } printf(&quot;\n\nNumber of %s = %zu\n\n&quot;, (flag ? &quot;sentences&quot; : &quot;words&quot;), i); for (size_t x = 0; x &lt; actual_number_of_units; x++) { printf(&quot;%s No. %03zu: &quot;, (flag ? &quot;Sentence&quot; : &quot;Word&quot;), x+1); for (size_t y = 0; y &lt; lengths_of_units[x]; y++) { if (starting_addresses_of_units[x][y] == '\n') putchar(' '); else putchar(starting_addresses_of_units[x][y]); } printf(&quot;\n&quot;); } free(starting_addresses_of_units); free(lengths_of_units); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T07:38:48.873", "Id": "527874", "Score": "2", "body": "Be careful when editing your code that you don't invalidate the answers, which breaks the question-and-answer nature of this site. See [What should I do when someone answers my question?](/help/someone-answers). In this case, the edit appears benign, but in general we prefer that the code isn't edited after receiving your first answer. Thanks!" } ]
[ { "body": "<p>There's no need to cast the return value from <code>malloc()</code> family of functions - in C, <code>void*</code> is convertible to any kind of object pointer without a cast.</p>\n<p>The error handling is very primitive - when allocation fails, I'd expect at least some message to <code>stderr</code> before terminating. It's a shame that we've wasted the care taken to avoid memory leak in <code>realloc()</code> - the call to <code>exit()</code> means we might as well have just written <code>foo = realloc(foo, n)</code> for what it's worth!</p>\n<p>We shouldn't need to do any allocation in the counting function anyway - and we shouldn't need to modify the input string, so accept <code>const char*</code> as argument.</p>\n<p><code>isspace(string[j])</code> is risky, because <code>char</code> may be a signed type. The functions in <code>&lt;ctype.h&gt;</code> take integers that represent values; the usual method is to cast to <code>unsigned char</code> so that promotion to <code>int</code> keeps valid characters positive.</p>\n<p>The name <code>count_and_print_units()</code> should be a clue that this function has two unrelated responsibilities. If we can separate those, then our functions become more reusable (e.g. we could do counting in a GUI program more easily).</p>\n<p>The name <code>flag</code> is very vague. A better name would be <code>count_sentences</code>.</p>\n<p>This is problematic:</p>\n<blockquote>\n<pre><code>if (isspace(string[j]))\n if ((string[j-1] == '.')\n</code></pre>\n</blockquote>\n<p>What if the first character is a space?</p>\n<p>This code block is redundant:</p>\n<blockquote>\n<pre><code>else\n{\n free(starting_addresses_of_units);\n starting_addresses_of_units = NULL;\n\n free(lengths_of_units);\n lengths_of_units = NULL;\n}\n</code></pre>\n</blockquote>\n<p>We could leave those variables as they are, and the same actions will happen later in the function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T04:02:24.460", "Id": "527871", "Score": "1", "body": "_This is problematic: `if (isspace(string[j])) if ((string[j-1] == '.')`.\nWhat if the first character is a space?_. I believe that `while (isspace(string[j])) j++;` at the beginning of the outer loop takes care of this possibility." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T07:29:46.557", "Id": "527873", "Score": "1", "body": "Yes, I missed that - it's some distance away." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T20:40:41.330", "Id": "267699", "ParentId": "267683", "Score": "2" } }, { "body": "<p>regarding:</p>\n<pre><code>char ** temp1 = realloc(starting_addresses_of_units, assumed_number_of_units * sizeof(char *));\n if (temp1 == NULL)\n exit(EXIT_FAILURE);\n</code></pre>\n<p>before exiting, pass all the allocated memory areas to <code>free()</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T21:35:41.817", "Id": "527913", "Score": "0", "body": "Why do you recommend that? `exit()` terminates the process, so all allocated memory will be released anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T22:25:29.740", "Id": "527951", "Score": "0", "body": "@TobySpeight, when you get past the 'toy' programs and enter the reliem of real time embedded programs (and/or server programs) The program ios rarely ever exited, so the programs need to cleanup after their selves. Expecting the OS to perform the cleanup for you will get you seriously burned" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T07:15:12.123", "Id": "527968", "Score": "0", "body": "You should be clearer in the answer that this is more of a general good habit then, since that concern obviously doesn't apply to this program. (Another good reason is to help keep Valgrind output uncluttered so we can easily identify genuine problems)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T16:47:10.173", "Id": "267710", "ParentId": "267683", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T13:08:54.630", "Id": "267683", "Score": "1", "Tags": [ "c" ], "Title": "Counting and printing sentences and words" }
267683
<p>I am attempting to make three-dimensional discrete cosine transformation spatial frequency components illustration. The 3D cubes is used to present the level of each coefficient. The more bright the cube, the higher value of its coefficient, and vice versa. The 3D inverse discrete cosine transformation is used here and the formula is given as below.</p> <p>The 3D inverse discrete cosine transformation <span class="math-container">$$x(n_1, n_{2}, n_{3})$$</span> of size <span class="math-container">$$N_{1} \times N_{2} \times N_{3}$$</span> is</p> <p><span class="math-container">$$x(n_{1}, n_{2}, n_{3}) = \sum_{{k_1 = 0}}^{N_1 - 1} \sum_{{k_2 = 0}}^{N_2 - 1} \sum_{{k_3 = 0}}^{N_3 - 1} \epsilon_{k_{1}} \epsilon_{k_{2}} \epsilon_{k_{3}} X(k_{1}, k_{2}, k_{3}) \times \cos({\frac {\pi}{2N_{1}} (2n_{1} + 1)k_{1}}) \times \cos({\frac {\pi}{2N_{2}} (2n_{2} + 1)k_{2}}) \times \cos({\frac {\pi}{2N_{3}} (2n_{3} + 1)k_{3}}) $$</span></p> <p>where</p> <p><span class="math-container">$$ n_{1} = 0, 1, \dots, N_{1} - 1 $$</span></p> <p><span class="math-container">$$ n_{2} = 0, 1, \dots, N_{2} - 1 $$</span></p> <p><span class="math-container">$$ n_{3} = 0, 1, \dots, N_{3} - 1 $$</span></p> <p><span class="math-container">$$ \epsilon_{k_{i}} = \begin{cases} \frac{1}{\sqrt{2}} &amp; \text{for $k_{i} = 0$} \\ 1 &amp; \text{otherwise} \end{cases} i = 1, 2, 3 $$</span></p> <p><strong>The experimental implementation</strong></p> <ul> <li><p><code>plot3dcube</code> function implementation: The function <code>plotcube</code> is from <a href="https://www.mathworks.com/matlabcentral/fileexchange/15161-plotcube" rel="nofollow noreferrer">here</a>.</p> <pre><code>function [] = plot3dcube(input_array, alpha, title_text, xlabel_text, ylabel_text, zlabel_text) for z = 1:size(input_array, 3) for y = 1:size(input_array, 2) for x = 1:size(input_array, 1) cubeColorR = input_array(x, y, z); cubeColorG = input_array(x, y, z); cubeColorB = input_array(x, y, z); plotcube([1 1 1], [x - 1 y - 1 z - 1], alpha, [cubeColorR cubeColorG cubeColorB]); end end end title(title_text); xlabel(xlabel_text); ylabel(ylabel_text); zlabel(zlabel_text); end </code></pre> </li> <li><p><code>IDCT3D.m</code>: The implementation of inverse DCT calculation.</p> <pre><code>function IDCT3DOutput=IDCT3D(X) N1=size(X,1); N2=size(X,2); N3=size(X,3); for n1=0:N1-1 for n2=0:N2-1 for n3=0:N3-1 sm=0; parfor k1=0:N1-1 for k2=0:N2-1 for k3=0:N3-1 if(k1==0) alpha1 = 1/sqrt(2); else alpha1 = 1; end if(k2==0) alpha2 = 1/sqrt(2); else alpha2 = 1; end if(k3==0) alpha3 = 1/sqrt(2); else alpha3 = 1; end sm=sm+ alpha1*alpha2*alpha3*X(k1+1,k2+1,k3+1)*... cos(pi/(2*N1)*(2*n1+1)*k1)*cos(pi/(2*N2)*(2*n2+1)*k2)*cos(pi/(2*N3)*(2*n3+1)*k3); end end end IDCT3DOutput(n1+1,n2+1,n3+1)=sm; end end end </code></pre> </li> </ul> <p>The main testing code:</p> <pre><code>sizex = 8; sizey = 8; sizez = 8; OutputFigureLocation = &quot;./Figures/&quot;; OutputCollection = cell(sizex, sizey, sizez); %%% calculation for z = 1:sizez for y = 1:sizey for x = 1:sizex Input = zeros(sizex, sizey, sizez); Input(x, y, z) = 1; Output = IDCT3D(Input); Output = (Output + 1) ./ 2; %% Adjust the range of numbers OutputCollection{x, y, z} = {Output}; fprintf('%d_%d_%d size 3D IDCT: The %d_%d_%d / %d_%d_%d block calculation has done. \n' , sizex, sizey, sizez, x, y, z, sizex, sizey, sizez); end end end %%% plot alpha = 0.3; title_text = &quot;Three-dimensional DCT spatial frequency components&quot;; xlabel_text = 'x'; ylabel_text = 'y'; zlabel_text = 'z'; for z = 1:sizez for y = 1:sizey for x = 1:sizex close all; OutputFilename = OutputFigureLocation + x + '_' + y + '_' + z + '.png'; if isfile(OutputFilename) continue; end plot3dcube(OutputCollection{x, y, z}{1}, alpha, title_text, xlabel_text, ylabel_text, zlabel_text); saveas(gcf, OutputFilename); end end end function [] = plot3dcube(input_array, alpha, title_text, xlabel_text, ylabel_text, zlabel_text) for z = 1:size(input_array, 3) for y = 1:size(input_array, 2) for x = 1:size(input_array, 1) cubeColorR = input_array(x, y, z); cubeColorG = input_array(x, y, z); cubeColorB = input_array(x, y, z); plotcube([1 1 1], [x - 1 y - 1 z - 1], alpha, [cubeColorR cubeColorG cubeColorB]); end end end title(title_text); xlabel(xlabel_text); ylabel(ylabel_text); zlabel(zlabel_text); end </code></pre> <p>The several output examples:</p> <p><a href="https://i.stack.imgur.com/lo2K5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lo2K5.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/Zg8Fg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Zg8Fg.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/Q1Ihf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q1Ihf.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/prKIe.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/prKIe.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/eCeS7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eCeS7.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/NGe1X.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NGe1X.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/au2AV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/au2AV.png" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/WbdZn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WbdZn.png" alt="enter image description here" /></a></p> <h1></h1> <p><strong>Another approach - with <a href="https://www.mathworks.com/help/matlab/ref/cellfun.html" rel="nofollow noreferrer"><code>cellfun</code> function</a></strong></p> <p>Besides using nested <code>for</code> for IDCT calculation, there is another way to simplify with <code>cellfun</code> function:</p> <pre><code>sizex = 8; sizey = 8; sizez = 8; OutputFigureLocation = &quot;./Figures/&quot;; %%% construct input blocks InputCollection = cell(sizex, sizey, sizez); for z = 1:sizez for y = 1:sizey for x = 1:sizex Input = zeros(sizex, sizey, sizez); Input(x, y, z) = 1; InputCollection{x, y, z} = Input; end end end %%% calculation OutputCollection = cell(sizex, sizey, sizez); OutputCollection = cellfun(@IDCT3D, InputCollection, 'UniformOutput', false); OutputCollection = cellfun(@myoffset, OutputCollection, 'UniformOutput', false); save(&quot;OutputCollection_&quot; + sizex + &quot;_&quot; + sizey + &quot;_&quot; + sizez + &quot;.mat&quot;, &quot;OutputCollection&quot;); %%% plot %load(&quot;OutputCollection_&quot; + sizex + &quot;_&quot; + sizey + &quot;_&quot; + sizez + &quot;.mat&quot;); alpha = 0.3; title_text = &quot;Three-dimensional DCT spatial frequency components&quot;; xlabel_text = 'x'; ylabel_text = 'y'; zlabel_text = 'z'; for z = 1:sizez for y = 1:sizey for x = 1:sizex close all; OutputFilename = OutputFigureLocation + x + '_' + y + '_' + z + '.png'; if isfile(OutputFilename) continue; end plot3dcube(OutputCollection{x, y, z}, alpha, title_text, xlabel_text, ylabel_text, zlabel_text); saveas(gcf, OutputFilename); end end end function [output_array] = myoffset(input_array) output_array = (input_array + 1) ./ 2; %% Adjust the range of numbers end function [] = plot3dcube(input_array, alpha, title_text, xlabel_text, ylabel_text, zlabel_text) for z = 1:size(input_array, 3) for y = 1:size(input_array, 2) for x = 1:size(input_array, 1) cubeColorR = input_array(x, y, z); cubeColorG = input_array(x, y, z); cubeColorB = input_array(x, y, z); plotcube([1 1 1], [x - 1 y - 1 z - 1], alpha, [cubeColorR cubeColorG cubeColorB]); end end end title(title_text); xlabel(xlabel_text); ylabel(ylabel_text); zlabel(zlabel_text); end </code></pre> <p>The syntax <code>OutputCollection = cellfun(@IDCT3D, InputCollection, 'UniformOutput', false)</code> used above is for calculating <strong>each</strong> cell in <code>InputCollection</code> with <code>IDCT3D</code> function and return the result to <code>OutputCollection</code>. However, as far as I know, there is one disadvantage which is that the intermediate status of calculation cannot be passed out. In other words, not like the <code>for</code> loop version which the saving operation can be inserted in to save the intermediate status, the object <code>OutputCollection</code> isn't updated until <code>cellfun</code> finish all the calculation. Based on this reason, I prefer to use the <code>for</code> version than the <code>cellfun</code> version. I am looking forward to some feedback, such as any other pros and cons, for the <code>for</code> loop version and the <code>cellfun</code> version.</p> <p><strong>Reference</strong></p> <ul> <li>Wikipedia - <a href="https://en.wikipedia.org/wiki/Discrete_cosine_transform" rel="nofollow noreferrer">Discrete cosine transform</a></li> <li>Malavika Bhaskaranand and Jerry D. Gibson, “Distributions of 3D DCT coefficients for video,” in Proceedings of the IEEE International Conference on Acoustics, Speech and Signal Processing, 2009.</li> <li>J. Augustin Jacob and N. Senthil Kumar, “Determining Optimal Cube for 3D-DCT Based Video Compression for Different Motion Levels,” ICTACT Journal on Image and Video Processing, Vol. 03, November 2012.</li> </ul> <p>If there is any possible improvement, please let me know.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T15:50:50.437", "Id": "527843", "Score": "1", "body": "In the equation at the top of the post, you probably meant to sum over k, not x. You also have two copies of the `plot3dcube` function. I maybe have time tonight to write a review, I see lots of opportunities for improvement, writing a review will take time! :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T00:09:04.953", "Id": "527868", "Score": "0", "body": "@Cris Luengo Thank you for letting me know the problem. The formula has been updated and it might be correct. If there is any problem, please let me know." } ]
[ { "body": "<p>Your DCT computation can be made significantly more efficient, though for these small array sizes it doesn't matter a whole lot. I'll tackle this in the 2nd part of this answer. First I'll discuss some MATLAB syntax and style improvements.</p>\n<blockquote>\n<pre><code>OutputCollection{x, y, z} = {Output};\n</code></pre>\n</blockquote>\n<p>This puts <code>Output</code> into a 1x1 cell array, and assigns this cell array into the larger cell array. You needed to retrieve your array later with <code>OutputCollection{x, y, z}{1}</code> because of this. The <code>{1}</code> is surprising, and useless. Instead, assign with either of these two syntaxes:</p>\n<pre><code>OutputCollection{x, y, z} = Output;\nOutputCollection(x, y, z) = {Output};\n</code></pre>\n<p>Either one of them assigns the array directly into one of the cells of the cell array.</p>\n<blockquote>\n<pre><code>function [] = plot3dcube(...)\n</code></pre>\n</blockquote>\n<p>It is not necessary to give <code>[]=</code> here:</p>\n<pre><code>function plot3dcube(...)\n</code></pre>\n<blockquote>\n<pre><code>cubeColorR = input_array(x, y, z);\ncubeColorG = input_array(x, y, z);\ncubeColorB = input_array(x, y, z);\nplotcube([1 1 1], [x - 1 y - 1 z - 1], alpha, [cubeColorR cubeColorG cubeColorB]);\n</code></pre>\n</blockquote>\n<p>Here you assigned the same value to three different variables. Simpler would be:</p>\n<pre><code>cubeColor = [1 1 1] * input_array(x, y, z);\nplotcube([1 1 1], [x - 1 y - 1 z - 1], alpha, cubeColor);\n</code></pre>\n<p>The MATLAB Editor highlights this line:</p>\n<blockquote>\n<pre><code>IDCT3DOutput(n1+1,n2+1,n3+1)=sm;\n</code></pre>\n</blockquote>\n<p>and notes that the variable changes size every loop iteration. This is highly inefficient. You should <strong>always</strong> <a href=\"https://www.mathworks.com/help/matlab/matlab_prog/preallocating-arrays.html\" rel=\"nofollow noreferrer\">preallocate</a>. Simply adding a line</p>\n<pre><code>IDCT3DOutput = zeros(N1,N2,N3);\n</code></pre>\n<p>at the top of the function, before the loops, significantly speeds up execution.</p>\n<p>Your loops are sorted in reverse order. When looping over an array, indexed with <code>X(k1,k2,k3)</code>, the loop over <code>k1</code> should be the inner loop, and the one over <code>k3</code> should be the outer loop. This causes the code to access the values in the array <code>X</code> in memory order, which is much faster because the cache will be used better. Likewise for the other three loops that iterate over the output array <code>IDCT3DOutput</code>. A 8x8x8 array is likely not large enough for this to matter a whole lot, but doing the same for a larger array that doesn't fit in the cache will make a big difference.</p>\n<p><code>parfor</code> should always be the outer loop. There is an overhead in distributing the work over the workers (and hopefully you have these configured as threaded, rather than separate processes as is the default), and doing so once or <code>N1 * N2 * N3</code> times makes a big difference.</p>\n<blockquote>\n<pre><code>N1=size(X,1);\nN2=size(X,2);\nN3=size(X,3);\n</code></pre>\n</blockquote>\n<p>can be more easily written as</p>\n<pre><code>[N1,N2,N3] = size(X);\n</code></pre>\n<p>Finally, try to be consistent with spacing around operators. Some assignments you don't use any spacing around the operator, and some you have spaces on both sides. I'd suggest to pick one style, and use it consistently. It's worst when there's spaces on one side of an operator only:</p>\n<blockquote>\n<pre><code>sm=sm+ alpha1 ...\n</code></pre>\n</blockquote>\n<p>is not as easy to read as</p>\n<pre><code>sm = sm + alpha1 ...\n</code></pre>\n<hr />\n<p>In this second part I want to discuss the implementation of the algorithm itself, which can be much more efficient. Let's look at the three inner loops only:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>sm=0;\nparfor k1=0:N1-1\n for k2=0:N2-1\n for k3=0:N3-1\n if(k1==0)\n alpha1 = 1/sqrt(2);\n else\n alpha1 = 1;\n end\n if(k2==0)\n alpha2 = 1/sqrt(2);\n else\n alpha2 = 1;\n end\n if(k3==0)\n alpha3 = 1/sqrt(2);\n else\n alpha3 = 1;\n end\n sm=sm+ alpha1*alpha2*alpha3*X(k1+1,k2+1,k3+1)*...\n cos(pi/(2*N1)*(2*n1+1)*k1)*cos(pi/(2*N2)*(2*n2+1)*k2)*cos(pi/(2*N3)*(2*n3+1)*k3);\n end\n end\nend\nIDCT3DOutput(n1+1,n2+1,n3+1)=sm;\n</code></pre>\n<p>You are doing a terrible amount of useless work. For example, you test <code>if(k1==0)</code> <code>N2*N3</code> times too many. For the <code>k2</code> and <code>k3</code> loops, this is a constant, so move the computation out of those loops. The same is true for the <code>cos</code> computations, which are quite expensive. This could look like this (additionally I've reversed the loop order as discussed earlier):</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>sm = 0;\nfor k3=0:N3-1\n if(k3==0)\n alpha3 = 1/sqrt(2);\n else\n alpha3 = 1;\n end\n alpha3 = alpha3 * cos(pi/(2*N3)*(2*n3+1)*k3);\n for k2=0:N2-1\n if(k2==0)\n alpha2 = 1/sqrt(2);\n else\n alpha2 = 1;\n end\n alpha2 = alpha2 * cos(pi/(2*N2)*(2*n2+1)*k2);\n for k1=0:N1-1\n if(k1==0)\n alpha1 = 1/sqrt(2);\n else\n alpha1 = 1;\n end\n alpha1 = alpha1 * cos(pi/(2*N1)*(2*n1+1)*k1);\n sm = sm + alpha1*alpha2*alpha3*X(k1+1,k2+1,k3+1);\n end\n end\nend\nIDCT3DOutput(n1+1,n2+1,n3+1) = sm;\n</code></pre>\n<p>In my test this is about a 50% reduction in time.\nBut we now sill compute <code>alpha1</code> <code>N3*N2</code> times too many, to avoid doing that we should compute all possible <code>alpha1</code> values before the loops:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>alpha1 = cos(pi/(2*N1)*(2*n1+1)*(0:N1-1));\nalpha1(1) = alpha1(1) / sqrt(2);\nalpha2 = cos(pi/(2*N2)*(2*n2+1)*(0:N2-1));\nalpha2(1) = alpha2(1) / sqrt(2);\nalpha3 = cos(pi/(2*N3)*(2*n3+1)*(0:N3-1));\nalpha3(1) = alpha3(1) / sqrt(2);\nsm = 0;\nfor k3=1:N3\n for k2=1:N2\n for k1=1:N1\n sm = sm + alpha1(k1)*alpha2(k2)*alpha3(k3)*X(k1,k2,k3);\n end\n end\nend\nIDCT3DOutput(n1+1,n2+1,n3+1) = sm;\n</code></pre>\n<p>This yields another 3.5x speed improvement. Code now also has become simpler: we can do natural loops <code>k1=1:N1</code>, and index naturally <code>X(k1,k2,k3)</code>. And it's now also much simpler to see how we can vectorize the computation. We use <a href=\"https://blogs.mathworks.com/loren/2016/10/24/matlab-arithmetic-expands-in-r2016b/\" rel=\"nofollow noreferrer\">MATLAB's implicit singleton expansion</a> here. This requires giving the arrays <code>alpha1</code>, <code>alpha2</code> and <code>alpha3</code> the right orientation:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>alpha1 = cos(pi/(2*N1)*(2*n1+1)*(0:N1-1).'); % along 1st dimension\nalpha1(1) = alpha1(1) / sqrt(2);\nalpha2 = cos(pi/(2*N2)*(2*n2+1)*(0:N2-1)); % along 2nd dimension\nalpha2(1) = alpha2(1) / sqrt(2);\nalpha3 = cos(pi/(2*N3)*(2*n3+1)*(0:N3-1));\nalpha3(1) = alpha3(1) / sqrt(2);\nalpha3 = reshape(alpha3,1,1,N3); % along 3rd dimension\nsm = ((X .* alpha1) .* alpha2) .* alpha3;\nIDCT3DOutput(n1+1,n2+1,n3+1) = sum(sm(:));\n</code></pre>\n<p>This yields yet again a 3.5x speed improvement, for a total of about 14x over the original code. And yet again, the code was simplified.</p>\n<p>When we now look at the outer loops, we again see that we can move some of these computations out of loops, which again significantly reduces the number of computations. But let's take a step back first. The DCT equation,\n<span class=\"math-container\">$$\\begin{split}\nx(n_{1}, n_{2}, n_{3}) = &amp;\\sum_{{k_1 = 0}}^{N_1 - 1} \\sum_{{k_2 = 0}}^{N_2 - 1} \\sum_{{k_3 = 0}}^{N_3 - 1} \\epsilon_{k_{1}} \\epsilon_{k_{2}} \\epsilon_{k_{3}} X(k_{1}, k_{2}, k_{3}) \\\\\n &amp; \\cos({\\frac {\\pi}{2N_{1}} (2n_{1} + 1)k_{1}}) \\\\\n &amp; \\cos({\\frac {\\pi}{2N_{2}} (2n_{2} + 1)k_{2}}) \\\\\n &amp; \\cos({\\frac {\\pi}{2N_{3}} (2n_{3} + 1)k_{3}})\n\\end{split}$$</span>\ncan be rewritten to separate out summations,\n<span class=\"math-container\">$$\\begin{split}\nx(n_{1}, n_{2}, n_{3}) =\n&amp; \\sum_{{k_1 = 0}}^{N_1 - 1} \\epsilon_{k_{1}} \\cos({\\frac {\\pi}{2N_{1}} (2n_{1} + 1)k_{1}}) \\Big[ \\\\\n&amp; \\sum_{{k_2 = 0}}^{N_2 - 1} \\epsilon_{k_{2}} \\cos({\\frac {\\pi}{2N_{2}} (2n_{2} + 1)k_{2}}) \\Big[ \\\\\n&amp; \\sum_{{k_3 = 0}}^{N_3 - 1} \\epsilon_{k_{3}} \\cos({\\frac {\\pi}{2N_{3}} (2n_{3} + 1)k_{3}}) \\Big[ X(k_{1}, k_{2}, k_{3}) \\Big] \\Big] \\Big]\n\\end{split}$$</span>\nI split the lines like this and added the big brackets to illustrate that we are applying the 1D DCT three times, on each of the axes of the image. We are basically doing:</p>\n<pre><code>out = DCT1D(in, 1);\nout = DCT1D(out, 2);\nout = DCT1D(out, 3);\n</code></pre>\n<p>(with the 2nd argument the axis over which it is applied.</p>\n<p>Let's implement this:</p>\n<pre class=\"lang-matlab prettyprint-override\"><code>function out = IDCT3D(X)\nout = IDCT1D(X, 1);\nout = IDCT1D(out, 2);\nout = IDCT1D(out, 3);\nend\n\nfunction out = IDCT1D(X, dim)\nN = size(X, dim);\nsz = ones(1,3);\nsz(dim) = N;\nindex = {':',':',':'};\nout = zeros(size(X));\nfor n = 0:N-1\n alpha = cos(pi/(2*N)*(2*n+1)*(0:N-1));\n alpha(1) = alpha(1) / sqrt(2);\n alpha = reshape(alpha, sz);\n index{dim} = n + 1;\n out(index{:}) = sum(X .* alpha, dim);\nend\nend\n</code></pre>\n<p>This gives me about 80x speedup over the previous fastest implementation, about 1200x speedup over the original one. (I hope I didn't mess up anything and the result is still correct...)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T06:03:31.903", "Id": "267720", "ParentId": "267685", "Score": "2" } } ]
{ "AcceptedAnswerId": "267720", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T13:58:33.413", "Id": "267685", "Score": "3", "Tags": [ "algorithm", "image", "matrix", "matlab", "data-visualization" ], "Title": "Three-dimensional DCT spatial frequency components illustration" }
267685
<p>I have a higher-order function to create another function given a regular expression:</p> <pre><code>export function createParser&lt;T extends { [k: string]: number }&gt;( regExp: RegExp ) { return function (content: string): T { const matchArray = [...content.matchAll(regExp)]; if (matchArray.length === 0) { throw new Error('Could not parse content!') } return Object.fromEntries( matchArray.map((match) =&gt; { const key = camelCase(match[1]); const value = Number(match[2].replace(/,/g, &quot;&quot;)); return [key, value]; }) ) as T; }; } </code></pre> <p>The returned function returns an object of type <code>{ [k: string]: number }</code>, but sometimes I know a more specific subtype should be returned when assigning the regexp, so I'm passing a generic to the higher order function to be able to type the returned value of the returned function:</p> <pre><code>type A = Record&lt;&quot;key1&quot; | &quot;key2&quot; | &quot;key3&quot;, number&gt; const parser = createParser&lt;A&gt;(/* regexp that will produce type A result */); const data = parser(/* some content to parse */); // ^ // type A </code></pre> <p>Everything works as expected, but not sure if this is the best approach.</p> <p>Any feedback in general is appreciated.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T15:35:05.943", "Id": "267689", "Score": "1", "Tags": [ "functional-programming", "typescript" ], "Title": "TypeScript generic higher-order function returned function returned type" }
267689
<p>I've implemented a custom trait on <code>std::path::Path</code> (and by extension <code>std::path::PathBuf</code>) with a method which turns the struct into a file url and a trait on <code>std::path::PathBuf</code> which constructs a PathBuf from a file url.</p> <p>Would love some feedback on the code, especially any violations of naming conventions, best practices (should I seal those traits or make something that currently isn't generic?) or unnecessary allocations, I'm pretty new to Rust.</p> <p>Also (of course) if there's some edge case in the logic I'm failing to consider please let me know!</p> <pre class="lang-rust prettyprint-override"><code>use std::error::Error; use std::fmt; use std::path::{Path, PathBuf}; use std::string::FromUtf8Error; use lazy_static::lazy_static; use regex::Regex; use urlencoding::{decode, encode}; lazy_static! { // We don't want to percent encode the colon on a Windows drive letter. static ref WINDOWS_DRIVE: Regex = Regex::new(r&quot;[a-zA-Z]:&quot;).unwrap(); static ref SEPARATOR: Regex = Regex::new(r&quot;[/\\]&quot;).unwrap(); } static FORWARD_SLASH: &amp;str = &quot;/&quot;; #[derive(Debug)] pub struct Utf8DecodeError { details: String, } impl Utf8DecodeError { fn new(msg: &amp;str) -&gt; Utf8DecodeError { Utf8DecodeError { details: msg.to_string(), } } } impl fmt::Display for Utf8DecodeError { fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result { write!(f, &quot;{}&quot;, self.details) } } impl Error for Utf8DecodeError { fn description(&amp;self) -&gt; &amp;str { &amp;self.details } } pub fn encode_file_component(path_part: &amp;str) -&gt; String { // If it's a separator char or a Windows drive return // as-is. if SEPARATOR.is_match(path_part) || WINDOWS_DRIVE.is_match(path_part) { path_part.to_owned() } else { encode(path_part).to_string() } } pub fn file_url_to_pathbuf(file_url: &amp;str) -&gt; Result&lt;PathBuf, FromUtf8Error&gt; { SEPARATOR .split(file_url) .enumerate() .map(|(i, url_piece)| { if i == 0 &amp;&amp; url_piece == &quot;file:&quot; { // File url should always be abspath Ok(String::from(FORWARD_SLASH)) } else { let dec_str = decode(url_piece)?; Ok(dec_str.into_owned()) } }) .collect() } pub trait PathFileUrlExt { fn to_file_url(&amp;self) -&gt; Result&lt;String, Utf8DecodeError&gt;; } pub trait PathFromFileUrlExt { fn from_file_url(file_url: &amp;str) -&gt; Result&lt;PathBuf, FromUtf8Error&gt;; } // NOTE: Because PathBuf implements Deref to Path, this also gets // implemented for PathBuf. impl PathFileUrlExt for Path { fn to_file_url(&amp;self) -&gt; Result&lt;String, Utf8DecodeError&gt; { let path_parts: Result&lt;PathBuf, Utf8DecodeError&gt; = self .components() .map(|part| match part.as_os_str().to_str() { Some(part) =&gt; Ok(encode_file_component(part)), None =&gt; Err(Utf8DecodeError::new(&quot;File path not UTF-8 compatible!&quot;)), }) .collect(); let parts = path_parts?; let path_str = parts .to_str() .ok_or_else(|| Utf8DecodeError::new(&quot;File path not UTF-8 compatible!&quot;))?; Ok(format!(&quot;file://{}&quot;, path_str)) } } impl PathFromFileUrlExt for PathBuf { fn from_file_url(file_url: &amp;str) -&gt; Result&lt;PathBuf, FromUtf8Error&gt; { file_url_to_pathbuf(file_url) } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T18:16:58.033", "Id": "267694", "Score": "1", "Tags": [ "rust", "encoding" ], "Title": "Convert PathBuf to file URL in Rust" }
267694
<p>Given a vector <code>&lt;Vec&lt;usize&gt;&gt;</code> of indices indicating where to split a string as follows:</p> <pre><code>println!(&quot;{:?}&quot;, idxs); [2, 1, 6, 2, 5, 2, 2, 1] </code></pre> <p>And the following string (The Series column in the <a href="https://download.bls.gov/pub/time.series/jt/jt.txt" rel="nofollow noreferrer">Bureau of Labor Statistics'</a> data):</p> <p><code>let mut sstr = &quot;JTS000000000000000JOR&quot;;</code></p> <p>I wrote a recursive function to split the string as follows:</p> <pre><code>fn split_str(cur: &amp;str, rest: &amp;str, idxs: Vec&lt;usize&gt;, mut res: Vec&lt;String&gt;) -&gt; Vec&lt;String&gt; { if idxs.len() &gt; 1 { //println!(&quot;cur: {} idx: {} rest: {}&quot;, cur, *idxs.first().unwrap(), rest); res.push(cur.to_owned()); let (cur, rest) = rest.split_at(*idxs.first().unwrap()); split_str(cur, rest, idxs[1..].to_vec(), res) } else { res.push(cur.to_string()); //println!(&quot;{}&quot;, rest); res[1..].to_vec() } } </code></pre> <p>The method is run as follows:</p> <pre><code>let r = split_str(&amp;sstr[0..idxs[0]], &amp;sstr[(idxs[1]+1)..], idxs[1..].to_vec(), vec![&quot;&quot;.to_string()]); </code></pre> <p>which correctly returns</p> <pre><code>[&quot;JT&quot;, &quot;S&quot;, &quot;000000&quot;, &quot;00&quot;, &quot;00000&quot;, &quot;00&quot;, &quot;JO&quot;, &quot;R&quot;] </code></pre> <p>How can I optimize this code? I'm used to Scala and it feels like I'm forcing Rust into a pattern it wasn't designed for, but I don't want to revert to traditional loops.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T11:42:47.427", "Id": "527882", "Score": "0", "body": "I see you edited the code slightly from the version on SO, but it still [doesn't perform as advertised](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a827bfd48051c620550d3a20452103cc)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T15:50:12.853", "Id": "527907", "Score": "1", "body": "@trentcl: Thanks for pointing out the error and showing me Rust Playground. I have updated my code and linked to a working copy on that site." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T16:03:26.023", "Id": "527908", "Score": "2", "body": "Welcome to Code Review! Incorporating advice from an answer into the question violates the question-and-answer nature of this site. You could post improved code as a new question, as an answer, or as a link to an external site - as described in [I improved my code based on the reviews. What next?](/help/someone-answers#help-post-body). I have rolled back the edit, so the answers make sense again." } ]
[ { "body": "<p>In Rust, we tend to make use of iterators rather than recursion. Map, filter, reduce, etc. are your friends, especially if you don't like loops. Also, when working with parameters, slices tend to be preferable over Vecs (though returning is usually a concrete collection). Another thing is that we tend to use method chaining where possible (acting as a poor man's function composition).</p>\n<p>Keeping the general method of splitting the string, I've refactored the given method to the following:</p>\n<pre class=\"lang-rust prettyprint-override\"><code>pub fn split_str(string: &amp;str, places: &amp;[usize]) -&gt; Vec&lt;String&gt; {\n let (mut res, rem) = places\n .iter()\n .fold((Vec::&lt;String&gt;::new(), string), |(res, rem), place| {\n let (cur, rem) = rem.split_at(place);\n res.push(String::from(cur));\n (res, rem)\n });\n res.push(String::from(cur));\n res\n}\n</code></pre>\n<p>Hope this was helpful!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T21:01:04.763", "Id": "527858", "Score": "0", "body": "Thanks! This is very helpful. As for your comment about a general preference for slices, is that due to performance or style preference or something else?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T21:08:15.810", "Id": "527860", "Score": "0", "body": "I'm getting a scope error on `cur`. By the time processing gets to `res.push(String::from(cur));`, `cur` is out of scope. I guess the trick is to initiate it above?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T21:09:49.833", "Id": "527861", "Score": "0", "body": "... and `rem.split_at(place);` needs to be `rem.split_at(*place);`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T19:54:17.563", "Id": "267698", "ParentId": "267696", "Score": "2" } }, { "body": "<p>I ended up rewriting the function with <code>fold</code> as follows:</p>\n<pre><code>fn str_splits(s: String, is: &amp;[usize]) -&gt; Vec&lt;String&gt; {\n let (first, mut rest) = s.split_at(is[0]); \n let cols = is.iter().skip(1).fold(vec![first.to_string()], |mut v, nxt| {\n //println!(&quot;Current vector: {:?} Next: {}, Remaining String: {}&quot;, v, nxt, rest);\n let (cur, rst) = &amp;rest.split_at(*nxt);\n rest = rst; \n v.push(cur.to_string());\n v});\n cols\n}\n</code></pre>\n<p>Given the following slice and string</p>\n<pre><code>let cs = str_splits(&amp;[2, 1, 6, 2, 5, 2, 2, 1]\nlet s = &quot;JTS000000000000000JOR&quot;.to_string();\n</code></pre>\n<p>The function can be run as follows:</p>\n<pre><code>let r = str_splits(s, cs);\n</code></pre>\n<p>Which correctly returns</p>\n<p><code>[&quot;JT&quot;, &quot;S&quot;, &quot;000000&quot;, &quot;00&quot;, &quot;00000&quot;, &quot;00&quot;, &quot;JO&quot;, &quot;R&quot;]</code></p>\n<p>A <a href=\"https://play.rust-lang.org/?version=stable&amp;mode=debug&amp;edition=2018&amp;gist=3ed3cee4595b23b552bb70714881b1b2\" rel=\"nofollow noreferrer\">demonstration can be found here.</a></p>\n<p>I believe this version is easier to grasp and more in line with Rust style. Fold has also proved to be fast in other cases.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T23:31:22.317", "Id": "527867", "Score": "1", "body": "Could you perhaps explain more about why this is better than the original code? Please remember that this is code *review*, not code alternatives. Please start by noting where the question code can be improved. Then illustrate that improvement with code in the answer (or not, code is not actually required in an answer, although strongly recommended)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T22:59:08.590", "Id": "267700", "ParentId": "267696", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-04T18:44:52.730", "Id": "267696", "Score": "3", "Tags": [ "functional-programming", "rust" ], "Title": "Split string at given positions" }
267696
<p>So I am still learning a lot of things and wanted to see if someone wanted to look over my code and tell me if there are ways to improve things and maybe make the code a little cleaner.</p> <p><strong>Here is what the piece of code does</strong>:</p> <ol> <li>When a user scrolls to the middle of the page, it will open a modal and set a cookie for 30 days.</li> </ol> <p><strong>Here is the full code</strong>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(document).ready(function () { const element = document.querySelector('.modalElement'); if (element) { window.addEventListener("scroll", function() { if (is_in_viewport(element)) { trigger_modal(element); } }); } /** * Trigger modal * * @param element */ function trigger_modal(element) { // Check if correct modal_target gets pulled &amp; user is logged in const modal_target = element.getAttribute('data-target'); const user_logged_in = document.body.classList.contains('logged-in'); // If user logged in, show modal unconditionally if (user_logged_in) { $(modal_target).modal('toggle'); } else { // This grabs the correct stored cookie. let stored_cookie = get_cookie('acceptedPardot' + modal_target + 'Cookie'); // If the cookie doesn't exist, set the cookie and allow for opening the modal if (!stored_cookie) { set_cookie('acceptedPardot' + modal_target + 'Cookie', 'true', 30); $(modal_target).modal('toggle'); } } } /** * Set cookie * * @param name * @param value * @param days_active * @return {string} */ function set_cookie(name, value, days_active) { let cookie = name + "=" + encodeURIComponent(value); if (typeof days_active === "number") { cookie += "; max-age=" + (days_active * 24 * 60 * 60) + "; path=/"; document.cookie = cookie; } } /** * Get cookie * * @param name * @return {string|null} */ function get_cookie(name) { const cookie_array = document.cookie.split(";"); for (let i = 0; i &lt; cookie_array.length; i++) { const cookie_pair = cookie_array[i].split("="); if (name === cookie_pair[0].trim()) { return decodeURIComponent(cookie_pair[1]); } } return null; } /** * Check if element is in viewport * * @param element * @return {boolean} */ function is_in_viewport(element) { const rect = element.getBoundingClientRect(); return ( rect.top &gt;= 0 &amp;&amp; rect.left &gt;= 0 &amp;&amp; rect.bottom &lt;= (window.innerHeight || document.documentElement.clientHeight) &amp;&amp; rect.right &lt;= (window.innerWidth || document.documentElement.clientWidth) ); } });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;div class="modalElement" data-toggle="modal" data-target="#modal-&lt;?= $id ?&gt;"&gt;&lt;/div&gt; &lt;div class="modal fade" id="modal-&lt;?= $id ?&gt;" tabindex="-1" role="dialog" aria-hidden="true"&gt; &lt;div class="modal-dialog modal-dialog-centered"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h5 class="modal-title" id="exampleModalLabel"&gt;Pardot Form&lt;/h5&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;#10005;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;form&gt; &lt;div class="form-group"&gt; &lt;label for="formGroupExampleInput"&gt;Example label&lt;/label&gt; &lt;input type="text" class="form-control" id="formGroupExampleInput" placeholder="Example input placeholder"&gt; &lt;/div&gt; &lt;div class="form-group"&gt; &lt;label for="formGroupExampleInput2"&gt;Another label&lt;/label&gt; &lt;input type="text" class="form-control" id="formGroupExampleInput2" placeholder="Another input placeholder"&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-secondary" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt; &lt;p&gt;Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.&lt;/p&gt;</code></pre> </div> </div> </p> <p>The script runs but of course it won't set the cookie since there is server-side scripting.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T02:27:05.930", "Id": "267701", "Score": "0", "Tags": [ "javascript", "jquery", "html" ], "Title": "Set cookie once modal opens on page scroll" }
267701
<p>Please be gentle with me-- I just began learning to code a few weeks ago as a hobby in order to support my other hobby of learning general relativity, so this is the first bit of code I've ever written. I would love to keep getting better at coding, though, so any feedback on ways to improve my code would be much appreciated.</p> <p>What this code does is take as input the number of dimensions of a manifold, the coordinate labels being used, and the components of a metric, and outputs the non-zero components of the metric (exactly what was input, it just looks prettier), and also of the inverse metric, derivatives of the metric, the Christoffel symbols, the derivatives of the Christoffel symbols, the Riemann curvature tensor, the Ricci curvature tensor, the Ricci scalar, and the Einstein tensor (with 2 covariant indices, but also with 1 contravariant and 1 covariant).</p> <p>For those of you who run the code, here are some useful tips on the user inputs (I will also include an example at the bottom): When inputting metric components, you can use '^' instead of '**' for exponents, and when multiplying a number by a symbol or something in parentheses, you don't need to include a '*'. Feel free to include undefined functions- just make sure you include its arguments if you want it to be differentiated correctly (e.g. if you want a function that will have a non-zero derivative of x, then type 'f(x)' in your expression instead of just 'f'). Also feel free to use greek letters (spelled out in English) when inputting coordinate labels and/or functions in your metric components.</p> <p>Here is the code:</p> <pre><code>from sympy import * from dataclasses import dataclass from IPython.display import display as Idisplay from IPython.display import Math greek = ['alpha', 'beta', 'gamma', 'Gamma', 'delta', 'Delta', 'epsilon', 'varepsilon', 'zeta', 'eta', 'theta', 'vartheta', 'Theta', 'iota', 'kappa', 'lambda', 'Lambda', 'mu', 'nu', 'xi', 'Xi', 'pi', 'Pi', 'rho', 'varrho', 'sigma', 'Sigma', 'tau', 'upsilon', 'Upsilon', 'phi', 'varphi', 'Phi', 'chi', 'psi', 'Psi', 'omega', 'Omega'] n = int(input('Enter the number of dimensions:\n')) coords = [] for i in range(n): coords.append(Symbol(str(input('Enter coordinate label %d:\n' % i)))) @dataclass(frozen=False, order=True) class Tensor: name: str symbol: str key: str components: list def rank(self): return self.key.count('*') def tensor_zeros(self, t=0): for i in range(self.rank()): t = [t,] * n return MutableDenseNDimArray(t) def coord_id(self, o): a = [] for i in range(self.rank()): c = int(o/(n**(self.rank() - i - 1))) a.append(str(coords[c])) if any(letter in a[i] for letter in greek) is True: a[i] = '\\' + a[i] + ' ' o -= c * (n**(self.rank() - i - 1)) x = self.key w = 0 for i in x: if i == '*': x = x.replace('*', a[w], 1) w += 1 return self.symbol + x def print_tensor(self): for o in range(len(self.components)): if self.components[o] != 0: Idisplay(Math(latex(Eq(Symbol(self.coord_id(o)), self.components[o])))) print('\n\n') def assign(instance, thing): instance.components = thing.reshape(len(thing)).tolist() def fix_input(expr): expr = expr.replace('^', '**') for i in range(len(expr)-1): if expr[i].isnumeric() and (expr[i+1].isalpha() or expr[i+1] == '('): expr = expr[:i+1] + '*' + expr[i+1:] return expr metric = Tensor('metric tensor', 'g', '_**', []) metric_inv = Tensor('inverse of metric tensor', 'g', '__**', []) metric_d = Tensor('partial derivative of metric tensor', 'g', '_**,*', []) Christoffel = Tensor('Christoffel symbol - 2nd kind', 'Gamma', '__*_**', []) Christoffel_d = Tensor('partial derivative of Christoffel symbol', 'Gamma', '__*_**,*', []) Riemann = Tensor('Riemann curvature tensor', 'R', '__*_***', []) Ricci = Tensor('Ricci curvature tensor', 'R', '_**', []) Einstein = Tensor('Einstein tensor', 'G', '_**', []) Einstein_alt = Tensor('Einstein tensor', 'G', '__*_*', []) # user inputs metric: g = eye(n) while True: diag = str(input('Is metric diagonal? y for yes, n for no\n')).lower() if diag == 'y': for i in range(n): g[i, i] = sympify(fix_input(str(input( 'What is g_[%s%s]?\n' % (str(coords[i]), str(coords[i]) ))))) else: for i in range(n): for j in range(i, n): g[i, j] = sympify(fix_input(str(input( 'What is g_[%s%s]?\n' % (str(coords[i]), str(coords[j]) ))))) g[j, i] = g[i, j] if g.det() == 0: print('\nMetric is singular, try again!\n') continue else: break # calculate everything: # inverse metric: g_inv = MutableDenseNDimArray(g.inv()) assign(metric_inv, g_inv) g = MutableDenseNDimArray(g) assign(metric, g) # first derivatives of metric components: g_d = metric_d.tensor_zeros() for i in range(n): for j in range(i): for d in range(n): g_d[i, j, d] = g_d[j, i, d] for j in range(i, n): for d in range(n): g_d[i, j, d] = diff(g[i, j], coords[d]) assign(metric_d, g_d) # Christoffel symbols for Levi-Civita connection (Gam^i_jk): Gamma = Christoffel.tensor_zeros() for i in range(n): for j in range(n): for k in range(j): Gamma[i, j, k] = Gamma[i, k, j] for k in range(j, n): for l in range(n): Gamma[i, j, k] += S(1)/2 * g_inv[i, l] * ( -g_d[j, k, l] + g_d[k, l, j] + g_d[l, j, k] ) assign(Christoffel, Gamma) # first derivatives of Christoffel symbols (Gam^i_jk,d): Gamma_d = Christoffel_d.tensor_zeros() for i in range(n): for j in range(n): for k in range(j): for d in range(n): Gamma_d[i, j, k, d] = Gamma_d[i, k, j, d] for k in range(j, n): for d in range(n): Gamma_d[i, j, k, d] = simplify(diff(Gamma[i, j, k], coords[d])) assign(Christoffel_d, Gamma_d) # Riemann curvature tensor (R^i_jkl): Rie = Riemann.tensor_zeros() for i in range(n): for j in range(n): for k in range(n): for l in range(k): Rie[i, j, k, l] = -Rie[i, j, l, k] for l in range(k, n): Rie[i, j, k, l] = Gamma_d[i, j, l, k] - Gamma_d[i, j, k, l] for h in range(n): Rie[i, j, k, l] += (Gamma[h, j, l] * Gamma[i, h, k] - Gamma[h, j, k] * Gamma[i, h, l]) Rie[i, j, k, l] = simplify(Rie[i, j, k, l]) assign(Riemann, Rie) # Ricci curvature tensor (R_jl): Ric = simplify(tensorcontraction(Rie, (0, 2))) assign(Ricci, Ric) # Ricci curvature scalar: R = 0 for i in range(n): for j in range(n): R += g_inv[i, j] * Ric[i, j] R = simplify(R) # Einstein tensor (G_ij): G = Einstein.tensor_zeros() for i in range(n): for j in range(i): G[i, j] = G[j, i] for j in range(i, n): G[i, j] = simplify(Ric[i, j] - S(1)/2 * R * g[i, j]) assign(Einstein, G) # G^i_j: G_alt = Einstein_alt.tensor_zeros() for i in range(n): for j in range(n): for k in range(n): G_alt[i, j] += g_inv[i, k] * G[k, j] G_alt[i, j] = simplify(G_alt[i, j]) assign(Einstein_alt, G_alt) # print it all print() metric.print_tensor() metric_inv.print_tensor() metric_d.print_tensor() Christoffel.print_tensor() Christoffel_d.print_tensor() Riemann.print_tensor() Ricci.print_tensor() if R != 0: Idisplay(Math(latex(Eq(Symbol('R'), R)))) print('\n\n') Einstein.print_tensor() Einstein_alt.print_tensor() </code></pre> <p>EDIT: this code should be executed in Jupyter</p> <p>Example input:</p> <ul> <li>number of dimensions: 4</li> <li>coordinate 0: t</li> <li>coordinate 1: l</li> <li>coordinate 2: theta</li> <li>coordinate 3: phi</li> <li>metric diagonal?: y</li> <li>g_tt: -1</li> <li>g_ll: 1</li> <li>g_thetatheta: r(l)^2</li> <li>g_phiphi: r(l)^2sin(theta)^2</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T15:03:47.503", "Id": "527928", "Score": "0", "body": "Please replace your output screenshot with a text block." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T15:18:31.493", "Id": "527930", "Score": "0", "body": "Also please indicate how this needs to be executed (i.e. ipython or Jupyter)" } ]
[ { "body": "<ul>\n<li>In general, have your classes on top of the file, and then all the code. Don't have them inbetween.</li>\n<li>In Python, if we know a variable won't change, and we just have it as a reference or only read from it, we call it a constant. By convention, we use all uppercase names for those: <code>greek</code> -&gt; <code>GREEK</code>.</li>\n<li>Names should be representative of what they contain. Does <code>greek</code> contain Greeks?!?? Maybe <code>GREEK_CHARACTERS</code> or <code>GREEK_SYMBOLS</code> or <code>GREEK_LETTERS</code> would represent better what's inside it.</li>\n<li>What happens if the user enters an invalid coordinate? You should account and check that the user input is a valid one.</li>\n<li>You should use the <code>if __name__ == '__main__'</code> pattern (see more <a href=\"https://stackoverflow.com/a/419185/9415337\">here</a>).</li>\n<li><strong>IMPORTANT</strong>: Divide your code into functions you can reuse. This will avoid code repetition and make your code more modular and easy to understand.</li>\n</ul>\n<p>This could become one function <code>def clean_coordinates(coordinates)</code>. And same for the rest of the code.</p>\n<pre><code>g = eye(n)\nwhile True:\n diag = str(input('Is metric diagonal? y for yes, n for no\\n')).lower()\n if diag == 'y':\n for i in range(n):\n g[i, i] = sympify(fix_input(str(input(\n 'What is g_[%s%s]?\\n' % (str(coords[i]), str(coords[i])\n )))))\n else:\n for i in range(n):\n for j in range(i, n):\n g[i, j] = sympify(fix_input(str(input(\n 'What is g_[%s%s]?\\n' % (str(coords[i]), str(coords[j])\n )))))\n g[j, i] = g[i, j]\n if g.det() == 0:\n print('\\nMetric is singular, try again!\\n')\n continue\n else:\n break\n</code></pre>\n<ul>\n<li>Try to avoid mixing logic with input. E.g., in the example above, you have logic (fixing the input, etc.), but also user input (asking for the diagonal). Instead, have logic functions which handle the logic and take as a parameter whatever they need (e.g. <code>def clean_coordinates(coordinates, diag):</code>) and call them with the user input. This will make your code more modular, testable, clean, organized, reusable, etc.</li>\n<li>200 lines of code is a moderately large file... Maybe you can split your code into multiple files which makes it easier to read/understand?</li>\n</ul>\n<p>There surely is a lot more, we are just scratching the surface, but I think this is enough for one CR. If you fix all of this and get back, ping me and we can look into more issues!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T10:08:31.153", "Id": "527877", "Score": "3", "body": "\"In general, have your classes on top of the file, and then all the code. Don't have them inbetween.\" If multiple classes are being used, separating all class-definitions into a separate file should be even better. I'm a bit on the fence whether it should already be preferred in this case. Could some of the remaining functions be put into a class for improved stability and maintainability?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T10:35:36.450", "Id": "527878", "Score": "0", "body": "I agree! I think however first refactoring into functions is key. Then we can start with the file separation if needed, etc.!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T15:08:13.977", "Id": "527929", "Score": "1", "body": "Overall good feedback. I'm not convinced that 200 lines is long enough to justify file separation for its own sake. Instead, file separation should be done on logical, structural and dependency boundaries, which @Mast hints at." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T15:42:23.110", "Id": "527932", "Score": "0", "body": "True. This is why I said \"**maybe** you can split\". Basically now it is a bit hard to figure out, but once divided into functions, we might see some separation become evident!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T19:52:38.933", "Id": "527944", "Score": "0", "body": "@kettle-corn-with-a-q-u please consider marking the question as answered if this is all! if you have any other question let us know" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T04:06:43.747", "Id": "528021", "Score": "0", "body": "Thanks so much for taking the time to read my code and give this feedback! I did have a follow-up question: I understand that `if __name__ == '__main__'` is used to specify code that should only be executed if you are running the file directly, but right now, I have no idea in what context I'd be importing my code, and therefore have no idea which portions of my code should or shouldn't be executed in this other context. Any insight? Also, I put more of my code into functions and made it more modular. What would be the appropriate way to share that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T05:51:11.220", "Id": "528025", "Score": "0", "body": "A GitHub repository link would be awesome to share the code. And if you have never used it, you get to try it! Now that you have your code into functions, imagine in one month time you do another porject, and want to reuse some of the functions you codes here. Then you will import this functions, but you don't want this whole project to execute and start asking greek letters to the user if you only needed to use one function of it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T03:54:15.473", "Id": "528123", "Score": "0", "body": "Here you go! https://github.com/kettlecornwitha-QU/Metric-Forward-GR-Tensor-Calculator" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T08:05:51.757", "Id": "267704", "ParentId": "267702", "Score": "4" } }, { "body": "<p>Interesting project!</p>\n<p>Your <code>greek</code> letter escaping and <code>fix_input</code> are unnecessary gymnastics that fight against the norm. You should simply let the user know that they should be using Sympy-compatible format and leave it at that. Replacing <code>^</code> with <code>**</code> is not &quot;fixing&quot; the input; it's presenting an ad-hoc, non-standard, undocumented equation interface to the user that fairly departs from what Python users would expect (<code>^</code> means xor).</p>\n<p>Overall <code>Tensor</code> being a class is a good idea. However, <code>components</code> being a list mutated via a class-external <code>assign</code> method is ungood. Don't accept a list <code>[]</code> at all; declare via <code>components: List[Any] = field(default_factory=list)</code>. The <code>Any</code> here is a placeholder because I don't know what actually goes here. But why degrade this to a list - why not keep the <code>NDimArray</code>? Also, <code>assign</code> should be a method on the class.</p>\n<p><code>thing</code>, <code>a</code>, <code>c</code>, <code>x</code>, <code>w</code>, <code>o</code> are pretty foot-directed firearms. They're utterly non-descriptive and will not help us review your code, nor will they likely mean anything to you in 9+ months.</p>\n<p><code>if any(...) is True</code> can just be <code>if any(...)</code>. However, this will go away if you abandon the equation conversion effort, which you should.</p>\n<p>You need to indicate that this code is to be executed from Jupyter, which you've left as a mystery to your readers. There should be an associated <code>.ipynb</code> that calls into this code. Also consider adding a <code>requirements.txt</code> which is parseable by <code>pip</code>, in which you'd include <code>sympy</code>, <code>notebook</code> and <code>IPython</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T04:09:27.620", "Id": "528022", "Score": "0", "body": "Thanks for your time and your input! So I’ve been laboring under a vague idea of eventually making this into a program that is easy to use for everyone regardless of familiarity with Python. Plus I personally was not familiar with Python before a month or two ago (but very familiar with LaTeX), so I still have a strong preference for using carrots over double asterisks. And if I had known that I could use NDimArray as a data type, I absolutely would have done that! So thanks for making my life easier!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T04:10:00.030", "Id": "528023", "Score": "0", "body": "And the nondescript variable names—yeah, I know. I’m a mathematician at heart and new to coding, so it’s taking a lot of effort for me to prioritize descriptiveness and clarity over succinctness. I’m working on it though!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:38:54.860", "Id": "528049", "Score": "0", "body": "All very fair. If you want to write a WYSIWYG equation editor frontend consider a MathJax web frontend browser component which can still have Sympy in the backend using something like flask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T02:09:51.677", "Id": "528120", "Score": "0", "body": "That looks very promising! Thanks for the tip!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T23:41:27.897", "Id": "267744", "ParentId": "267702", "Score": "0" } } ]
{ "AcceptedAnswerId": "267704", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T04:43:19.383", "Id": "267702", "Score": "5", "Tags": [ "python", "sympy", "latex" ], "Title": "Calculate general relativity-related tensors/arrays using metric tensor as input" }
267702
<p>I finished LeetCode 05 with simplified (for ease of implementation) <a href="https://en.wikipedia.org/wiki/Longest_palindromic_substring#Manacher%27s_algorithm" rel="nofollow noreferrer">Manacher's algorithm</a>. IMHO it should keeps <span class="math-container">\$\mathcal{O}(n)\$</span> time and space complexity. However, LeetCode's benchmark ranked my solution as worst 5% and 30%. What causes such poor performance (time and space)? Can anybody help me diagnose where it went wrong?</p> <p>Description:</p> <blockquote> <p>Given a string s, return the longest palindromic substring in s.</p> </blockquote> <p>Example:</p> <pre><code>Input: s = &quot;babad&quot; Output: &quot;bab&quot; Note: &quot;aba&quot; is also a valid answer. </code></pre> <p>Code:</p> <pre class="lang-kotlin prettyprint-override"><code>data class LimitInfo(var center: Int, var rightMost: Int) class Solution { fun longestPalindrome(s: String): String { val newS = s.fold(&quot;#&quot;) { acc, c -&gt; &quot;$acc$c#&quot; } val radii = MutableList(newS.length) { 0 } val limitInfo = LimitInfo(0, 0) fun symRadius(center: Int, checkedRadius: Int): Int { var radius = checkedRadius + 1 while (newS.getOrNull(center - radius)?.equals(newS.getOrNull(center + radius)) == true) radius += 1 return radius - 1 } newS.indices.forEach { center -&gt; val space = limitInfo.rightMost - center val checkedRadius = when { space &lt; 0 -&gt; 0 else -&gt; minOf(radii[limitInfo.center * 2 - center], space) } val radius = symRadius(center, checkedRadius) radii[center] = radius if (center + radius &gt; limitInfo.rightMost) { limitInfo.rightMost = center + radius limitInfo.center = center } } val res = radii.withIndex().maxBy { it.value }!!.let { (loc, radius) -&gt; newS.slice(loc - radius..loc + radius) }.filterIndexed { index, _ -&gt; index % 2 == 1 } return res } } </code></pre>
[]
[ { "body": "<p>At least in the worst case you can get <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span>. For some strings (like 'aaaaaaaaa') any substring is going to be symmetric. That's why <code>symRadius</code> function may take <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. So in worst case <code>symRadius</code> is called with <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> complexity for all <span class=\"math-container\">\\$n\\$</span> chars (which should lead to <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span> in total).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T16:14:23.017", "Id": "528155", "Score": "1", "body": "But the biggest performance issue indeed should be related to string concatenation in the fold. As already mentioned @Tenfour04." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T11:05:44.887", "Id": "528240", "Score": "0", "body": "In my logic, `symRadius` accepts `checkedRadius` as starting point for further checks. In your example, except for first several 'a', `symRadius` will get pretty big initial `checkedRadius` from `radii`, since preventing square complexity. is it right?\nBTW, I suppose it as linear since `rightMost` keeps going rightward, no very strict but intuitive inference." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T15:52:17.260", "Id": "267829", "ParentId": "267703", "Score": "0" } }, { "body": "<p>I think the way you're folding it to create <code>newS</code> is <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span>. Try instead:</p>\n<pre><code>val newS = buildString { \n append('#')\n s.forEach { append(it).append('#') } \n}\n</code></pre>\n<p>Also consider that most respondents are probably inputting <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> solutions, so smaller optimizations that don't affect big O might make a big difference in your percentile. For example, using an <code>IntArray</code> instead of <code>MutableList</code>, manually iterating instead of boxing with <code>withIndex()</code>, eliminating the unnecessary intermediate LimitInfo class, checking indices and using <code>get()</code> instead of <code>getOrNull()</code>, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T18:25:59.137", "Id": "267834", "ParentId": "267703", "Score": "1" } } ]
{ "AcceptedAnswerId": "267834", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T08:00:23.983", "Id": "267703", "Score": "0", "Tags": [ "performance", "algorithm", "kotlin" ], "Title": "LeetCode 05 with Manacher's algorithm" }
267703
<p>I have a class representing meter readings:</p> <pre><code>public class MeterReading { public double AccountId { get; set; } public DateTime MeterReadingDateTime { get; set; } public double MeterReadValue { get; set; } } </code></pre> <p>I also have a collection of <code>MeterReadings</code> called <code>MeterReadingParseResult</code>:</p> <pre><code>public class MeterReadingsParseResult : MeterReadingsBase { } </code></pre> <p>This inherits from MeterReadingBase</p> <pre><code>public class MeterReadingsBase { private List&lt;MeterReading&gt; meterReadings = new List&lt;MeterReading&gt;(); public List&lt;MeterReading&gt; MeterReadings { get =&gt; meterReadings; set =&gt; meterReadings = value; } public int FailedParseReadings { get; set; } } </code></pre> <p>The main method I am concerned with takes in an <code>IFormFile</code> which is a CSV and using the help of the <code>CSVHelper</code> NuGet packages I can validate the CSV file content, pass it into my <code>MeterReading</code> class and add it to my <code>MeterReadingParseResult</code> collection. The <code>CSVHelper</code> code is usually a few lines of code but some of the CSV file may contain words where it needs to be doubles so I have had to customise it to make the validation suit my purpose.</p> <pre><code> public class MeterReadingsCsvProcessor { private readonly IMeterReadingsRepository _meterReadingsRepository; private readonly IAccountsRepository _accountsRepository; private MeterReadingsParseResult _parseResult; public MeterReadingsCsvProcessor( IMeterReadingsRepository meterReadingsRepository, IAccountsRepository accountsRepository) { _meterReadingsRepository = meterReadingsRepository; _accountsRepository = accountsRepository; _parseResult = new MeterReadingsParseResult(); } public MeterReadingsParseResult CsvHandler(IFormFile file) { if (file == null) throw new ArgumentNullException(nameof(file)); ParseCsv(file); var accounts = _accountsRepository.GetAccounts(); return _parseResult; } private void ParseCsv(IFormFile file) { TextReader textReader = new StreamReader(file.OpenReadStream()); using (var csv = new CsvReader(textReader, CultureInfo.InvariantCulture)) { csv.Read(); csv.ReadHeader(); CsvCustomErrorHandler&lt;int&gt; customInt32Converter = new CsvCustomErrorHandler&lt;int&gt;(); int lineNumber = 0; while (csv.Read()) { lineNumber++; var meterReading = new MeterReading(); { meterReading.AccountId = csv.GetField&lt;int&gt;(&quot;AccountId&quot;); meterReading.MeterReadingDateTime = DateTime.ParseExact (csv.GetField(&quot;MeterReadingDateTime&quot;), &quot;dd/MM/yyyy HH:mm&quot;, CultureInfo.InvariantCulture); meterReading.MeterReadValue = csv.GetField&lt;int&gt;(&quot;MeterReadValue&quot;, customInt32Converter); if (meterReading.MeterReadValue &lt; 1 || meterReading.MeterReadValue &gt;= 100000) { _parseResult.FailedParseReadings++; continue; } } _parseResult.MeterReadings.Add(meterReading); } } } } </code></pre> <p>Can I refactor this code in anyway to make it look cleaner or in your opinions do you think I have done the best with the functionality I need to achieve?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T12:22:46.640", "Id": "527885", "Score": "0", "body": "Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T19:40:09.360", "Id": "527911", "Score": "1", "body": "why are using casting `AccountId` and `MeterReadValue` to `int` while they're `double` ? and why not using `CalssMap` and implements a custom `TypeConverter` instead ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T20:39:33.783", "Id": "527912", "Score": "0", "body": "`accounts` doesn't seem to be used, so why is the code there? `_meterReadingsRepository` also isn't used." } ]
[ { "body": "<p><strong>1. Document your code</strong></p>\n<p>While it seems a bit boring and useless to do now, in 6 months you will read your code again and it will take some time to remember what this class/field/property is used for...</p>\n<p>The minimum would be to document with XML comments all the public parts. You can type three slashes <code>///</code> and Visual Studio will insert the following :</p>\n<pre><code>/// &lt;summary&gt;\n/// \n/// &lt;/summary&gt;\n</code></pre>\n<p>In summary you can insert a short description for the item you are documenting. This will be visible in Visual Studio IntelliSense and can be really helpful.</p>\n<p><strong>2. Property Consistency</strong></p>\n<p>Everywhere you use autoproperties with no private field. Except once, for a List. Why is it not another autoproperty ?</p>\n<pre><code>public List&lt;MeterReading&gt; MeterReadings { get; set; } = new List&lt;MeterReading&gt;();\n</code></pre>\n<p><strong>3. Field naming conventions</strong></p>\n<p>At some point, a private field start with a low case letter. Somewhere else you start your private fields with an underscore. Keep it consistent by writing them always with the same convention. There are no strict rules, so you just have to be consistent with yourself (which is not always easy) or your team (which is even harder).</p>\n<p>On a personal matter, I don't like underscores because it is used by the compiler to generate some backing fields in the background, and I don't want to be interfering with that.</p>\n<p><strong>4. Unused Variables</strong></p>\n<p>You have unused variables. That could be a good startup to code cleaning. Every variable you write will take you some time to read and understand why it's there. If the variable is not used, you waste time understanding why it's not used...</p>\n<p>Maybe it is used in other parts of your code, but since you did not mention it, I will assume it is not used anywhere else.</p>\n<ul>\n<li><code>_meterReadingsRepository</code> : you set it in the constructor, then never again. Is it because the constructor should look like this ? Because it comes from another public interface on which you have no control ? This can happen, but commment it then, so you know why you wasted so time creating a variable you are not using.</li>\n<li><code>int lineNumber = 0;</code> : you set this value and increment it every iteration. Very nice. But you never actually read the value, so what's the point ? Debug issue ?</li>\n<li><code>private MeterReadingsParseResult _parseResult;</code> : You use this variable to store the csv parsing results, which is fine. But you never use it again. So you memorize it, maybe to save some time the next time the parsing method is called ? But you recreate it anyway ! So the variable is completely useless.</li>\n<li><code>var accounts = _accountsRepository.GetAccounts();</code> : This one is almost like magic... What is this call supposed to do ? Because you never use the accounts variable. Maybe the method itself does something important for the rest, but there is no way to know...</li>\n</ul>\n<p><strong>5. Type consistency</strong></p>\n<p>The fields AccountId &amp; MeterReadValue are of type double but when you parse them from csv they are supposed to be int. Why ? Are they supposed to be integer or double ?</p>\n<p>If they are supposed to be doubles, you have a bug and you should parse them as double instead of int.</p>\n<p>If they are supposed to be int, there is no need to make the properties double. Unless you have a real reason for that, in which case you should add a comment to explain why they are double but parsed as int.</p>\n<p><strong>6. Null checks</strong></p>\n<p>You check for null once. Which is good. But what about the rests. Should you be checking for nulls in the constructor, where you receive two values and assign them to your private fields ?</p>\n<p><strong>7. The method's job</strong></p>\n<p>What is the method <code>CsvHandler</code> doing exactly ?</p>\n<ul>\n<li>First, it checks that the file is not null.</li>\n<li>Then you call the method that will actually perform some work.</li>\n<li>Then you call a method that nobody knows what it does.</li>\n<li>Finally, you return the field value.</li>\n</ul>\n<p>Is this method really worth it ?</p>\n<p>Another remark would be on the method's name. Usually, you would choose a verb to start a method name, in order to know what the method is supposed to do...</p>\n<p>Here is what I would have done :</p>\n<pre><code>public class MeterReading\n{\n public double AccountId { get; set; }\n public DateTime MeterReadingDateTime { get; set; }\n public double MeterReadValue { get; set; }\n}\n\npublic class MeterReadingsBase\n{\n public List&lt;MeterReading&gt; MeterReadings { get; set; } = new List&lt;MeterReading&gt;();\n public int FailedParseReadings { get; set; }\n}\n\npublic class MeterReadingsParseResult : MeterReadingsBase\n{\n}\n\npublic class MeterReadingsCsvProcessor\n{\n /// &lt;summary&gt;\n /// Implements a new meter reading csv processor.\n /// &lt;/summary&gt;\n /// &lt;param name=&quot;meterReadingsRepository&quot;&gt;Unused parameter. Kept for retro compatibility&lt;/param&gt;\n /// &lt;param name=&quot;accountsRepository&quot;&gt;Unused parameter. Kept for retro compatibility&lt;/param&gt;\n public MeterReadingsCsvProcessor(IMeterReadingsRepository meterReadingsRepository, IAccountsRepository accountsRepository)\n {\n }\n\n public MeterReadingsParseResult ParseCsvFile(IFormFile file)\n {\n if (file == null)\n throw new ArgumentNullException(nameof(file));\n\n using (TextReader textReader = new StreamReader(file.OpenReadStream()))\n using (CsvReader csv = new CsvReader(textReader, CultureInfo.InvariantCulture))\n {\n return ParseCsv(csv);\n }\n }\n\n\n private MeterReadingsParseResult ParseCsv(CsvReader csv)\n {\n MeterReadingsParseResult parseResult = new MeterReadingsParseResult();\n csv.Read();\n csv.ReadHeader();\n\n CsvCustomErrorHandler&lt;int&gt; customInt32Converter = new CsvCustomErrorHandler&lt;int&gt;();\n\n while (csv.Read())\n {\n MeterReading reading = ReadOneValue(csv, customInt32Converter);\n if (reading == null)\n {\n parseResult.FailedParseReadings++;\n }\n else\n {\n parseResult.MeterReadings.Add(reading);\n }\n }\n return parseResult;\n }\n\n private MeterReading ReadOneValue(CsvReader csv, CsvCustomErrorHandler&lt;int&gt; customInt32Converter)\n {\n MeterReading reading = new MeterReading()\n {\n AccountId = csv.GetField&lt;int&gt;(&quot;AccountId&quot;),\n MeterReadingDateTime = DateTime.ParseExact(csv.GetField&lt;string&gt;(&quot;MeterReadingDateTime&quot;), &quot;dd/MM/yyyy HH:mm&quot;, CultureInfo.InvariantCulture),\n MeterReadValue = csv.GetField&lt;int&gt;(&quot;MeterReadValue&quot;, customInt32Converter)\n };\n if (reading.MeterReadValue &lt; 1 || reading.MeterReadValue &gt;= 100000)\n {\n return null;\n }\n return reading;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T11:07:34.887", "Id": "267726", "ParentId": "267705", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T09:35:47.263", "Id": "267705", "Score": "2", "Tags": [ "c#", "asp.net", "classes" ], "Title": "Parse meter readings from CSV file" }
267705
<p>Recently I started to learn Rust. I come from a mostly Java background, but spent roughly the last two years in Go. I am working on converting a small microservice that reads data from Kafka and stores data in a map locally. Right now I'm working on the Kafka piece, and while I've got it working it doesn't look like the best or cleanest code. I typically like to avoid nested blocks when possible, but 1-2 levels aren't the end of the world. However, my current error handling is going 4+ levels deep, and just seems like there is a cleaner way to do this.</p> <p>The main thing so far I'm not happy with is how the error handling is being done. I'd like to avoid the deeply nested blocks and match. But I'm also curious if having a function that never returns is idiomatic to Rust. On our team in Go this is very common as the expectation is the function will be launched via a gorotuine. Here I'm just following suit and launching in by spawning a thread. The logic is to start at the beginning of the topic and read through all the messages and store the messages of a certain type we are interested in, assuming the deserialization is successful. If an error occurs the expectation is a message will be logged out, but the application will continue to read through the topic.</p> <pre><code>/// Creates and configures a Kafka consumer and listens to a Kafka topic reading /// messages and processing them. /// /// This function loops forever and doesn't return thus it should be called from /// a new thread. pub fn consume_cms_documents() { let consumer: BaseConsumer = ClientConfig::new() .set(&quot;bootstrap.servers&quot;, &quot;localhost:9092&quot;) .set(&quot;enable.auto.commit&quot;, &quot;false&quot;) .set(&quot;group.id&quot;, &quot;experimentdocument&quot;) .set(&quot;auto.offset.reset&quot;, &quot;earliest&quot;) .set_log_level(RDKafkaLogLevel::Debug) .create() .expect(&quot;invalid consumer config&quot;); consumer .subscribe(&amp;[&quot;CmsDocuments&quot;]) .expect(&quot;topic subscribe failed&quot;); // Continuously poll messages from Kafka for msg_result in consumer.iter() { // On error just log error message out and continue to next iteration. If // the message is successfully read attempt to process it. match msg_result { Err(e) =&gt; println!(&quot;failed to retrieve message from Kafka: {:?}&quot;, e), Ok(msg) =&gt; { // If the payload is present attempt to read the payload as JSON, // otherwise log out message and continue to next iteration match msg.payload() { Some(payload) =&gt; { // Read the message envelope let event: Result&lt;CmsEvent, serde_json::error::Error&gt; = serde_json::from_slice(payload); // If the payload was successfully deserialized check the type of the // event. If the event matches the expected type attempt to deserialize // the datasource property. If successful store the value. match event { Ok(event) =&gt; { // Is the event the type we care about, if so then proceed // attempting to deserialize the datasource if event.r#type.eq(EXPERIMENT_DOCUMENT_TYPE) { let test_def: Result&lt;TestDefinition, serde_json::error::Error&gt; = serde_json::from_value(event.datasource); match test_def { Ok(td) =&gt; println!(&quot;found one!&quot;), // todo: this would actually call a fn to store the data somewhere Err(e) =&gt; println!(&quot;failed to deserialize message {:?}, offset {:?}&quot;, e, msg.offset()), } } } Err(e) =&gt; println!(&quot;failed to deserialize message {:?}&quot;, e), } } _ =&gt; println!(&quot;message payload was empty&quot;), } } } } } </code></pre> <p>I did make an attempt to break into smaller pieces but I was running into challenges because I was trying to return data that the closure owned. I was hoping by breaking into smaller pieces the result would be more readable code, that was 4 levels deep into match statements.</p> <pre><code>for msg_result in consumer.iter() { let payload = msg_result.and_then(|msg| { msg.payload().ok_or(KafkaError::Global(RDKafkaErrorCode::InvalidMessageSize)) }); match payload { Ok(data) =&gt; { // todo: do something with data println!(&quot;{:?}&quot;, data) } Err(e) =&gt; println!(&quot;Oh nooo we broke&quot;) } } </code></pre> <p>The error:</p> <pre><code>error[E0515]: cannot return value referencing function parameter `msg` --&gt; src/kafka.rs:153:13 | 153 | msg.payload().ok_or(KafkaError::Global(RDKafkaErrorCode::InvalidMessageSize)) | ---^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | | | returns a value referencing data owned by the current function | `msg` is borrowed here </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T12:21:47.117", "Id": "527985", "Score": "0", "body": "Make your function return (for example) a `Result<(), String>` and use question mark operator. String is easy to use and format to include whatever error data you want to see when it errors out. To be able to use question mark on Option inside a function like that you can do `ok_or_else(...)?`." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T17:55:47.123", "Id": "267711", "Score": "0", "Tags": [ "error-handling", "rust" ], "Title": "Rust Error Handling - Can this error handling be made cleaner?" }
267711
<p>I'm playing with the Real mode and was trying to code something when suddenly I exceeded the <code>510</code> boundary (<code>.org 510</code>) of the <code>512</code> boot sector size for BIOS and <code>as</code> warning popped out:</p> <pre><code>code.s: Assembler messages: code.s:&lt;line num&gt;: Error: attempt to move .org backwards </code></pre> <p>So I started reading about how to split the code into multiple sectors and load them from the disk using the floppy for simplicity.</p> <p>I'm probably missing a lot of stuff one of which would be manual stack init, though I'm not sure if that would affect the loading as it's coded here. I'm using <code>-monitor stdio</code> to check the values in registers if necessary with <code>info registers</code>. Seems sufficient enough for now, but feel free to suggest better debugging tools that work with Qemu.</p> <p>Feel free not to hold back, I'd like to learn more. :)</p> <p>The code is simple:</p> <ul> <li>stores the disk number the boot sector was loaded from</li> <li>prints <code>a</code> from the first sector via a <code>print</code> label</li> <li><a href="https://en.wikipedia.org/wiki/INT_13H#INT_13h_AH=02h:_Read_Sectors_From_Drive" rel="nofollow noreferrer">loads the next sector</a> right after the boot sector in memory (to <code>0x7c00</code> + <code>0x200</code>)</li> <li>prints <code>b</code> from the second sector using the <code>print</code> label from the first sector, so should prove that it's not overlapping in or something weird like that</li> <li>jumps to infinite loop to keep it running</li> </ul> <p><strong>Building:</strong></p> <pre class="lang-sh prettyprint-override"><code>#!/bin/sh -xe as -o code.o code.s -g --statistics --warn --fatal-warnings ld -o code.bin --oformat=binary -Ttext=0x7c00 --build-id=none code.o qemu-system-i386 -monitor stdio -drive file=code.bin,index=0,if=floppy,format=raw </code></pre> <p><strong>Code:</strong></p> <pre class="lang-lisp prettyprint-override"><code>.att_syntax .code16 .global _start .text // sector 1 begin _start: // store booted from disk number for sector loading mov %dl, diskNum mov $'a', %al call print jmp load_next_sector print: // expects char to print in %al mov $0x0e, %ah int $0x10 ret load_next_sector: // load the code to memory directly after the boot sector // boot: [0x7c00, 0x7c00 + 512); after: 0x7e00 = 0x7c00 + 512 // service 02h: Read Sectors From Drive mov $0x02, %ah // Sectors To Read Count mov $0x01, %al // Cylinder/Track number 1 (zero-based) mov $0x00, %ch // Sector number 2 (one-based) mov $0x02, %cl // Head 1 (zero-based) mov $0x00, %dh // Disk Number mov diskNum, %dl // set Buffer Address Pointer to after boot sector (0x7e00) // es:bx = 0x7e00 -&gt; es * 16 + bx = 0x7e00 -&gt; 0 * 16 + 0x7e00 push $0x00 pop %es mov $0x7e00, %bx int $0x13 // fail, AL codes: http://www.oocities.org/wangxuancong/int13h.html jc load_next_sector // success jmp sector_2 .org 510 .word 0xAA55 // sector 1 end // sector 2 begin sector_2: mov $'b', %al call print jmp pause pause: jmp pause .data diskNum: .byte 0xff .org 1024 // sector 2 end .end </code></pre> <p><strong>Binary:</strong></p> <pre><code>0000000 1688 8000 61b0 02e8 eb00 b405 cd0e c310 0000010 02b4 01b0 00b5 02b1 00b6 168a 8000 006a 0000020 bb07 7e00 13cd e872 d5e9 0001 0000 0000 0000030 0000 0000 0000 0000 0000 0000 0000 0000 * 00001f0 0000 0000 0000 0000 0000 0000 0000 aa55 0000200 62b0 06e8 ebfe eb00 00fe 0000 0000 0000 0000210 0000 0000 0000 0000 0000 0000 0000 0000 * 0000400 00ff 0000 0000 0000 0000 0000 0000 0000 0000410 0000 0000 0000 0000 0000 0000 0000 0000 * 0000800 </code></pre> <p><strong>Output:</strong></p> <p><img src="https://i.stack.imgur.com/6QvL2.png" alt="" /></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T02:00:43.633", "Id": "528018", "Score": "1", "body": "Funny that you should talk about \"overlapping in memory\", because that's exactly what would happen if you loaded the 2nd sector at `0x7c00` + `0x100`. In other words, you got a typo here: should read `0x200`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:13:35.940", "Id": "528030", "Score": "0", "body": "Hahaha, yeah, it bit me once when I used `256` (`0x100`, `0x7d00`) instead of `512` (`0x200`, `0x7e00`), then I forgot about it and left it in the text. Thanks, editing!" } ]
[ { "body": "\n<h2>Improvements</h2>\n<ul>\n<li><p>When BIOS starts your bootloader (after it got loaded at linear address 7C00h), the only register that has a defined meaning is the <code>%dl</code> register. It contains the bootdrive code.<br />\nFrom this follows that it is up to you to setup the segment registers. You really should not trust any BIOS, be it real or emulated, to have initialized the segment registers to 0, like you seem to expect. Although then, I'm a bit surprised to see that you have cleared the <code>%es</code> segment register manually in the <em>load_next_sector</em> routine.<br />\nGiven that you will load the following sector(s) above the bootsector, I would suggest you setup the stack beneath the bootsector:</p>\n<pre class=\"lang-none prettyprint-override\"><code>xor %ax, %ax\nmov %ax, %ds\nmov %ax, %es\nmov %ax, %ss \\ Always keep these 2 together and in this order\nmov $0x7C00, %sp /\n</code></pre>\n</li>\n<li><p>The BIOS.Teletype function 0Eh expects to find the desired DisplayPage in the <code>%bh</code> register.</p>\n<pre class=\"lang-none prettyprint-override\"><code>print:\n mov $0, %bh\n mov $0x0E, %ah\n int $0x10\n ret\n</code></pre>\n</li>\n<li><p>It's fine to repeat the LoadSector operation in case it failed, but you should not allow this to continue forever. You should limit the number of retries to, say 5 times. And in between you can use the BIOS.ResetDisk function 00h in case that helps.</p>\n</li>\n</ul>\n<h2>Optimization</h2>\n<p>A bootsector is limited to just 512 bytes. That's one reason to write compact code. Instead of loading related byte-sized registers separately, you could load these together in a word-sized operation:</p>\n<pre class=\"lang-none prettyprint-override\"><code>mov $0x0201, %ax // AH=02h ReadSectors, AL=1 SectorCount\nmov $0x0002, %cx // CH=0 Cylinder, CL=2 SectorNumber\n</code></pre>\n<p>Eventhough you mention &quot;(zero-based)&quot;, I find it confusing to see that you comment about &quot;Cylinder number 1&quot; and &quot;Head 1&quot; and then load 0 in the relevant registers.<br />\nBetter phrasing is &quot;Cylinder 0&quot; or &quot;First cylinder&quot;, and &quot;Head 0&quot; or &quot;First head&quot;.</p>\n<h2>Observation</h2>\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>0000400 00ff 0000 0000 0000 0000 0000 0000 0000\n</code></pre>\n</blockquote>\n<p>The <em>diskNum</em> variable is not part of any of the 2 sectors that get loaded into memory. In this extremely simple code, I see no harm, but once the project becomes bigger and possibly located elsewhere, you will have to make sure that that memory is available and remains available (depending on what your OS does).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:23:04.160", "Id": "528032", "Score": "0", "body": "Thanks! Clearing `%es` was done explicitly because I wanted to set the offset [`ES:BX`](https://en.wikipedia.org/wiki/INT_13H#INT_13h_AH=02h:_Read_Sectors_From_Drive) to `0x0000:0x7e00`, see the `0 * 16 + 0x7e00` part." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:24:06.620", "Id": "528033", "Score": "2", "body": "Is there any reason of using `mov` instead of `xor` for zeroing out the registers? I thought `xor` is faster/more efficient (in general, CPU-specific obviously) due to less operators." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:30:07.430", "Id": "528035", "Score": "0", "body": "The `diskNum` part, that I haven't noticed and in a longer code I just moved it to the top because it annoyed me to have it at the end without noticing the impact. I wonder, if I leave it like that and exceed the 512 bytes for the boot sector, is it considered an undefined behavior, CPU-specific behavior (as in the emulator does X and the real hw Y) or perhaps an error that went of silent (thus a possible bug in the assembler?). Because in general terms, it \"just works\" when I move after 2kB but that might be just some magic of Qemu and would break on a real hw." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:34:05.987", "Id": "528036", "Score": "0", "body": "Also re `diskNum`, I don't need to retrieve the `0xff` value, I just need a place to store `%dl` to, so perhaps that's the reason it \"works\" - it just gave me \"some\" memory from somewhere with a garbage value and then I have just overwritten it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:19:30.417", "Id": "528063", "Score": "1", "body": "@PeterBadida Indeed; besides not needing an immediate value (so shorter in original 8086 CPUs) modern pipelined CPUs understand both XOR and SUB of a register with itself as zeroing the value with no dependency on the old value, and handle it in the register remapping unit directly." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T01:56:46.820", "Id": "267776", "ParentId": "267712", "Score": "3" } } ]
{ "AcceptedAnswerId": "267776", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T18:07:26.237", "Id": "267712", "Score": "3", "Tags": [ "assembly", "x86" ], "Title": "GNU assembly (AT&T syntax) bootloader load the next sector from floppy" }
267712
<p>I obtain strings that contain chat messages, and they sometimes have formatting codes imbedded in them. A formatting code is a <code>§</code> followed by a character, and this character then defines how the code will affect the following text. Colour codes can occur at the very end of the String, a common case of a message would be:</p> <p><code>&quot;§r§aThis is a message.§r§bAnd this is blue...§r&quot;</code></p> <p>Currently I'm using this method, which simply iterates over the String and skips another character when it encounters a <code>§</code>. Is this a good solution, and how can I further improve it?</p> <pre class="lang-java prettyprint-override"><code>private String cleanFormattingCodes(String message) { StringBuilder newMessage = new StringBuilder(); for (int i = 0; i &lt; message.length(); i++) { char c = message.charAt(i); if (c == '§') { i++; continue; } newMessage.append(c); } return newMessage.toString(); } </code></pre>
[]
[ { "body": "<p>Quite straightforward code, no bells or whistles. Your implementation removes a lone § if it is at the end of the string (e.g. &quot;this gets removed §&quot;). Is it supposed to do that? I would rename <code>newMessage</code> to <code>cleanMessage</code> as the message is not new, just a cleaned one. And change the unmoddified variables to final (<code>final StringBuilder cleanMessage</code> and <code>final char c</code>).</p>\n<p>That ends my code review. Now for the improvements.</p>\n<p>The whole method can be replaced with a short <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html\" rel=\"nofollow noreferrer\">regular expression</a>.</p>\n<pre><code>return message.replaceAll(&quot;§.&quot;, &quot;&quot;);\n</code></pre>\n<p>It is also possible to make a regex that matches &quot;§ + letter&quot; instead of &quot;§ + any char&quot; as both our implementations now do.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T20:52:48.613", "Id": "527947", "Score": "0", "body": "I think you have an error: the regular expression should be `§.`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T04:15:44.090", "Id": "527961", "Score": "0", "body": "@RoToRa Thanks, my regex game is getting rusty..." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T04:21:45.613", "Id": "267717", "ParentId": "267713", "Score": "3" } }, { "body": "<p>I have only three small points:</p>\n<ol>\n<li><p>The formatting/indentation isn't quite ok, but that may be just a copy and past error.</p>\n</li>\n<li><p>Since you know the (maximum) length of the final string, you could initialize the <code>StringBuilder</code> with a capacity. That has the advantage, that the <code>StringBuilder</code> won't need to allocate new memory inbetween:</p>\n</li>\n</ol>\n<pre><code>StringBuilder newMessage = new StringBuilder(message.length());\n</code></pre>\n<ol start=\"3\">\n<li>I feel that the use of <code>continue</code> makes the loop a bit awkward to read. Since the rest of the loop body is just one line, I think a simple <code>else</code> would be better: (And a small comment wouldn't out of place.)</li>\n</ol>\n<pre><code>if (c == '§') {\n // Skip the following character\n i++;\n} else {\n newMessage.append(c);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T15:36:21.917", "Id": "267735", "ParentId": "267713", "Score": "3" } }, { "body": "<p>For me, this code breaks the rule of &quot;least surprise&quot; :</p>\n<pre><code>for (int i = 0; i &lt; message.length(); i++) {\n char c = message.charAt(i);\n if (c == '§') {\n i++;\n continue;\n }\n\n newMessage.append(c);\n}\n</code></pre>\n<p>The loop variable <code>i</code> is incremented in the loop control and in the body of the loop. That goes against my expectations of the behaviour of a <code>for</code> loop.</p>\n<p>If your code is going to work this way, my preference would be for the loop to be a <code>while</code> loop, with the index explicitly managed in the different code paths - like this (untested code).</p>\n<pre><code>int i = 0;\nwhile (i &lt; message.length()) {\n char c = message.charAt(i);\n if (c == '§') {\n i += 2; // skip the 2-character formatting code\n } else {\n newMessage.append(c);\n i += 1 // move on to the next character.\n }\n}\n</code></pre>\n<p>I've used &quot;i += <em>n</em>&quot; in both cases for symmetry.</p>\n<p>As Torben has pointed out, you could just use String.replaceAll(<em>regex</em>)...</p>\n<p>Torben's regex solution, like your manual copying, assumes that there is never any reason for your flag character to appear in the string other than as part of a formatting code. Can you confidently assert that that is the case? If, for example, the flag was allowed to appear as text, preceded perhaps by a quote character such as '\\' your code breaks:</p>\n<pre><code>&quot;I've learned how to remove \\§ from strings&quot;\n</code></pre>\n<p>would become</p>\n<pre><code>&quot;I've learned how to remove \\from strings&quot;\n</code></pre>\n<p>If this sort of thing is possible, your code needs to be more subtle. I'd probably use a State Machine, but that's just a little foible of mine...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T07:14:32.017", "Id": "267750", "ParentId": "267713", "Score": "1" } } ]
{ "AcceptedAnswerId": "267717", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-05T23:16:35.087", "Id": "267713", "Score": "3", "Tags": [ "java" ], "Title": "Remove Minecraft formatting codes from a String" }
267713
<p>I'm making a program that can add 2 terms that the user types.</p> <p>I think I've got identifying or evaluating the terms down. I used classes because I just recently learned it and I also heard it was good practice in order to make your programs shorter. But, when it comes to adding 2 terms together (which is the code under the <code>else</code> and <code>elif</code> statements) I tried using classes but I have no idea how that would work, so I just sort of brute forced it. Is there a shorter or otherwise better way to code the adding part? Surely there is, and I would appreciate it if someone could show me what to learn or focus on or pretty much just any good advice so that I can code it cleaner.</p> <pre><code>class TermEva: def __init__(self, Variable, Coefficient): self.Variable = Variable self.Coefficient = Coefficient self.ExVariable = Variable if self.Coefficient &lt; 0: self.ExVariable = &quot;-&quot; + self.Variable def SimTerm(self): return &quot;{}{}&quot;.format(self.Coefficient, self.Variable) def Expanded_Form(self): ExpandedForm = [] for n in range(abs(self.Coefficient)): ExpandedForm.append(self.ExVariable) return ExpandedForm Term1 = TermEva(input(&quot;Enter Variable 1: &quot;), int(input(&quot;Enter its Coefficient: &quot;))) Term2 = TermEva(input(&quot;Enter Variable 2: &quot;), int(input(&quot;Enter it's Coefficient: &quot;))) print(Term1.SimTerm()) print(Term2.SimTerm()) if Term1.Variable == Term2.Variable: VariableSum = Term1.Variable CoefficientSum = Term1.Coefficient + Term2.Coefficient ExVariableSum = VariableSum if CoefficientSum &lt; 0: ExVariableSum = &quot;-&quot; + VariableSum ExpandedFormSum = [] for num in range(abs(CoefficientSum)): ExpandedFormSum.append(ExVariableSum) TermSum = str(CoefficientSum) + str(VariableSum) elif Term1.Variable != Term2.Variable: ExTerm1_Variable = Term1.Variable ExTerm2_Variable = Term2.Variable if Term1.Coefficient &lt; 0: ExTerm1_Variable = &quot;-&quot; + Term1.Variable if Term2.Coefficient &lt; 0: ExTerm2_Variable = &quot;-&quot; + Term2.Variable ExpandedFormSum = [] for num in range(abs(Term1.Coefficient)): ExpandedFormSum.append(ExTerm1_Variable) for num in range(abs(Term2.Coefficient)): ExpandedFormSum.append(ExTerm2_Variable) if Term2.Coefficient &lt; 0: TermSum =(Term1.SimTerm() + Term2.SimTerm()) elif Term2.Coefficient &gt;= 0: TermSum =(Term1.SimTerm() + &quot;+&quot; + Term2.SimTerm()) print(TermSum) </code></pre>
[]
[ { "body": "<p><strong>General</strong></p>\n<p>Attributes, variable names, function names and function arguments should be lowercase / <code>snake_case</code>.</p>\n<p>You should wrap your main procedure in a main function, as well as a <code>if __name__ == '__main__'</code> guard. <a href=\"https://stackoverflow.com/a/419185/9173379\">More info</a>.</p>\n<p>Documentation makes your code easier to read and understand. Use docstrings and comments to explain why and how your code is doing what it's doing.</p>\n<p>Type hints make your code easier to read and understand, use them. <a href=\"https://www.python.org/dev/peps/pep-0484/\" rel=\"nofollow noreferrer\">PEP 484</a> | <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">Python Docs</a></p>\n<hr />\n<p><strong><code>TermEva.__init__</code></strong></p>\n<pre><code>self.ex_variable = ex_variable\nif self.coefficient &lt; 0:\n self.ex_variable = &quot;-&quot; + self.variable\n</code></pre>\n<p>Depending on the value of <code>self.coefficient</code>, <code>self.ex_variable</code> will either be a number or a string. Sticking to the number representation seems more intuitive here:</p>\n<pre><code>self.ex_variable = ex_variable\nif self.coefficient &lt; 0:\n self.ex_variable = self.variable * -1\n</code></pre>\n<p>On closer inspection, your <code>main</code> functionality always passes strings to the constructor of <code>TermEva</code>. I don't think this is intended, as your implementation of <code>TermEva</code> implies the arguments are numbers. You should generally check user input for correctness and then convert it to the desired type.</p>\n<hr />\n<p><strong><code>TermEva.sim_term</code></strong></p>\n<p>f-strings are a great tool for string formatting:</p>\n<pre><code>def sim_term(self):\n return f&quot;{self.coefficient}{self.variable}&quot;\n</code></pre>\n<hr />\n<p><strong><code>TermEva.expanded_form</code></strong></p>\n<p>This pattern of list creation</p>\n<pre><code>expanded_form = []\nfor num in range(abs(self.Coefficient)):\n ExpandedForm.append(self.ExVariable)\n</code></pre>\n<p>can (and often should) be replaced by a more functional approach:</p>\n<ul>\n<li><code>return [self.ex_variable for _ in range(abs(self.coefficient))]</code></li>\n<li><code>return [self.ex_variable] * abs(self.coefficient)</code></li>\n</ul>\n<p>Note that it's convention to use <code>_</code> as a variable name for loop variables you don't actually use. This makes it immediately clear to the reader that the value of <code>num</code> is not needed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T09:34:22.117", "Id": "267722", "ParentId": "267715", "Score": "2" } }, { "body": "<p>Building on what @riskypenguin suggests:</p>\n<ul>\n<li><code>TermEva</code> is a slightly awkward name, and is simpler and clearer as <code>Term</code>.</li>\n<li>Replace your <code>SimTerm</code> with a standard implementation of <code>__str__</code>.</li>\n<li><code>Expanded_Form</code> is not used, so you can just delete it; or if you want to keep it, you should be using <code>join</code> if it's only for print.</li>\n<li>This is a clear application for a frozen <code>dataclass</code> that enforces immutability and writes your constructor for you. You can then include a <code>@classmethod</code> pseudoconstructor to centralize your input capture routine.</li>\n<li>Consider implementing <code>__add__</code> on the class.</li>\n<li>An implementation that can generalize the &quot;expanded form sum&quot; as well as the basic two-term sum would separate the concept of a term and an equation, with the latter having its own class and holding references to terms in a list. I haven't shown this below.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from dataclasses import dataclass\nfrom numbers import Real\n\n\n@dataclass(frozen=True)\nclass Term:\n variable: str\n coefficient: Real\n\n def __str__(self) -&gt; str:\n return f'{self.coefficient:g}{self.variable}'\n\n @classmethod\n def from_stdin(cls, sequence: int) -&gt; 'Term':\n return cls(\n input(f'Enter variable {sequence}: '),\n float(input('Enter its coefficient: ')),\n )\n\n @property\n def expanded_form(self) -&gt; str:\n if not self.coefficient.is_integer():\n raise ValueError(f'Expanded form cannot be represented for {self}')\n\n n = int(abs(self.coefficient))\n\n if self.coefficient &gt;= 0:\n return ' + '.join((self.variable,) * n)\n\n return ' - '.join((\n f'-{self.variable}',\n *((self.variable,) * (n - 1))\n ))\n\n def __add__(self, other: 'Term') -&gt; str:\n if self.variable == other.variable:\n return str(Term(self.variable, self.coefficient + other.coefficient))\n\n if other.coefficient &lt; 0:\n return f'{self} - {-other.coefficient}{other.variable}'\n return f'{self} + {other}'\n\n\ndef main() -&gt; None:\n x = Term.from_stdin(1)\n y = Term.from_stdin(2)\n print(x + y)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T14:22:59.900", "Id": "267733", "ParentId": "267715", "Score": "2" } } ]
{ "AcceptedAnswerId": "267722", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T02:52:13.250", "Id": "267715", "Score": "1", "Tags": [ "python", "beginner", "python-3.x", "mathematics" ], "Title": "Ask 2 terms from user and add them" }
267715
<p>This <a href="https://stackoverflow.com/a/61842546/1068446">StackOverflow answer</a> gives a good suggestion for reproducting the 'after state updates, fire this callback' functionality that the old class component <a href="https://reactjs.org/docs/react-component.html#setstate" rel="nofollow noreferrer">setState function</a> had, but that the <a href="https://reactjs.org/docs/hooks-reference.html#usestate" rel="nofollow noreferrer">new useState hook</a> does not.</p> <p>Unfortunately, the solution does not fully replicate the old functionality - namely in that if the setState is called with an identical object/value then the callback will not be fired.</p> <p>Here is my remedy to this:</p> <pre class="lang-javascript prettyprint-override"><code> function useStateCallback(initialState) { const [state, setState] = useState(initialState); const cbRef = useRef(null); // init mutable ref container for callbacks const [uniqueState, setUniqueState] = useState(Symbol()); const setStateCallback = useCallback((state, cb) =&gt; { cbRef.current = cb; // store current, passed callback in ref setState(state); // Prevent unnecessary firing of the useEffect if there is no callback to fire if (cb) { setUniqueState(Symbol()); } }, []); // keep object reference stable, exactly like `useState` useEffect(() =&gt; { // cb.current is `null` on initial render, // so we only invoke callback on calls of setState, where there is a callback. if (cbRef.current) { cbRef.current(state); cbRef.current = null; // reset callback after execution } }, [state, uniqueState]); return [state, setStateCallback]; } </code></pre> <p><a href="https://codesandbox.io/s/cocky-mendel-tqh58?file=/src/App.js:790-1443" rel="nofollow noreferrer">Code Sandbox</a></p> <p>Any feedback on code like this? Any thing potentially dangerous I've missed? Performance concerns? Is this appropriate use of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol" rel="nofollow noreferrer">Symbol</a>?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T03:15:32.123", "Id": "267716", "Score": "0", "Tags": [ "react.js" ], "Title": "This custom hook to reproduce the callback functionality of this.setState" }
267716
<p>The <a href="https://en.wikipedia.org/wiki/Disjoint-set_data_structure" rel="nofollow noreferrer">Wikipedia page on Disjoint-Set data structures</a> presents <span class="math-container">\$4\$</span> distinct algorithms for finding the root node of the tree, and <span class="math-container">\$2\$</span> distinct algorithms for performing the union operation. In this post, I will present all <span class="math-container">\$4 * 2\$</span> combinations:</p> <p><strong><code>com.github.coderodde.util.disjointset.DisjointSet</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; import java.util.HashMap; import java.util.Map; import java.util.Objects; /** * This class implements the * &lt;a href=&quot;https://en.wikipedia.org/wiki/Disjoint-set_data_structure&quot;&gt; * disjoint-set data structure&lt;/a&gt;. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021). */ public final class DisjointSet&lt;E&gt; { private final Map&lt;E, DisjointSetNode&lt;E&gt;&gt; disjointSetMap = new HashMap&lt;&gt;(); /** * The disjoint set root finder. */ private final AbstractDisjointSetRootFinder&lt;E&gt; disjointSetRootFinder; /** * The disjoint set operation provider. */ private final AbstractDisjointSetUnionComputer&lt;E&gt; disjointSetUnionComputer; /** * Constructs a disjoint-set data structure with specific operation * implementations. * * @param disjointSetRootFinder the root finder operation implementation * object. * * @param disjointSetUnionComputer the union operation implementation * object. */ public DisjointSet(AbstractDisjointSetRootFinder&lt;E&gt; disjointSetRootFinder, AbstractDisjointSetUnionComputer&lt;E&gt; disjointSetUnionComputer) { this.disjointSetRootFinder = Objects.requireNonNull( disjointSetRootFinder, &quot;The input DisjointSetRootFinder is null.&quot;); this.disjointSetUnionComputer = Objects.requireNonNull( disjointSetUnionComputer, &quot;The input DisjointSetUnionComputer is null.&quot;); this.disjointSetRootFinder.ownerDisjointSet = this; this.disjointSetUnionComputer.ownerDisjointSet = this; } /** * Finds the root of the tree to which {@code item} belongs to. * * @param item the target item. * @return the root of the tree to which {@code item} belongs to. */ public E find(E item) { return disjointSetRootFinder.find(item); } /** * Unites the two trees into one, unless the two items already belong to the * same tree. * * @param item1 the first item. * @param item2 the second item. */ public void union(E item1, E item2) { disjointSetUnionComputer.union(item1, item2); } DisjointSetNode&lt;E&gt; find(DisjointSetNode&lt;E&gt; node) { if (node == node.getParent()) { return node; } return find(node.getParent()); } DisjointSetNode&lt;E&gt; getNode(E item) { DisjointSetNode&lt;E&gt; node = disjointSetMap.get(item); if (node == null) { node = new DisjointSetNode&lt;E&gt;(item); disjointSetMap.put(item, node); } return node; } } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.DisjointSetNode</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * This class implements the nodes of the disjoint-set data structures. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 4, 2021) * @since 1.6 (Sep 4, 2021) */ final class DisjointSetNode&lt;E&gt; { /** * The actual item being held. */ private final E item; /** * The parent node of this node. */ private DisjointSetNode&lt;E&gt; parent; /** * The rank of this node. The rank of a node is its maximum height from any * leaf node. */ private int rank; /** * The size of this node. The size of a node is the number of nodes under * it. */ private int size; public DisjointSetNode(E item) { this.item = item;; this.parent = this; } public E getItem() { return item; } public DisjointSetNode&lt;E&gt; getParent() { return parent; } public int getRank() { return rank; } public int getSize() { return size; } @Override public String toString() { return &quot;[&quot; + item + &quot;]&quot;; } void setParent(DisjointSetNode&lt;E&gt; parent) { this.parent = parent; } void setRank(int rank) { this.rank = rank; } void setSize(int size) { this.size = size; } } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.AbstractDisjointSetRootFinder</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * This abstract class defines the API for for root finding algorithms in a * disjoint-set data structure. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021) */ public abstract class AbstractDisjointSetRootFinder&lt;E&gt; { DisjointSet&lt;E&gt; ownerDisjointSet; /** * If {@code item} belongs to a tree, returns the root of that three. * Otherwise, a trivial, empty tree {@code T} is created, and {@code item} * is added to {@code T}. * * @param item the query item. * @return the root of the tree to which {@code item} belongs to. */ public abstract E find(E item); } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.AbstractDisjointSetUnionComputer</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * This abstract class defines the API for the union computer algorithms in a * disjoint-set data structure. * * @param &lt;E&gt; the satellite date type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021) */ public abstract class AbstractDisjointSetUnionComputer&lt;E&gt; { DisjointSet&lt;E&gt; ownerDisjointSet; /** * If both {@code item1} and {@code item2} belong to the same tree, does * nothing. Otherwise, unites the two into a single tree. * * @param item1 the first item. * @param item2 the second item; */ public abstract void union(E item1, E item2); } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.DisjointSetIterativePathCompressionNodeFinder</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * This class implements the root finding algorithm for the disjoint-set data * structure using iterative path compression. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021) */ public final class DisjointSetIterativePathCompressionNodeFinder&lt;E&gt; extends AbstractDisjointSetRootFinder&lt;E&gt; { /** * {@inheritDoc } */ @Override public E find(E item) { DisjointSetNode&lt;E&gt; node = ownerDisjointSet.find(ownerDisjointSet.getNode(item)); DisjointSetNode&lt;E&gt; root = node; while (root.getParent() != root) { root = root.getParent(); } while (node.getParent() != root) { DisjointSetNode&lt;E&gt; parent = node.getParent(); node.setParent(root); node = parent; } return root.getItem(); } } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.DisjointSetRecursivePathCompressionNodeFinder</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * This class implements the root finding algorithm for the disjoint-set data * structure using recursive path compression. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021) */ public final class DisjointSetRecursivePathCompressionNodeFinder&lt;E&gt; extends AbstractDisjointSetRootFinder&lt;E&gt; { /** * {@inheritDoc } */ @Override public E find(E item) { DisjointSetNode&lt;E&gt; node = ownerDisjointSet.find(ownerDisjointSet.getNode(item)); if (node == node.getParent()) { return node.getItem(); } node.setParent(ownerDisjointSet.find(node.getParent())); return node.getParent().getItem(); } } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.DisjointSetPathHalvingNodeFinder</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * This class implements the root finding algorithm for the disjoint-set data * structure using path halving. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021) */ public final class DisjointSetPathHalvingNodeFinder&lt;E&gt; extends AbstractDisjointSetRootFinder&lt;E&gt; { /** * {@inheritDoc } */ @Override public E find(E item) { DisjointSetNode&lt;E&gt; node = ownerDisjointSet.find(ownerDisjointSet.getNode(item)); while (node.getParent() != node) { node.setParent(node.getParent().getParent()); node = node.getParent(); } return node.getItem(); } } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.DisjointSetPathSplittingNodeFinder</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * * This class implements the root finding algorithm for the disjoint-set data * structure using path splitting. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021) */ public final class DisjointSetPathSplittingNodeFinder&lt;E&gt; extends AbstractDisjointSetRootFinder&lt;E&gt; { @Override public E find(E item) { DisjointSetNode&lt;E&gt; node = ownerDisjointSet.find(ownerDisjointSet.getNode(item)); while (node.getParent() != node) { DisjointSetNode&lt;E&gt; parent = node.getParent(); node.setParent(parent.getParent()); node = parent; } return node.getItem(); } } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.DisjointSetUnionByRankComputer</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * This class implements the union operation by rank. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021) */ public final class DisjointSetUnionByRankComputer&lt;E&gt; extends AbstractDisjointSetUnionComputer&lt;E&gt; { /** * {@inheritDoc } */ @Override public void union(E item1, E item2) { DisjointSetNode&lt;E&gt; node1 = ownerDisjointSet.find(ownerDisjointSet.getNode(item1)); DisjointSetNode&lt;E&gt; node2 = ownerDisjointSet.find(ownerDisjointSet.getNode(item2)); if (node1 == node2) { return; } if (node1.getRank() &lt; node2.getRank()) { DisjointSetNode&lt;E&gt; tempNode = node1; node1 = node2; node2 = tempNode; } node2.setParent(node1); if (node1.getRank() == node2.getRank()) { node1.setRank(node1.getRank() + 1); } } } </code></pre> <p><strong><code>com.github.coderodde.util.disjointset.DisjointSetUnionBySizeComputer</code>:</strong></p> <pre><code>package com.github.coderodde.util.disjointset; /** * This class implements the union operation by tree size. * * @param &lt;E&gt; the satellite data type. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 5, 2021) * @since 1.6 (Sep 5, 2021) */ public final class DisjointSetUnionBySizeComputer&lt;E&gt; extends AbstractDisjointSetUnionComputer&lt;E&gt; { /** * {@inheritDoc } */ @Override public void union(E item1, E item2) { DisjointSetNode&lt;E&gt; node1 = ownerDisjointSet.find(ownerDisjointSet.getNode(item1)); DisjointSetNode&lt;E&gt; node2 = ownerDisjointSet.find(ownerDisjointSet.getNode(item2)); if (node1 == node2) { return; } if (node1.getSize() &lt; node2.getSize()) { DisjointSetNode&lt;E&gt; tempNode = node1; node1 = node2; node2 = tempNode; } // Here, node1.getSize() &gt;= node2.getSize() node2.setParent(node1); node1.setSize(node1.getSize() + node2.getSize()); } } </code></pre> <h2>Repository</h2> <p>The entire story is <a href="https://github.com/coderodde/disjoint-sets" rel="nofollow noreferrer">here</a>.</p> <p>The typical benchmark output might be:</p> <pre><code>Seed: 1630845583522 The benchmark graph is built in 222 milliseconds. ................................................................................ Root finder: DisjointSetRecursivePathCompressionNodeFinder, union computer: DisjointSetUnionByRankComputer Duration: 149 ms. Total edges: 199997. Total weight: 36417.94367839121. ................................................................................ Root finder: DisjointSetRecursivePathCompressionNodeFinder, union computer: DisjointSetUnionBySizeComputer Duration: 4670 ms. Total edges: 199997. Total weight: 36417.94367839121. ................................................................................ Root finder: DisjointSetIterativePathCompressionNodeFinder, union computer: DisjointSetUnionByRankComputer Duration: 153 ms. Total edges: 199997. Total weight: 36417.94367839121. ................................................................................ Root finder: DisjointSetIterativePathCompressionNodeFinder, union computer: DisjointSetUnionBySizeComputer Duration: 4649 ms. Total edges: 199997. Total weight: 36417.94367839121. ................................................................................ Root finder: DisjointSetPathHalvingNodeFinder, union computer: DisjointSetUnionByRankComputer Duration: 157 ms. Total edges: 199997. Total weight: 36417.94367839121. ................................................................................ Root finder: DisjointSetPathHalvingNodeFinder, union computer: DisjointSetUnionBySizeComputer Duration: 4645 ms. Total edges: 199997. Total weight: 36417.94367839121. ................................................................................ Root finder: DisjointSetPathSplittingNodeFinder, union computer: DisjointSetUnionByRankComputer Duration: 141 ms. Total edges: 199997. Total weight: 36417.94367839121. ................................................................................ Root finder: DisjointSetPathSplittingNodeFinder, union computer: DisjointSetUnionBySizeComputer Duration: 4633 ms. Total edges: 199997. Total weight: 36417.94367839121. ................................................................................ 1. Root finder: DisjointSetPathSplittingNodeFinder, union computer: DisjointSetUnionByRankComputer, 141 milliseconds. 2. Root finder: DisjointSetRecursivePathCompressionNodeFinder, union computer: DisjointSetUnionByRankComputer, 149 milliseconds. 3. Root finder: DisjointSetIterativePathCompressionNodeFinder, union computer: DisjointSetUnionByRankComputer, 153 milliseconds. 4. Root finder: DisjointSetPathHalvingNodeFinder, union computer: DisjointSetUnionByRankComputer, 157 milliseconds. 5. Root finder: DisjointSetPathSplittingNodeFinder, union computer: DisjointSetUnionBySizeComputer, 4633 milliseconds. 6. Root finder: DisjointSetPathHalvingNodeFinder, union computer: DisjointSetUnionBySizeComputer, 4645 milliseconds. 7. Root finder: DisjointSetIterativePathCompressionNodeFinder, union computer: DisjointSetUnionBySizeComputer, 4649 milliseconds. 8. Root finder: DisjointSetRecursivePathCompressionNodeFinder, union computer: DisjointSetUnionBySizeComputer, 4670 milliseconds. </code></pre> <h2>Critique request</h2> <p>Please, tell me anything that comes to mind. In particular, is there any way to put the implementation classes into an implementation package (perhaps <code>com.github.coderodde.util.disjointset.impl</code>)?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T08:44:38.093", "Id": "530694", "Score": "0", "body": "Why prefer `abstract class` to `interface` for `[defining] the API`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T17:54:03.830", "Id": "530723", "Score": "0", "body": "I think there is one big mess starting with a naming confusion between nodes (undirected graph↔\"disjoint-set forest\") and not the intended methods getting called. Probably, it is unfortunate to not specify `RootFinder` to find the root *disjoint-set forest node*. (How did you build confidence the intended ones got called?)" } ]
[ { "body": "<p>There aren't many best practices on how to package classes, a rule of thumb is to package classes of a module/feature together in a way so that they aren't strongly coupled together. If you were to make a <code>...disjointset.impl</code> and a <code>...disjointset.abstr</code> pack for example, you'd couple them together strongly since you can't use the implementations without the abstract base classes.</p>\n<p>On the other hand, creating something like <code>...disjointset.finder</code> and <code>...disjointset.computer</code> works if the finders can compile without the computers and vice versa. I might have overlooked something, but they only seem to rely on <code>DisjointSet</code> and <code>DisjointSetNode</code> which would stay in the &quot;root&quot; <code>...disjointset</code> package so it would work.</p>\n<p>The result would look like this:</p>\n<pre><code>com/github/coderodde/util/disjointset/\n--&gt; computers/\n--&gt; finders/\n--&gt; DisjointSet.java\n--&gt; DisjointSetNode.java\n\ncom/github/coderodde/util/disjointset/computers\n--&gt; AbstractDisjointSetUnionComputer.java\n--&gt; DisjointSetUnionByRankComputer.java\n--&gt; DisjointSetUnionBySizeComputer.java\n\ncom/github/coderodde/util/disjointset/finders\n--&gt; AbstractDisjointSetRootFinder.java\n--&gt; DisjointSetIterativePathCompressionRootFinder.java\n--&gt; DisjointSetPathHalvingRootFinder.java\n--&gt; DisjointSetPathSplittingRootFinder.java\n--&gt; DisjointSetRecursivePathCompressionRootFinder.java\n</code></pre>\n<p><strong>You could also keep the package as it is</strong>. It's not too big and it all has to do with manipulating a <code>DisjointSet</code>, so adding further layers might not even be necessary! For comparison, <a href=\"https://github.com/mpatric/mp3agic/tree/master/src/main/java/com/mpatric/mp3agic\" rel=\"nofollow noreferrer\">this mp3 library</a> just puts all files into its main package and it has a lot more files.</p>\n<p>For some further info, <a href=\"http://www.javapractices.com/topic/TopicAction.do?Id=205\" rel=\"nofollow noreferrer\">this text</a> on how to divide an app into packages is a very interesting read.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T09:59:37.807", "Id": "267784", "ParentId": "267718", "Score": "3" } }, { "body": "<h1>Logic</h1>\n<p>If you're using Java 8+, in <code>getNode</code> I think you can simplify the logic using <a href=\"https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#computeIfAbsent-K-java.util.function.Function-\" rel=\"nofollow noreferrer\"><code>Map#computeIfAbsent</code></a> like this</p>\n<pre class=\"lang-java prettyprint-override\"><code>return disjointMapSet.computeIfAbsent(item, () -&gt; new DisjointSetNode&lt;&gt;(item));\n</code></pre>\n<p>Is there a reason not to implement <code>equals</code> / <code>hashcode</code> for the <code>DisjointSetNode</code> classes? Relying on reference equality seems less easier to reason about than using the <code>equals</code> method.</p>\n<p>In <code>DisjointSetIterativePathCompressionNodeFinder#find</code>, what is the purpose of</p>\n<pre class=\"lang-java prettyprint-override\"><code>while (root.getParent() != root) {\n root = root.getParent();\n}\n</code></pre>\n<p>shouldn't <code>ownerDisjointSet.find(ownerDisjointSet.getNode(item))</code> return the root of the tree or am I misreading this?</p>\n<p>In <code>DisjointSetRecursivePathCompressionNodeFinder</code>, what is the purpose of <code>node == node.getParent()</code> - won't the <code>if</code> always be true since <code>DisjointSet#find</code> only returns when <code>node == node.getParent()</code>?</p>\n<h1>Naming and Organization</h1>\n<p>Is there a reason why <code>DisjointSetNode</code> is not an inner <code>class</code> called <code>Node</code> scoped to the <code>DisjointSet</code> class itself? It feels like that would narrow the scoping of <code>DisjointSetNode</code> without having to worry about name-spacing with a prefix like <code>DisjointSet</code>.</p>\n<p>The relationship between the <code>Abstract</code> classes and the <code>DisjointSet</code> class seems circular - <code>DisjointSet</code> relies on these <code>Abstract</code> classes but then the <code>Abstract</code> classes rely on the <code>DisjointSet</code>. I feel like the <code>Abstract</code> classes are better represented by <code>interface</code>s (since there's really no shared logic between the implementations of the <code>Abstract</code> classes except the shared dependency. The only thing these <code>Abstract</code> classes depend on the <code>DisjointSet</code> to get are the <code>root</code> nodes - what if these were passed to the concrete implementations of the<code> Abstract</code> classes?</p>\n<p>Some other minor things are the naming for variables like <code>disjointSetMap</code> which is probably more descriptive as <code>itemsToNodes</code> or something of that nature. Or <code>getNode</code> is more like <code>getOrCreateNode</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T09:48:48.727", "Id": "530697", "Score": "0", "body": "*In `DisjointSetIterativePathCompressionNodeFinder.find()`, what is the purpose of [iteratively finding the root]?* I think that part implements the first pass of the two-pass algorithm presented in the hyperlinked en.wikipedia article. Now about all those introductory calls to `ownerDisjointSet.find()`…" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T09:57:48.633", "Id": "530698", "Score": "0", "body": "(One conceivable reason for `DisjointSetNode` not being an inner class of `DisjointSet` is that it doesn't need to know its instantiating instance - that leaves the question: Why not *nested*?)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-15T14:03:06.537", "Id": "269015", "ParentId": "267718", "Score": "2" } }, { "body": "<p>Jae Bradley raises a very <a href=\"https://codereview.stackexchange.com/a/269015/93149\">valid concern</a>:<br />\nThe use of <code>ownerDisjointSet.find()</code> on the node found by <code>owner….getNode(item)</code> prevents the differences in root finding algorithms to have any effect.<br />\nTo compound to the problem, union computation does *not use <code>disjointSetRootFinder</code>, but <code>ownerDisjointSet.find()</code>.</p>\n<hr />\n<p>From one step back, you<br />\n- try <em>multiple inheritance</em> without language support using manual <em>double dispatch</em>.<br />\n- miss the baseline cases:<br />\n  - <em>no</em> path shortening<br />\n  - union by seat-of-pants (first/second/random item gets to be parent)</p>\n<p>Many problems start with the way we <em>think about things</em>, intimately related to <em>naming</em>.<br />\nAnd one crux in this regard is <em>unhelpful established names</em> such as<br />\n<em>disjoint-set data structure</em>,<br />\n<em>union–find data structure</em>,\n<em>disjoint-set forest</em> - every one of them too long (and an indication that a concept may not (yet) be optimally formed&amp;established). While <code>DisjointSets</code> wouldn't be wrong, I'd slightly prefer <code>PartitionedSet</code>.</p>\n<p>One thing that doesn't sit well with me is <code>DisjointSetNode</code> sporting an <code>int rank</code> and an <code>int size</code> at the same time.</p>\n<hr />\n<p>What if we ditch <code>…Node</code>?</p>\n<ul>\n<li>Have a Map not from item(payload) to <code>…Node</code>, but to <em>parent (item)</em>.\n<ul>\n<li>asked for &quot;the&quot; representative of the set\n<ul>\n<li>an unknown item <em>i</em> is in, return <em>i</em></li>\n<li>for known items, do &quot;the walk&quot;</li>\n</ul>\n</li>\n<li>union of sets specified by two items as usual\n<ul>\n<li>by seat-of-pants (use with path shortening, only)<br />\n(a pity Java does not provide an attractive way to return more than one value - the number of steps taken in finding each representative would open an interesting can of worms)</li>\n<li>for by-rank or by-size (do you want to update these in case of path shortening?)<br />\nhave Maps <code>item2size</code>&amp;<code>item2rank</code>, <code>get()</code> overridden using <code>getOrDefault()</code> suitably instead of creating entries for leaves, initially null.<br />\nOn first access, instantiate appropriate Map.<br />\nOn subsequent accesses, check other Map for being null.</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n<hr />\n<p>My benchmark results using a 1.8 JRE stopped to look arbitrary after urging to collect garbage before <code>duration = runKruskalsAlgorithm(rootFinder, unionComputer)</code> (From GitHub repository, not presented for review.<br />\n(<code>findMinimumSpanningTree(graph, weightFunction)</code> is odd for constructing the result not from its <code>minimumSpanningTree</code>.))</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-16T22:22:24.937", "Id": "269048", "ParentId": "267718", "Score": "0" } } ]
{ "AcceptedAnswerId": "267784", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T04:34:10.783", "Id": "267718", "Score": "3", "Tags": [ "java", "algorithm", "comparative-review", "library" ], "Title": "Comparing 8 different Disjoint-Set data structure variants in Java" }
267718
<p>I have recently learned about using PDO. I created a db class which could handle common actions like create, update, delete and select. Is this method a correct way to connect to the database using prepared statements?</p> <pre><code>&lt;?php class Db { private $db_host = DB_HOST; private $db_user = DB_USERNAME; private $db_pass = DB_PASSWORD; private $db_port = DB_PORT; private $db_name = DB_DATABASE; private $db_charset = DB_CHARSET; private $dsn = &quot;&quot;; private $pdo = null; private $stmt = null; private $result = array(); private $conn = false; private $options = [ PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES =&gt; false, ]; public function __construct() { if(!$this-&gt;conn) { try { $this-&gt;dsn = &quot;mysql:host=&quot; . $this-&gt;db_host . &quot;;dbname=&quot; . $this-&gt;db_name . &quot;;charset=&quot; . $this-&gt;db_charset . &quot;;port=&quot; . $this-&gt;db_port; $this-&gt;pdo = new PDO($this-&gt;dsn, $this-&gt;db_user, $this-&gt;db_pass, $this-&gt;options); return $this-&gt;pdo; } catch (PDOException $e) { $err = &quot;Connection Failed: &quot; . $e-&gt;getMessage(); } } return false; } protected function select($table, $rows = &quot;*&quot;, $join = null, $join_side = null, $where = array(), $order = null, $limit = null) { if($this-&gt;tableExists($table)) { $sql = &quot;SELECT $rows FROM $table&quot;; $paramsArray_where = null; if($join != null &amp;&amp; $join_side != null) $sql .= &quot; $join_side $join&quot;; if(!empty($where)) { $table_val_where = &quot;:&quot; . implode(',:', array_keys($where)); // Create an array of new keys that contain : in front of them $table_key_where = explode(&quot;,&quot;, $table_val_where); // get array values $values_where = array_values($where); // combine key with their respective values $paramsArray_where = array_combine($table_key_where, $values_where); $args = array(); foreach($where as $key=&gt;$value) $args[] = &quot;$key=:$key&quot;; $sql .= &quot; WHERE &quot; . implode(' &amp;&amp; ', $args); } if($order != null) $sql .= &quot; ORDER BY $order&quot;; if($limit != null) $sql .= &quot; LIMIT $limit&quot;; $this-&gt;stmt = $this-&gt;pdo-&gt;prepare($sql); if($this-&gt;stmt-&gt;execute($paramsArray_where)) { $this-&gt;result = $this-&gt;stmt-&gt;fetchAll(); return true; } } return false; } protected function insert($table, $params=array()) { if(!empty($params)) { if($this-&gt;tableExists($table)) { // Seperating $params key and values $table_cols = implode(',', array_keys($params)); $table_val = &quot;:&quot; . implode(',:', array_keys($params)); // Create an array of new keys that contain : in front of them $table_key = explode(&quot;,&quot;, $table_val); // get array values $values = array_values($params); // combine key with their respective values $paramsArray = array_combine($table_key, $values); $sql = &quot;INSERT INTO $table ($table_cols) VALUES ($table_val)&quot;; $this-&gt;stmt = $this-&gt;pdo-&gt;prepare($sql); if($this-&gt;stmt-&gt;execute($paramsArray)) return true; } } return false; } protected function update($table, $params=array(), $where=array()) { if(!empty($params)) { if($this-&gt;tableExists($table)) { $table_val = &quot;:&quot; . implode(',:', array_keys($params)); // Create an array of new keys that contain : in front of them $table_key = explode(&quot;,&quot;, $table_val); // get array values $values = array_values($params); // combine key with their respective values $paramsArray = array_combine($table_key, $values); $args = array(); foreach($params as $key=&gt;$value) $args[] = &quot;$key=:$key&quot;; $sql = &quot;UPDATE $table SET &quot; . implode(', ', $args); if(!empty($where)) { $table_val_where = &quot;:&quot; . implode(',:', array_keys($where)); // Create an array of new keys that contain : in front of them $table_key_where = explode(&quot;,&quot;, $table_val_where); // get array values $values_where = array_values($where); // combine key with their respective values $paramsArray_where = array_combine($table_key_where, $values_where); $bind_params = array_merge($paramsArray, $paramsArray_where); $args = array(); foreach($where as $key=&gt;$value) $args[] = &quot;$key=:$key&quot;; $sql .= &quot; WHERE &quot; . implode(' &amp;&amp; ', $args); }else{ $bind_params = $paramsArray; } $this-&gt;stmt = $this-&gt;pdo-&gt;prepare($sql); if($this-&gt;stmt-&gt;execute($bind_params)) return true; } } return false; } protected function delete($table, $where = array()) { if($this-&gt;tableExists($table)) { $sql = &quot;DELETE FROM $table&quot;; $paramsArray_where = null; if(!empty($where)) { $table_val_where = &quot;:&quot; . implode(',:', array_keys($where)); // Create an array of new keys that contain : in front of them $table_key_where = explode(&quot;,&quot;, $table_val_where); // get array values $values_where = array_values($where); // combine key with their respective values $paramsArray_where = array_combine($table_key_where, $values_where); $args = array(); foreach($where as $key=&gt;$value) $args[] = &quot;$key=:$key&quot;; $sql .= &quot; WHERE &quot; . implode(' &amp;&amp; ', $args); } $this-&gt;stmt = $this-&gt;pdo-&gt;prepare($sql); if($this-&gt;stmt-&gt;execute($paramsArray_where)) return true; } return false; } private function tableExists($table) { $sql = &quot;SHOW TABLES FROM &quot; . $this-&gt;db_name . &quot; LIKE '$table'&quot;; $this-&gt;stmt = $this-&gt;pdo-&gt;query($sql); if($this-&gt;stmt-&gt;execute()) { if($this-&gt;stmt-&gt;rowCount() &gt; 0) return true; } return false; } public function getResult() { $result = $this-&gt;result; $this-&gt;result = array(); return $result; } public function __destruct() { if($this-&gt;conn) { $this-&gt;conn = false; $this-&gt;pdo = null; $this-&gt;dsn = &quot;&quot;; $this-&gt;stmt = null; $this-&gt;result = array(); return true; }else{ return false; } } } </code></pre> <p>I have tested the above code and it works fine.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T06:41:26.713", "Id": "527919", "Score": "1", "body": "\"Can Someone just review my code if this method is correct\" Does it produce the correct output? It seems like you did test it. What are your real concerns?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T07:13:34.400", "Id": "527920", "Score": "1", "body": "@Tec FYI: Constructors don't `return` https://stackoverflow.com/q/6849572/2943403 Okay I see a lot of things to refine. I'll wait to see if this question gets closed before I start an answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T12:15:17.810", "Id": "527923", "Score": "0", "body": "@Mast I just want to know that if this is the optimized and correct way of doing this database stuff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T12:16:50.847", "Id": "527924", "Score": "1", "body": "@mickmackusa Please review this code. I Hope you write an answer ASAP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T19:26:34.917", "Id": "527938", "Score": "4", "body": "There are indeed a lot of things to say about this code. Useful reading material could be this: [Your first database wrapper's childhood diseases](https://phpdelusions.net/pdo/common_mistakes). Do read on down the page, there are some interesting nuggets of knowledge in there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T22:12:23.293", "Id": "527950", "Score": "1", "body": "What is `$join_side` meant to hold? There is too much to critique with the little time I have. I'll defer to other contributors." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T04:12:37.917", "Id": "527959", "Score": "0", "body": "@KIKOSoftware Thanks for the Article. Would definately check it out!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T04:50:15.133", "Id": "527962", "Score": "0", "body": "@mickmackusa I just thought it would be needed for different types of join like inner join, left join, etc.." } ]
[ { "body": "<h2>Canonical advice from a helpful post</h2>\n<p>As was mentioned in a comment there is a post with helpful advice for classes like this: <a href=\"https://phpdelusions.net/pdo/common_mistakes\" rel=\"nofollow noreferrer\">Your first database wrapper's childhood diseases</a> (written by <a href=\"https://codereview.stackexchange.com/users/101565/your-common-sense\">@YourCommonSense</a>). It recommends setting the exception mode to <code>PDO::ERRMODE_EXCEPTION</code> which appears to be the case with the code here. It also recommends:</p>\n<blockquote>\n<ol>\n<li><p>Tell PHP to report ALL errors:</p>\n<pre><code>error_reporting(E_ALL);\n</code></pre>\n</li>\n<li><p>On a development server just turn displaying errors on:</p>\n<pre><code>ini_set('display_errors', 1);\n</code></pre>\n</li>\n<li><p>On a production server turn displaying errors off while logging errors on:</p>\n<pre><code>ini_set('display_errors', 0);\nini_set('log_errors', 1);\n</code></pre>\n</li>\n</ol>\n</blockquote>\n<p><sup><a href=\"https://phpdelusions.net/pdo/common_mistakes#errors\" rel=\"nofollow noreferrer\">1</a></sup></p>\n<p>It also recommends making the PDO connection <a href=\"https://phpdelusions.net/pdo/common_mistakes#connection\" rel=\"nofollow noreferrer\">once and only once per PHP request</a>. The code above appears to attempt to only connect once but that is flawed - see the section on <strong>Constructor Logic</strong> below for more on that topic.</p>\n<h2>Possibility for SQL injection</h2>\n<p>As I mentioned in <a href=\"https://codereview.stackexchange.com/a/269798/120114\">this review of a similar wrapper class</a> there is potential for SQL injection - likely from methods like <code>insert()</code> and <code>update()</code>. That article from phpdelusions.net has an <a href=\"https://phpdelusions.net/pdo/sql_injection_example\" rel=\"nofollow noreferrer\">entire post about how many update and insert methods are vulnerable to SQL injection</a>.</p>\n<blockquote>\n<p>&quot;placeholders are used and data is safely bound, therefore our query is safe&quot;. Yes, the <em>data</em> is safe. But in fact, what does this code do is <strong>taking user input and adding it directly to the query</strong>. Yes, it's a <code>$key</code> variable. Which goes right into your query untreated.</p>\n<p>Which means you've got an injection. <sup><a href=\"https://phpdelusions.net/pdo/sql_injection_example#helper\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote>\n<p>While it is up to the calling code to provide fields to update, where conditions etc. this code cannot prevent calling code from passing input straight from the client side. As the article explains later on that one can attempt to make a whitelist of fields that can be updated but for this central code that doesn’t seem feasible. However using backtick delimiters will help but then delimiters inside the name need to be escaped</p>\n<blockquote>\n<p>As it was said before, escaping delimiters would help. Therefore, your first level of defense should be escaping delimiters (backticks) by doubling them. Assembling your query this way,</p>\n<pre><code>$setStr .= &quot;`&quot;.str_replace(&quot;`&quot;, &quot;``&quot;, $key).&quot;` = :&quot;.$key.&quot;,&quot;;\n</code></pre>\n<p>you will get the injection eliminated.\n<sup><a href=\"https://phpdelusions.net/pdo/sql_injection_example#escaping_backticks\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote>\n<h3>Constructor logic</h3>\n<p>As was mentioned in a comment constructors typically don't have a <code>return</code> statement, though <a href=\"https://stackoverflow.com/a/21099742/1575353\">it is valid</a>.</p>\n<p>It appears that the <code>$conn</code> property is not assigned in the constructor (only in the destructor), but that property doesn't seem to be doing much. The default value is <code>false</code> so this conditional in the constructor will always evaluate to <code>true</code>:</p>\n<blockquote>\n<pre><code>if(!$this-&gt;conn) { \n</code></pre>\n</blockquote>\n<p>It might make more sense to check if <code>$this-&gt;pdo</code> is not <code>null</code> but in the constructor that seems pointless since the object is just being created.</p>\n<h3>Method visibility</h3>\n<p>It appears that the only public methods are the constructor, destructor and <code>getResult()</code>. Perhaps the intention is that subclasses should be defined in order to utilize the core CRUD methods but if that is not the case then consider making those methods have <code>public</code> visibility.</p>\n<h3>Conditionals</h3>\n<p>In method <code>tableExists()</code> the following lines exist towards the end:</p>\n<blockquote>\n<pre><code>if($this-&gt;stmt-&gt;execute()) {\n if($this-&gt;stmt-&gt;rowCount() &gt; 0)\n return true;\n }\n</code></pre>\n</blockquote>\n<p>Those conditionals could be combined into a single line:</p>\n<pre><code>if($this-&gt;stmt-&gt;execute() &amp;&amp; $this-&gt;stmt-&gt;rowCount() &gt; 0) {\n return true;\n}\n</code></pre>\n<h3>adding where conditions</h3>\n<p>A commonly accepted principle is the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself principle</a>. There are places where blocks of code are repeated - e.g. the following block appears to be repeated within <code>select()</code>, <code>update()</code>, <code>delete()</code>.</p>\n<blockquote>\n<pre><code> $args = array();\n foreach($where as $key=&gt;$value)\n $args[] = &quot;$key=:$key&quot;;\n \n $sql .= &quot; WHERE &quot; . implode(' &amp;&amp; ', $args);\n</code></pre>\n</blockquote>\n<p>It would be simpler to abstract that logic into a method instead of having it exist multiple times.</p>\n<p>Because it is a loop that pushes into an array, it can be simplified using <a href=\"https://www.php.net/array_map\" rel=\"nofollow noreferrer\"><code>array_map()</code></a>:</p>\n<pre><code> $args = array_map(function($key) {\n return &quot;$key = :{$key}&quot;; \n }, array_keys($where));\n $sql .= &quot;WHERE &quot; . implode(&quot; &amp;&amp; &quot;, $args);\n</code></pre>\n<p>And hopefully the server is running PHP 7.4 or later since <a href=\"https://www.php.net/supported-versions.php\" rel=\"nofollow noreferrer\">currently there is LTS for version 7.4+</a>, <a href=\"https://www.php.net/manual/en/functions.arrow.php\" rel=\"nofollow noreferrer\">arrow functions</a> can be used to simplify the mapping:</p>\n<pre><code> $args = array_map(fn($key) =&gt; &quot;$key = :{$key}&quot;, array_keys($where));\n $sql .= &quot;WHERE &quot; . implode(&quot; &amp;&amp; &quot;, $args);\n</code></pre>\n<p>To utilize the advice from the article on phpdelusions.net a method could be created to use delimeters on the field name and escape them within the name:</p>\n<pre><code>public static function sanitizeNameCondition($name)\n{\n return &quot;`&quot; . str_replace(&quot;`&quot;, &quot;``&quot;, $name) . &quot;` = :&quot; . $name;\n}\n</code></pre>\n<p>Then that can be used with <code>array_map()</code>:</p>\n<pre><code>$args = array_map([$this, 'sanitizeNameCondition'], array_keys($where));\n$sql .= &quot; WHERE &quot; . implode(&quot; &amp;&amp; &quot;, $args);\n</code></pre>\n<p>And that method can be used for the fields to set also:</p>\n<pre><code>$args = array_map([$this, 'sanitizeNameCondition'], array_keys($params));\n$sql = &quot;UPDATE $table SET &quot; . implode(', ', $args);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-08T23:16:56.507", "Id": "269894", "ParentId": "267719", "Score": "3" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/269894\">Sam's answer</a> covers a lot of good points I am not going to repeat, but I will tell you more issues.</p>\n<h3>Private properties</h3>\n<p>What is the point in setting constants as private properties? What is the purpose of having all these config values as private properties if they are only used in the constructor? These values should come from a config file that is stored outside of <a href=\"https://en.wikipedia.org/wiki/Version_control\" rel=\"nofollow noreferrer\">VCS</a>.</p>\n<h3>Catching PDO exception</h3>\n<p>You copied some code without understanding why. You catch an exception and do nothing with it, as a result shooting yourself in the leg. Either remove the <code>try-catch</code> entirely or throw a new exception in the catch block. See <a href=\"https://phpdelusions.net/pdo#catch\" rel=\"nofollow noreferrer\">https://phpdelusions.net/pdo#catch</a></p>\n<h3>Use strict types</h3>\n<p>Use any types at all! All your parameters and return values should have types specified. If you are not doing this, I guarantee you, at some point you will pass invalid value to one of your methods.</p>\n<h3>Use early returns.</h3>\n<p>Instead of wrapping 20 lines in an <code>if</code> block, use the opposite of that condition and <code>return</code>. For example:</p>\n<pre><code>if (!$this-&gt;tableExists($table)) {\n return false;\n}\n</code></pre>\n<h3>Avoid empty()</h3>\n<p>Usage of <code>empty()</code> is an antipattern. You can use it if you think the variable might be empty or <strong>undefined</strong> but when you know the variable is defined you don't need it. Change <code>if (!empty($where))</code> to <code>if ($where)</code>.</p>\n<h3>Don't check for the return value of PDOStatement::execute()</h3>\n<p>What do you expect to receive from this method? You set PDO to exception mode so that function should never return false. That <code>if</code> statement is useless.</p>\n<h3>Usage of rowCount()</h3>\n<p>Generally, you should never need to use this method. Especially you do not need <code>if ($this-&gt;stmt-&gt;rowCount() &gt; 0)</code>. <code>0</code> is false-ish and <code>rowCount()</code> should never return negative numbers. In this case, however, you can keep this method call, but reduce the whole return statement to a single line.</p>\n<pre><code>{\n $sql = &quot;SHOW TABLES FROM &quot; . $this-&gt;db_name . &quot; LIKE '$table'&quot;;\n return $this-&gt;pdo-&gt;query($sql)-&gt;rowCount() &gt; 0;\n}\n</code></pre>\n<h3>Destructor</h3>\n<p>Why, oh why? You are destroying the object and all your properties are private. Unless you go out of your way to leak one of these variables, that destructor is pointless. You are destroying all of this anyway when the object is destroyed!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-11T23:35:43.317", "Id": "270000", "ParentId": "267719", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T05:39:52.363", "Id": "267719", "Score": "7", "Tags": [ "php", "object-oriented", "mysql", "database", "pdo" ], "Title": "Connect to MYSQL database in PHP with prepared statements" }
267719
<p><em>Hi, I asked this question over <a href="https://stackoverflow.com/q/69044784">on stack overflow</a>. However, they closed the thread and suggested to ask it on code review. So here I am :)</em> <em>The code below is an updated version of my original code, incorporating suggestions made on stack overflow.</em></p> <p>I'm currently trying to improve my C skills and am practising with some tutorials. Right now I am trying to read a CSV file which contains names and phone numbers of party guests separated by ';'. Each line contains exactly one entry.</p> <p>Although my code seems to work, I would like to hear some feedback regarding performance, security and elegance (possible memory leaks, misconceptions, possible improvements, runtime errors caused by unexpected file contents) to avoid making a habit out of bad code.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #define MAX_LINE_WIDTH 100 struct Guest { char *name; char *number; }; void cleanUp(int, struct Guest *, char *, FILE *); int main() { FILE *file = fopen(&quot;gaesteliste.txt&quot;, &quot;r&quot;); if(file == NULL) { perror(&quot;Error while reading the file&quot;); exit(EXIT_FAILURE); } char *line = malloc(MAX_LINE_WIDTH * sizeof(char)); if(line == NULL) { free(file); perror(&quot;Error while allocating required memory space&quot;); exit(EXIT_FAILURE); } struct Guest *guests = NULL; int guestCounter = 0; /*read a line: */ while(fgets(line, MAX_LINE_WIDTH, file) != NULL) { /*allocate more space: */ struct Guest *guestsNew = realloc(guests, (guestCounter+1)*sizeof(struct Guest)); if(guestsNew == NULL) { free(guests); free(line); free(file); perror(&quot;Error while allocating required memory space&quot;); exit(EXIT_FAILURE); } guests = guestsNew; /*parse line: */ line[strlen(line)-1] = '\0'; /*delete line-break character*/ char *token = strtok(line, &quot;;&quot;); guests[guestCounter].name = strdup(token); token = strtok(NULL, &quot;;&quot;); if(token == NULL) { guests[guestCounter].number = strdup(&quot;missing&quot;); } else { guests[guestCounter].number = strdup(token); } if(guests[guestCounter].number == NULL) { perror(&quot;Error while allocating required memory space&quot;); cleanUp(guestCounter, guests, line, file); exit(EXIT_FAILURE); } guestCounter++; } /*input is done, now output file contents: */ int i; for(i=0; i&lt;guestCounter; i++) { printf(&quot;Name: %s, Number: %s\n&quot;, guests[i].name, guests[i].number); } /*clean up:*/ cleanUp(guestCounter, guests, line, file); return EXIT_SUCCESS; } void cleanUp(int guestCounter, struct Guest *guests, char *line, FILE *file) { int i; for(i=0; i&lt;guestCounter; i++) { free(guests[i].name); free(guests[i].number); } free(guests); free(line); fclose(file); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T00:22:23.903", "Id": "527952", "Score": "2", "body": "Just to be sure, you are aware that a CSV file structure is a bit more complex than that, and that fields can be quoted, and will be if they contain double quotes, the separator character, or line feeds? Also that the separator may be `;` or `,`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T06:43:17.907", "Id": "527964", "Score": "1", "body": "Thanks for the reminder. I havn't thought about this because I created the files to be read myself. Maybe I will wirte a new version that can handle more complex data." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T18:31:58.263", "Id": "528000", "Score": "0", "body": "@jcaron Not only _can_ the separator be a `,`, but it _should_ be a comma, as CSV literally stands for Comma Separated Value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T20:46:20.493", "Id": "528004", "Score": "0", "body": "@GlenYates in countries which use a comma rather than a dot as a decimal separator it is usual to use a semi-colon rather than a comma as column separator in CSV files. But CSV is just a mess that should be avoided at all costs." } ]
[ { "body": "<blockquote>\n<pre><code>#define MAX_LINE_WIDTH 100\n</code></pre>\n</blockquote>\n<p>Arbitrary limits such as this are difficult to get right. No matter how large you make it, the real world somehow always manages to find data that exceeds the limit.</p>\n<p>In this case, as we use this limit with <code>fgets()</code>, we really need to check whether the terminating newline was read instead of always assuming we get a complete line.</p>\n<hr />\n<blockquote>\n<pre><code>FILE *file = fopen(&quot;gaesteliste.txt&quot;, &quot;r&quot;);\nif(file == NULL) {\n perror(&quot;Error while reading the file&quot;);\n exit(EXIT_FAILURE);\n}\n</code></pre>\n</blockquote>\n<p>Consider just reading from <code>stdin</code>, and let the user redirect appropriately. This removes all the file handling from our program, allowing it to be simpler, and it gives more flexibility because we can now use any file we like.</p>\n<hr />\n<blockquote>\n<pre><code> free(file);\n</code></pre>\n</blockquote>\n<p>This is plain wrong - we are not allowed to free the pointer returned by <code>fopen()</code>. We need <code>fclose(file)</code> here instead.</p>\n<hr />\n<blockquote>\n<pre><code>char *line = malloc(MAX_LINE_WIDTH * sizeof(char));\n</code></pre>\n</blockquote>\n<p>It's not clear why we allocated this from dynamic memory. Since we never change its size or keep a long-lived pointer, we could just use automatic storage:</p>\n<pre><code>char line[MAX_LINE_WIDTH];\n</code></pre>\n<p>Alternatively, keep the dynamic allocation, but be prepared to enlarge the buffer when we find a longer line. On POSIX platforms (likely since we're assuming <code>strdup()</code> is available), we have <code>getline()</code> available to do that for us.</p>\n<p>As an aside, note that multiplying by <code>sizeof (char)</code> is a no-op, since <code>char</code> is the fundamental unit of storage used for measuring sizes and therefore its size must be 1.</p>\n<hr />\n<p>Reallocating the array of guests every time we add one is inefficient. It's better to allocate in larger chunks, and keep track of our capacity and how much of it that we've used so far:</p>\n<pre><code>struct GuestList {\n size_t capacity;\n size_t count;\n struct Guest *data;\n};\n</code></pre>\n<p>Then we only need to allocate when <code>count</code> reaches <code>capacity</code>, and we can then increase the capacity by a decent amount.</p>\n<p>(A more advanced approach would use a <em>flexible array member</em> to store the list and its data in a single allocation.)</p>\n<p>When we fail to reallocate, we free some of our storage:</p>\n<blockquote>\n<pre><code> if(guestsNew == NULL) {\n free(guests);\n free(line);\n free(file);\n perror(&quot;Error while allocating required memory space&quot;);\n exit(EXIT_FAILURE);\n }\n</code></pre>\n</blockquote>\n<p>Again, we should have <code>fclose(file)</code> rather than <code>free(file)</code>. The other error is that we haven't freed the contents of <code>guests</code>, as we would have done if we'd just called the <code>cleanUp()</code> function.</p>\n<p>I would actually change that <code>cleanUp()</code> as it's very closely tied to <code>main()</code> (and really ought to be declared with <code>static</code> linkage). Instead, we should have a general <code>guest_list_free()</code> that can be used by any code working with a <code>struct GuestList</code>:</p>\n<pre><code>void guest_list_free(struct GuestList* list)\n{\n if (!list) {\n return; /* nothing to do */\n }\n for (size_t i = 0; i &lt; list-&gt;count; ++i) {\n free(list-&gt;data[i].name);\n free(list-&gt;data[i].number);\n }\n free(list-&gt;data);\n free(list);\n}\n</code></pre>\n<p>That's best paired with a <em>constructor</em> function that creates a fully initialised list:</p>\n<pre><code>struct GuestList* guest_list_alloc(void)\n{\n struct GuestList* list = malloc(sizeof *list);\n if (list) {\n list-&gt;count = list-&gt;capacity = 0;\n list-&gt;data = NULL;\n }\n return list;\n}\n</code></pre>\n<hr />\n<blockquote>\n<pre><code> line[strlen(line)-1] = '\\0'; /*delete line-break character*/\n</code></pre>\n</blockquote>\n<p>This line doesn't do what the comment says if the input stream line was <code>MAX_LINE_WIDTH</code> or more.</p>\n<hr />\n<blockquote>\n<pre><code> guests[guestCounter].name = strdup(token);\n</code></pre>\n</blockquote>\n<p>We have null-pointer tests for almost all the memory allocation functions, except this one. I guess that's an oversight? It could easily be added to the <code>if</code> test of the <code>.number</code> copy.</p>\n<hr />\n<blockquote>\n<pre><code> if(token == NULL) {\n guests[guestCounter].number = strdup(&quot;missing&quot;);\n }\n else {\n guests[guestCounter].number = strdup(token);\n }\n</code></pre>\n</blockquote>\n<p>Simplification:</p>\n<pre><code> guests[guestCounter].number = strdup(token ? token : &quot;missing&quot;);\n</code></pre>\n<hr />\n<h1>Modified code</h1>\n<p>This is in two parts, and I've made some other changes not explicitly called out in the review above.</p>\n<p>First, the <code>GuestList</code> type and its methods:</p>\n<pre><code>#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n\nstruct Guest {\n char *name;\n char *number;\n};\n\nstruct GuestList {\n size_t capacity;\n size_t count;\n struct Guest *data;\n};\n\nstruct GuestList* guest_list_alloc(void)\n{\n struct GuestList* list = malloc(sizeof *list);\n if (!list) { return list; }\n list-&gt;count = list-&gt;capacity = 0;\n list-&gt;data = NULL;\n return list;\n}\n\nvoid guest_list_free(struct GuestList* list)\n{\n if (!list) {\n return; /* nothing to do */\n }\n for (size_t i = 0; i &lt; list-&gt;count; ++i) {\n free(list-&gt;data[i].name);\n free(list-&gt;data[i].number);\n }\n free(list-&gt;data);\n free(list);\n}\n\nstruct Guest *guest_list_item(const struct GuestList* list, size_t index)\n{\n return list-&gt;data + index;\n}\n\n/* allocation size */\nstatic const size_t guest_list_increment = 10;\n\nstruct Guest *guest_list_add(struct GuestList* list, const char *name, const char *number)\n{\n if (!list || !name || !number) {\n return NULL;\n }\n if (list-&gt;capacity &lt;= list-&gt;count) {\n /* increase capacity */\n size_t new_capacity = list-&gt;capacity + guest_list_increment;\n struct Guest *data = realloc(list-&gt;data, sizeof *data * new_capacity);\n if (!data) {\n return NULL;\n }\n list-&gt;data = data;\n list-&gt;capacity = new_capacity;\n }\n\n struct Guest *this_item = list-&gt;data + list-&gt;count;\n this_item-&gt;name = strdup(name);\n this_item-&gt;number = strdup(number);\n if (!this_item-&gt;name || !this_item-&gt;number) {\n free(this_item-&gt;name);\n free(this_item-&gt;number);\n return NULL;\n }\n ++list-&gt;count;\n return this_item;\n}\n</code></pre>\n<p>Then the program to use it:</p>\n<pre><code>#include &lt;errno.h&gt;\n#include &lt;stdio.h&gt;\n\n/* populate list from stream. Sets errno if it fails. */\nstatic void read_guest_list(struct GuestList* list, FILE *stream)\n{\n char *line = NULL;\n size_t line_len = 0;\n ssize_t chars_read;\n while ((chars_read = getline(&amp;line, &amp;line_len, stream)) &gt; 0) {\n /*parse line: */\n if (line[chars_read-1] == '\\n') {\n line[chars_read-1] = '\\0';\n }\n char *name = strtok(line, &quot;;&quot;);\n char *number = strtok(NULL, &quot;;&quot;);\n if (!number) {\n /* no delimiter - just ignore this line */\n continue;\n }\n if (!guest_list_add(list, name, number)) {\n free(line);\n return;\n }\n }\n free(line);\n}\n\n\nint main(void)\n{\n struct GuestList *guests = guest_list_alloc();\n if (!guests) {\n perror(&quot;Couldn't create guest list&quot;);\n return EXIT_FAILURE;\n }\n\n errno = 0;\n read_guest_list(guests, stdin);\n if (errno) {\n perror(&quot;Failed to add a guest&quot;);\n guest_list_free(guests);\n return EXIT_FAILURE;\n }\n\n /*input is done, now output file contents: */\n for (size_t i = 0; i &lt; guests-&gt;count; ++i) {\n const struct Guest *g = guest_list_item(guests, i);\n printf(&quot;Name: %s, Number: %s\\n&quot;, g-&gt;name, g-&gt;number);\n }\n\n guest_list_free(guests);\n return EXIT_SUCCESS;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T13:44:25.347", "Id": "527927", "Score": "0", "body": "Thanks for your detailed feedback. It helped a lot. I tried to implement the guestList structure and free-function you recommended. However, I do not know whether the name and number pointers at position guests.count have already been assigned, when guest_list_free is called. As both pointers use unitialized memory, do I risk to hand \"random pointers\" to free? If yes, how do I avoid it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T06:56:10.593", "Id": "527965", "Score": "0", "body": "The best way is to write a function that returns either a null pointer (if the allocation failed) or a pointer to a fully initialised structure. If you have ever done any object-oriented programming (perhaps in Java, for example), you'll recognise that pattern as a _constructor_." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T07:02:23.173", "Id": "527966", "Score": "0", "body": "I've edited to show a suitable constructor." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T15:33:23.063", "Id": "528201", "Score": "0", "body": "I can't help but see this as a continuous example of why C++ is better. Check for error and free up all the memory before exiting: destructors. Tracking space remaining in a collection and re-allocating when it gets full: `vector`. Fixed size string buffers when reading input -- yipes! `guest_list_free` : just busywork that you *must* get right, but the compiler should have done for you." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T07:43:43.120", "Id": "528835", "Score": "1", "body": "@JDługosz, agreed. C++, Java, Python and many other languages are much easier on the programmer. I guess the only good reason to choose C for this is the one given in the question: \"_trying to improve my C skills_\"... ;)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T11:12:52.700", "Id": "267727", "ParentId": "267725", "Score": "8" } }, { "body": "<p>Toby Speight has already given a great answer, I'd just like to highlight the security issues:</p>\n<h1>Remove the line length limit</h1>\n<p>You have arbitrarily set a limit to the length of lines. However, what happens if the input has a line longer than that? If <a href=\"https://en.cppreference.com/w/c/io/fgets\" rel=\"nofollow noreferrer\"><code>fgets()</code></a> reaches the maximum line length, it will stop reading any further characters, and will return a pointer to the start of the buffer. That means the buffer has no newline character at the end. You are deleting the last character blindly. You then proceed to parse the line, reading incorrect data.</p>\n<p>Even worse, the next call to <code>fgets()</code> will start where the previous one stopped. So it will continue reading the remainder of the line.</p>\n<p>A 100 character line length would mean you would not be able to store the full name of people like <a href=\"https://en.wikipedia.org/wiki/Pablo_Picasso\" rel=\"nofollow noreferrer\">Picasso</a>, and there are people with <a href=\"https://www.guinnessworldrecords.com/world-records/67285-longest-personal-name\" rel=\"nofollow noreferrer\">even longer names</a>.</p>\n<p>Note that phone numbers themselves can be quite long; the <a href=\"https://en.wikipedia.org/wiki/E.164\" rel=\"nofollow noreferrer\">E.164 standard</a> limits them to 15 digits, but that is excluding any dashes or leading + sign, and also excludes any further digits needed for private phone switches. While I don't think you will ever run into a 100 digit telephone number, it can reduce the amount of characters available for the person's name.</p>\n<p>Failure to correctly parse the line and continue without detecting the problem is a security issue. To solve it, there are a few options:</p>\n<ul>\n<li>Use a buffer allocated with <code>malloc()</code>, and if there is no newline at the end of the buffer when <code>fgets()</code> returns, double the size of the buffer with <code>realloc()</code>, and try to read the remaining part of the line with <code>fgets()</code>, until you do find a newline.</li>\n<li>Use the POSIX <a href=\"https://en.cppreference.com/w/c/experimental/dynamic/getline\" rel=\"nofollow noreferrer\"><code>getline()</code></a> function, which will allocate a buffer that is large enough for you.</li>\n<li>Use a fixed but much larger size for the buffer, but exit with an error if there is no newline at the end of the buffer after calling <code>fgets()</code>.</li>\n</ul>\n<h1>Validate the input</h1>\n<p>The CSV file might come from an untrusted source, or might have been corrupted in some way due to disk or network errors. It is possible that NUL bytes or <a href=\"https://en.wikipedia.org/wiki/Control_character\" rel=\"nofollow noreferrer\">control characters</a> are part of the lines. It is a good idea to validate the input, by checking that there are no unexpected characters in any of the fields.</p>\n<p>However, don't be too strict; in particular, don't assume anyhing about the format of <a href=\"https://shinesolutions.com/2018/01/08/falsehoods-programmers-believe-about-names-with-examples/\" rel=\"nofollow noreferrer\">names</a>.</p>\n<h1>Avoid using <code>strtok()</code></h1>\n<p>The function <code>strtok()</code> stores its state in a global buffer. This is fine for your program as it is now, but it will be a problem if your program grows and more parts of it want to parse things with <code>strtok()</code>. It is not thread-safe, and also has issues with <a href=\"https://en.wikipedia.org/wiki/Reentrancy_(computing)\" rel=\"nofollow noreferrer\">reentrancy</a>. I recommend you either use the C11 <a href=\"https://en.cppreference.com/w/c/string/byte/strtok\" rel=\"nofollow noreferrer\"><code>strtok_s()</code></a> or the POSIX <a href=\"https://man7.org/linux/man-pages/man3/strtok.3.html\" rel=\"nofollow noreferrer\"><code>strtok_r()</code></a> if available.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T11:37:55.437", "Id": "267728", "ParentId": "267725", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T10:37:10.783", "Id": "267725", "Score": "4", "Tags": [ "c", "file-system", "memory-management" ], "Title": "CSV file reader" }
267725
<p>Here is a template class to calculate various CRC checksums. I go out my way to achieve a good C++ encapsulation for a <a href="https://barrgroup.com/downloads/code-crc-c" rel="noreferrer">C style code </a>.</p> <p>Any advice or suggestion is welcome.</p> <pre><code>//crc.hpp #ifndef __CRC_HEADER_H__ #define __CRC_HEADER_H__ #include &lt;array&gt; #include &lt;mutex&gt; template &lt;typename T, T POLYNOMIAL, T INITIAL_REMAINDER, T FINAL_XOR_VALUE, bool REFLECT_DATA, bool REFLECT_REMAINDER&gt; class CrcCal { public: CrcCal(); T Cal(const uint8_t *message, int nBytes) const; private: unsigned long reflect(unsigned long data, unsigned char nBits) const; void InitTable(void); static std::array&lt;T, 256&gt; crc_table; static constexpr uint32_t WIDTH{ 8 * sizeof(T) }; static constexpr uint32_t TOPBIT{ 1u &lt;&lt; (uint32_t)(WIDTH - 1) }; static std::once_flag init_flag; }; using Crc32 = CrcCal&lt;uint32_t, 0x04C11DB7u, 0xFFFFFFFFu, 0xFFFFFFFFu, true, true&gt;; template class CrcCal&lt;uint32_t, 0x04C11DB7u, 0xFFFFFFFFu, 0xFFFFFFFFu, true, true&gt;; #endif //cpp #include &quot;crc.hpp&quot; template &lt;typename T, T POLYNOMIAL, T INITIAL_REMAINDER, T FINAL_XOR_VALUE, bool REFLECT_DATA, bool REFLECT_REMAINDER&gt; unsigned long CrcCal&lt;T, POLYNOMIAL, INITIAL_REMAINDER, FINAL_XOR_VALUE, REFLECT_DATA, REFLECT_REMAINDER&gt;::reflect(unsigned long data, unsigned char nBits) const { unsigned long reflection = 0x00000000; unsigned char bit; for (bit = 0; bit &lt; nBits; ++bit) { if (data &amp; 0x01) { reflection |= (1 &lt;&lt; ((nBits - 1) - bit)); } data = (data &gt;&gt; 1); } return (reflection); } template &lt;typename T, T POLYNOMIAL, T INITIAL_REMAINDER, T FINAL_XOR_VALUE, bool REFLECT_DATA, bool REFLECT_REMAINDER&gt; T CrcCal&lt;T, POLYNOMIAL, INITIAL_REMAINDER, FINAL_XOR_VALUE, REFLECT_DATA, REFLECT_REMAINDER&gt;::Cal(const uint8_t *message, int nBytes) const { T remainder = INITIAL_REMAINDER; unsigned char data; int byte; if (REFLECT_DATA) { for (byte = 0; byte &lt; nBytes; ++byte) { data = ((unsigned char) reflect(message[byte], 8)) ^ (remainder &gt;&gt; (WIDTH - 8)); remainder = crc_table[data] ^ (remainder &lt;&lt; 8); } } else { for (byte = 0; byte &lt; nBytes; ++byte) { data = (message[byte]) ^ (remainder &gt;&gt; (WIDTH - 8)); remainder = crc_table[data] ^ (remainder &lt;&lt; 8); } } if (REFLECT_REMAINDER) { return (((T) reflect(remainder, WIDTH)) ^ FINAL_XOR_VALUE); } else { return (remainder ^ FINAL_XOR_VALUE); } } template &lt;typename T, T POLYNOMIAL, T INITIAL_REMAINDER, T FINAL_XOR_VALUE, bool REFLECT_DATA, bool REFLECT_REMAINDER&gt; void CrcCal&lt;T, POLYNOMIAL, INITIAL_REMAINDER, FINAL_XOR_VALUE, REFLECT_DATA, REFLECT_REMAINDER&gt;::InitTable(void) { T remainder; int dividend; unsigned char bit; for (dividend = 0; dividend &lt; 256; ++dividend) { remainder = dividend &lt;&lt; (WIDTH - 8); for (bit = 8; bit &gt; 0; --bit) { if (remainder &amp; TOPBIT) { remainder = (remainder &lt;&lt; 1) ^ POLYNOMIAL; } else { remainder = (remainder &lt;&lt; 1); } } crc_table[dividend] = remainder; } } template &lt;typename T, T POLYNOMIAL, T INITIAL_REMAINDER, T FINAL_XOR_VALUE, bool REFLECT_DATA, bool REFLECT_REMAINDER&gt; CrcCal&lt;T, POLYNOMIAL, INITIAL_REMAINDER, FINAL_XOR_VALUE, REFLECT_DATA, REFLECT_REMAINDER&gt;::CrcCal() { std::call_once(init_flag, &amp;CrcCal&lt;T, POLYNOMIAL, INITIAL_REMAINDER, FINAL_XOR_VALUE, REFLECT_DATA, REFLECT_REMAINDER&gt;::InitTable, this); } template &lt;typename T, T POLYNOMIAL, T INITIAL_REMAINDER, T FINAL_XOR_VALUE, bool REFLECT_DATA, bool REFLECT_REMAINDER&gt; std::array&lt;T, 256&gt; CrcCal&lt;T, POLYNOMIAL, INITIAL_REMAINDER, FINAL_XOR_VALUE, REFLECT_DATA, REFLECT_REMAINDER&gt;::crc_table; template &lt;typename T, T POLYNOMIAL, T INITIAL_REMAINDER, T FINAL_XOR_VALUE, bool REFLECT_DATA, bool REFLECT_REMAINDER&gt; std::once_flag CrcCal&lt;T, POLYNOMIAL, INITIAL_REMAINDER, FINAL_XOR_VALUE, REFLECT_DATA, REFLECT_REMAINDER&gt;::init_flag; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T13:17:16.717", "Id": "527925", "Score": "1", "body": "Do you have the test suite that goes with this? It's probably worth including it the same review, as that helps us understand what testing you've done, and what you've missed. It also helps validate any suggested changes, which is very much in your own interests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T00:50:57.463", "Id": "527953", "Score": "0", "body": "@TobySpeight I am new to Code Review. Thank you for your advice. I will add it to the post soon." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T17:25:06.830", "Id": "528157", "Score": "0", "body": "I wrote something previously to do this: https://github.com/Loki-Astari/ThorsCrypto/blob/master/src/ThorsCrypto/crc.h reviewed here https://codereview.stackexchange.com/questions/248419/c-crypto-part-4-scram" } ]
[ { "body": "<p>Here are some things that may help you improve your code.</p>\n<h2>Understand the nature of templates</h2>\n<p>In modern C++, putting headers in a header file and the implementation in a <code>.cpp</code> file is common and ingrained. However, in this case, it's also not correct. The reason is that templated functions don't actually cause the compiler to generate any code until and unless the template is instantiated. That means that in this particular case, since all of the functions are templates, <em>all</em> of the code should be in the the <code>.hpp</code> file and you don't need a <code>.cpp</code> file at all.</p>\n<h2>Provide complete code to reviewers</h2>\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used. Here's the <code>main</code> file I used to test:</p>\n<pre><code>#include &quot;crc.hpp&quot;\n#include &lt;iostream&gt;\n#include &lt;iomanip&gt;\n\nint main() {\n CrcCal&lt;uint16_t, 0x1021u, 0xffffu, 0xffffu, true, true&gt; CCITT{};\n const uint8_t message[7] = {0xEE,0x00,0x00,0x00,0x00,0x01,0x20};\n auto crc{CCITT.Cal(message, 7)};\n std::cout &lt;&lt; &quot;CRC is 0x&quot; &lt;&lt; std::hex &lt;&lt; std::setw(4) &lt;&lt; std::setfill('0') \n &lt;&lt; crc &lt;&lt; '\\n';\n}\n</code></pre>\n<h2>Use modern C++ idiom</h2>\n<p>The site from which you've extracted some of this code includes some code that is not idiomatic, modern C++. For example, it includes these lines:</p>\n<pre><code> data = (data &gt;&gt; 1);\n}\nreturn (reflection);\n</code></pre>\n<p>The first line would be better as <code>data &gt;&gt;= 1;</code> and the second should omit the parentheses because <code>return</code> is a keyword and <strong>NOT</strong> a function call.</p>\n<h2>Don't use all capital letters for named constants</h2>\n<p>Traditionally, the use of all capital letters has been reserved for <code>#define</code> constants. To avoid confusing users, don't use such names for anything else, such as <code>WIDTH</code> but also <code>POLYNOMIAL</code>, etc. See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rl-all-caps\" rel=\"noreferrer\">NL.9</a></p>\n<h2>Simplify your functions</h2>\n<p>The body of the <code>reflect</code> call could be much better written, I think, like so:</p>\n<pre><code>unsigned long reflection{0};\nfor (unsigned long outmask{1u}, inmask{1u &lt;&lt; (nBits - 1)}; inmask; inmask &gt;&gt;= 1, outmask &lt;&lt;= 1) {\n if (data &amp; inmask) {\n reflection |= outmask;\n }\n}\nreturn reflection;\n</code></pre>\n<p>The rationale for this is that now only single-bit shifts and bitwise and and or functions are used (no addition, subtraction or multi-bit shifts) which are efficient machine language instructions for most modern processors.</p>\n<h2>Use the required <code>#include</code>s</h2>\n<p>The code uses <code>uint32_t</code> which means that it should <code>#include &lt;cstdint&gt;</code>. It was not difficult to infer, but it helps reviewers if the code is complete.</p>\n<h2>Shift computation to compile time</h2>\n<p>Rather than using <code>call_once</code>, I would suggest letting the compiler create this table instead. The effect is that the table thus requires no runtime overhead at all to compute and it can also be put into ROM which is helpful for such things as embedded systems where RAM space is typically smaller than ROM space. Here's how to do that by simply rewriting your <code>InitTable</code> as a lambda:</p>\n<pre><code>static constexpr auto crc_table = [] {\n std::array&lt;T, 256&gt; tbl{};\n for (int dividend = 0; dividend &lt; 256; ++dividend) {\n T remainder = dividend &lt;&lt; (width - 8);\n for (uint8_t bit = 8; bit &gt; 0; --bit) {\n if (remainder &amp; topbit) {\n remainder = (remainder &lt;&lt; 1) ^ polynomial;\n } else {\n remainder = (remainder &lt;&lt; 1);\n }\n }\n tbl[dividend] = remainder;\n }\n return tbl;\n}();\n</code></pre>\n<p>Note that lambdas are only implicitly <code>constexpr</code> in C++17 and later and that the use of <code>constexpr</code> in C++11 is very limited. It is possible to create a C++11 <code>constexpr</code> version, but it's long, difficult to follow and requires a number of helper functions. See <a href=\"https://codereview.stackexchange.com/questions/93775/compile-time-sieve-of-eratosthenes\">Compile-time sieve of Eratosthenes</a> for an example of how something like this might work.</p>\n<h2>Declare variables as late as possible</h2>\n<p>Don't declare all variables at the top of the function; that's an old C requirement, but it isn't done in C++. Instead, declare them when they are initialized. This avoids many kinds of errors that can occur with inadvertent use of uninitialized varibles.</p>\n<h2>Free your functions</h2>\n<p>There's no real good reason that <code>reflect</code> needs to be a member function. It doesn't even use any of the template parameters, so I'd instead declare it as a free function.</p>\n<h2>Declare functions <code>constexpr</code> if practical</h2>\n<p>Any time a function <em>might</em> be used at compile time, it helps the compiler optimizations if you declare it <code>constexpr</code>. So in this case, I'd write this:</p>\n<pre><code>constexpr unsigned long reflect(unsigned long data, unsigned char nBits) {\n</code></pre>\n<p>See <a href=\"https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines#Rf-constexpr\" rel=\"noreferrer\">F.4</a> for details.</p>\n<p>Note that if you really <em>must</em> use C++11, it is possible to write this in a way that complies with C++11, but it's not pretty:</p>\n<pre><code>constexpr unsigned long reflect(unsigned long reflection, \n unsigned long inmask, unsigned long outmask, \n unsigned long data) \n{\n return inmask ? reflect(reflection | ((data &amp; inmask) ? outmask : 0), \n inmask &lt;&lt; 1, outmask &gt;&gt; 1, data ) : reflection;\n}\nconstexpr unsigned long reflect(unsigned long data, unsigned char nBits) {\n return reflect(0ul, 1ul, 1ul &lt;&lt; (nBits - 1), data);\n}\n</code></pre>\n<p>Generally speaking, in C++11 <code>constexpr</code> one must abuse the <code>?:</code> operator to avoid using <code>if</code>...<code>else</code>, and use recursion to avoid using <code>for</code>.</p>\n<h2>Allow passing modern containers</h2>\n<p>The interface right now is restricted to a very antique C-style of passing a pointer and a length. Better would be to accept a pair of iterators, which would allow many kinds of modern containers such as <code>std::vector</code> or <code>std::array</code> or even <code>std::string_view</code> when you start using C++17.</p>\n<h2>Don't declare variables you'd don't use</h2>\n<p>The code currently contains these two lines:</p>\n<pre><code>using Crc32 = CrcCal&lt;uint32_t, 0x04C11DB7u, 0xFFFFFFFFu, 0xFFFFFFFFu, true, true&gt;;\ntemplate class CrcCal&lt;uint32_t, 0x04C11DB7u, 0xFFFFFFFFu, 0xFFFFFFFFu, true, true&gt;;\n</code></pre>\n<p>The first one is fine, because it only says that <em>if</em> one wants to use a standard <code>Crc32</code>, it's already declared. However, the next line causes a <code>Crc32</code> instantiation which is not necessary.</p>\n<h2>Results</h2>\n<p>Here's a <a href=\"https://godbolt.org/z/WrTY3PaY8\" rel=\"noreferrer\">live version</a> which shows the effects of using most of these suggestions. It also emphasizes the advantage to using <code>constexpr</code> where possible, since it causes this program to be reduced to exactly two runtime instructions:</p>\n<pre><code>#include &quot;crc.hpp&quot;\n\nint main() {\n constexpr CrcCal&lt;uint16_t, 0x1021u, 0xffffu, 0xffffu, true, true&gt; CCITT{};\n constexpr uint8_t message[7] = {0xEE,0x00,0x00,0x00,0x00,0x01,0x20};\n static_assert(CCITT.Cal(message, 7) == 0x1013);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T16:42:22.640", "Id": "527935", "Score": "0", "body": "This code is tagged C++11. I don’t think any of the `constexpr` suggestions will work in C++11, because `std::array` wasn’t `constexpr` until C++17." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T16:54:42.580", "Id": "527936", "Score": "0", "body": "You are right that some of the `constexpr` items are C++17 only. Yet another motivation for updating the compiler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T21:14:33.997", "Id": "527948", "Score": "2", "body": "Honestly, at this point, I don’t think the problem is the compiler, but just a lack of knowledge. I see lots of people insisting they have to work in C++11 (or even C++98!), but I have a hard time believing there are still huge numbers of people using GCC 4.x or Clang 3.x, or otherwise constrained (for intelligent reasons) to ancient standards. I suspect the reason people think they have to use old standards is 5–10 year old FUD. That’s why I’ve decided to stop coddling people using old standards unless they give a DAMN good reason for it; line 1 of my reviews will be “use a modern standard”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T21:16:37.450", "Id": "527949", "Score": "0", "body": "Oh, and I forgot to mention: the illegal identifiers “`__CRC_HEADER_H__`”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T02:04:17.913", "Id": "527954", "Score": "0", "body": "@Edward > \"The interface right now is restricted to a very antique C-style of passing a pointer and a length. Better would be to accept a pair of iterators, which would allow many kinds of modern containers such as `std::vector` or `std::array` or even `std::string_view ` when you start using C++17.\" *Reply*: `std::string_view` is better. `std::vector` and `std::array` add some overload(i.e. need copy memory)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T02:21:38.710", "Id": "527955", "Score": "0", "body": "@indi the illegal identifiers `__CRC_HEADER_H__`? Could you please explain that in more detail?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T03:02:39.493", "Id": "527958", "Score": "0", "body": "@Edward > \"However, the next line causes a Crc32 instantiation which is not necessary.\" ***Reply1***: To hide the implementation of the template class, so I instantiated CRC32. > \"Generally speaking, in C++11 `constexpr` one must abuse the ?: operator to avoid using if...else, and use recursion to avoid using `for`.\" ***Reply2***: Could you please explain that in more detail or suggest some document for me to understand it at higher level?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T07:20:22.233", "Id": "527969", "Score": "2", "body": "@John, indi's point is that identifiers with two consecutive underscores (or beginning with underscore and followed by an uppercase letter) are **reserved identifiers** for the implementation to use for any purpose. You are not permitted to define your own macros with such names; doing so is UB." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T10:40:08.763", "Id": "527978", "Score": "0", "body": "@John, what compiler are you intending to use?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T12:00:06.187", "Id": "527983", "Score": "0", "body": "@Edward g++ 4.9 (Ubuntu 16.04)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T13:28:28.960", "Id": "527986", "Score": "1", "body": "If that's the compiler you are stuck with *and* you can't update or upgrade it, you will either have to forego the benefits of `constexpr` or go through the effort to learn how to use the restrictive C++11 `constexpr` [function restrictions](https://en.wikipedia.org/wiki/C%2B%2B11#constexpr_%E2%80%93_Generalized_constant_expressions). I prefer not to spend my time learning obsolete skills, but you may enjoy the challenge." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T16:07:58.470", "Id": "267736", "ParentId": "267729", "Score": "9" } }, { "body": "<h2>use a function, not a class</h2>\n<p>A <code>CrcCal</code> class instance has no state (non-static member variables). The class therefore has no reason to exist. We can implement the algorithm as a simple function that operates on a range of data, and has some additional parameters, e.g.:</p>\n<pre><code>template&lt;class T, T polynomial, T initial_remainder, T final_xor_value, bool reflect_data, bool reflect_remainder, class It&gt;\nconstexpr T crc(It begin, It end)\n\ntemplate&lt;class It&gt;\nconstexpr std::uint32_t crc_32(It begin, It end) { return crc&lt;std::uint32_t{ 0x04C11DB7 }, std::uint32_t(-1), std::uint32_t(-1), true, true&gt;(begin, end); }\n</code></pre>\n<p>The table cache is a detail that can be taken care of with a static variable - but that does not need to be in a class either.</p>\n<p>Note that the current interface forces the choice of <code>polynomial</code>, <code>initial_remainder</code>, etc. to happen at compile-time only. It might be nice to change all these settings to be standard function arguments. Since the function is <code>constexpr</code> we'd then get the best of both worlds (compile-time evaluation where possible, otherwise run-time evaluation). Unfortunately changing <code>polynomial</code> from a template argument to a function argument would cause problems with the creation of the cache table at compile time, since since C++ lacks <code>static constexpr</code> or <code>static</code> variables inside <code>constexpr</code> functions. :(</p>\n<h2>add safety and reduce complexity with assertions</h2>\n<p>It's probable that your code works for sensible inputs... but there are no guarantees that the inputs will be sensible, and there are a lot of possibilities to consider, e.g.:</p>\n<p>What if message is a nullptr? What if <code>nBytes</code> is negative?</p>\n<p>What if <code>T</code> is a signed integer? And what if it's 8 bits, what if it's 64 bits. What if it's not an integral type at all?</p>\n<p><code>unsigned long</code> isn't a fixed size type... will the code work for all its possible sizes?</p>\n<p>We can use fixed size types and <code>static_assert</code>ions at compile time to rule out cases that we don't want to handle, and <code>assert</code>ions to catch remaining issues at run-time. Besides preventing edge-cases that would cause incorrect behavior (bugs), this helps catch user errors, documents the code, and reduces the burden of maintenance by reducing the complexity of the implementation.</p>\n<h2>avoid implicit conversions</h2>\n<p><code>reflect(message[byte], 8)</code> this hides an important change from <code>uint8_t</code> to <code>uint32_t</code> in an implicit cast. It works fine at the moment, but if we decided to change <code>reflect</code> to a template function it would suddenly break.</p>\n<p><code>(message[byte]) ^ (remainder &gt;&gt; (WIDTH - 8))</code> another hidden cast.</p>\n<p>We should instead use a <code>static_cast</code> or at least brace initialization (<code>std::uint32_t{ message[byte] }</code>) to highlight the changes explicitly.</p>\n<h2>use the <code>&lt;limits&gt;</code> header to write <code>reflect</code> as a template function</h2>\n<p>It looks like the second parameter of <code>reflect</code> is always the number of bits in the original type, before casting to <code>unsigned long</code>. Instead of casting the value, hard-coding the number of bits as an argument, and then casting the result back, why not just write <code>reflect</code> as a template function taking a value of the appropriate type?</p>\n<p>We can get the bit width directly from the type with <code>std::numeric_limits&lt;T&gt;::digits</code>.</p>\n<p>We can restrict the function to sensible types with <code>enable_if</code>, or a <code>static_assert</code>, e.g.:</p>\n<pre><code>static_assert(std::is_unsigned_v&lt;T&gt;, &quot;reflect expects an unsigned integral type.&quot;);\n</code></pre>\n<hr />\n<p>So maybe something like: <a href=\"https://godbolt.org/z/fjhcqP8hG\" rel=\"noreferrer\">https://godbolt.org/z/fjhcqP8hG</a> (untested)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T12:14:10.647", "Id": "528054", "Score": "1", "body": "Good comments! If I were writing this in C++20, I'd use [c++20 concepts](https://en.cppreference.com/w/cpp/language/constraints) to implement some of your ideas. But as a practical matter, I'd actually just use [Boost.CRC](https://www.boost.org/doc/libs/1_77_0/doc/html/crc.html). :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:38:48.453", "Id": "528066", "Score": "1", "body": "You can leave off the `static` and just use `constexpr` for variables scoped inside a function. If you don't expose its address somehow, it generates compile-time constant code and doesn't make a copy for each call." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T17:29:11.747", "Id": "528158", "Score": "1", "body": "I disagree with writing this as a function (rather than a class). This assumes you have all the data available at one time and ignored streaming interfaces. It may be very useful to be able to apply the data in chunks and thus you need to maintain state between the chunks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T14:24:40.223", "Id": "528200", "Score": "0", "body": "@MartinYork I agree with you." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:13:20.723", "Id": "267786", "ParentId": "267729", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T12:11:48.940", "Id": "267729", "Score": "5", "Tags": [ "c++", "c++11", "template", "checksum" ], "Title": "C++ template class to calculate CRC" }
267729
<p>I have this type of table:</p> <pre class="lang-php prettyprint-override"><code>$this-&gt;data = [ 0 =&gt; [ 'reference' =&gt; 'ABC123', 'title' =&gt; 'lorem', 'parent' =&gt; 12, ], 1 =&gt; [ 'reference' =&gt; 'ABC456', 'title' =&gt; 'ipsum', 'parent' =&gt; 42, ], 2 =&gt; [ 'reference' =&gt; 'ABC789', 'title' =&gt; 'dolor', 'parent' =&gt; 36, ], 3 =&gt; [ 'reference' =&gt; 'ABC123', 'title' =&gt; 'lorem', 'parent' =&gt; 18, ], 4 =&gt; [ 'reference' =&gt; 'ABC789', 'title' =&gt; 'dolor', 'parent' =&gt; 26, ] ]; </code></pre> <p>And I made this script to remove duplicates with keeping different known keys as subarrays:</p> <pre class="lang-php prettyprint-override"><code>// Get number of duplicates for each 'reference' of $this-&gt;data $occurences = array_count_values(array_column($this-&gt;data, 'reference')); // Array to put index to remove of $this-&gt;data $to_unset = []; foreach($occurences as $reference =&gt; $count) { // If item unique, continue if($count == 1) continue; // Get all indexes of 'reference' inside $this-&gt;data $indexes = array_keys(array_column($this-&gt;data, 'reference'), $reference); // Keep first index of occurence $first_index = $indexes[0]; // Remove it from indexes unset($indexes[0]); // Keep the first occurence $model = $this-&gt;data[$first_index]; // Convert different known keys as array $model['parent'] = [$model['parent']]; foreach($indexes as $index){ // Group 'parent' in same array array_push($model['parent'], $this-&gt;data[$index]['parent']); // Put index to remove then array_push($to_unset, $index); } // Replace the first item occurence by model $this-&gt;data[$first_index] = $model; } // Remove all occurences $this-&gt;data = array_diff_key($this-&gt;data, array_flip($to_unset)); // Reindex $this-&gt;data = array_values($this-&gt;data); </code></pre> <p>To get this:</p> <pre class="lang-php prettyprint-override"><code>$array = [ 0 =&gt; [ 'reference' =&gt; 'ABC123', 'title' =&gt; 'lorem', 'parent' =&gt; [12, 18], ], 1 =&gt; [ 'reference' =&gt; 'ABC456', 'title' =&gt; 'ipsum', 'parent' =&gt; 42, ], 2 =&gt; [ 'reference' =&gt; 'ABC789', 'title' =&gt; 'dolor', 'parent' =&gt; [36, 26], ] ]; </code></pre> <p>But my script is very slow (20 seconds for +13k items), how can I improve it ?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T15:35:51.920", "Id": "527931", "Score": "0", "body": "For a given reference, if present multiple times, can it have different titles?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T06:24:26.897", "Id": "527963", "Score": "0", "body": "What I need is to remove the duplicate data by grouping by the key \"reference\" and grouping the possible different values ​​in subarrays ;-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T22:36:47.987", "Id": "528007", "Score": "0", "body": "Same basic technique as https://stackoverflow.com/a/68885107/2943403 (don't mind the revenge vote on my answer -- it's Stack Overflow)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T21:25:50.867", "Id": "528104", "Score": "0", "body": "@Aur what is the source of this input data? Perhaps it can be restructured in an earlier layer. Or maybe I should ask _why_ you are doing this. Is this an XY Problem? Why do you need all 13000 rows of data?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T16:46:10.707", "Id": "528156", "Score": "0", "body": "@mickmackusa This input data comes from a data interface which unfortunately I cannot optimize further" } ]
[ { "body": "<h2>Broad review</h2>\n<p>It seems this code is part of a class method, yet it is difficult to know anything about the method or class other than the fact that it has a <code>data</code> member.</p>\n<p>Consider following <a href=\"https://www.php-fig.org/psr/psr-1/\" rel=\"nofollow noreferrer\">PSR-1</a> and <a href=\"https://www.php-fig.org/psr/psr-12/\" rel=\"nofollow noreferrer\">PSR-12</a>.</p>\n<p>Indentation is not always consistent - e.g. some lines are indented with two spaces and others appear to have four spaces yet at the same indentation level. For example:</p>\n<blockquote>\n<pre><code> // Keep the first occurence\n $model = $this-&gt;data[$first_index];\n // Convert different known keys as array\n $model['parent'] = [$model['parent']];\n</code></pre>\n</blockquote>\n<p>From PSR-12 Section 2. General:</p>\n<blockquote>\n<h3>2.4 Indenting</h3>\n<p>Code MUST use an indent of 4 spaces for each indent level, and MUST NOT use tabs for indenting.</p>\n</blockquote>\n<hr />\n<p>There is a loose equality comparison at the start of the loop:</p>\n<blockquote>\n<pre><code>if($count == 1) continue;\n</code></pre>\n</blockquote>\n<p>Since both operands in the condition should be integers strict equality comparison (i.e. <code>===</code>) can be used. <a href=\"https://softwareengineering.stackexchange.com/q/126585/244085\">It is a good habit to use strict equality operators</a> whenever possible.</p>\n<h2>Possible optimizations</h2>\n<p>My initial suggestion was going to be to make a new array with the <em>reference</em> values as the keys and have the values be arrays from the <em>parent</em> values of the original data, however that may likely require a lot more memory than is acceptable.</p>\n<p>If memory allows, it could be simplified like this:</p>\n<pre><code>$trimmedData = [];\nforeach ($this-&gt;data as $model) {\n // reference already exists in final array\n if (isset($trimmedData[$model['reference']])) {\n $target = &amp;$trimmedData[$model['reference']];\n // ensure parent list is an array\n if (!is_array($target['parent'])) {\n $target['parent'] = [$target['parent']];\n }\n $target['parent'][] = $model['parent'];\n } else {\n //set the index using the reference value\n $trimmedData[$model['reference']] = $model;\n }\n}\n// reindex, remove index by reference\n$this-&gt;data = array_values($trimmedData);\n</code></pre>\n<hr />\n<p>I noticed that there is a call to <code>array_column($this-&gt;data, 'reference')</code> on two lines:</p>\n<blockquote>\n<pre><code>$occurences = array_count_values(array_column($this-&gt;data, 'reference'));\n</code></pre>\n</blockquote>\n<p>as well as this line within the <code>foreach</code> loop:</p>\n<blockquote>\n<pre><code>$indexes = array_keys(array_column($this-&gt;data, 'reference'), $reference);\n</code></pre>\n</blockquote>\n<p>For the sample data those inner calls to get the values in the <code>reference</code> column yield the same value - that could be stored in a variable before the loop and used in those two lines, which would eliminate the call on each iteration of the loop where the count of that value occurs more than once.</p>\n<hr />\n<p>Instead of storing <code>$first_index</code> and then calling <code>unset</code> on that index, you could consider doing that in one line using <a href=\"https://php.net/array_splice\" rel=\"nofollow noreferrer\"><code>array_splice()</code></a> though I'm not sure if performance would be better or worse.</p>\n<p>Instead of:</p>\n<blockquote>\n<pre><code>// Keep first index of occurence\n$first_index = $indexes[0];\n// Remove it from indexes\nunset($indexes[0]);\n</code></pre>\n</blockquote>\n<p>use <code>array_splice()</code>:</p>\n<pre><code>$first_index = array_splice($indexes, 0, 1)[0];\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:03:47.610", "Id": "528062", "Score": "0", "body": "Thanks ! array_reduce method is better, but still too long (~19 seconds now)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T15:14:29.830", "Id": "528071", "Score": "0", "body": "In hindsight I should have mentioned using `array_reduce()` would most likely be slower because it is executing an additional function for each iteration - perhaps that wasn't worth mentioning" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T21:13:44.910", "Id": "267770", "ParentId": "267730", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T12:26:25.537", "Id": "267730", "Score": "1", "Tags": [ "performance", "php", "array" ], "Title": "PHP Group associative Array duplicates and make subarrays of different values" }
267730
<p>As the title, I am building a pre-loader for Wordpress that will deliver performance boosts in loading, as well as metrics such as Google Page Speed.</p> <p>Now, this is something that we do at work, and I could quite easily copy what has been used there but feel it is 'stolen knowledge'. I could be writing anything and have very little understanding of what I am typing as it was developed by seniors.</p> <p>So, given that I know what the basics of the pre-loader are (load critical styles, defer certain scripts, remove unwanted WP scripts) I had a bash at creating one myself that appears to work:</p> <pre class="lang-php prettyprint-override"><code>// If there are problems with caching, // change this version number define('CACHE_VERSION', '1.0.0'); class WpboilerInliner { function __construct() { add_action( 'init', array(&amp;$this, 'init') ); add_action( 'wp_head', array(&amp;$this, 'addCriticalCss') ); add_action( 'wp_footer', array(&amp;$this, 'addGeneralCss') ); } // This will add the critical CSS to the header function addCriticalCss() { // Set to not load in the admin as this will 'break' it if(!is_admin()) { $criticalFonts = '&lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.googleapis.com&quot;&gt; &lt;link rel=&quot;preconnect&quot; href=&quot;https://fonts.gstatic.com&quot; crossorigin&gt; &lt;link href=&quot;https://fonts.googleapis.com/css2?family=Poppins:ital,wght@0,200;0,300;1,300&amp;display=swap&quot; rel=&quot;stylesheet&quot;&gt; '; $criticalCSSContent = file_get_contents( get_template_directory_uri() . '/css/atf.css' ); $criticalCSS = &quot;&lt;style type='text/css'&gt; &lt;!-- BEGIN CRITICAL STYLES --&gt; {$criticalCSSContent} &lt;!-- END CRITICAL STYLES --&gt; &lt;/style&gt;&quot;; echo $criticalFonts . $criticalCSS; } } // General styles, these will be added in the footer function addGeneralCss() { // Add the filename to be added to the footer(below the fold) here // Add files in their correct cascade order // e.g filename.css // filename.min.css // subdirectory/filename.css $generalCssFileName = array( 'general.css', 'type.css', ); foreach($generalCssFileName as $cssFileName) { $linkFormat = '&lt;link rel=&quot;stylesheet&quot; href=&quot;' . get_template_directory_uri() . '/css/%s?ver=%s&quot; /&gt;'; $cssLink = sprintf($linkFormat, $cssFileName, CACHE_VERSION); echo $cssLink; } } function init() { // Remove everything to do with emojis remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' ); add_filter( 'wp_resource_hints', 'disable_emojis_remove_dns_prefetch', 10, 2 ); // Remove version number from header remove_action( 'wp_head', 'wp_generator' ); remove_action( 'wp_head', 'wlwmanifest_link'); remove_action( 'wp_head', 'rsd_link' ); // Removes shortlink remove_action( 'wp_head', 'wp_shortlink_wp_head' ); // Removes feed links remove_action( 'wp_head', 'feed_links', 2 ); // // Removes comments feed remove_action( 'wp_head', 'feed_links_extra', 3 ); /** * Filter function used to remove the TinyMCE emoji plugin * * @param array $plugins * @return array Difference between the two arrays */ function disable_emojis_tinymce( $plugins ) { if( is_array( $plugins ) ) { return array_diff( $plugins, array( 'wpemoji' ) ); } else { return array(); } } /** * Remove emoji CDN hostname from DNS prefetching hints * * @param array $urls URLs to print for resource hints * @param string $relation_type The relation type the URLs are printed for * @return array Difference between the two arrays */ function disable_emojis_remove_dns_prefetch( $urls, $relation_type ) { if( 'dns-prefetch' == $relation_type ) { /** This filter is documented in wp-includes/formatting.php */ $emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' ); $urls = array_diff( $urls, array( $emoji_svg_url ) ); } return $urls; } // Load JS files wp_enqueue_script('wpboiler-critical-js', get_template_directory_uri() . '/js/atf.min.js', array(), CACHE_VERSION, false); wp_enqueue_script('wpboiler-general-js', get_template_directory_uri() . '/js/general.min.js', array(), CACHE_VERSION, true); } } $wpboilerInliner = new WpboilerInliner(); </code></pre> <p>Are there ways of improving this? It has not yet been tested with plugins, but on a basic install it seems to work as expected (from what I can tell). I came into an issue with the admin area when trying to load in the fonts and the critical styles which is why they are wrapped in <code>!is_admin()</code>. Functions <code>disable_emojis_tinymce()</code> and <code>disable_emojis_remove_dns_prefetch()</code> were taken from a post by <a href="https://kinsta.com/knowledgebase/disable-emojis-wordpress/" rel="nofollow noreferrer">Kinsta</a>.</p> <p>Are there methods I can improve here? Are there some major errors that I am likely to encounter with what I have currently written? My PHP knowledge is limited so I understand some of the more basic concepts such as <code>sprintf</code> and the basic use of arrays and loops.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T13:33:27.957", "Id": "267731", "Score": "0", "Tags": [ "php", "wordpress" ], "Title": "Building a pre-loader for performance gains in Wordpress" }
267731
<p>Given a rectilinear path, find if it has a loop. A rectilinear path is made up of made up of alternating horizontal and vertical segments.</p> <p>Input =&gt; Ordered set of points representing ra ectilinear path. Points have been sanitised to ensure that they represent alternating horizontal and vertical segments. This means there are no two consecutive horizontal (or vertical) segments.</p> <p>Output =&gt; <code>True</code> if it has loop, <code>False</code> otherwise.</p> <p><a href="https://i.stack.imgur.com/lI70I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lI70I.png" alt="enter image description here" /></a></p> <hr /> <p>I could think of two algorithms.</p> <h1>Algorithm 1</h1> <p><strong>For a loop, there must be crossing between horizontal and vertical line segments.</strong><br /> <strong>Crossing/Overlap of two horizontal (or vertical) line segments can't lead to loop.</strong></p> <ol> <li>Break path into horizontal and vertical line segments.</li> <li>Check if any horizontal line segment crosses any vertical line segment.</li> <li>If crossing found return <code>True</code>. Else return <code>False</code></li> </ol> <h2>Algorithm 1 Complexity:</h2> <ul> <li>N points means N-1 line segments.</li> <li>Vertical segment count is (N-1)/2. Same for horizontal segment count.</li> <li>Checking each pair of horizontal and vertical segments means (N-1)(N-2)/4 check. That gives complexity <strong>O(N²)</strong>.</li> </ul> <hr /> <h1>Algorithm 2</h1> <p><strong>For a loop, there must be crossing between horizontal and vertical line segments.</strong><br /> <strong>These line segments shouldn't be consecutive to each other in rectilinear path.</strong></p> <ol> <li>Break path into horizontal and vertical line segments.</li> <li>Sort vertical line segments based on their x-values.</li> <li>Iterate over horizontal line segments and check if any vertical line segment falls in its x-range. Use binary search over sorted vertical segments to find candidate vertical segments.</li> <li>Check if horizontal line segment cross with any of the vertical line segments.</li> <li>If crossing found return <code>True</code>. Else return <code>False</code></li> </ol> <h2>Algorithm 2 Complexity:</h2> <ul> <li>Split into horizontal and vertical segments = O(N).</li> <li>vertical segment count = (N-1)/2.</li> <li>Sorting vertical segments: O(NLogN)</li> <li>Iteration over horizontal segment = O(N).</li> <li>For each iteration, Binary search O(LogN).<br /> For each iteration, Check for crossing with candidate vertical segments. Worst case (N-1)/4.</li> <li>Worst case complexity remains <strong>O(N²)</strong>. But number of pairs checked will be less than for Algorithm 1.</li> </ul> <hr /> <h1>Implementation of Algorithm 2</h1> <pre><code>#Code for Algorithm 2 from functools import cmp_to_key # Represents line_segment which is either horizontal or vertical. class line_segment: __start_point = (0, 0) __end_point = (0, 0) def __init__(self, start_point, end_point): if start_point[0] == end_point[0]: self.__start_point = (start_point, end_point)[start_point[1] &gt; end_point[1]] self.__end_point = (start_point, end_point)[start_point[1] &lt; end_point[1]] else: self.__start_point = (start_point, end_point)[start_point[0] &gt; end_point[0]] self.__end_point = (start_point, end_point)[start_point[0] &lt; end_point[0]] def does_intersect(self, target_line_segment): is_vertical = self.is_segment_vertical() is_traget_vertical = target_line_segment.is_segment_vertical() # Check for parallel segments if is_vertical and is_traget_vertical: return False if is_vertical: return self.__start_point[0] &gt;= target_line_segment.__start_point[0] and \ self.__start_point[0] &lt;= target_line_segment.__end_point[0] and \ target_line_segment.__start_point[1] &gt;= self.__start_point[1] and \ target_line_segment.__start_point[1] &lt;= self.__end_point[1] else: return target_line_segment.__start_point[0] &gt;= self.__start_point[0] and \ target_line_segment.__start_point[0] &lt;= self.__end_point[0] and \ self.__start_point[1] &gt;= target_line_segment.__start_point[1] and \ self.__start_point[1] &lt;= target_line_segment.__end_point[1] def is_segment_vertical(self): return self.__start_point[0] == self.__end_point[0] def get_value(self): if self.is_segment_vertical(): return self.__start_point[0] else: return self.__start_point[1] def get_non_constant_start_coordinate(self): if self.is_segment_vertical(): return self.__start_point[1] else: return self.__start_point[0] def get_non_constant_end_coordinate(self): if self.is_segment_vertical(): return self.__end_point[1] else: return self.__end_point[0] # Line segment comparator def compare(item_1, item_2): return item_1[0].get_value() - item_2[0].get_value() def binary_serach_comparator(segment, search_value): return segment[0].get_value() - search_value def binary_serach(sorted_collection, serach_value, comparator): high = len(sorted_collection) - 1 low = 0 index = -1 mid = 0 while(low &lt;= high): mid = int((low + high)/2) comparator_value = comparator(sorted_collection[mid], serach_value) if comparator_value &lt; 0: low = mid + 1 elif comparator_value &gt; 0: high = mid - 1 else: index = mid break return (index, low, high) def split_path_in_segments(path_points): vertical_segment_start_index = (0, 1) [path_points[0][0] == path_points[1][0]] vertical_segments = [(line_segment(path_points[index], path_points[index + 1]), index)\ for index in range(vertical_segment_start_index, len(path_points) - 1, 2)] horizontal_segments = [(line_segment(path_points[index], path_points[index + 1]), index)\ for index in range(int(not(vertical_segment_start_index)), len(path_points) - 1, 2)] return vertical_segments, horizontal_segments def find_segments_in_range(segments, range_start, range_end): (start_index, start_low, start_high) = binary_serach(segments, range_start, binary_serach_comparator) (end_index, end_low, end_high) = binary_serach(segments, range_end, binary_serach_comparator) return (start_low, end_high) # Input: Ordered set of points representing rectilinear paths # which is made up of alternating horizontal and vertical segments def check_loop(path_points): # For loop we need 4 or more segments. Hence more than 5 points if len(path_points) &lt;= 4: return False vertical_segments, horizontal_segments = split_path_in_segments(path_points) # Sort vertical segmnets for easy serach vertical_segments = sorted(vertical_segments, key=cmp_to_key(compare)) # Iterate through horizontal segments, find vertical segments # which fall in rane of horizontal segment and check for intersection for horizontal_counter in range(len(horizontal_segments)): horizontal_segment = horizontal_segments[horizontal_counter][0] horizontal_segment_index = horizontal_segments[horizontal_counter][1] (start, end) = find_segments_in_range(vertical_segments,\ horizontal_segment.get_non_constant_start_coordinate(),\ horizontal_segment.get_non_constant_end_coordinate()) for vertical_counter in range(start, end + 1): vertical_segment = vertical_segments[vertical_counter][0] vertical_segment_index = vertical_segments[vertical_counter][1] # Avoid adjacent segments. They will always have one endpoint in common if abs(horizontal_segment_index - vertical_segment_index) &lt;= 1: continue if horizontal_segment.does_intersect(vertical_segment): return True return False print(check_loop([(0,0), (5,0), (5, 5)])) # False print(check_loop([(0,0), (5,0), (5, 5), (0, 5), (0, 0)])) # True print(check_loop([(0,0), (5,0), (5, 5), (4, 5)])) # False print(check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, 2)])) # False print(check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, -1)])) # True print(check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, 0)])) # True print(check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2)]))# False print(check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2), (11, 2), (11, 1), (-5, 1), (-5, 15)]))# False print(check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2), (10, -1), (2, -1), (2, 15)]))# True </code></pre> <hr /> <h1>Review request</h1> <ol> <li>Algorithm improvements.</li> <li>Functional correctness of implemented algorithm.</li> <li>Boundary and error cases.</li> <li>Python-specific feedback.</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T11:00:32.337", "Id": "527980", "Score": "0", "body": "*“For loop there must be crossing between horizontal and vertical line segments”* – What about the path (1, 0) -> (3, 0) -> (3, 1) -> (0, 1) -> (0, 0) -> (2, 0) ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T12:17:45.983", "Id": "527984", "Score": "0", "body": "@MartinR: There is an assumption that overlapping segments will be merged during sanitization step before calling into check_loop. So in your example, input should become (3, 0) -> (3, 1) ->(0, 1)->(0, 0)->(3, 0). It will become a loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T15:52:32.400", "Id": "527988", "Score": "0", "body": "Are the coordinates guaranteed to be integral or may they be floating-point? Are there any coordinate limits?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T15:55:37.517", "Id": "527989", "Score": "1", "body": "Coordinates are guaranteed to be integers. No restriction on number of points." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T16:04:34.743", "Id": "527992", "Score": "0", "body": "Is there a restriction on the range of the coordinates? i.e. 0 <= x < 1000" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T16:21:04.817", "Id": "527993", "Score": "1", "body": "@Reinderien: No restriction on range assumed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T20:28:14.907", "Id": "528002", "Score": "0", "body": "_Points have been sanitised_ - do you mean prior to entering this program, or that your implementation is responsible for doing this sanitisation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T07:48:24.293", "Id": "528138", "Score": "1", "body": "`binary_serach`? You'll make your code more maintainable if you correct the spellings." } ]
[ { "body": "<p>I'm not going to really talk much about the algorithm for the first part, and more about Python usage.</p>\n<ul>\n<li><code>line_segment</code> needs to be <code>LineSegment</code> by PEP8</li>\n<li><code>__start_point</code> should not be double-underscored, and should not be declared at the static level, so delete <code>__start_point = (0, 0)</code></li>\n<li>Add PEP484 type hints</li>\n<li>Don't index <code>[0]</code> and <code>[1]</code> when you actually just mean <code>.x</code> and <code>.y</code>, for which named tuples are well-suited</li>\n<li>Convert many (most?) of your class methods to <code>@properties</code></li>\n<li>Do not implement your own binary search; call into <code>bisect</code> (I have not shown this in my reference implementation)</li>\n<li>Fix up minor typos such as <code>segmnets</code>, <code>serach</code></li>\n<li>Replace your <code>print</code>s with <code>assert</code>s to magically get actual unit tests</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code># Code for Algorithm-2\nfrom functools import cmp_to_key\nfrom typing import Tuple, Sequence, List, NamedTuple, Callable\n\n\nclass Point(NamedTuple):\n x: int\n y: int\n\n\nclass LineSegment:\n &quot;&quot;&quot;\n Represents line_segment which is either horizontal or vertical.\n &quot;&quot;&quot;\n\n def __init__(self, start_point: Point, end_point: Point) -&gt; None:\n if start_point.x == end_point.x:\n self._start_point = (start_point, end_point)[start_point.y &gt; end_point.y]\n self._end_point = (start_point, end_point)[start_point.y &lt; end_point.y]\n else:\n self._start_point = (start_point, end_point)[start_point.x &gt; end_point.x]\n self._end_point = (start_point, end_point)[start_point.x &lt; end_point.x]\n\n def does_intersect(self, target_line_segment: 'LineSegment') -&gt; bool:\n is_vertical = self.is_segment_vertical\n is_target_vertical = target_line_segment.is_segment_vertical\n\n # Check for parallel segments\n if is_vertical and is_target_vertical:\n return False\n\n if is_vertical:\n return (\n target_line_segment._start_point.x &lt;= self._start_point.x &lt;= target_line_segment._end_point.x and\n self._start_point.y &lt;= target_line_segment._start_point.y &lt;= self._end_point.y\n )\n else:\n return (\n target_line_segment._start_point.y &lt;= self._start_point.y &lt;= target_line_segment._end_point.y and\n self._start_point.x &lt;= target_line_segment._start_point.x &lt;= self._end_point.x\n )\n\n @property\n def is_segment_vertical(self) -&gt; bool:\n return self._start_point.x == self._end_point.x\n\n @property\n def value(self) -&gt; int:\n if self.is_segment_vertical:\n return self._start_point.x\n else:\n return self._start_point.y\n\n @property\n def non_constant_start_coordinate(self) -&gt; int:\n if self.is_segment_vertical:\n return self._start_point.y\n else:\n return self._start_point.x\n\n @property\n def non_constant_end_coordinate(self) -&gt; int:\n if self.is_segment_vertical:\n return self._end_point.y\n else:\n return self._end_point.x\n\n\nclass IndexedSegment(NamedTuple):\n segment: LineSegment\n index: int\n\n\n# Line segment comparator\ndef compare(item_1: IndexedSegment, item_2: IndexedSegment) -&gt; int:\n return item_1.segment.value - item_2.segment.value\n\n\ndef binary_search_comparator(segment: IndexedSegment, search_value: int) -&gt; int:\n return segment.segment.value - search_value\n\n\ndef binary_search(\n sorted_collection: Sequence[IndexedSegment],\n search_value: int,\n comparator: Callable[[IndexedSegment, int], int],\n) -&gt; Tuple[\n int, # index\n int, # low\n int, # high\n]:\n high = len(sorted_collection) - 1\n low = 0\n index = -1\n \n while low &lt;= high:\n mid = (low + high)//2\n comparator_value = comparator(sorted_collection[mid], search_value)\n if comparator_value &lt; 0:\n low = mid + 1\n elif comparator_value &gt; 0:\n high = mid - 1\n else:\n index = mid\n break\n\n return index, low, high\n\n\ndef split_path_in_segments(path_points: Sequence[Point]) -&gt; Tuple[\n List[IndexedSegment], # vert segments\n List[IndexedSegment], # horz segments\n]:\n vertical_segment_start_index = (0, 1) [path_points[0].x == path_points[1].x]\n\n vertical_segments = [\n IndexedSegment(LineSegment(path_points[index], path_points[index + 1]), index)\n for index in range(vertical_segment_start_index, len(path_points) - 1, 2)\n ]\n\n horizontal_segments = [\n IndexedSegment(LineSegment(path_points[index], path_points[index + 1]), index)\n for index in range(int(not vertical_segment_start_index), len(path_points) - 1, 2)\n ]\n\n return vertical_segments, horizontal_segments\n\n\ndef find_segments_in_range(\n segments: Sequence[IndexedSegment],\n range_start: int,\n range_end: int,\n) -&gt; Tuple[\n int, # start low\n int, # end high\n]:\n start_index, start_low, start_high = binary_search(segments, range_start, binary_search_comparator)\n end_index, end_low, end_high = binary_search(segments, range_end, binary_search_comparator)\n return start_low, end_high\n\n\n# Input: Ordered set of points representing rectilinear paths\n# which is made up of alternating horizontal and vertical segments\ndef check_loop(path_points: Sequence[Tuple[int, int]]) -&gt; bool:\n\n # For loop we need 4 or more segments. Hence more than 5 points\n if len(path_points) &lt;= 4:\n return False\n\n points = [Point(*point) for point in path_points]\n\n vertical_segments, horizontal_segments = split_path_in_segments(points)\n\n # Sort vertical segments for easy search\n vertical_segments = sorted(vertical_segments, key=cmp_to_key(compare))\n\n # Iterate through horizontal segments, find vertical segments\n # which fall in range of horizontal segment and check for intersection\n for horizontal_counter in range(len(horizontal_segments)):\n horizontal_segment = horizontal_segments[horizontal_counter][0]\n horizontal_segment_index = horizontal_segments[horizontal_counter][1]\n\n start, end = find_segments_in_range(\n vertical_segments,\n horizontal_segment.non_constant_start_coordinate,\n horizontal_segment.non_constant_end_coordinate,\n )\n\n for vertical_counter in range(start, end + 1):\n vertical_segment = vertical_segments[vertical_counter][0]\n vertical_segment_index = vertical_segments[vertical_counter][1]\n\n # Avoid adjacent segments. They will always have one endpoint in common\n if abs(horizontal_segment_index - vertical_segment_index) &lt;= 1:\n continue\n\n if horizontal_segment.does_intersect(vertical_segment):\n return True\n\n return False\n\n\ndef test() -&gt; None:\n assert not check_loop([(0,0), (5,0), (5, 5)])\n assert not check_loop([(0,0), (5,0), (5, 5), (4, 5)])\n assert not check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, 2)])\n assert not check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2)])\n assert not check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2),\n (11, 2), (11, 1), (-5, 1), (-5, 15)])\n assert check_loop([(0,0), (5,0), (5, 5), (0, 5), (0, 0)])\n assert check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, -1)])\n assert check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, 0)])\n assert check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2), (10, -1), (2, -1), (2, 15)])\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n<h2>Correctness</h2>\n<p>Are you sure that your second-last test case is correct? It seems to me that there's clear segment collision but you've marked it <code>False</code>. It seems that your original algorithm is not able to find this collision.</p>\n<h2>Vectorization</h2>\n<p>A somewhat brute-force but straightforwardly vectorized solution stands a chance at being performance-competitive:</p>\n<ul>\n<li>Use the discrete differential to find segment groups</li>\n<li>Broadcast to arrays representing the Cartesian product of the horizontal and vertical segments</li>\n<li>Ignore diagonals k=0 and k=1 as those represent adjacent line segments that, whereas they share one endpoint by definition, are not considered collisions</li>\n</ul>\n<p>This passes your tests, so long as the second-last one is adjusted to assert <code>True</code> which I think is necessary. For what it's worth, it's also much more terse.</p>\n<pre class=\"lang-py prettyprint-override\"><code>def new(points: Sequence[Tuple[int, int]]) -&gt; bool:\n # shape: points, x/y\n continuous_points = np.array(points)\n\n def sanitise_segments(axis: int) -&gt; np.ndarray:\n # This does NOT check for contiguous segments, only segments that fail\n # to alternate in orientation\n on_axis = continuous_points[:, axis]\n groups = np.split(continuous_points, np.where(np.diff(on_axis) == 0)[0] + 1)\n segment_list = []\n for group in groups:\n if group.shape[0] &gt; 1:\n segment = np.empty((2, 2), dtype=np.int64)\n segment[:, 1 - axis] = group[0, 1 - axis]\n segment[0, axis] = np.min(group[:, axis])\n segment[1, axis] = np.max(group[:, axis])\n segment_list.append(segment)\n return np.stack(segment_list)\n\n # Each of these is of shape (segments, start/end, x/y)\n horz_segs = sanitise_segments(0)\n vert_segs = sanitise_segments(1)\n\n # Given linear equations x = xc, y = yc\n # they would intersect (in a segment or not) at xc, yc.\n # If xc, yc is within the bounds for both segments, that's a &quot;loop&quot;.\n x = vert_segs[:, 0, 0:1]\n in_x1 = horz_segs[:, 0, 0:1].T &lt;= x\n in_x2 = horz_segs[:, 1, 0:1].T &gt;= x\n\n y = horz_segs[:, 0, 1:2].T\n in_y1 = vert_segs[:, 0, 1:2] &lt;= y\n in_y2 = vert_segs[:, 1, 1:2] &gt;= y\n\n # Mask out adjacent segments, which are assumed not to collide.\n collisions = in_x1 &amp; in_x2 &amp; in_y1 &amp; in_y2\n masked = np.tril(collisions, k=-1) | np.triu(collisions, k=2)\n return np.any(masked)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T19:49:58.580", "Id": "267765", "ParentId": "267737", "Score": "1" } }, { "body": "<p>There is a problem with the algorithm described - if the first and last segment are both horizontal or both vertical, they could overlap without meeting a line of opposite direction:</p>\n<pre class=\"lang-none prettyprint-override\"><code>+---O &lt;--+\n| |\n+---------+\n</code></pre>\n<p>You might be able to catch this by simply adding a zero-length segment to the end if the input has an odd number of segments.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T07:47:50.633", "Id": "267819", "ParentId": "267737", "Score": "0" } }, { "body": "<blockquote>\n<pre><code>print(check_loop([(0,0), (5,0), (5, 5)])) # False\nprint(check_loop([(0,0), (5,0), (5, 5), (0, 5), (0, 0)])) # True\nprint(check_loop([(0,0), (5,0), (5, 5), (4, 5)])) # False\nprint(check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, 2)])) # False\nprint(check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, -1)])) # True\nprint(check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, 0)])) # True\nprint(check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2)]))# False\nprint(check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2), (11, 2), (11, 1), (-5, 1), (-5, 15)]))# False\nprint(check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2), (10, -1), (2, -1), (2, 15)]))# True\n</code></pre>\n</blockquote>\n<p>This looks like a candidate for a proper unit test:</p>\n<pre><code>def check_loop(path_points):\n &quot;&quot;&quot;\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5)])\n False\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5), (0, 5), (0, 0)])\n True\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5), (4, 5)])\n False\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, 2)])\n False\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, -1)])\n True\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5), (4, 5), (4, 0)])\n True\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2)])\n False\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2), (11, 2), (11, 1), (-5, 1), (-5, 15)])\n False\n &gt;&gt;&gt; check_loop([(0,0), (5,0), (5, 5), (8, 5), (8, 2), (10, 2), (10, -1), (2, -1), (2, 15)])\n True\n &quot;&quot;&quot;\n ⋮\n</code></pre>\n\n<pre><code>if __name__ == &quot;__main__&quot;:\n import doctest\n doctest.testmod()\n</code></pre>\n<p>Now, instead of an error-prone visual check (or <code>diff</code> against expected results, with error-prone lookup of which one failed), we get useful diagnostic output, just by running the code. For example, if we add the case from <a href=\"/a/267819/75307\">my algorithm answer</a>:</p>\n<pre><code>&gt;&gt;&gt; check_loop([(4,0), (0,0), (0, 1), (5, 1), (5, 0), (1,0)])\nTrue\n</code></pre>\n<p>Then we get this output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>**********************************************************************\nFile &quot;267737.py&quot;, line 105, in __main__.check_loop\nFailed example:\n check_loop([(4,0), (0,0), (0, 1), (5, 1), (5, 0), (1,0)])\nExpected:\n True\nGot:\n False\n**********************************************************************\n1 items had failures:\n 1 of 10 in __main__.check_loop\n***Test Failed*** 1 failures.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T08:01:31.220", "Id": "267820", "ParentId": "267737", "Score": "2" } } ]
{ "AcceptedAnswerId": "267765", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T16:54:38.213", "Id": "267737", "Score": "5", "Tags": [ "python", "python-3.x", "algorithm", "computational-geometry" ], "Title": "Detect loop in rectilinear path" }
267737
<p>I am doing a project for a calculator in JavaScript.</p> <p>Here is the project GitHub page: <a href="https://github.com/florinpop17/app-ideas/blob/master/Projects/1-Beginner/Calculator-App.md" rel="nofollow noreferrer">https://github.com/florinpop17/app-ideas/blob/master/Projects/1-Beginner/Calculator-App.md</a></p> <p>Demo: <a href="https://kdevcalculator.web.app/" rel="nofollow noreferrer">https://kdevcalculator.web.app/</a></p> <p>My <a href="https://github.com/AmishBaztard/Calculator/blob/main/script.js" rel="nofollow noreferrer">GitHub JS Code</a></p> <pre><code>'use strict'; const calculatorResultCurrent = document.querySelector('.calculator__result__current'); const calculatorResultPrev = document.querySelector('.calculator__result__prev'); const buttons = document.querySelector(&quot;.calculator__buttons&quot;); const clearAll = document.querySelector(&quot;[data-action='clearAll']&quot;); let current = 0; let inputStack = []; let currentOperation = false; let prevText; const operations = { plus: function (...args) { let sum = 0; for (let x of args) { sum = +sum + +x; } return sum; }, minus: function (...args) { let sum = args[0]; for (let i = 1; i &lt; args.length; i++) { sum -= +args[i]; } return sum; }, division: function (...args) { let sum = args[0]; for (let i = 1; i &lt; args.length; i++) { sum /= +args[i]; } return sum; }, sum: (input, op) =&gt; { if (!op) return 0; let sum = +op(...input); let currentSplit = sum.toString().split('.'); if (currentSplit[0].length &gt; 8) { sum = &quot;ERR&quot;; } else if (currentSplit[1] &amp;&amp; currentSplit[1].length &gt; 3) { sum = +sum.toFixed(3); } return sum; } }; buttons.addEventListener('click', (e) =&gt; { if (e.target.tagName !== &quot;BUTTON&quot;) return; let action = e.target.dataset.action ? e.target.dataset.action : null; let textVal; if (current == &quot;ERR&quot; &amp;&amp; action != &quot;clearAll&quot;) { clearAll.classList.add('calculator__button--border'); return; } else { clearAll.classList.remove('calculator__button--border'); } if (action == &quot;clearAll&quot;) { inputStack = []; current = 0; prevText = &quot;&quot;; textVal = 0; } else if (action == &quot;clear&quot;) { if (current === 0 &amp;&amp; currentOperation) { currentOperation = null; current = inputStack.pop(); prevText = &quot;&quot;; textVal = current; } else { current = 0; textVal = current; } } else if (action == &quot;decimal&quot;) { if (current.toString().indexOf(&quot;.&quot;) &gt; -1) return; current = current + &quot;.&quot;; textVal = current; } else if (action == &quot;inverse&quot;) { current -= current * 2; textVal = current; } else if (action === &quot;sum&quot;) { if (current === 0) { current = inputStack[0]; } inputStack.push(current); current = operations.sum(inputStack, currentOperation); inputStack = []; prevText = &quot;&quot;; textVal = current; } else if (action) { if (inputStack.length &gt;= 1) { if (current === 0) { current = inputStack[0]; } inputStack.push(current); current = operations.sum(inputStack, currentOperation); inputStack = []; } if (current == &quot;ERR&quot;) { inputStack = []; prevText = ''; textVal = &quot;ERR&quot;; } else { prevText = current + e.target.textContent currentOperation = operations[action]; inputStack.push(current); current = 0; textVal = ''; } } else { let currentSplit = current.toString().split('.'); if (currentSplit[0].length &lt; 8) { let val = +e.target.textContent; if (current.toString().indexOf(&quot;.&quot;) !== -1) { let num = current + val; if (currentSplit[1].length &lt; 3) { current = current + val; } } else if (current &lt; 0) { current *= 10; current -= val; } else { current *= 10; current += val; } } textVal = current; } calculatorResultPrev.textContent = prevText; calculatorResultCurrent.textContent = textVal; }); </code></pre> <p>I think my code could be refactored to be better. I thought about doing it in an OOP way but figured I'd stick to the traditional &quot;functional&quot; method. Maybe this is better called &quot;procedural&quot; though.</p> <p>Please give me advice on how I can write cleaner, more professional and efficient code. You don't need to fix the code for me, just point me in a direction that I can learn and research.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T19:18:22.813", "Id": "267739", "Score": "0", "Tags": [ "javascript", "html", "css", "calculator" ], "Title": "Calculator with vanilla procedural JavaScript" }
267739
<p>I am trying to solve the <a href="https://www.hackerrank.com/challenges/climbing-the-leaderboard/problem" rel="nofollow noreferrer">Climbing the leaderboard problem</a> on Hacker Rank. My code passes all the test cases except Test Cases 6 to 9, which I assume are using large data sets.</p> <p>I'm using binary search to find the optimal insertion point for each score and using the index as the rank. I know there are loads of solutions online but I want to pass the test cases with my own code.</p> <p>Original problem: <a href="https://i.stack.imgur.com/lOSCV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lOSCV.png" alt="enter image description here" /></a></p> <pre class="lang-py prettyprint-override"><code>def climbingLeaderboard(ranked, player): climb = [] ranked2 = sorted(set(ranked),reverse = True) for i in player: if i in ranked2: climb.append(ranked2.index(i)+1) elif i &gt; ranked2[0]: climb.append(1) ranked2.insert(0, i) elif i &lt; ranked2[-1]: climb.append(len(ranked2) + 1) ranked2.append(i) else: a = binary_search(ranked2, i, 0,len(ranked2)) climb.append(a+1) ranked2.insert(a, i) return climb def binary_search(arr, n, lo, hi): mid = int((hi+lo)/2) if lo &gt; hi: return lo elif arr[mid] &lt; n: return binary_search(arr, n, lo, mid -1) elif arr[mid] &gt; n: return binary_search(arr, n, mid + 1, hi) else: return mid </code></pre> <p>Where can I optimise my code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T20:22:03.440", "Id": "527946", "Score": "0", "body": "Welcome to Code Review! Please explain / summarize what the challenge task is, so that the question makes sense even if the link goes dead." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T10:41:13.537", "Id": "527979", "Score": "0", "body": "Hi, @200_success I have inserted a screenshot of the original problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T11:38:57.077", "Id": "527982", "Score": "0", "body": "I have solved this optimisation, thread can be closed. Thanks" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T17:25:36.270", "Id": "527999", "Score": "0", "body": "We don't delete questions on Code Review just because you have solved the challenge yourself. Rather, you should post an answer to your own question that explains your successful approach and your thought process, so that future readers can benefit from this post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T17:08:39.683", "Id": "528076", "Score": "1", "body": "I have posted a comment under Anab's proposals with a brief summary of how I solved it in the end." } ]
[ { "body": "<p>I see three ways to improve your runtime. I have never done this problem so I can't guarantee that it will be enough to pass all the tests.</p>\n<h2>Sorted input</h2>\n<p>The leaderboard scores are sorted in decreasing order. Your duplicate-removal code converts a sorted list to a set to remove duplicates (O(n)), then converts it back to a list (O(n)), then sorts it (O(n*log(n)). You could use the fact that it is sorted: duplicates will always be side by side. You could do something like the following, for example:</p>\n<pre><code>prev = ranked[0]\nduplicateIndices = set()\nfor index, val in enumerate(ranked[1:], 1):\n if val == prev:\n duplicateIndices.add(index)\n prev = val\nranked2 = [x for i,x in enumerate(ranked) if i not in duplicateIndices]\n</code></pre>\n<p>This may not be the most efficient way to remove duplicate but it runs in O(n).</p>\n<h2>Sorted input 2</h2>\n<p><code>player</code> is sorted as well. That means that after each iteration, the player's rank is at most the previous one. This has two consequences:</p>\n<ol>\n<li>You don't need to add the player's score to <code>ranked2</code> (either two consecutive scores are equal, which is easy enough to detect without altering <code>ranked2</code>, or the second one is strictly better than the first and having inserted the first in <code>ranked2</code> will not change the insertion point of the second)</li>\n<li>The right boundary of your binary search is your previous insertion point.</li>\n</ol>\n<p>This will not change your asymptotical complexity but it should have an interesting effect on your runtime anyway.</p>\n<h2>Skipping the linear search</h2>\n<p>With a single line, your code goes from O(m*log(n)) to O(m*n). Since <code>ranked2</code> is a list, and Python does not know that it is sorted, <code>if i in ranked2</code> will iterate over the entire list searching for a match. This operation runs in O(n) and is repeated for each of the player's score. Besides, you have already handled the equality case in your binary search, so why bother?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T11:38:08.547", "Id": "527981", "Score": "0", "body": "Thanks @Anab I removed the linear search per iteration and made use of the fact that my binary search returns the index if it finds the value in the list. Passed all cases" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T17:09:12.837", "Id": "527997", "Score": "0", "body": "Glad that it worked for you. Could you accept the answer if you're satisfied with it?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T19:55:36.573", "Id": "267741", "ParentId": "267740", "Score": "2" } } ]
{ "AcceptedAnswerId": "267741", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T19:28:03.667", "Id": "267740", "Score": "0", "Tags": [ "python", "python-3.x", "programming-challenge", "time-limit-exceeded", "binary-search" ], "Title": "Climbing the leaderboard (Hacker Rank) via binary search" }
267740
<p>I am just beginning to learn Python, this is my own take on a <a href="https://en.wikipedia.org/wiki/Caesar_cipher" rel="noreferrer">Caesar cipher</a> just looking at Python docs. I would like to know how I could have made it better and how would you rate this. Is it any good?</p> <pre><code>#caeser cipher import string message = str(input(&quot;Enter the Message you want to encrypt: &quot;)) shift = int(input(&quot;Enter the number of letters for cipher shift: &quot;)) def cipher(message,shift): encList = [] messageLst = [] alphabet = list(string.ascii_lowercase * 2) punct = list(string.punctuation) for i in message: messageLst.append(i) for i in messageLst : for j in alphabet: if i == j: replaceChar = alphabet[alphabet.index(j)+(shift)] encList.append(replaceChar) break elif i == &quot; &quot;: encList.append(i) break elif i in punct: encList.append(i) break encMessage = &quot;&quot; encMessage = encMessage.join(encList) #print(alphabet) #print(messageLst) #print(encList) print(&quot;Encrypted Message is : &quot;, encMessage) cipher(message,shift) </code></pre>
[]
[ { "body": "<h1>Alphabet list</h1>\n<p>Alphabet doesn't need to be a <code>list</code>, you can just use the <code>ascii_lowercase</code> string:</p>\n<pre class=\"lang-py prettyprint-override\"><code># just a copy\nalphabet = string.ascii_lowercase\n\n# two copies\nalphabet = string.ascii_lowercase * 2\n\n\n# alternatively\nfrom string import ascii_lowercase as alphabet\n</code></pre>\n<h1>Using the Modulo Operator</h1>\n<p>Instead of using two copies of <code>ascii_lowercase</code> to cover index overflows, you can use the modulo operation as shown by your linked Wikipedia entry:</p>\n<pre class=\"lang-py prettyprint-override\"><code>alphabet = string.ascii_lowercase\n\nshift = 5\n\n# index is in range(0, 25)\nalphabet[(6 + shift) % 26]\n'l'\n\n# index would be &gt; 25, so it loops back around\nalphabet[(21 + shift) % 26]\n'a'\n</code></pre>\n<h1>Cipher Lookup with a Dictionary</h1>\n<p>Now, what you could do is use a dictionary to build the lookups ahead of time so that you don't have to use <code>alphabet.index</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>cipher_lookup = {char: alphabet[(i + shift) % 26] for i, char in enumerate(alphabet)}\n</code></pre>\n<p>Now, there's no more need to track indices:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def cipher(message, shift):\n cipher_lookup = {char: alphabet[(i + shift) % 26] for i, char in enumerate(alphabet)}\n\n encrypted = []\n\n for letter in message:\n # simply look it up in the dictionary\n encrypted.append(cipher[letter])\n</code></pre>\n<h1>Checking for Punctuation</h1>\n<p>Use a <code>set</code> here, rather than a list. Membership testing for a <code>set</code>/<code>dict</code> is a time-constant operation, rather than O(N), where N is the length of the list:</p>\n<pre class=\"lang-py prettyprint-override\"><code>punct = set(string.punctuation)\n\n'a' in punct\nFalse\n\n'.' in punct\nTrue\n</code></pre>\n<p>However, you don't actually have to test for punctuation. You could instead use <code>dict.get</code> to return the value from the dictionary if it's there, and return the letter if it isn't:</p>\n<pre class=\"lang-py prettyprint-override\"><code># say shift is 5\ncipher_lookup.get('a', 'a')\n'f'\n\n# punctuation is not in the cipher\n# so we just return that character\ncipher_lookup.get('.', '.')\n'.'\n</code></pre>\n<h1>Predefining <code>encMessage</code></h1>\n<p>You can just use:</p>\n<pre class=\"lang-py prettyprint-override\"><code>enc_message = ''.join(enc_list)\n</code></pre>\n<h1>Variable Naming</h1>\n<p>Variable and function names are to be <code>snake_case</code> with all lowercase letters</p>\n<h1>Function params</h1>\n<p>Separate your parameters in your function definitions with a space:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def cipher(message, shift):\n</code></pre>\n<h1><code>input</code></h1>\n<p>You don't need to cast <code>message</code> to <code>str</code>, since <code>input</code> only outputs strings</p>\n<h1><code>if __name__ == &quot;__main__&quot;</code> Guard</h1>\n<p>This will allow you to import this function without executing the program if you wanted to reuse it:</p>\n<pre class=\"lang-py prettyprint-override\"><code># This goes at the very bottom\nif __name__ == &quot;__main__&quot;:\n message = input(&quot;Enter the Message you want to encrypt: &quot;)\n shift = int(input(&quot;Enter the number of letters for cipher shift: &quot;))\n\n print(cipher(message, shift))\n</code></pre>\n<p>You can put your <code>message</code> and <code>shift</code> prompts here as well so that they don't execute unless you are running the program.</p>\n<h1>Refactored</h1>\n<pre class=\"lang-py prettyprint-override\"><code>from string import ascii_lowercase as alphabet\n\n\ndef cipher(message, shift):\n cipher_lookup = {char: alphabet[(i + shift) % 26] for i, char in enumerate(alphabet)}\n\n encrypted_message = &quot;&quot;\n\n for letter in message:\n encrypted_message += cipher_lookup.get(letter, letter)\n\n return encrypted_message\n\n\nif __name__ == &quot;__main__&quot;:\n message = input(&quot;Enter the Message you want to encrypt: &quot;)\n shift = int(input(&quot;Enter the number of letters for cipher shift: &quot;))\n\n print(cipher(message, shift))\n</code></pre>\n<h1>String concatenation</h1>\n<p>It's not usually best practice to use string concatenation, but I think this is a good start to demonstrate the concepts of what's going on in the program. A better practice than the <code>for</code> loop would be to use a generator expression:</p>\n<pre class=\"lang-py prettyprint-override\"><code>encrypted_message = ''.join((cipher_lookup.get(letter, letter) for letter in message))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T14:55:35.577", "Id": "267760", "ParentId": "267742", "Score": "7" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/267760/100620\">C.Nivs</a> has made excellent points about:</p>\n<ul>\n<li>not needing to convert <code>alphabet</code> into a list</li>\n<li>using the Modulo Operator (<code>%</code>)</li>\n<li>storing the translations in a dictionary</li>\n<li>using <code>set</code>/<code>dict</code> and <code>in</code> for membership tests</li>\n<li>naming, spaces, unnecessary casts and initializations</li>\n<li><code>__main__</code> guards</li>\n</ul>\n<p>I won't repeat those here, but please study those and follow their advice on those points.</p>\n<hr />\n<h1>Additional Code Review Points</h1>\n<h2>Loop Invariants</h2>\n<p>You wrote this double <code>for</code> loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in messageLst :\n for j in alphabet:\n if i == j:\n replaceChar = alphabet[alphabet.index(j)+(shift)]\n encList.append(replaceChar)\n break\n elif i == &quot; &quot;:\n encList.append(i)\n break\n elif i in punct:\n encList.append(i)\n break\n</code></pre>\n<p>The tests <code>i == &quot; &quot;</code> and <code>i in punct</code> are nested inside the inner loop, which loops <code>for j in alphabet</code>. Notice that neither those tests nor the code executed based on passing either of those tests depends on <code>j</code>. This is inefficient.</p>\n<p>Consider a <code>messageLst</code> which contains <code>['z', 'e', 'b', 'r', 'a']</code>. The first iteration of the outer loop</p>\n<ul>\n<li>assigns <code>'z'</code> to the variable <code>i</code>, and then</li>\n<li>executes the body of that loop, which is the inner loop. That loop:\n<ul>\n<li>assign <code>j</code> to the first letter of <code>alphabet</code> (an <code>'a'</code>), and since <code>i == j</code> is false, goes on to check if <code>i</code> is a space, and if not, if <code>i</code> is a punctuation character. Since both were false, the loop continues and,</li>\n<li>assign <code>j</code> to the second letter of <code>alphabet</code> (a <code>'b'</code>), and since <code>i == j</code> is false, goes on to check if <code>i</code> is a space, and if not, if <code>i</code> is a punctuation character. Since both were false, the loop continues and,</li>\n<li>assign <code>j</code> to the third letter of <code>alphabet</code> (a <code>'c'</code>), and since <code>i == j</code> is false, goes on to check if <code>i</code> is a space, and if not, if <code>i</code> is a punctuation character. Since both were false, the loop continues and,</li>\n</ul>\n</li>\n</ul>\n<p>Notice those checks for <code>i == ' '</code> and <code>i in punct</code> are redundantly executed ... 26 times in case of the letter <code>'z'</code>!</p>\n<p>If those tests are moved out of the loop, we can get a more efficient implementation:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in messageLst :\n if i == &quot; &quot;:\n encList.append(i)\n elif i in punct:\n encList.append(i)\n else:\n for j in alphabet:\n if i == j:\n replaceChar = alphabet[alphabet.index(j)+(shift)]\n encList.append(replaceChar)\n break\n</code></pre>\n<h2>Unnecessary looping</h2>\n<p>Consider just the inner loop:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for j in alphabet:\n if i == j:\n ...\n break\n</code></pre>\n<p>This searches <code>alphabet</code> for values <code>j</code> that equals <code>i</code>, and (due to the <code>break</code>) stops at the first occurrence. When that occurrence is found, <code>j</code> will equal <code>i</code>.</p>\n<p>This is a complicated way of writing:</p>\n<pre class=\"lang-py prettyprint-override\"><code> if i in alphabet:\n j = i\n ...\n</code></pre>\n<p>In fact, you don't even need the extra <code>j</code> variable. You can simply use <code>i</code> in the <code>...</code> code.</p>\n<pre class=\"lang-py prettyprint-override\"><code> if i in alphabet:\n replaceChar = alphabet[alphabet.index(i) + shift]\n encList.append(replaceChar)\n</code></pre>\n<h2>Improved code</h2>\n<p>Fixing the loop invariant and removing the unnecessary looping (but without applying improvements from the other answer), we get:</p>\n<pre class=\"lang-py prettyprint-override\"><code> for i in messageLst :\n if i in alphabet:\n replaceChar = alphabet[alphabet.index(i) + shift]\n encList.append(replaceChar)\n elif i == &quot; &quot;:\n encList.append(i)\n elif i in punct:\n encList.append(i)\n</code></pre>\n<p>... which is certainly an improvement over the original code.</p>\n<h1>Batteries Included</h1>\n<p>C.Nivs also gave you improvements on string concatenation, culminating with a generator expression to produce the encrypted message. We can do even better...</p>\n<p>Python comes with a <a href=\"https://docs.python.org/3/library/stdtypes.html?highlight=trans#str.translate\" rel=\"nofollow noreferrer\"><code>str.translate</code></a> function, which does a letter-by-letter substitution on a string ... which is exactly what the Caesar cipher is doing.</p>\n<pre class=\"lang-py prettyprint-override\"><code>from string import ascii_lowercase as alphabet\n\ndef cipher(message: str, shift: int) -&gt; str:\n &quot;&quot;&quot;\n Encode a message using a Caesar Cipher with a user-defined shift on\n a 26 letter lowercase alphabet.\n &quot;&quot;&quot;\n\n shift %= len(alphabet)\n code = str.maketrans(alphabet, alphabet[shift:] + alphabet[:shift])\n return message.translate(code)\n\nif __name__ == &quot;__main__&quot;:\n message = input(&quot;Enter the Message you want to encrypt: &quot;)\n shift = int(input(&quot;Enter the number of letters for cipher shift: &quot;))\n\n print(cipher(message, shift))\n</code></pre>\n<p><em>Note</em>: I've added a <code>&quot;&quot;&quot;docstring&quot;&quot;&quot;</code> and type-hints to the <code>cipher</code> function. Both are extremely useful in Python development. Make sure you study them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T20:54:22.823", "Id": "528164", "Score": "1", "body": "Great answer! Minor nitpicks, just reading the code the part `code = ...` is a bit terse, adding `shifted_alphabet = alphabet[shift:] + alphabet[:shift]` above would make it clearer. `len` of alphabet is called each time a new cipher is called. Maybe make it a constant `ALPHABET_LEN = len(alphabet)`. Some minor checking on the inputs would be nice. What happens if `shift` is not an int? Also some very brief `doctests` would make `cipher` clearer as it is a bit terse. `code` is better named `translation_table` or `cipher` =)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T21:09:37.747", "Id": "528166", "Score": "1", "body": "As a last comment =) `str` is imho not helping much. Typing hints should ideally _hint_ at what is going on. I find it clearer adding `from typing import Annotated` and then do something like `Plaintext = Annotated[str, \"a plaintext to be ciphered\"]`, `Ciphertext = Annotated[str, \"an encrypted plaintext using a cipher\"]` and then `def cipher(message: Plaintext, shift: int) -> Ciphertext:`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T17:42:26.577", "Id": "267832", "ParentId": "267742", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T22:31:38.653", "Id": "267742", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "caesar-cipher" ], "Title": "Caesar cipher using Python" }
267742
<p>I'm getting into backend with postgresql and I would like to know how much of my example would fit for a real website database, just for storing and then displaying it on website.</p> <pre class="lang-sql prettyprint-override"><code>create table clients ( id BIGSERIAL PRIMARY KEY, first_name VARCHAR(50) NOT NULL, last_name VARCHAR(50) NOT NULL, age INT CHECK (age &gt;= 18) NOT NULL, email VARCHAR(70) UNIQUE NOT NULL, password VARCHAR(100) NOT NULL, card VARCHAR(70) DEFAULT ('undefined') UNIQUE NOT NULL, joined TIMESTAMP NOT NULL, country VARCHAR(50) DEFAULT ('undefined') NOT NULL, language VARCHAR(50) DEFAULT ('undefined') NOT NULL ); insert into clients (first_name, last_name, age, email, password, joined, language) values ('Rustie', 'Matchell', 18, 'rmatchell0@mayoclinic.com', 'OSauq0z2suY', '2021-04-18 05:26:40', 'Kurdish'); insert into clients (first_name, last_name, age, email, password, card, joined, country, language) values ('Ulric', 'Hoggins', 20, 'uhoggins1@goo.gl', 'M4hnFLJ5XeP', '30243414381012', '2021-02-20 08:07:13', 'China', 'Mongolian'); insert into clients (first_name, last_name, age, email, password, card, joined, country, language) values ('Sephira', 'Bayly', 26, 'sbayly2@rambler.ru', 'INL57w6gXe', '5100138794351466', '2021-04-25 06:17:26', 'North Korea', 'Gujarati'); insert into clients (first_name, last_name, age, email, password, card, joined, country, language) values ('Hermine', 'Fassman', 29, 'hfassman3@smh.com.au', '1UX4TApQMEuV', '3552094428434244', '2021-06-18 06:48:54', 'Indonesia', 'Albanian'); </code></pre> <p>RESULT:</p> <pre class="lang-sql prettyprint-override"><code> id | first_name | last_name | age | email | password | card | joined | country | language ----+------------+-----------+-----+------------------------------+--------------+--------------------+---------------------+-----------------------+------------ 1 | Rustie | Matchell | 18 | rmatchell0@mayoclinic.com | OSauq0z2suY | undefined | 2021-04-18 05:26:40 | undefined | Kurdish 2 | Ulric | Hoggins | 20 | uhoggins1@goo.gl | M4hnFLJ5XeP | 30243414381012 | 2021-02-20 08:07:13 | China | Mongolian 3 | Sephira | Bayly | 26 | sbayly2@rambler.ru | INL57w6gXe | 5100138794351466 | 2021-04-25 06:17:26 | North Korea | Gujarati 4 | Hermine | Fassman | 29 | hfassman3@smh.com.au | 1UX4TApQMEuV | 3552094428434244 | 2021-06-18 06:48:54 | Indonesia | Albanian </code></pre>
[]
[ { "body": "<p><code>serial</code> / <code>bigserial</code> are deprecated and you should instead use a <code>generated always as identity</code> <a href=\"https://www.postgresql.org/docs/current/ddl-generated-columns.html\" rel=\"nofollow noreferrer\">clause</a> on an integer-type column.</p>\n<p>It looks like you're storing a plaintext password. No, please, no. You need to read about password hashing and salting in general, and then the <a href=\"https://www.postgresql.org/docs/13/pgcrypto.html\" rel=\"nofollow noreferrer\">PostgreSQL crypto support routines</a>.</p>\n<p>The string <code>undefined</code> is not a good way to represent a field being missing; this is an in-band value when you need an out-of-band value. The more reasonable thing to do for your card, country and language columns is to allow them to be nullable and to give them a default of null.</p>\n<p>Consider combining your inserts into one insert statement with multiple rows in your <code>values</code> expression.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:50:44.033", "Id": "528068", "Score": "0", "body": "Reinderien can you explain why should I use null values instead of \"undefined\"? I've made some research, and I've found that using null values isn't advisable. What would happen if I don't use null values in this particular case?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T15:36:51.900", "Id": "528072", "Score": "1", "body": "The use of nullable columns is not advisable _if_ you know that your data for that column has an always-defined guarantee. If it's necessary to represent an \"undefined\" value, then using nullable columns is the way to go." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T14:07:06.270", "Id": "267758", "ParentId": "267743", "Score": "1" } } ]
{ "AcceptedAnswerId": "267758", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-06T23:22:41.630", "Id": "267743", "Score": "1", "Tags": [ "sql", "postgresql" ], "Title": "Simple website sql database" }
267743
<p>I wan't to set different type of users in my app, two main types: <strong>Customers</strong> and <strong>Employee</strong>, and the Employee User's have two different role: <strong>Driver</strong> and <strong>Responsable</strong>.<br /> So I extended the <strong>AbstractBaseUser</strong> model to get a Customized User Model and create a different models that I need which inherit from this main model.<br /> My models design is:</p> <pre class="lang-py prettyprint-override"><code>class UserAccountManager(BaseUserManager): def create_superuser(self, email, first_name, last_name, password, **other_fields): other_fields.setdefault(&quot;is_staff&quot;, True) other_fields.setdefault(&quot;is_superuser&quot;, True) other_fields.setdefault(&quot;is_active&quot;, True) other_fields.setdefault(&quot;is_driver&quot;, True) other_fields.setdefault(&quot;is_customer&quot;, True) other_fields.setdefault(&quot;is_responsable&quot;, True) if other_fields.get(&quot;is_staff&quot;) is not True: raise ValueError(_(&quot;Supperuser must be assigned to is_staff.&quot;)) if other_fields.get(&quot;is_superuser&quot;) is not True: raise ValueError(_(&quot;Superuser must be assigned to is_superuser.&quot;)) return self.create_user(email, first_name, last_name, password, **other_fields) def create_user(self, email, first_name, last_name, password, **other_fields): if not email: raise ValueError(_(&quot;You must provide an email address&quot;)) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_(&quot;Email Address&quot;), unique=True) first_name = models.CharField(_(&quot;First Name&quot;), max_length=150, unique=True) last_name = models.CharField(_(&quot;Last Name&quot;), max_length=150, unique=True) mobile = models.CharField(_(&quot;Mobile Number&quot;), max_length=150, blank=True) is_active = models.BooleanField(_(&quot;Is Active&quot;), default=False) is_staff = models.BooleanField(_(&quot;Is Staff&quot;), default=False) is_driver = models.BooleanField(_(&quot;Is Driver&quot;), default=False) is_responsable = models.BooleanField(_(&quot;Is Responsable&quot;), default=False) is_customer = models.BooleanField(_(&quot;Is Customer&quot;), default=False) created_at = models.DateTimeField(_(&quot;Created at&quot;), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_(&quot;Updated at&quot;), auto_now=True) objects = UserAccountManager() USERNAME_FIELD = &quot;email&quot; REQUIRED_FIELDS = [&quot;first_name&quot;, &quot;last_name&quot;] class Meta: verbose_name = &quot;Account&quot; verbose_name_plural = &quot;Accounts&quot; def __str__(self): return self.first_name class Employee(User): registration_number = models.PositiveSmallIntegerField(_(&quot;Driver Registration Number&quot;), unique=True) cni = models.CharField(_(&quot;National Identity Code&quot;), max_length=8, unique=True, blank=False) picture = models.ImageField( verbose_name=_(&quot;Driver Pic&quot;), help_text=_(&quot;Driver Identity Picture&quot;), upload_to=&quot;images/driver/&quot; ) birth_date = models.DateField(_(&quot;Date Birth of the Driver&quot;)) birth_city = models.CharField(_(&quot;Birth City of the Driver&quot;), max_length=150, blank=True)recruitment_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) city_id = models.ForeignKey(&quot;City&quot;, blank=True, null=True, on_delete=models.SET_NULL) class Meta: verbose_name = &quot;Employee&quot; verbose_name_plural = &quot;Employees&quot; def __str__(self): return self.first_name + &quot; &quot; + self.last_name class Responsable(Employee): PERMANENT = &quot;Per.&quot; TEMPORAIRE = &quot;Tem.&quot; TYPE_OF_RESPONSABILITY = [ (TEMPORAIRE, &quot;Temporaire&quot;), (PERMANENT, &quot;Permanent&quot;), ] responsability_type = models.CharField(max_length=4, choices=TYPE_OF_RESPONSABILITY, default=PERMANENT) class Meta: verbose_name = &quot;Responsable&quot; verbose_name_plural = &quot;Responsables&quot; def __str__(self): return self.first_name + &quot; &quot; + self.last_name class Driver(Employee): driving_licence = models.ImageField( verbose_name=_(&quot;Driver Licence&quot;), help_text=_(&quot;Driver Licence Picture&quot;), upload_to=&quot;images/driver_licence/&quot; ) driver_licence_expiration_date = models.DateField(_(&quot;Expiration Date for Driver Licence&quot;)) class Meta: verbose_name = &quot;Driver&quot; verbose_name_plural = &quot;Drivers&quot; def __str__(self): return self.first_name + &quot; &quot; + self.last_name class Customer(User): company_name = models.CharField(_(&quot;Company Name&quot;), max_length=150, unique=True) ice = models.PositiveIntegerField(_(&quot;ICE of the Company&quot;), unique=True, null=True, blank=True) website = models.CharField(_(&quot;Company website&quot;), max_length=150, unique=True) class Meta: verbose_name = &quot;Customer&quot; verbose_name_plural = &quot;Customers&quot; def __str__(self): return self.first_name + &quot; &quot; + self.last_name </code></pre> <p>I want to set different login pages for each type of user's, and I don't want to have many tables with login informations. is this way of doing a good architecture or I'm missing some rules in the best practices (I know that there is always a better way to doing things).</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T01:34:40.287", "Id": "267745", "Score": "0", "Tags": [ "python", "django" ], "Title": "User's models with different roles" }
267745
<p>This code was done to allow a user to input, edit, search, delete and print a report of all the products in the company. Is there any way to improve my code?</p> <pre><code>public class Admin /** * @param args the command line arguments */ public static void main(String[] args) { String menuTask, exit; Scanner sc = new Scanner(System.in); // Allows user input Products product = new Products(); // Creates the Products class System.out.println(&quot;BRIGHT FUTURE TECHNOLOGIES APPLICATION&quot;); System.out.println(&quot;***************************************&quot;); System.out.println(&quot;Enter (1) to launch menu or any other key to exit: &quot;); exit = sc.next(); if (exit.equals(&quot;1&quot;) == false) { product.ExitApplication(); // Exits the application } do { menuTask = product.DisplayMenu(); // Displays the menu switch (menuTask) { case &quot;1&quot;: exit = product.CaptureProduct(); // Allows user to capture a product break; case &quot;2&quot;: exit = product.SearchProduct(); // Allows user to search for a product break; case &quot;3&quot;: exit = product.UpdateProduct(); // Allows user to update the product data break; case &quot;4&quot;: exit = product.DeleteProduct(); // Allows user to delete a product break; case &quot;5&quot;: exit = product.DisplayReport(); // Displays all the products and its data break; case &quot;6&quot;: product.ExitApplication(); // Exits the application break; default: System.out.println(&quot;Thats not a valid key&quot;); // Displays if the user enters an invalid key } } while (exit.equals(&quot;1&quot;)); // Loops executes at least once and will continue until the user wants to exit } } </code></pre> <p><strong>Products.java</strong></p> <pre><code>public class Products { Scanner sc = new Scanner(System.in); ReportData data = new ReportData(); public String SearchProduct() { int locationOfProduct; System.out.println(&quot;Please enter the product code to search: &quot;); locationOfProduct = data.getLocationOfProduct(sc.next()); System.out.println(&quot;***************************************&quot;); if (locationOfProduct != -1) { System.out.println(&quot;***************************************&quot;); System.out.println(&quot;PRODUCT SEARCH RESULTS&quot;); System.out.println(&quot;***************************************&quot;); data.toString(locationOfProduct); } else { System.out.println(&quot;The product cannot be located. Invalid product key&quot;); } System.out.println(&quot;Enter (1) to launch the menu or any other key to exit&quot;); return sc.next(); } public void SaveProduct(String prodName, String prodCat, String prodCode, String prodSup, String prodWar, int prodLevel, double prodPrice) { data.setProductName(prodName); switch (prodCat) { case &quot;1&quot;: data.setProductCat(&quot;Desktop Computer&quot;); break; case &quot;2&quot;: data.setProductCat(&quot;Laptop&quot;); break; case &quot;3&quot;: data.setProductCat(&quot;Tablet&quot;); break; case &quot;4&quot;: data.setProductCat(&quot;Printer&quot;); break; case &quot;5&quot;: data.setProductCat(&quot;Gaming Console&quot;); break; } data.setProductCode(prodCode); data.setProductSup(prodSup); data.setProductWar(prodWar); data.setProductLevel(prodLevel); data.setProductPrice(prodPrice); } public String UpdateProduct() { String update, war; int locationOfProduct; System.out.println(&quot;Please enter the product code to update: &quot;); locationOfProduct = data.getLocationOfProduct(sc.next()); System.out.println(&quot;***************************************&quot;); if (locationOfProduct != -1) { System.out.println(&quot;Update the warranty? (y) Yes, (n) No &quot;); update = sc.next(); if (update.equals(&quot;y&quot;)) { System.out.printf(&quot;Indicate the new warrenty for %s. Enter (1) for 6 months or any other key for 2 years &quot;, data.getProductName().get(locationOfProduct)); if (sc.next().equals(&quot;1&quot;)) { war = &quot;6 Months&quot;; } else { war = &quot;2 years&quot;; } data.getProductWar().set(locationOfProduct, war); System.out.println(&quot;Update the product price? (y) Yes, (n) No &quot;); update = sc.next(); if (update.equals(&quot;y&quot;)) { System.out.printf(&quot;Enter the new price for %s &quot;, data.getProductName().get(locationOfProduct)); data.getProductPrice().set(locationOfProduct, sc.nextDouble()); } System.out.println(&quot;Update the stock level? (y) Yes, (n) No &quot;); update = sc.next(); if (update.equals(&quot;y&quot;)) { System.out.printf(&quot;Enter the new stock level for %s &quot;, data.getProductName().get(locationOfProduct)); data.getProductLevel().set(locationOfProduct, sc.nextInt()); } } } else { System.out.println(&quot;The product cannot be located. Invalid product key&quot;); } System.out.println(&quot;Product details have been saved successfully&quot;); System.out.println(&quot;Enter (1) to launch the menu or any other key to exit&quot;); return sc.next(); } public String DeleteProduct() { int locationOfProduct; System.out.println(&quot;Please enter the product code to delete: &quot;); System.out.println(&quot;***************************************&quot;); locationOfProduct = data.getLocationOfProduct(sc.next()); if (locationOfProduct != -1) { data.getProductCat().remove(locationOfProduct); data.getProductCode().remove(locationOfProduct); data.getProductLevel().remove(locationOfProduct); data.getProductName().remove(locationOfProduct); data.getProductPrice().remove(locationOfProduct); data.getProductSup().remove(locationOfProduct); data.getProductWar().remove(locationOfProduct); } else { System.out.println(&quot;The product cannot be located. Invalid product key&quot;); } System.out.println(&quot;Enter (1) to launch the menu or any other key to exit&quot;); return sc.next(); } public String DisplayMenu() { System.out.println(&quot;Please select one of the following menu items: &quot;); System.out.println(&quot;(1) Capture a new product. \n&quot; + &quot;(2) Search for a product. \n&quot; + &quot;(3) Update a product. \n&quot; + &quot;(4) Delete a product. \n&quot; + &quot;(5) Print report. \n&quot; + &quot;(6) Exit application. &quot;); return sc.next(); } public String CaptureProduct() { String name, cat, sup, war; int level; double price; System.out.println(&quot;CAPTURE A NEW PRODUCT&quot;); System.out.println(&quot;*********************&quot;); System.out.println(&quot;Enter the product code: &quot;); String code = sc.nextLine(); System.out.println(&quot;Enter the product name: &quot;); name = sc.nextLine(); System.out.print(&quot;Select the product Category:\n&quot; + &quot;Desktop Computer - 1\n&quot; + &quot;Laptop - 2\n&quot; + &quot;Tablet - 3\n&quot; + &quot;Printer - 4\n&quot; + &quot;Gaming Console - 5 \nProduct Category &gt;&gt; &quot;); cat = sc.nextLine(); System.out.println(&quot;Indicate the product warrenty. Enter (1) for 6 months or any other key for 2 years&quot;); if (sc.next().equals(&quot;1&quot;)) { war = &quot;6 Months&quot;; } else { war = &quot;2 years&quot;; } System.out.printf(&quot;Enter the price for %s: &quot;, name); price = sc.nextDouble(); System.out.printf(&quot;Enter the stock level for %s: &quot;, name); level = sc.nextInt(); System.out.printf(&quot;Enter the supplier for %s: &quot;, name); sup = sc.next(); SaveProduct(name, cat, code, sup, war, level, price); // Saves the details of the product System.out.println(&quot;Product details have been saved successfully&quot;); System.out.println(&quot;Enter (1) to launch the menu or any other key to exit&quot;); return sc.next(); } public void ExitApplication() { System.exit(0); } public String DisplayReport() { double totalPrice = 0, itemPrice; int count; System.out.println(&quot;PRODUCT REPORT&quot;); System.out.println(&quot;=====================================================&quot;); count = data.getProductCat().size(); for (int i = 0; i &lt; count; i++) { System.out.printf(&quot;PRODUCT %s\n&quot;, i + 1); System.out.println(&quot;-----------------------------------------------------&quot;); data.toString(i); System.out.println(&quot;-----------------------------------------------------&quot;); itemPrice = Integer.parseInt(data.getProductSup().get(i)) * data.getProductPrice().get(i); totalPrice = totalPrice + itemPrice ; } System.out.println(&quot;=====================================================&quot;); System.out.printf(&quot;TOTAL PRODUCT COUNT: \t%s\n&quot;, count); System.out.printf(&quot;TOTAL PRODUCT VALUE: \tR %s\n&quot;, totalPrice); System.out.printf(&quot;AVERAGE PRODUCT VALUE: \tR %s\n&quot;, totalPrice / count); System.out.println(&quot;=====================================================&quot;); System.out.println(&quot;Enter (1) to launch the menu or any other key to exit&quot;); return sc.next(); } } </code></pre> <p><strong>ReportData.java</strong></p> <pre><code>public class ReportData { ArrayList&lt;String&gt; productName = new ArrayList&lt;&gt;(); ArrayList&lt;String&gt; productCat = new ArrayList&lt;&gt;(); ArrayList&lt;String&gt; productCode = new ArrayList&lt;&gt;(); ArrayList&lt;String&gt; productSup = new ArrayList&lt;&gt;(); ArrayList&lt;String&gt; productWar = new ArrayList&lt;&gt;(); ArrayList&lt;Integer&gt; productLevel = new ArrayList&lt;&gt;(); ArrayList&lt;Double&gt; productPrice = new ArrayList&lt;&gt;(); public void setProductName(String productName) { this.productName.add(productName); } public void setProductCat(String productCat) { this.productCat.add(productCat); } public void setProductCode(String productCode) { this.productCode.add(productCode); } public void setProductSup(String productSup) { this.productSup.add(productSup); } public void setProductWar(String productWar) { this.productWar.add(productWar); } public void setProductLevel(int productLevel) { this.productLevel.add(productLevel); } public void setProductPrice(double productPrice) { this.productPrice.add(productPrice); } public ArrayList&lt;String&gt; getProductName() { return productName; } public ArrayList&lt;String&gt; getProductCat() { return productCat; } public ArrayList&lt;String&gt; getProductCode() { return productCode; } public ArrayList&lt;String&gt; getProductSup() { return productSup; } public ArrayList&lt;String&gt; getProductWar() { return productWar; } public ArrayList&lt;Integer&gt; getProductLevel() { return productLevel; } public ArrayList&lt;Double&gt; getProductPrice() { return productPrice; } public int getLocationOfProduct(String prodCode) { return getProductCode().indexOf(prodCode); // Gets the location of the product in the array } public void toString(int locationOfProduct){ System.out.printf(&quot;PRODUCT CODE:\t\t%s\n&quot;, getProductCode().get(locationOfProduct)); System.out.printf(&quot;PRODUCT NAME:\t\t%s\n&quot;, getProductName().get(locationOfProduct)); System.out.printf(&quot;PRODUCT WARRANTY:\t%s\n&quot;, getProductWar().get(locationOfProduct)); System.out.printf(&quot;PRODUCT CATEGORY:\t%s\n&quot;, getProductCat().get(locationOfProduct)); System.out.printf(&quot;PRODUCT PRICE:\t\tR%s\n&quot;, getProductPrice().get(locationOfProduct)); System.out.printf(&quot;PRODUCT STOCK LEVEL:\t%s\n&quot;, getProductLevel().get(locationOfProduct)); System.out.printf(&quot;PRODUCT SUPPLIER:\t%s\n&quot;, getProductSup().get(locationOfProduct)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T08:32:44.530", "Id": "527971", "Score": "0", "body": "Uhh... is your company ok with you posting the source of an internal tool online? It seems like a generic tool, nothing too closely business-related, but you still might get in trouble, especially if tyou're working for an IT company." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T10:31:22.660", "Id": "527977", "Score": "0", "body": "I was going to ask if this was actually used by some company to run their business or was this a school assignment? Reviews are wholly different for production code and beginner level class room code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T16:01:12.213", "Id": "527990", "Score": "0", "body": "It's an assignment I'm working on." } ]
[ { "body": "<h2>Naming Conventions</h2>\n<p>Methods in Java use <code>lowerCamelCase</code>, as seen in your ReportData class. <code>PascalCase</code> ist only used for classes, so the method names in the Products class should be changed</p>\n<h2>Confusing names</h2>\n<ul>\n<li><code>Products</code> isn't a class related to products, it handles user input (suggesting <code>Menu</code> instead)</li>\n<li><code>exit</code> isn't an exit flag, it stores the user's menu selection (suggesting <code>input</code> instead)</li>\n<li><code>setProduct*()</code> doesn't set anything, it adds to a list (suggesting <code>addProduct*()</code> instead)</li>\n<li><code>getProduct*()</code> doesn't get a single product's value, it gets a list of values of all products (suggesting <code>getAllProducts*()</code> instead)</li>\n<li><code>ReportData.toString()</code> prints a product composed from a list. As this overloads <code>Object.toString()</code> this is especially problematic, since methods with that name are expected to return a string representation of the entire ReportData object. Suggesting <code>printAll()</code> instead.</li>\n</ul>\n<h2>System.exit()</h2>\n<p>In general, this method should be used rarely. It stops the JVM immediately, and so the rest of the program may not be able to clean up and/or terminate gracefully. This is not a problem here, but if you want to save your data to a file, this won't be possible unless you use a shutdown hook, introducing unneeded complexity.</p>\n<p>Also, it's not necessary in this case. Instead, <code>exit</code> may be set to anything but <code>&quot;1&quot;</code> and the do-while-loop terminates normally, as if the user requested it in one of the other dialogues.</p>\n<h1>Comparing to boolean</h1>\n<p><code>exit.equals(&quot;1&quot;) == false</code> is clunky to read. <code>equals()</code> already returns a boolean that can be used directly in the if-statement, so no need to compare it to <code>false</code>.</p>\n<pre><code>if (exit.equals(&quot;1&quot;) == false)\n// reads &quot;if exit equals &quot;1&quot; is the same as false&quot; --&gt; weird and long\n\nif (!exit.equals(&quot;1&quot;))\n// reads &quot;if not exit equals &quot;1&quot;&quot; --&gt; better and shorter\n</code></pre>\n<h2>ReportData class</h2>\n<p>It seems like there is an array list for each of the product's attributes (name, code, warranty), and a product is everything at one index. This is overcomplicated and will lead to bugs and inconsistent data eventually.</p>\n<p>Instead make a class <code>Product</code> where each instance has one name/code/etc. You can then manipulate a simpler and consistent <code>ArrayList&lt;Product&gt;</code> instead. This list could even be a static member of the Product class. After all, this is what OOP is about: model a real-life product in a simple/abstract way, a <code>Product</code> class for example.</p>\n<h2>Input validation</h2>\n<p>In most cases, the program does simple string comparisons which seems stable enough. At some point, the user has to input a number (int/float) though which will cause <code>InputMismatchExceptions</code> if something invalid is entered. These aren't caught here. Also, the numbers should be checked according to common sense and/or business logic, entering a negative prize is nonsensical at best and expensive at worst.</p>\n<h2>Menu implementation</h2>\n<p>The program asks in a pre-menu for a &quot;1&quot; to launch the menu or something else to quit and then offers a seperate quit option in the main menu. This might be confusing or annoying to use. If the pre-menu is removed, the do-while loop in <code>main</code> could print the main menu each time it loops while also providing the functionality of exiting the program. This way the methods in <code>Products</code> wouldn't need to print the pre-menu themselves (which is an unnecessary duplication of code that wastes time if the dialogue is changed) and the <code>exit</code> flag can be removed from most cases. It'll still be needed in the exiting case, since the do-while loop has to end somehow.</p>\n<p>The numerical menu choices could be constants or an <code>enum</code>.</p>\n<p>In big menus it can make sense to move each dialogue to its own class and then have these classes either extend an abstract base class or implement an interface. I'm keeping this short and vague since in your case, having one class handle the entire interface is still reasonable enough.</p>\n<h2>Long println</h2>\n<pre><code>System.out.println(&quot;(1) Capture a new product. \\n&quot; + &quot;(2) Search for a product. \\n&quot; + &quot;(3) Update a product. \\n&quot; + &quot;(4) Delete a product. \\n&quot; + &quot;(5) Print report. \\n&quot; + &quot;(6) Exit application. &quot;);\n</code></pre>\n<p>This line is weird to read and should be split onto multile <code>println()</code>s.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T20:12:35.023", "Id": "267805", "ParentId": "267746", "Score": "3" } }, { "body": "<p>One additional comment:</p>\n<p>You text-based menus are not a professional way of creating a user interface (it feels like in the 1980s). On your learning curve, you probably haven't covered graphical user interfaces (e.g. using Swing or a web server) yet, so that's fine. But maybe you want to read on how to improve your professional skills.</p>\n<p>Text-based programs have their professional use mainly when they are controlled by command-line parameters, meaning to get all input from the <code>args</code> in <code>main(String[] args)</code>. Then they can be easily automated in batch files or shell scripts. Interactive programs typically have a GUI or a web front end.</p>\n<p>Talking about user input/output: professional code separates data processing from the user interface, having one set of classes responsible for processing (maintaining a products list, searching, calculating cost etc., not talking with the user), and different classes for input and output (entering descriptions of products, querying the list, accepting orders, etc.).</p>\n<p>Well-designed code even allows to easily switch between GUI and web front-end, by just using a different set of user interface classes, and using the same processing classes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T16:35:04.760", "Id": "267831", "ParentId": "267746", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T01:43:29.257", "Id": "267746", "Score": "0", "Tags": [ "java", "object-oriented" ], "Title": "Inventory maintenance for a company" }
267746
<p>In the process of migrating an ancient CoffeeScript codebase to TypeScript, I'm <em>also</em> attempting to abandon lodash/underscore.js-alikes in favour of modern JavaScript-standard-library-features (or shims thereof.)</p> <p>One thing my codebase makes a lot of use of, though, is <code>map()</code> over <em><code>Object</code></em> instead of <code>Array</code>. In lodash, that's <a href="https://lodash.com/docs/4.17.15#map" rel="nofollow noreferrer">this</a>.</p> <p>The following is the as-generic-as-I-could-make-it version:</p> <pre class="lang-js prettyprint-override"><code>export type Entry&lt;T&gt; = [string, T] export type EntriesMapper&lt;T, U&gt; = ( entry: Entry&lt;T&gt;, index: number, object: Record&lt;string, T&gt;, ) =&gt; Entry&lt;U&gt; // FIXME: Support `Symbol`-keyed objects. Unfortunately, TypeScript themselves seem to have // sidestepped this issue; so I'm not sure what I can do, myself: // &lt;https://git.io/JuGVg&gt; export function ObjectMap&lt;T, U&gt;( object: Record&lt;string, T&gt;, mapper: EntriesMapper&lt;T, U&gt;, ): { [k: string]: U } { const entries = Object.entries(object) const result = entries.map((entry: Entry&lt;T&gt;, index: number) =&gt; { return mapper(entry, index, object) }) const return_value = Object.fromEntries(result) return return_value } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-24T12:36:10.563", "Id": "529115", "Score": "0", "body": "There are type definitions for lodash available online: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/common/collection.d.ts" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T03:33:16.590", "Id": "267747", "Score": "0", "Tags": [ "typescript", "generics", "lodash.js" ], "Title": "Map over an Object's keys/values, returning a new Object, ala Array#map" }
267747
<p>I have the following algorithm to calculate certain ratios of &quot;work&quot;, &quot;low work&quot; and &quot;no work&quot; over a set date range (<code>startDate</code>, <code>endDate</code>). The algorithm works fine, but when I increase the date range it obviously runs slower because it has to loop over every day of that range for every minute. Is there a way to improve the performance with a different kind of loop or for the where clause to find the current date within the <code>listWorkTime</code>.</p> <pre><code>private List&lt;DateSharedWork&gt; CalculateDateSharedWork(DateTime startDate, DateTime endDate, ICollection&lt;WorkTime&gt; listWorkTime) { List&lt;DateSharedWork&gt; listDateSharedWork = new List&lt;DateSharedWork&gt;(); // +1 to include last day at full int range = endDate.Subtract(startDate).Days + 1; // start at startDate Parallel.For(0, range, i =&gt; { DateTime currDate = startDate.AddDays(i); //set minute interval double everyNMinutes = 1.0; double minutesADay = 1440.0; // reset counter int work_counter = 0; int lowWork_counter = 0; int noWork_counter = 0; int l = (int)(minutesADay / everyNMinutes); for (int j = 0; j &lt; l; j++) { DateTime check15 = currDate.AddMinutes(j * everyNMinutes); // check if listWorkTime includes current date var foundTime = listWorkTime.Where(x =&gt; check15 &gt;= x.FromDate &amp;&amp; check15 &lt;= x.ToDate).ToList(); if (foundTime.Count(x =&gt; x.TimeRangeId == 1) &gt; 0) { // found interval that is within work hours work_counter++; noWork_counter++; } else { if (foundTime.Count(x =&gt; x.TimeRangeId == 2) &gt; 0) { // found intervall that is within low work hours lowWork_counter++; noWork_counter++; } } }; double work = everyNMinutes / minutesADay * work_counter; double lowWork = everyNMinutes / minutesADay * lowWork_counter; double noWork = 1.0 - (everyNMinutes / minutesADay * noWork_counter); listDateSharedWork.Add(new DateSharedWork(currDate, work, lowWork, noWork)); }); listDateSharedWork.Sort((x, y) =&gt; DateTime.Compare(x.Date, y.Date)); return listDateSharedWork; } </code></pre> <p><strong>Edit</strong></p> <p>class definitions of DateSharedWork and WorkTime</p> <pre><code>public class DateSharedWork { public DateSharedWork(DateTime date, double? work = 0.0, double? lowWork = 0.0, double? noWork = 1.0) { this.Date = date; this.Work = work.Value; this.LowWork = lowWork.Value; this.NoWork = noWork.Value; } public DateTime Date { get; private set; } public double Work { get; private set; } public double LowWork { get; private set; } public double NoWork { get; private set; } } public class WorkTime { public int Id { get; set; } public DateTime? FromDate{ get; set; } public DateTime? ToDate{ get; set; } public int? TimeRangeId{ get; set; } } </code></pre> <p><strong>Edit2</strong></p> <p>starting from the <code>startDate</code> value as the first day and increasing on a minute scale for a the whole day, I get the ratios of <em>normal work</em> and <em>low work</em> for that day by the flag <code>TimeRangeId</code>, <code>listWorkTime</code> contains information when a certain period was either work or low work, these periods can overlap and also beeing a duplicate, but <em>normal work</em> (<code>TimeRangeId == 1</code>) dominates</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T07:12:36.940", "Id": "527967", "Score": "0", "body": "Could you please share with us the definitions of `WorkTime` and `DateSharedWork`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T07:54:39.800", "Id": "527970", "Score": "0", "body": "Could you please confirm the following? You receive a start, an end datetime and a collection of timeframes. You want to calculate the intersection on a minute scale. You also want to distinguish *normal work* and *low work* based on a flag. Is my understanding correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T08:35:02.510", "Id": "527972", "Score": "1", "body": "that is correct, additional information on Edit2" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T08:40:10.243", "Id": "527973", "Score": "0", "body": "Can please provide some sample data to be able to test / play with it locally?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T08:58:23.340", "Id": "527974", "Score": "0", "body": "Performance upgrading is often a careful balance between reasonable performance and reasonable code readability/maintainability. To that end: at what kind of date range (and with how many `WorkTime` entries) is the performance becoming unreasonable by your standards? How long does it then take? How long are you expecting it to take? If not a hard line, how much are you willing to sacrifice readability/maintainability for squeezed performance?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T09:01:53.127", "Id": "527975", "Score": "0", "body": "Is the \"every N minutes\" check a requirement, or is it an implementation detail to save on performance by not having to check every literal minute? If a solution was presented that calculates the answer down to the minute or even second and ignores any concept of time chunks, would this be an acceptable solution?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T09:03:24.887", "Id": "527976", "Score": "0", "body": "Would pre-emptive calculation and caching be a valid answer, or must this specifically be an on-the-fly calculation?" } ]
[ { "body": "<p>Just a few quick shots...</p>\n<ul>\n<li><p>Instead of having <code>DateTime check15</code> which leads to the assumption there may be some more <code>DateTime</code> structs laying around like check1...check15 you could just juse <code>currDate</code> which by the way should be renamed to <code>currentDate</code> because abbreviations will make the code harder to read. By using <code>currentDate</code> you could replace <code>(j * everyNMinutes</code> in <code>currDate.AddMinutes()</code>by just <code>1.0</code> or better <code>everyNMinutes</code>.</p>\n</li>\n<li><p><code>foundTime</code> as a name for a <code>List</code> isn't the best choice as a <code>List</code> implies more than one item. How about <code>foundTimes</code> ? But much more important is that for each minute the code iterates over <code>listWorkTime</code> at worst twice. If you only use <code>Count()</code> to check if there is <strong>any</strong> item found, then just use <code>Any()</code>. <code>Count()</code> will iterate over all items while <code>Any()</code> stops at the first found item.</p>\n</li>\n<li><p>You should use a profiler to check if removing <code>ToList</code> after <code>Where()</code> will get more performance.</p>\n</li>\n<li><p>the ideomatic way in c# to name variables is using <code>camelCase</code> casing instead of <code>snake_case</code>casing.</p>\n</li>\n<li><p>instead of an <code>if</code> inside an <code>else</code> block you should use a <code>else if</code> instead.</p>\n</li>\n<li><p>What bothers me more is what happens if there are items in <code>foundTimes</code> which would satisfy both conditions?</p>\n</li>\n</ul>\n<p>Implementing the mentioned changes without taking into account the last point looks like so</p>\n<pre><code>private List&lt;DateSharedWork&gt; CalculateDateSharedWork(DateTime startDate, DateTime endDate, ICollection&lt;WorkTime&gt; listWorkTime)\n{\n\n List&lt;DateSharedWork&gt; listDateSharedWork = new List&lt;DateSharedWork&gt;();\n\n // +1 to include last day at full\n int range = endDate.Subtract(startDate).Days + 1;\n\n // start at startDate\n Parallel.For(0, range, i =&gt;\n {\n\n DateTime currentDate = startDate.AddDays(i);\n\n //set minute interval\n double everyNMinutes = 1.0;\n double minutesADay = 1440.0;\n\n // reset counter\n int workCounter = 0;\n int lowWorkCounter = 0;\n int noWorkCounter = 0;\n\n int l = (int)(minutesADay / everyNMinutes);\n\n for (int j = 0; j &lt; l; j++)\n {\n\n currentDate = currentDate.AddMinutes(everyNMinutes);\n // check if listWorkTime includes current date\n var foundTimes = listWorkTime.Where(x =&gt; currentDate &gt;= x.FromDate &amp;&amp; currentDate &lt;= x.ToDate).ToList();\n\n if (foundTimes.Any(x =&gt; x.TimeRangeId == 1))\n {\n // found interval that is within work hours\n workCounter++;\n noWorkCounter++;\n }\n else if (foundTimes.Any(x =&gt; x.TimeRangeId == 2))\n {\n // found intervall that is within low work hours\n lowWorkCounter++;\n noWorkCounter++;\n }\n\n };\n\n double work = everyNMinutes / minutesADay * workCounter;\n double lowWork = everyNMinutes / minutesADay * lowWorkCounter;\n double noWork = 1.0 - (everyNMinutes / minutesADay * noWorkCounter);\n\n listDateSharedWork.Add(new DateSharedWork(currentDate, work, lowWork, noWork));\n\n });\n\n listDateSharedWork.Sort((x, y) =&gt; DateTime.Compare(x.Date, y.Date));\n\n return listDateSharedWork;\n\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T14:41:33.770", "Id": "267759", "ParentId": "267748", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T04:29:56.430", "Id": "267748", "Score": "-1", "Tags": [ "c#", "performance", "algorithm" ], "Title": "Calculate certain ratios of \"work\", \"low work\", and \"no work\" over large date ranges" }
267748
<p>I am writing a function that I would use to handle parameters with options for use later in another project.</p> <p>A sample input would be similar to this:</p> <pre><code>foo bar --baz con str --w=1920 --h=1080 </code></pre> <p>From the example above I would expect <code>foo</code> and <code>bar</code> to be not part of any flag and <code>baz</code> would contain <code>con</code> and <code>str</code> and <code>w</code> with the value of <code>1920</code> and <code>h</code> with <code>1080</code>:</p> <pre><code>foo bar baz = [con, str] w = 1920 h = 1080 </code></pre> <p>This <code>getFlags</code> function would take a string and perform the &quot;flag&quot; logic that I had in mind.</p> <pre class="lang-javascript prettyprint-override"><code>const getFlags = (str) =&gt; { const prefix = '--'; const strArray = str .trim() .replaceAll(/\s+/ig, ' ') .split(' '); let flagArray = { _noFlag: { values: [], }, }; let lastArg = ''; strArray.forEach((arg) =&gt; { if (arg.startsWith(prefix) &amp;&amp; arg.length &gt; prefix.length) { noPrefixFlag = arg.slice(prefix.length); if (noPrefixFlag.includes('=')) { const pair = noPrefixFlag.split('='); flagArray[pair[0]] = { values: [pair[1]], }; lastArg = ''; } else { lastArg = noPrefixFlag; flagArray[lastArg] = { values: [], }; } } else if (lastArg) { flagArray[lastArg].values.push(arg); } else { flagArray._noFlag.values.push(arg); } }); return flagArray; }; </code></pre> <p>It works as I expect it, but I feel like this function can be improved.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T06:10:06.477", "Id": "267749", "Score": "1", "Tags": [ "javascript" ], "Title": "Small JavaScript function that mimics flag handling of the command line" }
267749
<p><strong><a href="https://www.codewars.com/kata/5765870e190b1472ec0022a2/train/javascript" rel="nofollow noreferrer">Task</a></strong></p> <blockquote> <p>You are at position [0, 0] in maze NxN and you can only move in one of the four cardinal directions (i.e. North, East, South, West). Return true if you can reach position [N-1, N-1] or false otherwise.</p> <ul> <li>Empty positions are marked ..</li> <li>Walls are marked W.</li> <li>Start and exit positions are empty in all test cases.</li> </ul> </blockquote> <p>I know this <a href="https://codereview.stackexchange.com/questions/229564/maze-path-finder-using-depth-first-search-algorithm">exist</a> already, but my solution is a bit different, so...</p> <p>It is very cool and i see that people struggle a lot because of performance (tests are big). I had 3 problems here:</p> <ol> <li>How to make recursion stop after finding solution</li> <li>Before adding &quot;visited&quot; array, i modificated maze array on each turn: maze = maze.slice(0, pos) + 'p' + maze.slice(pos + 1). Adding space complexity (&quot;visited&quot; array) SOLVED A LOT.</li> <li>Converting [x, y] &lt;=&gt; userPosition, as initially maze is by pure string. I found out that it's not even needed to do this convert (division, modulus). Does this improvement means something?</li> </ol> <p>Solution:</p> <pre><code>&quot;use strict&quot;; function pathFinder(maze) { const size = maze.split(&quot;\n&quot;)[0].length; const visited = new Array((size + 1) * size); return solveMaze(maze, visited, size, 0); } function solveMaze(maze, visited, size, userPosition){ if (userPosition === maze.length - 1) { return true; } else { let result; visited[userPosition] = true; const allSteps = [userPosition - (size + 1), //up userPosition + 1, //right userPosition + (size + 1), //down userPosition - 1]; //left const possibleSteps = allSteps.filter(pos =&gt; pos &gt; 0 &amp;&amp; pos &lt; maze.length &amp;&amp; maze[pos] !== 'W' &amp;&amp; !visited[pos] &amp;&amp; maze[pos] !== '\n'); for (const step of possibleSteps) { result = solveMaze(maze, visited, size, step); if (result) return result; } return false; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T17:11:18.997", "Id": "527998", "Score": "0", "body": "`if(userPosition...) { return true } else { ...}` The \"hard return\" makes \"else\" unnecessary. Just let code fall through. That final `return false` - instead: `return result` because Hard coding \"false\" potentially masks bugs; or creates them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T08:52:03.593", "Id": "528141", "Score": "0", "body": "thanks very much! I understand. My approach here was that recursion === base case => recursive case order, but definitely this can be changed to make code cleaner." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T11:01:02.767", "Id": "267753", "Score": "1", "Tags": [ "javascript", "performance", "programming-challenge", "recursion", "depth-first-search" ], "Title": "Codewars: Path Finder" }
267753
<p>We are using Dapper as our ORM and have chosen the repository pattern for organizing our operations. This has worked very well for us but I'd like to confirm that this configuration is capable of sharing and disposing of SQL connections properly.</p> <p><strong>Startup.cs</strong></p> <pre><code>services.AddScoped(_ =&gt; new DeploymentManagerDbConnection( new SqlConnection(Configuration.GetConnectionString(&quot;DeploymentManagement&quot;)) )); services.AddScoped&lt;IDeploymentManagerDbContext, DeploymentManagerDbContext&gt;(); services.AddTransient&lt;IChangeRequestRepository, ChangeRequestRepository&gt;(); services.AddTransient&lt;IBuildRepository, BuildRepository&gt;(); services.AddTransient&lt;IBatchRepository, BatchRepository&gt;(); services.AddTransient&lt;IUserRepository, UserRepository&gt;(); </code></pre> <p><strong>DeploymentManagerDbConnection.cs</strong></p> <pre><code>public DeploymentManagerDbConnection(IDbConnection dbConnection) : base(dbConnection) { } </code></pre> <p><strong>DbConnection.cs</strong></p> <pre><code>public class DbConnection : IDisposable { private bool _disposed; public DbConnection(IDbConnection dbConnection) { Connection = dbConnection; } public IDbConnection Connection { get; } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposed) if (disposing) Connection.Dispose(); _disposed = true; } } </code></pre> <p><strong>DeploymentManagerDbContext.cs</strong></p> <pre><code>public class DeploymentManagerDbContext : IDeploymentManagerDbContext { private readonly IServiceProvider _serviceProvider; public DeploymentManagerDbContext(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } public IChangeRequestRepository ChangeRequests =&gt; _serviceProvider.GetService(typeof(IChangeRequestRepository)) as IChangeRequestRepository; public IBuildRepository Build =&gt; _serviceProvider.GetService(typeof(IBuildRepository)) as IBuildRepository; public IBatchRepository Batch =&gt; _serviceProvider.GetService(typeof(IBatchRepository)) as IBatchRepository; public IUserRepository Users =&gt; _serviceProvider.GetService(typeof(IUserRepository)) as IUserRepository; } </code></pre> <p><strong>UserRepository.cs</strong></p> <pre><code>public class UserRepository : IUserRepository { private readonly IDbConnection _dbConnection; public UserRepository(DeploymentManagerDbConnection deploymentManagerDbConnection) { _dbConnection = deploymentManagerDbConnection?.Connection; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T05:41:17.543", "Id": "528024", "Score": "0", "body": "I would recommand moving the `Startup` code into an extension or you can put it under a namespace, and use Reflection to get all instances and register them, try to automate things. The connectionString should be used inside the `DeploymentManagerDbContext` and not the `Repository`. if used on `Repository` then what purpose the `DeploymentManagerDbContext` serves ?" } ]
[ { "body": "<p><strong>Extra boiler plating</strong></p>\n<p>To start with unless there is missing code from <code>DeploymentManagerDbConnection.cs</code> or <code>DbConnection.cs</code> they aren't doing anything interesting or cleaver with the underlying <code>IDbConnction</code> you're wrapping. If anything I would say to directly use it as is.</p>\n<ul>\n<li><strong>Startup.cs</strong></li>\n</ul>\n<pre><code>services.AddScoped&lt;IDbConnection&gt;(_ =&gt; \n new SqlConnection(Configuration.GetConnectionString(&quot;DeploymentManagement&quot;))\n));\n</code></pre>\n<ul>\n<li><strong>UserRepository.cs</strong></li>\n</ul>\n<pre><code>public UserRepository(IDbConnection connection)\n{\n _dbConnection = connection;\n}\n</code></pre>\n<p><strong>Using <code>IServiceProvider</code> outside of <code>Startup.cs</code></strong></p>\n<p>In almost all cases it isn't recommended to be accessing the di container directly. Registrations or dynamic factories should know about the container <code>IServiceProvider</code>, but other wise it really shouldn't leak out to other places.</p>\n<p>That being said <code>DeploymentManagerDbContext</code> <em>looks</em> like a factory but is far too simple to justify <code>IServiceProvider</code> leaking.</p>\n<ul>\n<li><strong>Register Disposables as <code>Func&lt;T&gt;</code></strong></li>\n</ul>\n<p>To preface, I would expect your interfaces like <code>IUserRepository</code> to inherit from <code>IDisposable</code> and in turn would call the dispose method on your <code>IDbConnection</code>.</p>\n<p>What I would expect for your use-case for your repositories, you want to build them at runtime where ever you need them, but also want to follow/use DI to wire them up correctly. This is where <code>Func&lt;T&gt;</code> comes in.</p>\n<ul>\n<li><strong>Startup.cs</strong></li>\n</ul>\n<pre><code>services.AddTransient&lt;IBuildRepository, BuildRepository&gt;();\nservices.AddTransient&lt;Func&lt;IBuildRepository&gt;&gt;(_ =&gt; _.GetService&lt;IBuildRepository&gt;);\n</code></pre>\n<p>If you find you're seeing a bit of duplication, an extension method can cut down on this.</p>\n<ul>\n<li><strong>RegistrationExtentions.cs</strong></li>\n</ul>\n<pre><code>public static IServiceCollection AddRepository&lt;TInterface, TImplimentation&gt;(this IServiceCollection services)\n where TInterface : class\n where TImplimentation: TInterface\n{\n services.AddTransient&lt;TInterface, TImplimentation&gt;();\n services.AddTransient&lt;Func&lt;TInterface&gt;&gt;(_ =&gt; _.GetService&lt;TInterface&gt;);\n return services;\n}\n</code></pre>\n<p>However, if you don't want to create helper functions for this type of extra registrations, I'd recommend using <code>Lamar</code> as it auto-adds a type build rule for <code>Func&lt;T&gt;</code> and even <code>Lazy&lt;T&gt;</code>.</p>\n<ul>\n<li><strong>Startup.cs</strong></li>\n</ul>\n<pre><code>services.AddRepository&lt;IBuildRepository, BuildRepository&gt;()\n .AddRepository&lt;IBatchRepository, BatchRepository&gt;();\n</code></pre>\n<ul>\n<li><strong>Back to DeploymentManagerDbContext</strong></li>\n</ul>\n<p>We can now directly ask from the container for a <strong>Buildable</strong> repository.</p>\n<pre><code>//this class is also entirely optional to keep or throw\npublic class DeploymentManagerDbContext : IDeploymentManagerDbContext\n{\n\n public DeploymentManagerDbContext(\n Func&lt;IChangeRequestRepository&gt; change,\n Func&lt;IBuildRepository&gt; build,\n Func&lt;IBatchRepository&gt; batch,\n Func&lt;IUserRepository&gt; user)\n {\n _change = change;\n _build = build;\n _batch = batch;\n _user = user;\n }\n \n private readonly Func&lt;IChangeRequestRepository&gt; _change;\n public IChangeRequestRepository ChangeRequests =&gt; _change();\n //skipping the other 3, just follow the pattern\n}\n</code></pre>\n<ul>\n<li><strong>Usage</strong>\nNow in any code file you can directly ask for what you want built.</li>\n</ul>\n<pre><code>public class ProcessController : Controller\n{\n private readonly IDeploymentManagerDbContext _contextFactory;\n public ProcessController(IDeploymentManagerDbContext contextFactory)\n {\n _contextFactory = contextFactory;\n }\n\n public void DoWork()\n {\n using userContext = _contextFactory.Users;\n //sample only for this purpose there are better ways to do authentication\n userContext.IsValidUser(Request.Context.CurrentUser);\n\n using buildContext = _contextFactory.Build;\n buildContext.BuildFoo();\n\n using batchContext = _contextFactory.Batch;\n batchContext.BatchBar();\n }\n}\n</code></pre>\n<ul>\n<li><strong>Without <code>IDeploymentManagerDbContext</code></strong>\nSince the registrations are at the DI level you can also just directly ask for a specific builder.</li>\n</ul>\n<pre><code>public class ProcessController : Controller\n{\n //skipping other fields\n private readonly Func&lt;IBuildRepository&gt; _build;\n public ProcessController(\n Func&lt;IBuildRepository&gt; build,\n Func&lt;IBatchRepository&gt; batch,\n Func&lt;IUserRepository&gt; user)\n {\n //skipping assignments\n }\n\n public void DoWork()\n {\n using userContext = _users();\n //sample only for this purpose there are better ways to do authentication\n userContext.IsValidUser(Request.Context.CurrentUser);\n\n using buildContext = _build();\n buildContext.BuildFoo();\n\n using batchContext = _batch();\n batchContext.BatchBar();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T17:53:47.137", "Id": "528211", "Score": "0", "body": "Hi @Michael Rieger. Thanks for your review. Just to clarify, `DeploymentManagerDbConnection` exists to create separation between multiple database connections. The database connection may not be the same between these repositories so by specifying `DeploymentManagerDbConnection` instead of `SomeOtherDbConnection`, the idea was that DI would be able to inject the appropriate connection. Do you have any thoughts on this approach?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T19:51:07.443", "Id": "528214", "Score": "0", "body": "@AdamChubbuck doing this in 3 parts\n it might be a bit of a leaky abstraction where a class knows which implementation of an interface to use but the sample from [this answer](https://stackoverflow.com/a/44177920/3846633) does what you expect without extra hoops while still keeping this stuff in `Startup.cs`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T19:51:22.660", "Id": "528215", "Score": "0", "body": "[this answer](https://stackoverflow.com/a/48387767/3846633) can look simpler but introduces a lot of redundant types., but had the benefit of types don't directly try to say *i want the `SpecificImplimentation` for interface x*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T19:51:26.517", "Id": "528216", "Score": "0", "body": "[this answer](https://stackoverflow.com/a/52122571/3846633) is more direct by only adding 1 extra type but make you implement some property to tag/filter the right implementation you want." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T21:07:48.777", "Id": "528394", "Score": "0", "body": "Thanks again @Michael Rieger. For the extension above, were you able to test that? It looks like it doesn't work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T22:03:56.933", "Id": "528396", "Score": "0", "body": "I'm also still curious if `IDeploymentManagerDbContext` should be Scoped" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T14:11:13.100", "Id": "528432", "Score": "0", "body": "@AdamChubbuck function fixed, partially going off of memory there. I typically use `Lamar` like I suggested as an alternative. \n\nas for `IDeploymentManagerDbContext` ... it really won't make a difference either way since the `.Built` or `.Batch` and such always make *new* instances at that line call. In fact it could even be `Singleton` to maybe gain limited perf gains of making this builder/factory only once" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T16:25:24.730", "Id": "528454", "Score": "1", "body": "No problem @Michael Rieger. So just to sum everything up, the repository interfaces should implement IDisposable and be added as transients. IDeploymentManagerDbContext should be injected as scoped, although it doesn't really matter much since the associated repositories will be retrieved as new instances regardless. And DeploymentManagerDbConnection and DbConnection can be removed in favor of a transient IDBConnection instance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T16:45:50.533", "Id": "528457", "Score": "0", "body": "@AdamChubbuck you got it. \nthe repositories are things we want to leverage the DI to build, but still follow the expected disposable behavior.\n\nthen the extra classes don't need to be in place since we've resolved where and when the service collection gets used, while keeping relevant things visible where you would expect to find them." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T17:05:54.577", "Id": "528458", "Score": "0", "body": "Wonderful. This makes a lot of sense. The only other change that I did need to make was to turn IDbConnection into a transient since when it was scoped, the connection wouldn't be available for subsequent requests. I'll be doing plenty of testing today to make sure there are no faults but I think I'm back on the right track. :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T19:00:20.013", "Id": "528477", "Score": "0", "body": "Oddly, I am seeing errors stating \"The ConnectionString property has not been initialized.\"." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T21:57:01.640", "Id": "267838", "ParentId": "267755", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T13:13:15.657", "Id": "267755", "Score": "0", "Tags": [ "c#", "dependency-injection", "asp.net-core" ], "Title": "Using the repository pattern with Dapper and a single accessor object" }
267755
<p>This function (in a React web application) code takes a random sample of items to test in each test function, for end-to-end testing:</p> <pre><code>if (randomSample) { for (const test of selectedTestFunctions) { let total = getSampleSize(testFunctions.filter(tf =&gt; tf.testID === test)[0].itemTypeFilter); let item; let itemsTested = []; for (let count = 0; itemsTested.length &lt; total; count++) { while (itemsTested.includes(item) || !item) { item = itemTypes[getRandomItemType()]; } const payload = { &quot;itemPrefix&quot;: item.itemPrefix, &quot;testFunction&quot;: test, }; await apis.testRunner(payload).then(res =&gt; { setOutput((prevOutput) =&gt; [...prevOutput, `${item.itemPrefix}: ${res.data.result}`]); if (res.data.completed) { itemsTested.push(item); } else { item = null; } }); } } return; } </code></pre> <p>The function <code>getSampleSize</code> returns an integer depending on the test, and the <code>for</code> loop loops until the required number of samples is run. The <code>while</code> loop is meant to ensure the same item is not tested more than once. If the test is not completed, I set <code>item = null</code> so another item is selected, because that indicates the test errored out, not that it failed.</p> <p>Although it works correctly, I'm getting the warning <code>Function declared in a loop contains unsafe references to variable(s) 'item', 'item', 'item' no-loop-func</code> at the line <code>await apis.testRunner(payload).then(res =&gt; {</code>.</p> <p>How can I improve this code? In particular, can I eliminate the warning?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T16:01:45.673", "Id": "527991", "Score": "1", "body": "Hi. Welcome to Code Review! If there is a warning, then the code does not do what you want (run without warnings in this case). You should make an MCVE and post on Stack Overflow. Once you've fixed the code, you are welcome to to post the revised code here for review. You may want to post more code when you do that, as this is light on context as well (e.g. what is `selectedTestFunctions`). But as stands, this is not a Code Review question and will end up closed. In general, we do not help you debug your code. We may occasionally notify you of an unnoticed bug but not our purpose." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T16:33:38.580", "Id": "527994", "Score": "0", "body": "[MCVE](https://meta.stackoverflow.com/a/367019/463206) *\"It refers to the least amount of code required for someone to run the program on a stated architecture and be likely to reproduce the problem that's being described in the question.\"*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T16:38:04.167", "Id": "527995", "Score": "0", "body": "Copy-Paste the entire error message into <search engine of choice>. I'm always impressed with the hits I get even with the message customization." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T22:47:52.093", "Id": "528008", "Score": "0", "body": "After reading responses to [this meta posts](https://codereview.meta.stackexchange.com/q/6523/120114) it seems that this post shouldn't be closed simply because it asks about removing warnings, though it doesn't have much context for reviewers. Does the code work as expected (despite the warning)?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T13:18:52.277", "Id": "267756", "Score": "0", "Tags": [ "javascript", "random", "react.js" ], "Title": "Random sample items for testing" }
267756
<h2>Introduction</h2> <hr /> <p>I've started to learn C programming a bit and wanted to create a simple 2D console game. Let me first introduce you to the game level/map structure:</p> <pre><code>(1) ################# (2) ################# # # # # # v S ^# # S # # # # # # &lt; ####### # v # # &gt; # # &gt; &lt; # # A # # ^ # # # # A# ########### # A # # # ################# </code></pre> <p>The different symbols represent the following game objects:</p> <ul> <li><code>#</code> = wall</li> <li><code>S</code> = player</li> <li><code>A</code> = goal</li> <li><code>^,v,&lt;,&gt;</code> monster looking up/down/left/right, respectively.</li> </ul> <p>The goal is to get to one of the goal cells without touching a monster.</p> <p>There can be only one player <code>S</code>, but multiple monsters and goals on the map. On each game tick, the player enters <code>w</code>, <code>a</code>, <code>s</code>, or <code>d</code> and moves up/left/down/right one cell, respectively. Then, all the monster entities move one unit in their corresponding direction.</p> <p>If the player moves &quot;into&quot; a wall, the player's position is not updated. Monsters, however, bounce back <code>180 deg</code> from the wall.</p> <p>The goals (<code>A</code>) and walls (<code>#</code>) do not ever move. However, <code>#</code> acts as a boundary for both the player and monsters. The player can move onto the <code>A</code> but monsters treat the goal cells as walls as well.</p> <p>One caveat is that monsters may overlap (see Level 2) such that only the monster first read from the level file is displayed in such an overlapping cell. If the player runs into a monster the monster is displayer on top and the game ends printing out a lose message. If the player reaches the goal, the goal symbol stays on top and the game ends printing out a win message.</p> <p>Internally, I read in the level file into a 2D <code>char</code> array and save all dynamic entities (player and monsters) in a separate data structure. I then remove all dynamic entities from the 2D array to use it as a &quot;canvas&quot; for drawing. That way I can update all entities' locations and then decide how they're going to be painted onto the canvas, but am still able to use static elements (<code>#</code> and <code>A</code>) for collision detection.</p> <h2>Code</h2> <hr /> <p>Note that I'm only allowed to use the <strong>C99 standard.</strong></p> <p><strong>common.h</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef COMMON_H #define COMMON_H #include &lt;stdio.h&gt; typedef enum error_code { OK = 0, COULD_NOT_OPEN_FILE = 1, COULD_NOT_READ_FILE = 2, INVALID_OPTIONS = 3, ALLOC_FAILED = 4 } t_error_code; typedef struct error_object { char msg[100]; t_error_code error_code; } t_error_object; t_error_object make_error(const char *message, t_error_code error_code); int get_file_size(FILE *f); int get_line_count(FILE *f); char* strdup_(const char* src); #endif </code></pre> <p><strong>common.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;common.h&quot; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; t_error_object make_error(const char *message, t_error_code error_code) { t_error_object error_obj; strncpy(error_obj.msg, message, 100); error_obj.error_code = error_code; return error_obj; } int get_file_size(FILE *f) { fseek(f, 0, SEEK_END); int len = ftell(f); fseek(f, 0, SEEK_SET); return len; } char *strdup_(const char *src) { char *dst = malloc(strlen (src) + 1); if (dst == NULL) return NULL; strcpy(dst, src); return dst; } </code></pre> <hr /> <p><strong>game_params.h</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef GAME_PARAMS_H #define GAME_PARAMS_H #include &lt;stdio.h&gt; #include &quot;common.h&quot; typedef struct game_params { FILE *level_file; FILE *input_file; FILE *output_file; } t_game_params; void cleanup_game_files(t_game_params *params); t_error_object open_game_files(t_game_params *params, const char* level_file_name, const char* input_file_name, const char* output_file_name); t_error_object parse_game_parameters(t_game_params *params_out, int argc, char **argv); #endif </code></pre> <p><strong>game_params.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;game_params.h&quot; #include &quot;common.h&quot; #include &lt;getopt.h&gt; #include &lt;errno.h&gt; #include &lt;string.h&gt; void cleanup_game_files(t_game_params *params) { if (params-&gt;level_file != NULL) fclose(params-&gt;level_file); params-&gt;level_file = NULL; if (params-&gt;input_file != NULL) fclose(params-&gt;input_file); params-&gt;input_file = NULL; if (params-&gt;output_file != NULL) fclose(params-&gt;output_file); params-&gt;output_file = NULL; } t_error_object open_game_files(t_game_params *params, const char *level_file_name, const char *input_file_name, const char *output_file_name) { params-&gt;input_file = stdin; params-&gt;output_file = stdout; if (input_file_name != NULL) { if (strstr(input_file_name, &quot;.txt&quot;) == NULL) { return make_error(&quot;Eingabe-Datei kann nicht gelesen werden&quot;, COULD_NOT_READ_FILE); } params-&gt;input_file = fopen(input_file_name, &quot;r&quot;); if (params-&gt;input_file == NULL) { return make_error(&quot;Eingabe-Datei konnte nicht geöffnet werden&quot;, COULD_NOT_OPEN_FILE); } } if (output_file_name != NULL) { params-&gt;output_file = fopen(output_file_name, &quot;w&quot;); if (params-&gt;output_file == NULL) { return make_error(&quot;Ausgabe-Datei konnte nicht geöffnet werden&quot;, COULD_NOT_OPEN_FILE); } } if (level_file_name == NULL) { return make_error(&quot;Level-Datei muss angegeben werden&quot;, COULD_NOT_OPEN_FILE); } params-&gt;level_file = fopen(level_file_name, &quot;r&quot;); if (params-&gt;level_file == NULL) { return make_error(&quot;Level-Datei konnte nicht geöffnet werden&quot;, COULD_NOT_OPEN_FILE); } return make_error(&quot;&quot;, OK); } t_error_object parse_game_parameters(t_game_params *params_out, int argc, char **argv) { char *level_file_name = NULL; char *input_file_name = NULL; char *output_file_name = NULL; while (optind &lt; argc) { if (argv[optind][0] != '-') { if (level_file_name != NULL) return make_error(&quot;Level-Datei darf nur einmal angegeben werden&quot;, INVALID_OPTIONS); level_file_name = argv[optind]; optind++; } int opt; if ((opt = getopt(argc, argv, &quot;i:o:&quot;)) != -1) { switch (opt) { case 'i': if (input_file_name != NULL) return make_error(&quot;Eingabe-Datei darf nur einmal angegeben werden&quot;, INVALID_OPTIONS); input_file_name = optarg; break; case 'o': if (output_file_name != NULL) return make_error(&quot;Ausgabe-Datei darf nur einmal angegeben werden&quot;, INVALID_OPTIONS); output_file_name = optarg; break; default: return make_error(&quot;Falsche Optionen übergeben&quot;, INVALID_OPTIONS); } } } // Öffne die Dateien zum Lesen/Schreiben und speichere File-Handles in `params` t_error_object ret = open_game_files(params_out, level_file_name, input_file_name, output_file_name); return ret; } </code></pre> <hr /> <p><strong>entity.h</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef ENTITY_H #define ENTITY_H #include &quot;board.h&quot; typedef enum entity_type { PLAYER, MONSTER, NO_ENT } t_entity_type; typedef struct position { int x; int y; } t_position; typedef struct entity { t_position pos; t_direction facing_dir; t_entity_type type; } t_entity; t_entity_type get_entity_type(char c); t_entity create_entity(t_entity_type type, int x, int y, t_direction dir); int compare_positions(t_position *pos1, t_position* pos2); void handle_collision(t_board *board, t_entity *entity, t_position *new_pos); int check_wall(t_board *board, t_position *new_pos); int check_valid_move(t_board *board, t_position *new_pos); void move_entity(t_board *board, t_entity *entity, t_direction dir); #endif </code></pre> <p><strong>entity.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;common.h&quot; #include &quot;direction.h&quot; #include &quot;entity.h&quot; #include &quot;board.h&quot; t_entity_type get_entity_type(char c) { int is_player = (c == 'S'); int is_monster = (map_char_to_direction(c) != NONE); if (is_player) return PLAYER; if (is_monster) return MONSTER; return NO_ENT; } t_entity create_entity(t_entity_type type, int x, int y, t_direction dir) { t_entity entity; t_position pos; pos.x = x; pos.y = y; entity.type = type; entity.pos = pos; entity.facing_dir = dir; return entity; } int check_wall(t_board *board, t_position *new_pos) { if (board-&gt;cells[new_pos-&gt;y][new_pos-&gt;x] == '#') return 1; return 0; } int check_valid_move(t_board *board, t_position *new_pos) { if (new_pos-&gt;x &gt;= board-&gt;col_size || new_pos-&gt;x &lt; 0) return 0; if (new_pos-&gt;y &gt;= board-&gt;num_rows || new_pos-&gt;y &lt; 0) return 0; return 1; } void handle_collision(t_board *board, t_entity *entity, t_position *new_pos) { t_position old_pos = entity-&gt;pos; if (!check_valid_move(board, new_pos)) { *new_pos = old_pos; return; } int collided_with_wall = check_wall(board, new_pos); if (entity-&gt;type == MONSTER) { if (collided_with_wall || get_cell_at(board, new_pos-&gt;x, new_pos-&gt;y) == 'A') { entity-&gt;facing_dir = get_opposite_direction(entity-&gt;facing_dir); *new_pos = old_pos; char c = map_direction_to_char(entity-&gt;facing_dir); set_cell_at(board, new_pos-&gt;x, new_pos-&gt;y, c); return; } } if (entity-&gt;type == PLAYER &amp;&amp; collided_with_wall) { *new_pos = old_pos; } } int compare_positions(t_position *pos1, t_position* pos2) { if (pos1-&gt;y &lt; pos2-&gt;y) return -1; if (pos1-&gt;y &gt; pos2-&gt;y) return 2; if (pos1-&gt;x &lt; pos2-&gt;x) return -1; if (pos1-&gt;x &gt; pos2-&gt;x) return 1; return 0; } void move_entity(t_board *board, t_entity *entity, t_direction dir) { t_position old_pos; old_pos.x = entity-&gt;pos.x; old_pos.y = entity-&gt;pos.y; t_position new_pos = old_pos; t_direction new_dir = dir; if (entity-&gt;type == MONSTER) { new_dir = entity-&gt;facing_dir; } switch (new_dir) { case UPWARDS: new_pos.y--; break; case LEFT: new_pos.x--; break; case DOWNWARDS: new_pos.y++; break; case RIGHT: new_pos.x++; break; case NONE: break; } handle_collision(board, entity, &amp;new_pos); entity-&gt;pos = new_pos; } </code></pre> <hr /> <p><strong>board.h</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef BOARD_H #define BOARD_H #include &quot;game_params.h&quot; #include &quot;direction.h&quot; #include &lt;stdio.h&gt; typedef struct position t_position; typedef struct entity t_entity; typedef enum cell_type { ENTITY, WALL, EMPTY } t_cell_type; typedef struct board { int num_rows; int col_size; char **cells; int num_entities; int player_index; t_entity *entities; t_position *goal_positions; } t_board; void cleanup_board(t_board *board); char get_cell_at(t_board *board, int x, int y); void set_cell_at(t_board *board, int x, int y, char c); t_cell_type get_cell_type(char c); void clear_entities_from_board(t_board *board); void place_entities_on_board(t_board *board); void print_board(t_board *b, FILE *output); void get_board_dims(char *buf, int *num_rows, int *col_size); t_error_object fill_board(t_board *board, char *board_data, int len); t_error_object handle_entity_alloc(t_board *board, const t_entity *entity, int *actual_entity_count, int *expected_entity_count); t_error_object set_initial_positions(t_board *board); t_error_object initialize_board(t_board* board, const t_game_params *params); #endif </code></pre> <p><strong>board.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;common.h&quot; #include &quot;entity.h&quot; #include &quot;board.h&quot; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; void cleanup_board(t_board *board) { for (int i = 0; i &lt; board-&gt;num_rows; i++) { if (board-&gt;cells[i] != NULL) free(board-&gt;cells[i]); } if (board-&gt;cells != NULL) free(board-&gt;cells); if (board-&gt;entities) free(board-&gt;entities); } char get_cell_at(t_board* board, int x, int y) { return board-&gt;cells[y][x]; } void set_cell_at(t_board *board, int x, int y, char c) { board-&gt;cells[y][x] = c; } void clear_entities_from_board(t_board *board) { for (int i = 0; i &lt; board-&gt;num_entities; i++) { t_entity ent = board-&gt;entities[i]; set_cell_at(board, ent.pos.x, ent.pos.y, ' '); } } void place_entities_on_board(t_board *board) { // First draw Player (S) t_entity *player = &amp;board-&gt;entities[board-&gt;player_index]; // 'A' always stays on top of 'S' when they overlap if (get_cell_at(board, player-&gt;pos.x, player-&gt;pos.y) != 'A') set_cell_at(board, player-&gt;pos.x, player-&gt;pos.y, 'S'); // Then draw Monsters (M) in reverse (right-to-left) // to satisfy the condition that monsters seen earlier // should appear before monsters seen at a later point // in case some monsters overlap at a single position for (int i = board-&gt;num_entities - 1; i &gt;= 0; i--) { t_entity ent = board-&gt;entities[i]; char symbol = ' '; if (ent.type != MONSTER) continue; symbol = map_direction_to_char(ent.facing_dir); set_cell_at(board, ent.pos.x, ent.pos.y, symbol); } } void print_board(t_board *board, FILE *output) { place_entities_on_board(board); for (int row = 0; row &lt; board-&gt;num_rows; row++) { for (int col = 0; col &lt; board-&gt;col_size; col++) { char c = board-&gt;cells[row][col]; if (c != 0) fputc(c, output); } fputc('\n', output); } clear_entities_from_board(board); } void get_board_dims(char *buf, int *num_rows, int *col_size) { int num_lines = 0; int longest_line_len = 0; char* buf_copy = strdup_(buf); char* pch = strtok(buf_copy, &quot;\n&quot;); while (pch != NULL) { num_lines++; if (strlen(pch) &gt; longest_line_len) longest_line_len = strlen(pch); pch = strtok(NULL, &quot;\n&quot;); } free(buf_copy); buf_copy = NULL; *num_rows = num_lines; *col_size = longest_line_len; } t_error_object fill_board(t_board *board, char *board_data, int len) { int cur_row = 0; int cur_col = 0; char **b = calloc(board-&gt;num_rows, sizeof(char*)); if (b == NULL) { return make_error(&quot;Konnte keinen Speicherplatz für das Gameboard allozieren&quot;, ALLOC_FAILED); } for (int i = 0; i &lt; board-&gt;num_rows; i++) { b[i] = calloc(board-&gt;col_size, sizeof(char)); if (b[i] == NULL) { return make_error(&quot;Konnte keinen Speicherplatz für das Gameboard allozieren&quot;, ALLOC_FAILED); } } for (int i = 0; i &lt; len; i++) { if (board_data[i] == '\n') { cur_row++; cur_col = 0; continue; } b[cur_row][cur_col] = board_data[i]; cur_col++; } free(board_data); board-&gt;cells = b; return make_error(&quot;&quot;, OK); } t_error_object handle_entity_alloc(t_board *board, const t_entity *entity, int *actual_entity_count, int *expected_entity_count) { *actual_entity_count += 1; if (*actual_entity_count &gt; *expected_entity_count) { *expected_entity_count = *expected_entity_count * 2 + 1; board-&gt;entities = realloc(board-&gt;entities, *expected_entity_count * sizeof(t_entity)); } if (board-&gt;entities == NULL) { return make_error(&quot;Konnte keinen Speicherplatz für die Entitäten allozieren&quot;, ALLOC_FAILED); } board-&gt;entities[*actual_entity_count - 1] = *entity; return make_error(&quot;&quot;, OK); } t_cell_type get_cell_type(char c) { t_entity_type ent_type = get_entity_type(c); int is_wall = (c == '#'); int is_empty = (c == ' '); if (ent_type != NO_ENT) return ENTITY; if (is_wall) return WALL; if (is_empty) return EMPTY; return EMPTY; } t_error_object set_initial_positions(t_board *board) { int expected_entity_count = 1; int actual_entity_count = 0; board-&gt;entities = calloc(expected_entity_count, sizeof(t_entity)); if(board-&gt;entities == NULL) { return make_error(&quot;Konnte keinen Speicherplatz für die Entitäten allozieren&quot;, ALLOC_FAILED); } for (int y = 0; y &lt; board-&gt;num_rows; y++) { for (int x = 0; x &lt; board-&gt;col_size; x++) { int c = board-&gt;cells[y][x]; t_cell_type type = get_cell_type(c); if (type != ENTITY) continue; t_entity_type ent_type = get_entity_type(c); t_direction ent_dir = map_char_to_direction(c); t_entity ent = create_entity(ent_type, x, y, ent_dir); t_error_object ret = handle_entity_alloc(board, &amp;ent, &amp;actual_entity_count, &amp;expected_entity_count); if (ret.error_code != OK) return ret; if (ent_type == PLAYER) board-&gt;player_index = actual_entity_count - 1; } } board-&gt;num_entities = actual_entity_count; return make_error(&quot;&quot;, OK); } t_error_object initialize_board(t_board *board, const t_game_params *params) { int num_rows; int col_size; int file_size = get_file_size(params-&gt;level_file); char *level_data = calloc(file_size + 1, sizeof(char)); if (level_data == NULL) { return make_error(&quot;Konnte keinen Speicherplatz für das Gameboard allozieren&quot;, ALLOC_FAILED); } fread(level_data, file_size, 1, params-&gt;level_file); if (ferror(params-&gt;level_file) != 0) { return make_error(&quot;Konnte Level-Datei nicht lesen&quot;, COULD_NOT_READ_FILE); } get_board_dims(level_data, &amp;num_rows, &amp;col_size); board-&gt;num_rows = num_rows; board-&gt;col_size = col_size; fill_board(board, level_data, file_size); set_initial_positions(board); return make_error(&quot;&quot;, OK); } </code></pre> <hr /> <p><strong>direction.h</strong></p> <pre class="lang-c prettyprint-override"><code>#ifndef DIRECTION_H #define DIRECTION_H typedef enum direction { UPWARDS, LEFT, DOWNWARDS, RIGHT, NONE } t_direction; char map_direction_to_char(t_direction dir); t_direction map_char_to_direction(char dir); t_direction get_opposite_direction(t_direction dir); #endif </code></pre> <p><strong>direction.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;direction.h&quot; char map_direction_to_char(t_direction dir) { switch (dir) { case UPWARDS: return '^'; case LEFT: return '&lt;'; case DOWNWARDS: return 'v'; case RIGHT: return '&gt;'; case NONE: return 0; } return 0; } t_direction map_char_to_direction(char dir) { switch (dir) { case '^': case 'w': return UPWARDS; case '&lt;': case 'a': return LEFT; case 'v': case 's': return DOWNWARDS; case '&gt;': case 'd': return RIGHT; } return NONE; } t_direction get_opposite_direction(t_direction dir) { switch (dir) { case UPWARDS: return DOWNWARDS; case LEFT: return RIGHT; case DOWNWARDS: return UPWARDS; case RIGHT: return LEFT; case NONE: return NONE; } return NONE; } </code></pre> <hr /> <p><strong>dungeon.h</strong></p> <pre><code>#define DUNGEON_H #include &quot;game_params.h&quot; #include &quot;board.h&quot; typedef enum game_status { RUNNING, WON, LOST } t_game_status; void cleanup(t_game_params *params, t_board *board); t_game_status check_win_or_death(t_board *board); void game_loop(t_board *board, t_game_params *params); int main(int argc, char **argv); #endif </code></pre> <p><strong>dungeon.c</strong></p> <pre class="lang-c prettyprint-override"><code>#include &quot;common.h&quot; #include &quot;direction.h&quot; #include &quot;entity.h&quot; #include &quot;board.h&quot; #include &quot;dungeon.h&quot; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; void cleanup(t_game_params *params, t_board *board) { cleanup_game_files(params); cleanup_board(board); } t_game_status check_win_or_death(t_board *board) { t_entity *player = &amp;board-&gt;entities[board-&gt;player_index]; if (get_cell_at(board, player-&gt;pos.x, player-&gt;pos.y) == 'A') return WON; for (int i = 0; i &lt; board-&gt;num_entities; i++) { t_entity *ent = &amp;board-&gt;entities[i]; if (ent-&gt;type == PLAYER) continue; int positions_match = compare_positions(&amp;player-&gt;pos, &amp;ent-&gt;pos) == 0; if (positions_match &amp;&amp; ent-&gt;type == MONSTER) return LOST; } return RUNNING; } void game_loop(t_board *board, t_game_params *params) { FILE *input_stream = params-&gt;input_file; FILE *output_stream = params-&gt;output_file; int step = 1; char command = 0; t_game_status game_status = RUNNING; while (1) { fprintf(output_stream, &quot;%d &quot;, step); fscanf(input_stream, &quot; %c&quot;, &amp;command); if (input_stream != stdin) { fprintf(output_stream, &quot;%c&quot;, command); fprintf(output_stream, &quot;\n&quot;); } t_direction dir = map_char_to_direction(command); for (int i = 0; i &lt; board-&gt;num_entities; i++) { t_entity *ent = &amp;board-&gt;entities[i]; move_entity(board, ent, dir); } game_status = check_win_or_death(board); print_board(board, params-&gt;output_file); if (game_status != RUNNING) break; step++; } if (game_status == LOST) fprintf(output_stream, &quot;Du wurdest von einem Monster gefressen.\n&quot;); else if (game_status == WON) fprintf(output_stream, &quot;Gewonnen!\n&quot;); } int main(int argc, char **argv) { t_game_params params = {NULL, NULL, NULL}; t_board board = {0, 0, NULL, 0, 0, NULL, NULL}; t_error_object err; err = parse_game_parameters(&amp;params, argc, argv); if (err.error_code != OK) { cleanup(&amp;params, &amp;board); fprintf(stderr, &quot;%s, error_code: %d\n&quot;, err.msg, err.error_code); return err.error_code; } err = initialize_board(&amp;board, &amp;params); if (err.error_code != OK) { cleanup(&amp;params, &amp;board); fprintf(stderr, &quot;%s, error_code: %d\n&quot;, err.msg, err.error_code); return err.error_code; } print_board(&amp;board, params.output_file); game_loop(&amp;board, &amp;params); cleanup(&amp;params, &amp;board); return 0; } </code></pre> <h2>Questions</h2> <ul> <li>How can I deal with cleaning up resources in a more concise way? As of now, I'm trying to emulate exception handling by letting errors bubble up to <code>main</code> and doing general cleanup there. I thought about passing around a structure (allocator pattern) to error-throwing functions.</li> <li>Better error handling</li> <li>Instead of &quot;abusing&quot; the game board for both drawing and collision checking, should I wrap cells in a custom data structure?</li> <li>I'm still working on fixing <code>const</code> correctness here and there.</li> <li>Is the <code>direction</code> abstraction a good pattern or uselessly bloating my codebase?</li> <li>Is there a better data structure to represent my game board and the dynamic entities?</li> <li>Unifying collision and win checks. I use the canvas state to check for collisions and win but compare the &quot;virtual&quot; player and monster positions to check for a lose.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T01:27:01.617", "Id": "528013", "Score": "0", "body": "Minor: `strcpy(dst, src); return dst;` rewritable as `return strcpy(dst, src);`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:52:41.077", "Id": "528069", "Score": "0", "body": "`strncpy` won't terminate the string when the input is too long. You can't use it like a limiting `strcpy` but need to also make sure the last char is written to the destination." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T21:37:31.050", "Id": "528106", "Score": "0", "body": "Just out of curiosity, why are you \"allowed\" to only use C99? Is this for a class? Or maybe you're going to put it on a microcontroller to make a retro game?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T21:39:43.767", "Id": "528107", "Score": "0", "body": "P.S. see https://en.cppreference.com/w/c/string/byte/strncpy \"If count is reached before the entire array src was copied, the resulting character array is not null-terminated.\n If, after copying the terminating null character from src, count is not reached, additional null characters are written to dest until the total of count characters have been written.\"" } ]
[ { "body": "<h1>Answers to your questions</h1>\n<blockquote>\n<p>How can I deal with cleaning up resources in a more concise way? As of now, I'm trying to emulate exception handling by letting errors bubble up to <code>main</code> and doing general cleanup there. I thought about passing around a structure (allocator pattern) to error-throwing functions.</p>\n</blockquote>\n<p>C++ makes this a <em>lot</em> easier, with <a href=\"https://en.cppreference.com/w/cpp/language/raii\" rel=\"noreferrer\">RAII</a> and language support for <a href=\"https://en.cppreference.com/w/cpp/language/throw\" rel=\"noreferrer\">exceptions</a>. In C, letting errors &quot;bubble up&quot; and letting <code>main()</code> do the cleanup only works if <code>main()</code> did all the allocations, or can somehow see allocations done by other functions. In larger programs, that is usually not a good strategy.</p>\n<p>Split errors into two categories:</p>\n<ol>\n<li><p>Unrecoverable errors, like failing to allocate memory or failing to read a required file. In this case, just print the error message to <code>stderr</code> and call <code>exit(EXIT_FAILURE)</code>.</p>\n</li>\n<li><p>Recoverable errors. Use a return type that can indicate an error status, like a <code>bool</code> representing success or failure, an integer or enum with an error code, or if you return a pointer to an object, <code>NULL</code> might represent failure. Then the caller can decide how to recover from that error.</p>\n</li>\n</ol>\n<blockquote>\n<p>Instead of &quot;abusing&quot; the game board for both drawing and collision checking, should I wrap cells in a custom data structure?</p>\n</blockquote>\n<p>Having a dedicated type for cells is indeed a good idea.</p>\n<blockquote>\n<p>I'm still working on fixing const correctness here and there.</p>\n</blockquote>\n<p>Yes, a lot of function arguments can be made <code>const</code>.</p>\n<blockquote>\n<p>Is the direction abstraction a good pattern or uselessly bloating my codebase?</p>\n</blockquote>\n<p>I don't think it adds that much bloat, but there are other ways it could have been handled. Consider creating a <code>struct</code> that stores a direction as x and y coordinates, like so:</p>\n<pre><code>typedef struct direction {\n int8_t dx;\n int8_t dy;\n} t_direction;\n</code></pre>\n<p>Then for example in <code>move_entity()</code>, you no longer need the <code>switch</code>-statement, but can just write:</p>\n<pre><code>new_pos.x = old_pos.x + new_dir.dx;\nnew_pos.y = old_pos.y + new_dir.dy;\n</code></pre>\n<blockquote>\n<p>Is there a better data structure to represent my game board and the dynamic entities?</p>\n</blockquote>\n<p>There are many ways you can store the board and the entities, all with their own pros and cons. Yours has the advantage that both printing the board and looking up what is at a given position is very easy. If you treat the goal as a dynamic entity, then the only static things remaining are the walls. So you could use a <a href=\"https://en.wikipedia.org/wiki/Bit_array\" rel=\"noreferrer\">bit array</a> to store it in only one eigth the amount of memory you are currently using, and still be able to fast wall collision detection. Printing the board would be a bit more complex though.</p>\n<blockquote>\n<p>Unifying collision and win checks. I use the canvas state to check for collisions and win but compare the &quot;virtual&quot; player and monster positions to check for a lose.</p>\n</blockquote>\n<p>Yes, ideally when updating the enemies and the player, set <code>game_status</code> if they collide with each other, or if the player collides with the goal.</p>\n<h1>Unsafe use of <code>strncpy()</code></h1>\n<p>When calling <code>make_error()</code>, you copy the string <code>message</code> into the array <code>msg[100]</code> using <a href=\"https://en.cppreference.com/w/c/string/byte/strncpy\" rel=\"noreferrer\"><code>strncpy()</code></a>. However, if the length of <code>message</code> was 100 or more characters, then <code>strncpy()</code> will not have written a NUL-byte at the end of <code>msg[]</code>. Either write a NUL-byte to <code>msg[sizeof(msg) - 1]</code> unconditionally, or use a safer function to write into <code>msg[]</code>, like <a href=\"https://en.cppreference.com/w/c/io/fprintf\" rel=\"noreferrer\"><code>snprintf()</code></a>.</p>\n<p>Alternatively, don't make a copy at all. You are only ever calling <code>make_error()</code> with a string literal, so you could just store a pointer to the string in <code>t_error_object</code>. This would also make this object much more light-weight.</p>\n<h1>Misleading error message</h1>\n<p>If the input filename does not contain &quot;.txt&quot; anywhere in the filename, you return an error that translates to &quot;input file cannot be read&quot;. However, the file might be perfectly fine. Either don't restrict the filename, or return an error message saying that the filename should end in &quot;.txt&quot;.</p>\n<h1>Prefer <code>bool</code> for true/false results</h1>\n<p>A function like <code>check_valid_move()</code> should return a <a href=\"https://en.cppreference.com/w/c/types/boolean\" rel=\"noreferrer\"><code>bool</code></a> to indicate true or false values.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:26:18.063", "Id": "528064", "Score": "0", "body": "Thank you very much for the thorough answers.\n\nI have a question regarding this statement:\n\"Unrecoverable errors, [...] print the error message to stderr and call exit(EXIT_FAILURE).\"\n\nDoes that mean I don't have to do any cleanup if I simply call `exit`? The whole point of introducing error structures was to be able to call the cleanup function without passing around a pointer to all resources to every function that may throw an error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:38:48.437", "Id": "528067", "Score": "1", "body": "Open files and allocated memory gets cleaned up automatically by the operating system (I assume even on the console you are writing your game for) when a program exits." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:55:22.643", "Id": "528070", "Score": "0", "body": "Ok that would make things a lot easier!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T21:42:48.757", "Id": "267771", "ParentId": "267757", "Score": "5" } }, { "body": "<pre><code>char *strdup_(const char *src) {\n char *dst = malloc(strlen (src) + 1); \n if (dst == NULL) return NULL; \n strcpy(dst, src); \n return dst; \n}\n</code></pre>\n<p>You are calling <code>strlen</code> in order to allocate memory, and then calling <code>strcpy</code> which works by calling <code>strlen</code> first! Remember the length, and use <code>memcpy</code> instead.</p>\n<pre><code>void cleanup_board(t_board *board) {\n for (int i = 0; i &lt; board-&gt;num_rows; i++) {\n if (board-&gt;cells[i] != NULL)\n free(board-&gt;cells[i]);\n }\n\n if (board-&gt;cells != NULL)\n free(board-&gt;cells);\n\n if (board-&gt;entities)\n free(board-&gt;entities);\n}\n</code></pre>\n<p>Your <code>NULL</code> checking everywhere is unnecessary, since <a href=\"https://en.cppreference.com/w/c/memory/free\" rel=\"nofollow noreferrer\"><code>free</code></a> already contains such a check!</p>\n<pre><code>t_error_object fill_board(t_board *board, char *board_data, int len) {\n</code></pre>\n<p>This function <code>free</code>'s <code>board_data</code>, which is a parameter passed in and not something it allocated. In C, you need to be careful with ownership responsibilities! This includes being neat about allocating and freeing in the same place, and using naming conventions as to when a copy is returned, when ownership is of a parameter is retained, etc. It is really the bane of existence in the C world.</p>\n<p>It does not seem logical that this is really &quot;fill the board, and meanwhile destroy the parameter&quot;. And what's the <code>len</code> for?</p>\n<p>In this function, <code>board-&gt;cells</code> is overwritten, but any old value is not freed. Should it be called something like <code>initialize_board</code> instead, since it must only be called when the board is either freshly declared or after destroying?</p>\n<pre><code>return make_error(&quot;&quot;, OK);\n</code></pre>\n<p>Just pointing out that this will copy 100 <code>'\\0'</code> characters into the structure.</p>\n<hr />\n<p>You're going to a lot of trouble to measure the file size to read in the whole file, then copying the whole thing again in order to use the destructive <code>strtok</code>, breaking it into lines. You might be better off just using the line-at-a-time file reading functions.</p>\n<hr />\n<p>You're reprinting the board at every step. How about using control codes to reposition the cursor, so you can re-draw in place each time?</p>\n<hr />\n<p>Instead of your 2-D array being an array of pointers to individually allocated rows, you could use a single pointer and allocation for the entire (rows × cols) block. You already abstracted out get and set functions, so just change them to calculate <code>row * col_count + column</code> explicitly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T22:18:35.683", "Id": "267811", "ParentId": "267757", "Score": "1" } } ]
{ "AcceptedAnswerId": "267771", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T14:06:44.917", "Id": "267757", "Score": "7", "Tags": [ "c", "game", "error-handling", "memory-management" ], "Title": "2D Maze Game with Monsters" }
267757
<p>Please can you <strong>suggest</strong> a better / <strong>Optimized</strong> logic or code for the question. It has been asked that when you find a zero value in a matrix, make that element the sum of its upper, lower ,left, right value and make the upper, lower ,left, right elements zero. I assume to the matrix provided has at least 2 rows and 2 columns but if you can post code for any type of matrix , it would be of utmost help. I have fully <strong>commented</strong> the code for easy understanding, just <strong>copy and paste</strong> it in editor and <strong>tweak the values of the matrix variable in the main function of the program</strong>.</p> <pre><code> import java.util.ArrayList; public class Main { static void MakeSurroundingElementsZero(int i,int j,int[][]matrix){ //when the element is not on the boundary of matrix.means it has // all surrounding elements if(i &gt;0 &amp;&amp; i &lt; matrix.length-1 &amp;&amp; j &gt;0 &amp;&amp; j &lt; matrix[i].length-1){ matrix[i][j-1]=matrix[i][j+1]=matrix[i-1][j]=matrix[i+1][j]=0; } //when it is in the first row else if(i ==0){ // when it is not the first or last element in the first row if(j &gt;0 &amp;&amp; j &lt; matrix[i].length-1){ matrix[i][j+1]=matrix[i][j-1]=matrix[i+1][j]=0; } //when it is the first element of the first row else if(j ==0){ matrix[i][j+1]=matrix[i+1][j]=0; } // when it is the last element of the first row else{ matrix[i][j-1]=matrix[i+1][j]=0; } } //when the element is present in the last row else{ //element not the last or the first in the last row if (j &gt;0 &amp;&amp; j &lt; matrix[i].length-1 ){ matrix[i][j+1]=matrix[i-1][j]=matrix[i][j-1]=0; } //first element in the last row else if (j==0){ matrix[i-1][j]=matrix[i][j+1]=0; } //last element of the last row else{ matrix[i][j-1]=matrix[i-1][j]=0; } } } static void addElements(int i,int j,int[][]matrix){ //when the element is not on the boundary of matrix.means it has // all surrounding elements if(i &gt;0 &amp;&amp; i &lt; matrix.length-1 &amp;&amp; j &gt;0 &amp;&amp; j &lt; matrix[i].length-1){ matrix[i][j] = matrix[i][j-1]+matrix[i][j+1]+matrix[i-1][j]+matrix[i+1][j]; } //when it is in the first row else if(i ==0){ // when it is not the first or last element in the first row if(j &gt;0 &amp;&amp; j &lt; matrix[i].length-1){ matrix[i][j] = matrix[i][j+1]+matrix[i][j-1]+matrix[i+1][j]; } //when it is the first element of the first row else if(j ==0){ matrix[i][j] = matrix[i][j+1]+matrix[i+1][j]; } // when it is the last element of the first row else{ matrix[i][j] = matrix[i][j-1]+matrix[i+1][j]; } } //when the element is present in the last row else{ //element not the last or the first in the last row if (j &gt;0 &amp;&amp; j &lt; matrix[i].length-1 ){ matrix[i][j] = matrix[i][j+1]+matrix[i-1][j]+matrix[i][j-1]; } //first element in the last row else if (j==0){ matrix[i][j]= matrix[i-1][j]+matrix[i][j+1]; } //last element of the last row else{ matrix[i][j] = matrix[i][j-1]+matrix[i-1][j]; } } } static void MakeZeroes(int[][] matrix) { ArrayList&lt;Integer[]&gt; zeroElements = new ArrayList&lt;Integer[]&gt;(); for (int i = 0;i &lt; matrix.length;i++) { for(int j = 0;j &lt; matrix[i].length;j++){ //checking each element for zero value if(matrix[i][j] == 0){ addElements(i,j,matrix); //store it as we haven't made the surrounding elements zero yet Integer[] zeroelem = {i,j}; zeroElements.add(zeroelem); } } } //finally, make surrounding elements zero for (int i = 0;i&lt;zeroElements.size();i++){ MakeSurroundingElementsZero(zeroElements.get(i)[0],zeroElements.get(i)[1],matrix); } } public static void main(String[] args) { int[][] matrix = {{2,0,4,0}, {5,9,7,9}, {2,0,8,0}}; MakeZeroes(matrix); for (int i =0;i &lt; matrix.length;i++){ for (int j = 0; j &lt; matrix[i].length;j++){ System.out.print(matrix[i][j]+&quot; &quot;); } System.out.println(); } } } </code></pre> <p>My approach is to:-</p> <ul> <li>Go to each element.</li> <li>Check if it is zero or not.</li> <li>If zero, then check where that element lies , whether totally inside the matrix or on the boundary.</li> <li>Add accordingly the elements around that zero value element.</li> <li>Store the index of that zero element in an ArrayList.</li> <li>Loop the ArrayList to make the surrounding elements zero.</li> </ul>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T12:35:21.533", "Id": "528057", "Score": "0", "body": "Can you use libraries other than the standard lib?" } ]
[ { "body": "<p><em><strong>Fitting Abstraction</strong></em></p>\n<p>Use spaces please. Let the IDE reformat your code.</p>\n<p>The neighbors' offsets can be elements from {(1, 0), (-1, 0), (0, 1), (0, -1)}.</p>\n<p>For instance:</p>\n<pre><code>private static final int[] UP = {-1, 0};\nprivate static final int[] DOWN = {1, 0};\nprivate static final int[] LEFT = {0, -1};\nprivate static final int[] RIGHT = {0, 1};\n// Num Pad orientaton:\n// 7 8 9\n// 4 5 6\n// 1 2 3\nprivate static final int[][] NEIGHBORS7 = {DOWN, RIGHT};\nprivate static final int[][] NEIGHBORS8 = {DOWN, LEFT, RIGHT};\nprivate static final int[][] NEIGHBORS9 = {DOWN, LEFT};\nprivate static final int[][] NEIGHBORS4 = {UP, DOWN, RIGHT};\nprivate static final int[][] NEIGHBORS5 = {UP, DOWN, LEFT, RIGHT};\nprivate static final int[][] NEIGHBORS6 = {UP, DOWN, LEFT};\nprivate static final int[][] NEIGHBORS1 = {UP, RIGHT};\nprivate static final int[][] NEIGHBORS2 = {UP, LEFT, RIGHT};\nprivate static final int[][] NEIGHBORS3 = {UP, LEFT};\n\nint[][] neighbors(int i, int j, int[][] matrix) {\n if (i == 0) {\n if (j == 0) return NEIGHBORS7;\n if (j == matrix[0].length - 1) return NEIGHBORS9;\n return NEIGHBORS8;\n }\n if (i == matrix.length - 1) {\n if (j == 0) return NEIGHBORS1;\n if (j == matrix[0].length - 1) return NEIGHBORS3;\n return NEIGHBORS2;\n }\n if (j == 0) return NEIGHBORS4;\n if (j == matrix[0].length - 1) return NEIGHBORS6;\n return NEIGHBORS5;\n}\n\nfor (int[] neighborIJ: neighbors(i, j, matrix)) {\n int nI = i + neighborIJ[0];\n int nJ = j + neighborIJ[1];\n ...\n}\n</code></pre>\n<p>It is better to provide the available neighbors from every point, and walk through them to take their values.</p>\n<p>So two abstractions: provide neighbors to loop over. And neighbor as offset, not calculated anew for every (i, j).</p>\n<p>This will give less code, less branches, so glitches will be captured faster.</p>\n<p><em><strong>Java Style</strong></em></p>\n<p>Then there is:</p>\n<pre><code> ArrayList&lt;Integer[]&gt; zeroElements = new ArrayList&lt;Integer[]&gt;();\n</code></pre>\n<p>which should be</p>\n<pre><code> List&lt;int[]&gt; zeroElements = new ArrayList&lt;&gt;();\n</code></pre>\n<p>That is:</p>\n<ul>\n<li>program against interfaces, most general code that way;</li>\n<li>use diamond operator <code>&lt;&gt;</code>;</li>\n<li><code>int[]</code> is a <strong>class</strong> too, usable as generic type.</li>\n</ul>\n<p><em><strong>Beautifying</strong></em></p>\n<p>Instead of</p>\n<pre><code>System.out.print(matrix[i][j]+&quot; &quot;);\n</code></pre>\n<p>formatted looks nicer when the sums get more digits:</p>\n<pre><code>System.out.printf(&quot;%3d &quot;, matrix[i][j]);\n</code></pre>\n<p><em><strong>Algorithmic Questions</strong></em></p>\n<p>You collect candidates, and after that do the summation/heaping of values.</p>\n<p>If one candidate is summed, then two other neighboring candidates may no longer be candidates, or get different sums. One steals from neighbor candidates.</p>\n<p>It is probably done, as if one candidate is summed, automatically its neighbors become zero, hence a candidate too.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T10:20:21.217", "Id": "528041", "Score": "0", "body": "Apart from the spelling of \"neighbor\" or \"neighbour\" if you like, I truly dislike identifiers named using a counter such as `NAYBOURS7` to be honest. What does that number represent?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:26:22.047", "Id": "528047", "Score": "0", "body": "@MaartenBodewes I tried to americanize the British neighbour. The numbering is as one the numeric keypad 789 top line, then 456 in the middle and 123 at the bottom. I thought of adding a comment, but did not want to lengthen the answer. I'll correct the spelling" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:33:49.817", "Id": "528048", "Score": "0", "body": "Yeah, I was assuming that it was a mistranslation. I'm a leighman myself when it comes to US spelling :P `NEIGHBORS5` will probably hunt me tonight though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:47:20.933", "Id": "528051", "Score": "0", "body": "@MaartenBodewes your name seems Flamish, mine is Dutch, neighbours so to say. I thought to remember a larger distinction than colour/color, but that must have been an other word." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T13:34:13.690", "Id": "528060", "Score": "0", "body": "It originated from Groningen it seems, and I'm currently situated in Haarlem. There is even a shipyard named \"Bodewes\" in NL of one far away relative. It's not as uncommon a name as you might think." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T21:23:40.003", "Id": "528103", "Score": "0", "body": "Yes, Maarten is quite Dutch. But better to err on the Flamish side." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T20:29:36.340", "Id": "267767", "ParentId": "267761", "Score": "3" } }, { "body": "<p>Styling specific:</p>\n<ol>\n<li>multiple assignments on a single line is only harder to read, it won't make your code faster;</li>\n<li>there is way too little whitespace:\n<ul>\n<li>after comma's;</li>\n<li>surrounding assignments using <code>=</code>;</li>\n<li>surrounding operators such as <code>+</code>;</li>\n<li>after the <code>int[][]</code> array of arrays type;</li>\n<li>before opening parentheses and after closing parentheses;</li>\n<li>after <code>else</code>;</li>\n</ul>\n</li>\n<li><code>MakeZeroes</code> is not using the Java coding convention to start methods with a small cap letter.</li>\n</ol>\n<p>Note that (2) can be obtained by simply using a formatter for you code, in case you don't want to explicitly type out every space. That way you get convenience and nicely formatted / readable code.</p>\n<hr />\n<p>Programming specific:</p>\n<ol>\n<li>there is copy / paste code when assigning to zero and when adding up, this is a generic red flag;</li>\n<li>you are using indexing for the <code>ArrayList</code> while you go through the indices sequentially when you are setting values. For this you'd use an iterator, or more generally, a <em>for-each</em> construct.</li>\n</ol>\n<hr />\n<p>Design specific:</p>\n<ol>\n<li><code>i</code> and <code>j</code> (commonly used for loops) are used instead of e.g. <code>x</code> and <code>y</code>, commonly used for coordinates;</li>\n<li><code>addElements(i,j,matrix)</code> is called in <code>MakeZeroes</code> <strong>which goes completely against the principle of least surprise</strong>;</li>\n<li><code>Main</code> is of course not a good class name;</li>\n<li>(minor): I commonly use the table as initial parameter, but if it was a field, it may not have to be a parameter at all.</li>\n</ol>\n<hr />\n<p>The design would have been much easier if you would have created a <code>Position</code> class. This would have allowed you to create functions to check if a position is valid (you might be astounded how many <code>0</code> and such literals are suddenly not required anymore). If you wanted to store the locations that needed to be zerod then you could then simply store the <code>Position</code> instead of another array.</p>\n<hr />\n<p>I would also encourage you to create a <code>Matrix</code> or <code>Table</code> class of sorts. This would allow you to make sure that the field is a nice table - currently the array sizes <em>within</em> the array could well be different. Generally you use classes to encapsulate data and keep your program from reaching an invalid state.</p>\n<hr />\n<p>Instead of keeping track of all zero values, you can also create a copy of the matrix and perform the operations immediately, using the data of the original matrix. This has, of course, the disadvantage that you require the memory for two matrices, but you only have to traverse the matrix once and can calculate and/or zero the values directly. Besides, a list of integer arrays is rather expensive as well.</p>\n<p><em>This is however more of a alternative than a criticism, your current design is pretty decent.</em></p>\n<p>Do note that you may get duplicate positions that are zero'd, so you could also use a <code>Set</code> of positions. But note that this requires you to have the right <code>equals</code> and <code>hashCode</code> functionality - easily created using a <em>record</em> for <code>Position</code> (Java 14 and onwards).</p>\n<hr />\n<p>One more advanced trick is to use enums to get positions relative to the other position.</p>\n<p>E.g. you could use</p>\n<pre><code>enum Neighbor {\n NORD, EAST, SOUTH, WEST;\n}\n</code></pre>\n<p>or even parameterized</p>\n<pre><code>enum Neighbor {\n NORD(0, -1), EAST(1, 0), SOUTH(0, 1), WEST(-1, 0);\n\n private Neighbor(deltaX, deltaY) {\n ...\n }\n\n ...\n}\n</code></pre>\n<hr />\n<p>That's all great, but that's a lot of work for a beginner. Hence, here's a template to play around with:</p>\n<pre><code>\npublic static record Position(int x, int y) {\n Position getNeighbor(Neighbor neighbor) {\n return new Position(this.x + neighbor.getDeltaX(), this.y + neighbor.getDeltaY());\n }\n}\n\npublic static record Dimensions(int width, int height) {}\n\n\npublic enum Neighbor {\n NORTH(0, -1), EAST(1, 0), SOUTH(0, 1), WEST(-1, 0);\n\n private int deltaX;\n private int deltaY;\n\n private Neighbor(int deltaX, int deltaY) {\n this.deltaX = deltaX;\n this.deltaY = deltaY;\n \n }\n \n public int getDeltaX() {\n return deltaX;\n }\n \n public int getDeltaY() {\n return deltaY;\n }\n}\n\npublic static class Matrix implements Cloneable {\n private int[][] matrix;\n private Dimensions dimensions;\n \n public Matrix(int[][] initialMatrix) {\n this.dimensions = new Dimensions(initialMatrix[0].length, initialMatrix.length);\n \n // clones 2-dimensional array and checks row size\n this.matrix = initialMatrix.clone();\n for (int y = 0; y &lt; dimensions.height(); y++) {\n int[] row = initialMatrix[y];\n if (row.length != dimensions.width()) {\n throw new IllegalArgumentException(&quot;Row &quot; + y + &quot; is not of the same width as the preceding rows&quot;);\n }\n this.matrix[y] = row.clone();\n }\n }\n \n public boolean isValid(Position pos) {\n return pos.x &gt;= 0 &amp;&amp; pos.x &lt; dimensions.width() &amp;&amp; pos.y &gt;= 0 &amp;&amp; pos.y &lt; dimensions.height();\n }\n \n public void set(Position pos, int value) {\n assert isValid(pos);\n matrix[pos.y()][pos.x()] = value;\n }\n \n public int get(Position pos) {\n assert isValid(pos);\n return matrix[pos.y()][pos.x()];\n }\n \n public Matrix clone() {\n return new Matrix(matrix);\n }\n \n public Dimensions getDimensions() {\n return dimensions;\n }\n}\n</code></pre>\n<p>This is all code you can write without even looking at the actual calculations required. Having a base set of classes and methods can really help you focus on the problem. You can copy/paste it into an alternate <code>Main</code> class. It is possible to use <code>Neighbor.values()</code> to iterate over all of the neighbors.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:43:40.840", "Id": "528050", "Score": "0", "body": "Really really minor points: `public enum Neighbor` suffices (implicitly static), and `private final int deltaX;` - might then use public without getters. `record Position` is a good idea / better abstraction." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T12:50:29.177", "Id": "528059", "Score": "0", "body": "You are of course right about `enum` being static by default, as the compiler will create separate class files for each `enum` instance. However, I don't see how I can use that fact to introduce a const value for each class instance from within the `enum` specification. If I'm not mistaken the above trick is straight from \"Effective Java\" by Joshua. In my case neighbor is *relative* to position, so `Position` is the main idea, and `Neighbor` enhances that as `new Position(oldPos.x() - 1, oldPos.y())` is a bit too cryptic for my taste." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T20:30:13.953", "Id": "267768", "ParentId": "267761", "Score": "3" } }, { "body": "<pre><code> }\n //when it is in the first row\n else if(i ==0){\n</code></pre>\n<p>Please don't do this. Yes, C-style languages support arbitrary amounts of whitespace (including comments) between a <code>}</code> and an <code>else</code>. The compiler will be happy with this. But separating the end of the previous block and the code that tells you the next block is part of the same structure is just making things more difficult. It makes it much easier for the next person who is editing the code to do something like</p>\n<pre><code> } else {\n // do something here\n }\n //when it is in the first row\n else if(i ==0){\n</code></pre>\n<p>Which can either cause a compiler error or worse, can move your <code>else if</code> into a different control structure.</p>\n<p>C-style languages do not differ between ending a block and ending the control structure. So please help readers by always keeping the <code>}</code> and the <code>else</code> as close as possible. If not on the same line (which I personally prefer), at least on adjacent lines. Code that does one thing when it looks like it does something else can be incredibly hard to debug.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T20:44:56.830", "Id": "267769", "ParentId": "267761", "Score": "4" } }, { "body": "<p>There's something you'll learn while programming, it's that nesting (having multiple conditions/loops inside one another) makes code difficult to read. In this case, it also promotes code repetition, which is something we usually like to avoid.</p>\n<p>Let's first look at <code>MakeSurroundingElementsZero</code>. The goal of that function is pretty clear, good job on that naming. Although something could be made better : Is it really the whole neighborhood or really just the directly adjacent elements? For example, is the result to :</p>\n<pre><code>[1, 2, 3]\n[4, 0, 6]\n[7, 8, 9] \n</code></pre>\n<p>Supposed to be the first result or the second?</p>\n<pre><code>[1, 0, 3]\n[0, 20, 0]\n[7, 0, 9]\n</code></pre>\n<p>or</p>\n<pre><code>[0, 0, 0]\n[0, 40, 0]\n[0, 0, 0]\n</code></pre>\n<p>Looking at your code, it looks like the first answer is the right one, but from the description of the problem, it isn't clear. There's a name for these kind of neighborhoods in image processing that is 4-neighbor and 8-neighbor. The 4-neighbor represents the first example and 8-neighbord the second. Well, now that this is cleared up, onwards!</p>\n<p>Regarding the code itself : my trick, when I work with algorithms, is to try and think of the simplest way to explain the algorithm, and start with that. In this case, we want to make the left,right,up,down positions values zero if they are within bounds of our matrix.</p>\n<p>So, we have the following positions : <code>[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]</code> and we want to set them to zero if it's possible :</p>\n<pre><code>static void MakeSurroundingElementsZero(int i, int j, int[][] matrix){\n if (i - 1 &gt; 0) {\n matrix[i-1][j] = 0;\n }\n if (i + 1 &lt; matrix[i].length) {\n matrix[i+1][j] = 0;\n }\n if (j - 1 &gt; 0) {\n matrix[i][j-1] = 0;\n }\n if (j + 1 &lt; matrix[j].length) {\n matrix[i][j+1] = 0;\n }\n}\n</code></pre>\n<p>This code checks if the 4 neighbors can be set to zero and does it. It's also much simpler than what you've written, but it does the job. The main takeaway from this is that you should try to decompose big problems into smaller ones, where solving all the small problems take care of the big one.</p>\n<p>The same goes for the <code>addElements</code> function. We can use pretty much the same code. However, I introduced a variable named <code>sumOfNeighbors</code>. It's helpful to use variables when dealing with matrices because the whole indexing clutters the code, it makes it hard to read. Using a variable, we can define exactly what we're doing and we can then assign the <code>sumOfNeighbors</code> value to the center cell :</p>\n<pre><code>static void addElements(int i,int j,int[][]matrix){\n int sumOfNeighbors = 0\n\n if (i - 1 &gt; 0) {\n sumOfNeighbors += matrix[i-1][j];\n }\n if (i + 1 &lt; matrix[i].length) {\n sumOfNeighbors += matrix[i+1][j];\n }\n if (j - 1 &gt; 0) {\n sumOfNeighbors += matrix[i][j-1];\n }\n if (j + 1 &lt; matrix[j].length) {\n sumOfNeighbors += matrix[i][j+1];\n }\n\n matrix[i][j] = sumOfNeighbors;\n}\n</code></pre>\n<p>As @Joop Eggen pointed out in their answer, there's an edge case that isn't considered in your description of the problem.</p>\n<p>What happens in this scenario?</p>\n<pre><code>[1,2,3,4]\n[5,0,0,6]\n[7,8,9,10]\n</code></pre>\n<p>Should the result be :</p>\n<pre><code>[1,0,0,4]\n[0,15,18,0]\n[7,0,0,10]\n</code></pre>\n<p>or</p>\n<pre><code>[1,0,0,4]\n[0,0,33,0]\n[7,0,0,10]\n</code></pre>\n<p>or</p>\n<pre><code>[1,0,0,4]\n[0,33,0,0]\n[7,0,0,10]\n</code></pre>\n<p>Maybe you don't have the answer to this question, but it's also important to think about edge cases when programming!</p>\n<p>All in all, your code really wasn't that bad, but you need to take a look at the problem in your head (or on paper) before writing the code in order to simplify it, so you can write better code :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T18:36:59.617", "Id": "528083", "Score": "0", "body": "Yes, IEatBagels , My code has a lot of flaws, I realised now . Can you tell me is this a beginner level problem, I mean as a beginner am I supposed to have solved this question considering all the edge cases. I am still wondering what can be the proper code for this- Which can be understood by a beginner" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T21:28:54.200", "Id": "528105", "Score": "0", "body": "I think the latter two options are rather far fetched, if just because they use some kind of unspecified ordering. Having a row of all zeros would also be an option if you ask me (and that may actually be the result in the code in the question, as you store which positions to zero in the `List`). But yeah, good catch of a problematic question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T00:53:50.607", "Id": "528118", "Score": "0", "body": "@Aryaman It's a good problem, I think you would've been able to solve this problem if you knew about how to handle the edge case. This might be a good exercise. Also, don't worry about flaws in your code, every code has some :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T13:49:19.237", "Id": "267791", "ParentId": "267761", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T16:25:44.050", "Id": "267761", "Score": "4", "Tags": [ "java", "matrix" ], "Title": "Make surrounding elements zero in a matrix, when you find a zero value" }
267761
<p>I made this small program which takes some inputs (emails) and after looking if they exist it looks for the respective id and delete it. It works (I use it with crontab) but seems redundant. I had several problems with split and decode function, mainly because decode gives me lists of strings spaced by a tab. I would like to optimize the code and get rid of all these <code>for</code> loops, because the code seems long and sloppy. Any tips?</p> <pre><code>bastards = [ &quot;team@mail.kamernet.nl&quot;, &quot;supportdesk@kamernet.nl&quot;, &quot;noreply@pararius.nl&quot;, ] with imaplib.IMAP4_SSL(host='imap.gmail.com',port=993) as imap: imap.login(email,password) imap.select('INBOX',readonly=False) listy = [] for bastard in bastards: resp_code, respy = imap.search(None, f'FROM {bastard}') respy = respy[0].decode().split() listy.append(respy) listy = [x for x in listy if x] for i in listy: for j in i: imap.store(j,'+FLAGS','\\Deleted') print('email_deleted') imap.expunge() imap.close() imap.logout() </code></pre>
[]
[ { "body": "<p>The <code>listy</code> comprehension could be refactored into a generator:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def search_emails(imap, senders):\n for sender in senders:\n typ, data = imap.search(None, f'FROM {sender}')\n msg_nums = data[0].decode().split()\n \n # check for content here\n if msg_nums:\n yield msg_nums\n\n\nwith imaplib.IMAP4_SSL(host='imap.gmail.com', port=993) as imap:\n imap.login(email, password)\n imap.select('INBOX', readonly=False)\n\n # also, visually breaking up the program with newlines\n # makes it more readable\n for email in search_emails(imap, senders):\n for j in email:\n imap.store(j, '+FLAGS', '\\\\Deleted')\n print('email_deleted')\n</code></pre>\n<p>This evaluates lazily, so you don't have to keep all of your emails in a list that you filter out later. It filters them as you iterate over the generator.</p>\n<h1><code>for j in email</code></h1>\n<p>This inner loop doesn't need to be there, per the docs on <a href=\"https://docs.python.org/3/library/imaplib.html#imaplib.IMAP4.store\" rel=\"nofollow noreferrer\"><code>IMAP4.store</code></a>, it takes a set of messages, not one at a time:</p>\n<pre class=\"lang-py prettyprint-override\"><code> ~snip~\n for emails in search_emails(imap, senders):\n imap.store(emails, '+FLAGS', '\\\\Deleted')\n print('emails_deleted')\n</code></pre>\n<p>The official docs also don't have the <code>decode</code> section when parsing the output from <code>IMAP4.search</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>typ, data = M.search(None, 'ALL')\n\nfor num in data[0].split(): # &lt;------ Here\n M.store(num, '+FLAGS', '\\\\Deleted')\n</code></pre>\n<p>I haven't used this library, so I won't speculate on why your snippet is different, but just a note.</p>\n<h1>Variable Names</h1>\n<p>Things like <code>for i in iterable</code> and <code>for j in iterable</code> usually imply indices. I'd change the names here to more accurately represent what they are, it makes the code more readable</p>\n<h1>Function Params</h1>\n<p>Add spaces in between your function parameters:</p>\n<pre class=\"lang-py prettyprint-override\"><code># go from this\nimap.login(email,password)\n\n# to this\nimap.login(email, password)\n</code></pre>\n<h1>Passwords</h1>\n<p>You can use the <code>getpass</code> library for a masked password prompt:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from getpass import getpass\n\npassword = getpass()\n</code></pre>\n<p>I'm not sure how you're currently implementing storing the password, since you haven't included it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T10:25:55.670", "Id": "528044", "Score": "0", "body": "incredible explanation" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T19:36:20.990", "Id": "267764", "ParentId": "267762", "Score": "1" } } ]
{ "AcceptedAnswerId": "267764", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-07T18:29:38.350", "Id": "267762", "Score": "1", "Tags": [ "python" ], "Title": "Cron email-deleter" }
267762
<p>I am working on a machine learning problem with object detection. For now, I am trying to find GPS coordinates that are close to other GPS coordinates. If they are close, I want to make note of it by index. So in my example below, with test data, these two areas are not actually close to one another, so their 'close_points_index' should be just their index. But my actual data set has ~100k observations.</p> <p>This code is slow with 100k observations. I am looking for some help optimizing this code as I can get correct output but would like it if someone could point out any inefficiencies.</p> <p>My data looks like:</p> <pre><code>[{'area_name': 'ElephantRock', 'us_state': 'Colorado', 'url': 'https://www.mountainproject.com/area/105746486/elephant-rock', 'lnglat': [38.88463, -106.15182], 'metadata': {'lnglat_from_parent': False}}, {'area_name': 'RaspberryBoulders', 'us_state': 'Colorado', 'url': 'https://www.mountainproject.com/area/108289128/raspberry-boulders', 'lnglat': [39.491, -106.0501], 'metadata': {'lnglat_from_parent': False}}] </code></pre> <p>My code solution is below. I avoided using two for loops but realize that I am sure a map() is just syntatical sugar for a for loop. Note that latLongDistance I assume is fairly optimized but if not I don't mind. My focus is on my findClusters() function.</p> <pre><code>from math import cos, asin, sqrt, pi from functools import partial def latLongDistance(coord1, coord2): lat2 = coord2[0] lat1 = coord1[0] lon1 = coord1[1] lon2 = coord2[1] p = pi/180 a = 0.5 - cos((lat2-lat1)*p)/2 + cos(lat1*p) * cos(lat2*p) * (1-cos((lon2-lon1)*p))/2 kmDistance = 12742 * asin(sqrt(a)) return kmDistance def findClusters(listOfPoints, thresholdValueM = 800): coords = [x['lnglat'] for x in listOfPoints] for index, data in enumerate(listOfPoints): lngLat = data['lnglat'] modifiedLLDistance = partial(latLongDistance,coord2 = lngLat) listOfDistances = list(map(modifiedLLDistance,coords)) meterDistance = [x*1000 for x in listOfDistances] closePoints = [i for i in range(len(meterDistance)) if meterDistance[i] &lt; thresholdValueM] listOfPoints[index]['close_points_index'] = closePoints return listOfPoints </code></pre> <p>After the function is ran, see below. Note that these have multiple indices as I ran this output on the actual data set. If I were to run just these two points their indices should be: [0] and [1] respectively.</p> <pre><code> [{'area_name': 'ElephantRock', 'us_state': 'Colorado', 'url': 'https://www.mountainproject.com/area/105746486/elephant-rock', 'lnglat': [38.88463, -106.15182], 'metadata': {'lnglat_from_parent': False}, 'close_points_index': [0]}, {'area_name': 'RaspberryBoulders', 'us_state': 'Colorado', 'url': 'https://www.mountainproject.com/area/108289128/raspberry-boulders', 'lnglat': [39.491, -106.0501], 'metadata': {'lnglat_from_parent': False}, 'close_points_index': [1]}] </code></pre> <p>I've experimented with a few things, but am coming up short. Primarily, I am a bit inexperienced with finding speed increases as I am relatively new to Python. Any critical input would be helpful. I have not posted here so let me know if I need some more information for it to be reproducible.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T03:21:57.587", "Id": "528019", "Score": "0", "body": "It sounds like this code does not work as expected. Is it a working solution? If not, this might be a bit better for Stack Overflow rather than Code Review" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T03:56:59.723", "Id": "528020", "Score": "0", "body": "This code does work as expected. Apologies if that is not clear. I will edit my example output and my comment." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T22:01:35.210", "Id": "528108", "Score": "1", "body": "Have you looked at `scipy.spatial.KDTree`? Convert lat/long to x/y/z and build the KDTree. Use the `query_pairs(d)` method to find points that are < `d` distance apart." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T03:17:44.743", "Id": "528121", "Score": "0", "body": "@RootTwo That is a solution that is faster. I implemented it although I had to write some code to grab all of the clusters after producing the pairs. Ex: (10, 20), (20, 30), (10, 30). For 10 I need to know that it is close to 20 and 30. But that is pretty trivial. For my education I am still hoping there is some efficiency in my code to be gained outside of using that library/method. Primarily because I am aiming to get over my 'beginner hump' of knowledge with Python. Long comment, but thank you as your solution is great! I will leave open for a day or two then close this question." } ]
[ { "body": "<p>First some general comments</p>\n<p>In the dataset, the key <code>lnglat</code> is confusing, because the data is clearly latitude and then longitude. That is just asking for a bug.</p>\n<p><code>lng</code>, <code>lon</code>, and <code>long</code> are all used as abbreviations for longitude in the code, pick one.</p>\n<p>Take a look at PEP8 to see what people expect to see when looking at Python code, e.g., <code>latlongdistance</code> or <code>lat_long_distance</code></p>\n<p>Use sequence unpacking:</p>\n<pre><code>lat1, lon1 = coord1\n</code></pre>\n<p><code>list(map(....))</code> is a bit of an anti-pattern. The whole point of using <code>map</code> is the generate values as needed rather than create a list of all the values. If you want a list, many people find a list comprehension clearer.</p>\n<p><code>enumerate()</code> works in comprehensions too:</p>\n<pre><code>closePoints = [i for i, distance in enumerate(meterDistance)\n if distance &lt; thresholdValueM]\n</code></pre>\n<p>Each of <code>listOfDistances</code> and <code>meterDistance</code> create a long list of distances (100k of them), only to discard most of the distances when creating <code>closePoints</code>. Use a generator expression to avoid creating the lists.</p>\n<p>Instead of multiplying each distance by 1000, divide <code>thresholdvalue</code> by 1000 just once outside of the <code>for</code>-loop. That's 1 division instead of 10G multiplications (100k loops and 100k multiplies in the list comprehension).</p>\n<p>The code calculates each distance twice. For example, in the first loop iteration it calculates the distance from the first coord to the second coord, then on the second loop iteration it calculates the distance from the second to the first.</p>\n<p>So something like this would be somewhat more efficient (untested code).</p>\n<pre><code>def findclusters(points, threshold=800):\n\n coords = [x['lnglat'] for x in points]\n\n # convert to meters\n threshold /= 1000\n\n for index, data in enumerate(points):\n \n lngLat = data['lnglat']\n\n # this is a generator expression\n distances = (latlongdistance(lnglat, coord) for coord in coords[index:])\n\n for i, d in enumerate(distances, index)):\n if d &lt; threshold:\n points[index].setdefault('close_points_index', []).append(i)\n points[i].setdefault('close_points_index', []).append(index)\n\n return points\n</code></pre>\n<p>But the biggest efficiency issue is that <code>findClusters()</code> has O(n^2) complexity. The <code>for index, data</code> loop runs for each point in <code>listOfPoints</code>. Inside the loop, each of these lines also loops over the entire list.</p>\n<pre><code>listOfDistances = list(map(modifiedLLDistance,coords))\nmeterDistance = [x*1000 for x in listOfDistances]\n</code></pre>\n<p>That's n * n. To get significant speedups, a different approach is needed. There are various data structures that can be built in O(n * log n) time and then queried to find nearby points. I mentioned KDTrees in a comment to the question, but there are others.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T03:05:07.990", "Id": "528180", "Score": "0", "body": "Thank you. I am coding Python code primarily by myself so I don't have much of a critical eye on my code. I really appreciate it." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T23:32:45.650", "Id": "267840", "ParentId": "267777", "Score": "2" } } ]
{ "AcceptedAnswerId": "267840", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T02:27:56.827", "Id": "267777", "Score": "3", "Tags": [ "python", "performance", "python-3.x" ], "Title": "Finding similar values within a list of lists in Python" }
267777
<h3>description</h3> <ul> <li>I'm using influxDB, I need use Java to generate a query command.</li> <li>The <code>TestingTag</code> struct maybe missing 0-3 fields.</li> </ul> <h3>code:</h3> <pre><code> public List&lt;FluxTable&gt; getAggregatedValueWithTag(String type, String fieldName, String func, TestingTag tag) { queryApi = influxDBClient.getQueryApi(); String flux = String.format(&quot;from(bucket: \&quot;%s\&quot;)\n&quot;,bucket) + &quot; |&gt; range(start: 0)\n&quot; + String.format(&quot; |&gt; filter(fn: (r) =&gt; r[\&quot;_measurement\&quot;] == \&quot;%s\&quot;)\n&quot;,type) + (tag.getPackageName() == null ? &quot;&quot; : String.format(&quot; |&gt; filter(fn: (r) =&gt; r[\&quot;packageName\&quot;] == \&quot;%s\&quot;)\n&quot;,tag.getPackageName())) + (tag.getDeviceID() == null ? &quot;&quot; : String.format(&quot; |&gt; filter(fn: (r) =&gt; r[\&quot;deviceID\&quot;] == \&quot;%s\&quot;)\n&quot;,tag.getDeviceID())) + (tag.getRunTime() == null ? &quot;&quot; : String.format(&quot; |&gt; filter(fn: (r) =&gt; r[\&quot;runTime\&quot;] == \&quot;%s\&quot;)\n&quot;,tag.getRunTime())) + String.format(&quot; |&gt; filter(fn: (r) =&gt; r[\&quot;_field\&quot;] == \&quot;%s\&quot;)\n&quot;,fieldName) + String.format(&quot; |&gt; aggregateWindow(every: 1mo, fn: %s, createEmpty: false)\n&quot;,func) + String.format(&quot; |&gt; yield(name: \&quot;%s\&quot;)&quot;,func); return queryApi.query(flux, org); } </code></pre> <ul> <li>I need to copy-paste the field command for 3 times. The fields may be much more, such as 10. When I have to copy-paste it for many times, may forget to change some parts of code to make it buggy.</li> </ul> <h3>my try:</h3> <ul> <li>Use a loop to deal with it. But I have to use <code>reflection</code> to do <code>tag.get{fieldName}</code>, which maybe not a proper way in Java?</li> </ul> <h3>question:</h3> <ul> <li>Any better way to format this string?</li> </ul>
[]
[ { "body": "<p>Please don't post random slapped-together lines of code that couldn't possibly compile to CodeReview. We strongly prefer code that compiles, even if all the dependencies aren't available to us. This method will never compile.</p>\n<p>In canonical Java, there is whitespace after a <code>,</code></p>\n<p>String building is typically cleaner when done with a StringBuilder.</p>\n<p>A simple helper method to generate a filter string would greatly clean up the numerous repetitions of string formatting.</p>\n<p>More helper methods would make the whole method read more cleanly.</p>\n<p>If you need a generally useful filter, instead of just this one method, make a QueryBuilder class to do the heavy lifting.</p>\n<p>Helper methods would look something like:</p>\n<pre><code>public List&lt;FluxTable&gt; getAggregatedValueWithTag(String type, String fieldName, String func, TestingTag tag) {\n QueryApi queryApi = influxDBClient.getQueryApi();\n String flux = new StringBuilder()\n .append(from(bucket))\n .append(range(0))\n .append(filter(&quot;_measurement&quot;, type))\n .append(filter(&quot;packageName&quot;, tag.getPackageName()))\n .append(filter(&quot;deviceID&quot;, tag.getDeviceID()))\n .append(filter(&quot;runTime&quot;, tag.getRunTime()))\n .append(filter(&quot;_field&quot;, fieldName))\n .append(aggregateWindow(&quot;1m&quot;, func, false))\n .append(yield(func))\n .toString();\n return queryApi.query(flux, org);\n}\n\nprivate String from(String bucket) {\n return String.format(&quot;from(bucket: \\&quot;%s\\&quot;)\\n&quot;, bucket);\n}\n\nprivate String range(int start) {\n return String.format(&quot; |&gt; range(start: %d)\\n&quot;, start);\n}\n\nprivate String filter(String name, String value) {\n if (value == null) {\n return &quot;&quot;;\n }\n return String.format(&quot; |&gt; filter(fn: (r) =&gt; r[\\&quot;%s\\&quot;] == \\&quot;%s\\&quot;)\\n&quot;, name, value);\n}\n\nprivate String aggregateWindow(String frequency, String function, boolean createEmpty) {\n return String.format(&quot; |&gt; aggregateWindow(every: %s, fn: %s, createEmpty: %b)\\n&quot;, frequency, function, createEmpty);\n}\n\nprivate String yield(String name) {\n return String.format(&quot; |&gt; yield(name: \\&quot;%s\\&quot;)&quot;, name);\n}\n</code></pre>\n<p>A QueryBuilder class would look something like:</p>\n<pre><code>public final class QueryBuilder {\n\n private final StringBuilder query = new StringBuilder();\n\n public static QueryBuilder fromBucket(String bucket) {\n return new QueryBuilder(&quot;bucket&quot;, bucket);\n }\n\n private QueryBuilder(String fromType, String from) {\n append(&quot;from(%s: \\&quot;%s\\&quot;)\\n&quot;, fromType, from);\n }\n\n public QueryBuilder range(int start) {\n append(&quot; |&gt; range(start: %d)\\n&quot;, start);\n return this;\n }\n\n public QueryBuilder filter(String name, String value) {\n if (value != null) {\n append(&quot; |&gt; filter(fn: (r) =&gt; r[\\&quot;%s\\&quot;] == \\&quot;%s\\&quot;)\\n&quot;, name, value);\n }\n return this;\n }\n\n public QueryBuilder aggregateWindow(String frequency, String function, boolean createEmpty) {\n append(&quot; |&gt; aggregateWindow(every: %s, fn: %s, createEmpty: %b)\\n&quot;, frequency, function, createEmpty);\n return this;\n }\n\n public QueryBuilder yield(String name) {\n append(&quot; |&gt; yield(name: \\&quot;%s\\&quot;)&quot;, name);\n return this;\n }\n\n public String toString() {\n return query.toString();\n }\n\n private void append(String formatString, Object... values) {\n query.append(String.format(formatString, values));\n }\n}\n</code></pre>\n<p>and the calling method would then look like:</p>\n<pre><code>public List&lt;FluxTable&gt; getAggregatedValueWithTag(String type, String fieldName, String func, TestingTag tag) {\n QueryApi queryApi = influxDBClient.getQueryApi();\n String flux = QueryBuilder.fromBucket(bucket)\n .range(0)\n .filter(&quot;_measurement&quot;, type)\n .filter(&quot;packageName&quot;, tag.getPackageName())\n .filter(&quot;deviceID&quot;, tag.getDeviceID())\n .filter(&quot;runTime&quot;, tag.getRunTime())\n .filter(&quot;_field&quot;, fieldName)\n .aggregateWindow(&quot;1m&quot;, func, false)\n .yield(func)\n .toString();\n return queryApi.query(flux, org);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T06:37:35.627", "Id": "528028", "Score": "0", "body": "Last time I post a MRE code in question, then my question got removed. They told me I need to provide real code not the example code. If I provide a real compilable code, it'll contain a lot irrevent code in it, then no one want to review such a long code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:49:18.583", "Id": "528052", "Score": "0", "body": "https://codereview.meta.stackexchange.com/questions/3649/my-question-was-closed-as-being-off-topic-what-are-my-options/3652#3652" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:50:38.253", "Id": "528053", "Score": "0", "body": "Also, you might want to give a little more time for other people to give answers before you accept an answer. Seeing an accepted answer discourages others from providing answers." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T05:01:35.717", "Id": "267780", "ParentId": "267779", "Score": "1" } } ]
{ "AcceptedAnswerId": "267780", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T03:36:46.430", "Id": "267779", "Score": "-1", "Tags": [ "java", "strings", "formatting" ], "Title": "Better way to format a query string in Java" }
267779
<p>Everything works perfectly fine. However, I just want to know if there's a way for these codes to be shorter and non-repetitive and how?</p> <p>I have these increment counters to update the stocks after submitting them.</p> <p>The <code>selectedItem</code>:</p> <pre><code>&lt;SelectItem value={selectedItem} onChange={handleChange} items={items} /&gt; </code></pre> <p>The first submit:</p> <pre><code>function incrementCounter() { const collRef = firestore .collection(&quot;items&quot;) .where(&quot;item&quot;, &quot;==&quot;, selectedItem); collRef.get().then(async (qSnap) =&gt; { const batch = firestore.batch(); qSnap.docs.forEach((doc) =&gt; { batch.update(doc.ref, { stocks: firebase.firestore.FieldValue.increment(-1), }); }); await batch.commit(); }); } const handleSubmit = (e) =&gt; { e.preventDefault(); try { const userRef = firestore.collection(&quot;users&quot;).doc(id); const ref = userRef.set( { ...data here }, { merge: true } ); console.log(&quot; saved&quot;); incrementCounter(); } catch (err) { console.log(err); } }; </code></pre> <p>Now at the second submit. I have created another increment counter since the <code>selectedItem</code> will be empty since I'm only showing the data of the <code>selectedItem</code> in the screen rather than having a value of it. So, instead of a similar <code>select</code> from above. I just used this <code>textfield</code> in which value is taken from <code>users</code>:</p> <pre><code>const [users, setUsers] = useState([]); useEffect(() =&gt; { const unsubscribe = firestore .collection(&quot;users&quot;) .doc(id) .onSnapshot((snapshot) =&gt; { const user = []; user.push({ ...snapshot.data(), }); setUsers(user); }); return () =&gt; { unsubscribe(); }; }, []); {users &amp;&amp; users.map((user) =&gt; { &lt;TextField type=&quot;text&quot; value={user.items.selectedItem} disabled={true} /&gt; })} </code></pre> <p>The 2nd submit:</p> <pre><code>let ar2 = []; const userItems2 = users[0]?.items?.selectedItem; if (userItems2) { for (const [key, value] of Object.entries(userItems2)) { ar2.push(value); } } const selected2 = ar2.join(&quot;&quot;); function incrementCounter2() { const collRef = firestore .collection(&quot;items&quot;) .where(&quot;item&quot;, &quot;==&quot;, selected2); collRef.get().then(async (qSnap) =&gt; { const batch = firestore.batch(); qSnap.docs.forEach((doc) =&gt; { batch.update(doc.ref, { stocks: firebase.firestore.FieldValue.increment(-1), }); }); await batch.commit(); }); } const handleSubmit2 = (e) =&gt; { e.preventDefault(); try { const userRef = firestore.collection(&quot;users&quot;).doc(id); const ref = userRef.set( { ...data here }, { merge: true } ); console.log(&quot; saved&quot;); incrementCounter2(); } catch (err) { console.log(err); } }; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:22:28.957", "Id": "528031", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:25:29.797", "Id": "528034", "Score": "0", "body": "@BCdotWEB Thank you. I've updated my title" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:35:42.043", "Id": "528037", "Score": "0", "body": "Your title still does not follow the rules. Please re-read them and look at other questions and their titles." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T07:19:41.710", "Id": "267781", "Score": "0", "Tags": [ "javascript", "react.js", "firebase" ], "Title": "Single incrementCounter for 2 form submissions" }
267781
<p>Please critique my implementation of Quicksort in python 3.8:</p> <pre><code>import random from typing import List def quicksort(A: List[int], left: int, right: int): &quot;&quot;&quot; Sort the array in-place in the range [left, right( &quot;&quot;&quot; if left &gt;= right: return pivot_index = random.randint(left, right - 1) swap(A, left, pivot_index) pivot_new_index = partition(A, left, right) quicksort(A, left, pivot_new_index) quicksort(A, pivot_new_index + 1, right) def partition(A: List[int], left: int, right: int) -&gt; int: &quot;&quot;&quot; in-place partition around first item &quot;&quot;&quot; if left &gt;= right: return left pivot = A[left] # initialize i, j pointers j = left + 1 while j &lt; right and A[j] &lt;= pivot: j += 1 i = j # invariant : # A[left+1 ... i-1] &lt;= pivot # A[i ... j-1] &gt; pivot # A[j ... right( unexplored while j &lt; right: if A[j] &lt;= pivot: swap(A, i, j) i += 1 j += 1 swap(A, left, i - 1) return i - 1 def swap(A: List[int], i: int, j: int): A[i], A[j] = A[j], A[i] </code></pre> <p>I followed Tim Roughgarden's explanations in his MOOC on algorithms. But he assumes the keys are all distinct and says that having Quicksort work efficiently on many duplicated keys is trickier than it seems and point to Robert Sedgewick and Kevin Wayne book on algorithms. I checked it and the partition method looks indeed way different.</p> <p>My current code seems to work even with duplicated keys but I think if all the keys are the same, I will get a O(n²) complexity (partitioned arrays will be very unbalanced). How can I update my current code to address this issue?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:21:48.217", "Id": "528130", "Score": "0", "body": "(Please do *not* change in your code (after the first CR answer): when using round *and* square brackets for the notation of intervals, they are in standard orientation. I've seen mirrored ones when using (round) parentheses exclusively.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:23:33.887", "Id": "528131", "Score": "0", "body": "(*Dual pivot* is superior to *three way (<,=,>) partition*.)" } ]
[ { "body": "<p>One possible solution to handle duplicates without a big performance degrade is to randomly shuffle the input list before doing the sort. A specific algorithm to do so is a Fisher Yates Shuffle.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T20:19:07.630", "Id": "528096", "Score": "0", "body": "What does shuffling duplicates achieve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T20:21:10.617", "Id": "528097", "Score": "0", "body": "This allows expected complexity to be stated which does not depend on the algorithms input" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T21:28:11.573", "Id": "528167", "Score": "0", "body": "(When some information has not been just overlooked by a commenter, add the elaboration to your post rather than commenting a comment.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-09T21:32:55.797", "Id": "530260", "Score": "0", "body": "Did you notice the `quicksort()` presented already tries to evade *systematic bad choice of pivot value*: `pivot_index = random.randint(left, right - 1)`? This doesn't help coping with *significantly fewer key values than items* - neither does shuffling." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T19:38:10.027", "Id": "267803", "ParentId": "267782", "Score": "0" } }, { "body": "<p>Performance problems with quicksort are due to one single partition getting almost all of the items, incurring repeated &quot;partition cost&quot;.<br />\nIn the extreme (undetected, if for sake of argument) case of <em>all equal keys</em>, the code presented (implementing <a href=\"https://en.m.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme\" rel=\"nofollow noreferrer\">Lomuto's partition scheme</a>) puts all items equal to pivot in the left partition, returning the index of the rightmost one, leading to quadratic time.<br />\nCareful implementations of Hoare partition move values equal to pivot to &quot;the other partition&quot;, resulting in a balanced split here.<br />\n(When implementing dual pivot, checking they differ seems prudent.)</p>\n<p>The minimally invasive change would seem to be to change the way values equal to pivot are handled - <em>either</em></p>\n<ul>\n<li>Keep a toggle indicating where to put the next one - <em>or</em></li>\n<li>Put the item in the partition currently smaller.\n<pre><code>if A[j] &lt; pivot or (\n A[j] == pivot and i-left &lt; j-i):\n</code></pre>\n</li>\n</ul>\n<hr />\n<ul>\n<li>Why restrict items to <code>int</code>?</li>\n<li>Most of the implementation looks minimalistic (down to function docstrings, only - without full-stops).<br />\nThe special handling of values not exceeding pivot before the main loop of <code>partition()</code> doesn't quite seem in line.</li>\n<li>While you can put pivot selection in <code>partition()</code> just as well as in <code>quicksort()</code>, you could put it in a function of its own to emphasize mutual independance.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-10T07:39:00.907", "Id": "268839", "ParentId": "267782", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T09:07:41.443", "Id": "267782", "Score": "0", "Tags": [ "python", "python-3.x", "algorithm", "quick-sort" ], "Title": "Python Quicksort Implementation with duplicates" }
267782
<p>I have written this small program in Python to calculate decimal places of <span class="math-container">\$\pi\$</span>. I tried to code it as readably as possible, but since this is a bit calculation heavy, it is reasonable to think about performance optimizations.</p> <p>The program calculates the first root of the cosine function using the <a href="https://en.wikipedia.org/wiki/Newton%27s_method" rel="nofollow noreferrer">Newton–Raphson method</a> and computes sine and cosine with the <a href="https://en.wikipedia.org/wiki/Taylor_series#Trigonometric_functions" rel="nofollow noreferrer">Taylor series</a>. Since the first root of the cosine function is at <span class="math-container">\$\frac{\pi}{2}\$</span>, the result is doubled before it is printed.</p> <pre><code># coding: utf-8 &quot;&quot;&quot; calculate decimal places of pi &quot;&quot;&quot; from decimal import Decimal, getcontext from itertools import count c = getcontext() c.prec = 1000 def is_close(a, b): return abs(a - b).adjusted() + c.prec &lt; 2 def newton(x): sums = [Decimal(0) for i in range(4)] value = Decimal(1) sums[0] += value for i in count(1): value *= x / i tmp = sums[i % 4] + value if tmp == sums[i % 4]: break sums[i % 4] = tmp cos_x = sums[0] - sums[2] sin_x = sums[1] - sums[3] return x + cos_x / sin_x def main(): x = Decimal(1) while True: tmp = newton(x) if is_close(tmp, x): x = tmp break x = tmp print(x * 2) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>Thanks @Aemyl for your post. From a quick check of your code, these initial issues jump out at me:</p>\n<ul>\n<li>Using <code>__name__</code> entry point as a runner for <code>main()</code> function</li>\n<li>Global statements (<code>c = getcontext()</code>) outside of <code>__main__</code></li>\n<li><code>sums = [Decimal(0) for i in range(4)]</code> - unused variable <code>i</code></li>\n<li>Function <code>is_close</code> naming. Is close to what?</li>\n<li>Using break (twice) instead of a flag variable explaining why you're ending the loop. in main and in newton</li>\n</ul>\n<p>Let's go over them, and then look at some performance tuning.</p>\n<h1>Entry point as runner</h1>\n<p>I see this a lot from people who come from C, but <code>__main__</code> IS your main already. You should place the content of <code>main()</code> into the entry point where it belongs. This is where other programmers will come to understand how your code runs and why it's doing what it's doing. i.e.:</p>\n<pre><code>if __name__ == '__main__':\n x = Decimal(1)\n while True:\n tmp = newton(x)\n ....\n</code></pre>\n<h1>Global statements</h1>\n<pre><code>c = getcontext()\nc.prec = 1000\n</code></pre>\n<p>Understanding the import system of Python is important if you want to improve your Python skills. In this case, the modification of the Decimal can be done inside <code>__main__</code>, so we now have:</p>\n<pre><code>if __name__ == '__main__':\n c = getcontext()\n c.prec = 1000\n x = Decimal(1)\n while True:\n ....\n</code></pre>\n<h1>Unused variable i</h1>\n<p>The statement <code>sums = [Decimal(0) for i in range(4)]</code> doesn't do anything with <code>i</code>.\nWhen I look at that line in my debugger, I can see that it's just populating <code>sums</code> with 4 entries of <code>Decimal(0)</code>. Let's look at it from the performance checker's view:</p>\n<pre><code>Line # Hits Time Per Hit % Time Line Contents\n==============================================================\n 19 8 84.0 10.5 0.0 sums = [Decimal(0) for i in range(4)]\n</code></pre>\n<p>And now let's convert the loop into a static statement and re-run that to see if it's improved performance:</p>\n<pre><code>Line # Hits Time Per Hit % Time Line Contents\n============================================================== \n 21 8 55.0 6.9 0.0 sums = [Decimal(0),Decimal(0),Decimal(0),Decimal(0)]\n</code></pre>\n<p>That's a little better...</p>\n<h1>Variable naming</h1>\n<p>When you're writing code, it's not about you &quot;now&quot; - it's about the &quot;future you&quot;, as well as - if you do it professionally - the other coders who will look at your code. Think about how many times you've come back to your code after a few weeks or months, and you ask yourself &quot;who wrote this rubbish?&quot; and &quot;what the hell was I thinking?&quot; - I know I've had that experience quite a few times.</p>\n<p>Variable naming is an important part of explaining what your code is trying to do.</p>\n<p>So, as an example of throwaway variables, one of the things Python allows you to do, is use <code>_</code> as a variable for these throwaway variables. For example, this code:</p>\n<pre><code>for i in count(1):\n value *= x / i\n tmp = sums[i % 4] + value\n if tmp == sums[i % 4]:\n break\n sums[i % 4] = tmp\n \n</code></pre>\n<p>Let's replace all the <code>tmp</code> variables with <code>_</code>:</p>\n<pre><code>for i in count(1):\n value *= x / i\n _ = sums[i % 4] + value\n if _ == sums[i % 4]:\n break\n sums[i % 4] = _\n \n</code></pre>\n<p>Looks better right? Actually no, it doesn't. So <code>tmp</code> really isn't a throwaway variable right? It means something. We need to name the variables to explain what they're doing. Perhaps <code>calc_val</code> or quickly looking at some notes about the Newton method, it looks like it's calculating area. So perhaps <code>area</code> is better? If I'm wrong, sorry, it was a <em>very</em> quick look.</p>\n<h1>Using Break</h1>\n<p>Looking at the main, we see break being used to escape the loop. This approach results in spaghetti code. You should cleanly exit any loop using a control variable or refactor it into a function with a return statement.</p>\n<p>Original code is:</p>\n<pre><code>while True:\n tmp = newton(x)\n if is_close(tmp, x):\n x = tmp\n break\n x = tmp\nprint(x * 2)\n</code></pre>\n<p>Let's introduce a control variable and complete the if into an if/else:</p>\n<pre><code>calc_pi = True\nwhile calc_pi:\n tmp = newton(x)\n if is_close(tmp, x):\n x = tmp\n calc_pi = False\n else:\n x = tmp\nprint(x * 2)\n \n</code></pre>\n<p>Now we're not using break, the loop will exit cleanly into the print statement.</p>\n<p>Ah! But what is this? What do we see?</p>\n<p>It's now clear that both paths of the <code>if</code> statement perform the same action. Is this an error? Let's make sure the output is the same, then make a change.</p>\n<pre><code>result = x * 2\nprint(result)\nif str(result) != &quot;3.14159265....0214&quot;:\n print(&quot;wrong, didn't match&quot;)\n</code></pre>\n<p>And write the changes:</p>\n<pre><code>while calc_pi:\n tmp = newton(x)\n if is_close(tmp, x):\n calc_pi = False\n x = tmp\n</code></pre>\n<p>And run the code - yes, the result matches. So this proves the paths were equal and we were correct to refactor that code into that final version (above).</p>\n<p>We can also perform a similar change to the <code>newton(x)</code> code, but this is getting a little long, and you asked for performance enhancements.</p>\n<h1>Performance Checking</h1>\n<p>Running line_profiler (there's lots of examples how on the 'net), we have the following results:</p>\n<pre><code>Line # Hits Time Per Hit % Time Line Contents\n==============================================================\n 19 @profile\n 20 def newton(x):\n 21 8 55.0 6.9 0.0 sums = [Decimal(0),Decimal(0),Decimal(0),Decimal(0)]\n 22 8 15.0 1.9 0.0 value = Decimal(1)\n 23 8 24.0 3.0 0.0 sums[0] += value\n 24 3857 3140.0 0.8 1.2 for i in count(1):\n 25 3857 233157.0 60.5 86.2 value *= x / i\n 26 3857 13665.0 3.5 5.0 tmp = sums[i % 4] + value\n 27 3857 15645.0 4.1 5.8 if tmp == sums[i % 4]:\n 28 8 9.0 1.1 0.0 break\n 29 3849 4438.0 1.2 1.6 sums[i % 4] = tmp\n 30 8 21.0 2.6 0.0 cos_x = sums[0] - sums[2]\n 31 8 19.0 2.4 0.0 sin_x = sums[1] - sums[3]\n 32 8 416.0 52.0 0.2 return x + cos_x / sin_x\n</code></pre>\n<p>Well, value and sums creations still don't look right. Line 23 is doing another static assignment which we can roll into line 21. So, let's change <code>sums[0]</code> into <code>Decimal(1)</code> and remove line 23.</p>\n<p>Line 25 seems to be doing most of the work, but I can see that you're continually recalculating modulo. Let's create a variable storing the modulo result and use that instead.</p>\n<pre><code>Line # Hits Time Per Hit % Time Line Contents\n==============================================================\n 14 @profile\n 15 def newton(x):\n 16 8 33.0 4.1 0.0 sums = [Decimal(1), Decimal(0), Decimal(0), Decimal(0)]\n 17 8 9.0 1.1 0.0 value = Decimal(1)\n 18 3857 2314.0 0.6 1.3 for i in count(1):\n 19 3857 152870.0 39.6 87.9 value *= x / i\n 20 3857 3353.0 0.9 1.9 mod_val = i % 4\n 21 3857 8470.0 2.2 4.9 tmp = sums[mod_val] + value\n 22 3857 3670.0 1.0 2.1 if tmp == sums[mod_val]:\n 23 8 4.0 0.5 0.0 break\n 24 3849 2961.0 0.8 1.7 sums[mod_val] = tmp\n 25 8 13.0 1.6 0.0 cos_x = sums[0] - sums[2]\n 26 8 11.0 1.4 0.0 sin_x = sums[1] - sums[3]\n 27 8 274.0 34.2 0.2 return x + cos_x / sin_x\n</code></pre>\n<p>So changes thus far have made it run about 60% better (270604 -&gt; 173982). And changing the <code>for</code> loop into a <code>while</code> loop with a control variable:</p>\n<pre><code>Line # Hits Time Per Hit % Time Line Contents\n==============================================================\n 14 @profile\n 15 def newton(x):\n 16 8 31.0 3.9 0.0 sums = [Decimal(1), Decimal(0), Decimal(0), Decimal(0)]\n 17 8 9.0 1.1 0.0 value = Decimal(1)\n 18 8 6.0 0.8 0.0 do_calcs = True\n 19 8 3.0 0.4 0.0 counter = 1\n 20 3865 2430.0 0.6 1.2 while do_calcs:\n 21 3857 173534.0 45.0 87.4 value *= x / counter\n 22 3857 3466.0 0.9 1.7 mod_val = counter % 4\n 23 3857 8579.0 2.2 4.3 tmp = sums[mod_val] + value\n 24 3857 3994.0 1.0 2.0 if tmp == sums[mod_val]:\n 25 8 6.0 0.8 0.0 do_calcs = False\n 26 else:\n 27 3849 3214.0 0.8 1.6 sums[mod_val] = tmp\n 28 3849 2973.0 0.8 1.5 counter += 1\n 29 8 16.0 2.0 0.0 cos_x = sums[0] - sums[2]\n 30 8 13.0 1.6 0.0 sin_x = sums[1] - sums[3]\n 31 8 283.0 35.4 0.1 return x + cos_x / sin_x\n</code></pre>\n<p>But as you can see, that slowed it down a little (198274; slower by 24292) although the code is much clearer, and we can now refactor that into a function - because the <code>break</code> has been removed (I use PyCharm's Refactor-&gt;Extract-&gt;Method approach).</p>\n<p>Also, we unwrap the <code>*=</code> into a full calculation, and reintroduce your original for loop via <code>count(1)</code>, primarily because we've wrapped it into a function so it can exit cleanly with a return statement:</p>\n<pre><code>Total time: 0.191908 s\nFile: 0908_calc_pi.py\nFunction: newton at line 14\n\nLine # Hits Time Per Hit % Time Line Contents\n==============================================================\n 14 @profile\n 15 def newton(x):\n 16 8 35.0 4.4 0.0 sums = [Decimal(1), Decimal(0), Decimal(0), Decimal(0)]\n 17 8 9.0 1.1 0.0 value = Decimal(1)\n 18 8 191565.0 23945.6 99.8 sums = perform_calcs(sums, value, x)\n 19 8 16.0 2.0 0.0 cos_x = sums[0] - sums[2]\n 20 8 11.0 1.4 0.0 sin_x = sums[1] - sums[3]\n 21 8 272.0 34.0 0.1 return x + cos_x / sin_x\n\nTotal time: 0.18069 s\nFile: 0908_calc_pi.py\nFunction: perform_calcs at line 23\n\nLine # Hits Time Per Hit % Time Line Contents\n==============================================================\n 23 @profile\n 24 def perform_calcs(sums, value, x):\n 25 3857 2152.0 0.6 1.2 for counter in count(1):\n 26 3857 162137.0 42.0 89.7 value = value * (x / counter)\n 27 3857 2765.0 0.7 1.5 mod_val = counter % 4\n 28 3857 7591.0 2.0 4.2 tmp = sums[mod_val] + value\n 29 3857 3497.0 0.9 1.9 if tmp == sums[mod_val]:\n 30 8 8.0 1.0 0.0 return sums\n 31 else:\n 32 3849 2540.0 0.7 1.4 sums[mod_val] = tmp\n</code></pre>\n<p>Giving us a value of 191908. That's a little slower than the best, but it's cleaner and refactored (variable naming needs some work still). That's about the best I can think of off the top of my head. I hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T13:46:44.677", "Id": "528061", "Score": "0", "body": "Thanks for the answer, looks like you invested a lot of time to write it. Can you explain why the line `value *= x / i` runs much faster after introducing `mod_val`? It looks totally unrelated to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T17:00:52.830", "Id": "528074", "Score": "0", "body": "Cheers. To know that, we'd have to ask someone more familiar with lower-level compiler knowledge or have the before and after assembly dump reviewed to obtain an answer. I don't know anyone with either skill-set. Maybe someone from the reverseengineering forum would be able to answer it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T17:26:26.477", "Id": "528077", "Score": "8", "body": "If there shouldn't be a `main` function, then why does the [official documentation for `__main__`](https://docs.python.org/3/library/__main__.html) show doing exactly that?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T17:56:51.837", "Id": "528079", "Score": "4", "body": "@don'ttalkjustcode in the python standard library, both versions appear: `aifc.py` runs the main routine directly in `if __name__ == '__main__':`, while `ast.py` uses a `main` function. I think I should ask myself how likely it is for another script to import the `main` function and how likely it is to have a bug because the variables I use inside `if __name__ == '__main__':` are in the global name scope. I personally prefer using a `main` function but I wouldn't be surprised if there are good reasons against it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T18:12:41.330", "Id": "528080", "Score": "4", "body": "@Aemyl Yeah I find it odd to say one \"should\" pollute globals." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T18:14:07.390", "Id": "528081", "Score": "1", "body": "@Aemyl My guess is that the speed difference after introducing `mod_val` is because their CPU was busier with other things during the earlier run." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T18:20:28.573", "Id": "528082", "Score": "0", "body": "@don'ttalkjustcode sometimes I notice a significant speed difference between the first run of a script and following runs. For example, when I open the python console right after starting my computer and execute `import tensorflow`, it takes a really long time to load. When I close the console, open a new one and run `import tensorflow` again, it is much faster. I can imagine something similar happening here, but I don't know how to measure that properly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T18:49:02.483", "Id": "528086", "Score": "0", "body": "@Aemyl Running both the \"before\" version and the \"after\" version a few times alternatingly, [I see no speed difference](https://pastebin.com/raw/Xy4Baa3B)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T19:01:18.383", "Id": "528089", "Score": "1", "body": "Relevant (albeit closed) StackOverflow question: [What is the style guideline for if \\_\\_name\\_\\_ == '\\_\\_main\\_\\_'?](https://stackoverflow.com/q/23922503)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T00:22:31.823", "Id": "528115", "Score": "0", "body": "@don'ttalkjustcode That's a contrived example to end the point about launching as a script or operating as a library import. Later on, as Aemyl improves coding, they will write libraries or utilise TDD. If you write C code, you place the entire program logic inside main. For Python, if you're writing a single-executable script, you write the logic in the entry point. If you're writing a library, there is no entry point. If another coder reads your code, they don't want to chase the logic around and lose their train of thought. YMMV, but experienced coders taught me these valuable lessons." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T03:40:00.997", "Id": "528122", "Score": "4", "body": "Actually the `__main__` documentation just got rewritten and expanded for the upcoming Python 3.10, including an \"[Idiomatic Usage](https://docs.python.org/3.10/library/__main__.html#idiomatic-usage)\" section which says *\"Most often, a function named main encapsulates the program’s primary behavior\"*. And Guido van Rossum [called that rewrite \"great\"](https://bugs.python.org/issue39452#msg400671) and explicitly advocated using a `main` function like done here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T03:54:26.617", "Id": "528124", "Score": "3", "body": "The _entry point as runner_ section is plain wrong. Having a main routine is not redundant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T07:00:53.173", "Id": "528135", "Score": "1", "body": "I think the `while` loop would be clearer as `while not is_close(calc_val, x):` and no need for a `break` or an artificial \"keep looping\" variable; obviously we should initialise `calc_val` to something reasonable outside the loop (perhaps `calc_val = 0` and `x = 3`)." } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T13:23:24.657", "Id": "267790", "ParentId": "267783", "Score": "5" } } ]
{ "AcceptedAnswerId": "267790", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T09:45:56.810", "Id": "267783", "Score": "6", "Tags": [ "python", "mathematics" ], "Title": "Calculating decimal places of pi in Python" }
267783
<p>This is a script that can convert any numerical value to any arbitrary radix representation and back, well, technically it can convert a number to any base, but because the output is a string representation with each a character as a digit, and possible digits are 10 Arabic numerals plus 26 basic Latin (lowercase) letters, the base can only be an integer from 2 to 36 (including both ends).</p> <p>The possible digits are 0..9 + a..z, just like how hexadecimal orders them, I used bit shifting to convert to and from a base that is a power of two, and divmod for every other base. In my testing, bit-shifting is actually a bit slower than divmoding, I don't know why.</p> <p>I have written a function that converts a decimal number to a base between 2 and 36, and another function that converts a number from a base between 2 and 36 to decimal, both functions validate the possibility of conversion before the actual conversion.</p> <p>I have also written three sets of function that converts binary data to and from base-36.</p> <p>The first set encode and decode the hexadecimal value of the binary data as a whole, rather than individual bytes, so the result can be more compact.</p> <p>The second set encode and decode each character as two base-36 bits, with the highest possible two-bit being <code>zz</code> which in decimal is 1295 or (36 ^ 2) - 1, as such it can be accurate up to <code>\u050f</code> or <code>ԏ</code>, but extended ASCII has only 256 code points the second set is sufficient for non-UNICODE characters.</p> <p>The third set encode and decode each byte as two base-36 bits, it can therefore represent any UNICODE code point, and its output is same as the second set for code points below 1296.</p> <p>The code:</p> <pre class="lang-py prettyprint-override"><code>from string import ascii_lowercase from string import digits def log2(n): return n.bit_length() - 1 def power_of_2(n): return (n &amp; (n-1) == 0) and n != 0 glyphs = digits + ascii_lowercase def parser(s, base): sep = ',' if base == 60: sep = ':' elif base == 256: sep = '.' if 2 &lt;= base &lt;= 36: return [glyphs.index(i) for i in s] return s.split(sep) def to_base(num, base): if base &lt; 2 or not isinstance(base, int): return sep = ',' if base == 60: sep = ':' elif base == 256: sep = '.' if power_of_2(base): l = log2(base) powers = range(num.bit_length() // l + (num.bit_length() % l != 0)) places = [(num &gt;&gt; l * i) % base for i in powers] else: if num == 0: return ('0', base) places = [] while num: n, p = divmod(num, base) places.append(p) num = n if base &gt; 36: return (sep.join(map(str, reversed(places))), base) return (''.join([glyphs[p] for p in reversed(places)]), base) def from_base(s, base): if base &lt; 2 or not isinstance(base, int): return sep = ',' if base == 60: sep = ':' elif base == 256: sep = '.' if base &lt;= 36: for i in s: if glyphs.index(i) &gt;= base: return else: for i in s.split(sep): if int(i) &gt;= base: return places = parser(s, base) if power_of_2(base): l = log2(base) return sum([int(n) &lt;&lt; l * p for p, n in enumerate(reversed(places))]) powers = reversed([base ** i for i in range(len(places))]) return sum(int(a) * b for a, b in zip(places, powers)) def b36encode(s): msg = s.encode('utf8').hex() n = int(msg, 16) return to_base(n, 36)[0] def b36decode(m): n = from_base(m, 36) h = hex(n).lstrip('0x') return bytes.fromhex(h).decode('utf8') def b36_encode(s): msg = [ord(i) for i in s] return ''.join([to_base(n, 36)[0].zfill(2) for n in msg]) def b36_decode(m): s = [from_base(n, 36) for n in [m[i:i+2] for i in range(0, len(m), 2)]] return ''.join(chr(n) for n in s) def base36_encode(s): msg = s.encode('utf8') return ''.join([to_base(n, 36)[0] for n in msg]) def base36_decode(m): s = [from_base(n, 36) for n in [m[i:i+2] for i in range(0, len(m), 2)]] return bytearray(s).decode('utf8') </code></pre> <p>Sample usage:</p> <pre><code>In [282]: to_base(16777215, 3) Out[282]: ('1011120101000100', 3) In [283]: from_base(*to_base(16777215, 3)) Out[283]: 16777215 In [284]: to_base(2**32-1, 3) Out[284]: ('102002022201221111210', 3) In [285]: from_base(*to_base(2**32-1, 3)) Out[285]: 4294967295 In [286]: from_base(*to_base(2**64-1, 36)) Out[286]: 18446744073709551615 In [287]: to_base(2**64-1, 36) Out[287]: ('3w5e11264sgsf', 36) In [288]: to_base(46610, 16) Out[288]: ('b612', 16) In [289]: to_base(54, 13) Out[289]: ('42', 13) In [290]: from_base('zzz', 36) Out[290]: 46655 In [291]: from_base('computer', 36) Out[291]: 993986429283 In [292]: to_base(from_base('computer', 36),36) Out[292]: ('computer', 36) In [293]: '\u1800' Out[293]: '᠀' In [294]: b36encode('whoami') Out[294]: '1ajdznl1ex' In [295]: b36decode(b36encode('whoami')) Out[295]: 'whoami' In [296]: b36decode(b36encode('\u1800\u1800\u1800')) Out[296]: '᠀᠀᠀' In [297]: base36_decode(base36_encode('\u1800\u1800\u1800')) Out[297]: '᠀᠀᠀' </code></pre> <p>What improvement can be made to my code?</p> <hr /> <p>Update:</p> <p>I have improved representation scheme to make it able to represent numbers in any base.</p> <p>For bases bigger than 36, the resultant string is a mixed radix representation, with the digits represented in their decimal form instead of having a single character representing its value, and a separator delimit the digits.</p> <p>The separator is determined by the base, for base 60 the separator is a colon (<code>:</code>), similar to how time is represented, for base 256 the separator is a dot (<code>.</code>), similar to how IPv4 addresses are represented, and a comma (<code>,</code>) for any other base.</p> <p>I have considered using the Greek alphabet after Latin alphabet (after Arabic numerals) to make single character notation representation form able to represent numbers in base-60, however many Greek letters and Latin letters are homoglyphs I abandoned the idea to avoid ambiguity.</p> <p>Examples:</p> <pre><code>In [52]: to_base(16777216,64) Out[52]: ('1,0,0,0,0', 64) In [53]: to_base(16777215,64) Out[53]: ('63,63,63,63', 64) In [54]: to_base(33554431,64) Out[54]: ('1,63,63,63,63', 64) In [55]: to_base(86399,60) Out[55]: ('23:59:59', 60) In [56]: to_base(86399,365) Out[56]: ('236,259', 365) In [57]: to_base(2**32-1,256) Out[57]: ('255.255.255.255', 256) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T00:17:02.740", "Id": "528114", "Score": "0", "body": "You realize that `from_base` can be entirely replaced with a call to `int()`, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T04:38:07.440", "Id": "528125", "Score": "1", "body": "@Reinderien Of course I do realize `from_base` can be entirely replaced with a call to `int`, I even make it accept the same types of positional arguments in the same order, while using `int` is far more performant than `from_base`, using `int` doesn't demonstrate that I know how to do the conversion." } ]
[ { "body": "<p>If your goal is to have good code, most of this shouldn't exist and you should make better use of built-ins, but it seems like that isn't your goal.</p>\n<p>If your goal is to demonstrate that you know how to write functions equivalent to the built-ins, you haven't quite hit your mark, because the built-ins are able to deal with negative numbers and your functions are not.</p>\n<p>As for a review laundry-list:</p>\n<ul>\n<li>You need PEP484 type hints</li>\n<li><code>glyphs</code> should be capitalized since it's a global constant</li>\n<li>You have a bunch of verbatim-repeated code, such as your selection of separators, for which you should factor out functions</li>\n<li><code>parser</code> looks up a separator even when it doesn't need one. Only look up the separator if base is greater than 36.</li>\n<li>Do not <code>return</code> on failure; <code>raise</code> instead.</li>\n<li>There is no value in returning the base as a second tuple element from <code>to_base</code>; the caller knows what base it's going to be.</li>\n<li><code>lstrip('0x')</code> does not do what you think it does. Hint: what is <code>'xxx000xxx'.lstrip('0x')</code> ? Use <code>removeprefix</code> instead.</li>\n<li>More repeated code in the comprehensions for your <code>b36_decode</code> and <code>base36_decode</code> functions that need to be factored out.</li>\n<li>Convert your sample usage into unit tests.</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from string import ascii_lowercase\nfrom string import digits\nfrom typing import List, Iterable\n\nGLYPHS = digits + ascii_lowercase\n\n\ndef log2(n: int) -&gt; int:\n return n.bit_length() - 1\n\n\ndef power_of_2(n: int) -&gt; bool:\n return (n &amp; (n-1) == 0) and n != 0\n\n\ndef sep_for_base(base: int) -&gt; str:\n return {\n 60: ':',\n 256: '.',\n }.get(base, ',')\n\n\ndef parser(s: str, base: int) -&gt; List[int]:\n if 2 &lt;= base &lt;= 36:\n return [GLYPHS.index(i) for i in s]\n\n return s.split(sep_for_base(base))\n\n\ndef to_base(num: int, base: int) -&gt; str:\n if base &lt; 2 or not isinstance(base, int):\n raise ValueError()\n\n if power_of_2(base):\n l = log2(base)\n powers = range(num.bit_length() // l + (num.bit_length() % l != 0))\n places = [(num &gt;&gt; l * i) % base for i in powers]\n\n else:\n if num == 0:\n return '0'\n\n places = []\n while num:\n n, p = divmod(num, base)\n places.append(p)\n num = n\n\n if base &gt; 36:\n sep = sep_for_base(base)\n return sep.join(map(str, reversed(places)))\n\n return ''.join([GLYPHS[p] for p in reversed(places)])\n\n\ndef from_base(s: str, base: int) -&gt; int:\n if base &lt; 2 or not isinstance(base, int):\n raise ValueError()\n\n if base &lt;= 36:\n for i in s:\n if GLYPHS.index(i) &gt;= base:\n raise ValueError()\n\n else:\n sep = sep_for_base(base)\n for i in s.split(sep):\n if int(i) &gt;= base:\n raise ValueError()\n\n places = parser(s, base)\n\n if power_of_2(base):\n l = log2(base)\n return sum([int(n) &lt;&lt; l * p for p, n in enumerate(reversed(places))])\n\n powers = reversed([base ** i for i in range(len(places))])\n return sum(int(a) * b for a, b in zip(places, powers))\n\n\ndef b36encode(s: str) -&gt; str:\n msg = s.encode('utf8').hex()\n n = int(msg, 16)\n return to_base(n, 36)\n\n\ndef b36decode(m: str) -&gt; str:\n n = from_base(m, 36)\n h = hex(n).removeprefix('0x')\n return bytes.fromhex(h).decode('utf8')\n\n\ndef b36_encode(s: str) -&gt; str:\n msg = [ord(i) for i in s]\n return ''.join([to_base(n, 36).zfill(2) for n in msg])\n\n\ndef b36_digits(m: str) -&gt; Iterable[int]:\n for i in range(0, len(m), 2):\n n = m[i:i+2]\n yield from_base(n, 36)\n\n\ndef b36_decode(m) -&gt; str:\n s = b36_digits(m)\n return ''.join(chr(n) for n in s)\n\n\ndef base36_encode(s: str) -&gt; str:\n msg = s.encode('utf8')\n return ''.join([to_base(n, 36) for n in msg])\n\n\ndef base36_decode(m: str) -&gt; str:\n s = b36_digits(m)\n return bytearray(s).decode('utf8')\n\n\ndef assert_from_base(s: str, base: int, exp: int) -&gt; None:\n assert int(s, base) == exp\n assert from_base(s, base) == exp\n\n\ndef round_trip(x: int, base: int, s: str) -&gt; None:\n s_actual = to_base(x, base)\n assert s == s_actual\n assert_from_base(s, base, x)\n\n\ndef test() -&gt; None:\n round_trip(2**24-1, 3, '1011120101000100')\n round_trip(2**32-1, 3, '102002022201221111210')\n round_trip(2**64-1, 36, '3w5e11264sgsf')\n\n assert to_base(46610, 16) == 'b612'\n\n assert to_base(54, 13) == '42'\n\n assert_from_base('zzz', 36, 46655)\n\n round_trip(993986429283, 36, 'computer')\n\n assert b36encode('whoami') == '1ajdznl1ex'\n assert b36decode('1ajdznl1ex') == 'whoami'\n\n assert '᠀᠀᠀' == '\\u1800\\u1800\\u1800'\n assert b36encode('᠀᠀᠀') == 'oedjywcl6i78g0'\n assert b36decode('oedjywcl6i78g0') == '᠀᠀᠀'\n assert base36_encode('᠀᠀᠀') == '694g3k694g3k694g3k'\n assert base36_decode('694g3k694g3k694g3k') == '᠀᠀᠀'\n\n\nif __name__ == '__main__':\n test()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T20:00:06.220", "Id": "267872", "ParentId": "267787", "Score": "2" } } ]
{ "AcceptedAnswerId": "267872", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:26:52.157", "Id": "267787", "Score": "1", "Tags": [ "python", "python-3.x", "reinventing-the-wheel", "converting" ], "Title": "Python 3 arbitrary base converter and base36 encoder" }
267787
<p>There is a string &quot;abcdebfkj&quot;, we need to transform this string to the below array:</p> <p>expected o/p:  </p> <pre><code>[&quot;a&quot;, &quot;a.b&quot;, &quot;a.b.c&quot;, &quot;a.b.c.d&quot;, &quot;a.b.c.d.e&quot;, &quot;a.b.c.d.e.b&quot;, &quot;a.b.c.d.e.b.f&quot;, &quot;a.b.c.d.e.b.f.k&quot;, &quot;a.b.c.d.e.b.f.k.j&quot;] </code></pre> <p>I am able to do that, but was looking for more promising solution if any. I did that in O(n) time complexity. Please let me know if the below can be improved in any way.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>function splitString(str) { const result = []; for (let i = 0; i &lt; str.length; i++) { i === 0 ? result.push(str[i]) : result.push(`${result[i-1]}.${str[i]}`); } return result; } console.log(splitString("abcdebfkj"))</code></pre> </div> </div> </p> <p>How can I avoid checking the index and make the <code>for</code> loop work?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T17:52:46.353", "Id": "528078", "Score": "0", "body": "Can't be \\$O(n)\\$. The result itself is \\$O(n^2)\\$, and you cannot build it faster." } ]
[ { "body": "<p>I am not into JavaScript anymore, but:</p>\n<pre><code>function splitString(str) {\n const result = [];\n var o = &quot;&quot;;\n for (let ch of str) {\n result.push(o + ch);\n o += ch + '.';\n }\n return result;\n}\n\nfunction splitString(str) {\n const result = [];\n var o = &quot;&quot;;\n Array.fromString(str).forEach(ch =&gt; {\n result.push(o + ch);\n o += ch + '.';\n });\n return result;\n}\n\nfunction splitString(str) {\n const result = [];\n var o = &quot;&quot;;\n for (let ch of str) {\n result.push(o + ch);\n o = ch + '.';\n }\n return result;\n}\n</code></pre>\n<p>Another variable remains, but the backtick evaluation becomes senceless.</p>\n<p>Your requirement is fulfilled by:</p>\n<pre><code>function splitString(str) {\n let result = str.split(''); // Array with letters\n //let result = Array.fromString(str); // Array with letters\n for (let i = 1; i &lt; str.length; ++i) {\n result[i] = result[i-1] + '.' + result[i];\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T12:23:33.903", "Id": "528056", "Score": "0", "body": "If you run this code it doesn't return the expected results, but the last one works well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T21:15:00.613", "Id": "528101", "Score": "1", "body": "You are right, corrected, though I intended to let `o` contain the pushed value." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T12:17:36.707", "Id": "267789", "ParentId": "267788", "Score": "2" } }, { "body": "<blockquote>\n<p>I am able to do that, but was looking for more promising solution if any. I did that in O(n) time complexity.</p>\n</blockquote>\n<p>It's not quite clear what you mean by &quot;more promising&quot;. But it should be obvious that it can't be done in better than O(str.length<sup>2</sup>) steps and space.</p>\n<blockquote>\n<p>How can I avoid checking the index and make the <code>for</code> loop work?</p>\n</blockquote>\n<p>The best way to avoid checking the index and make the <code>for</code> loop work is to not use the index and not use a <code>for</code> loop. There are plenty of very powerful iteration methods on <a href=\"https://tc39.es/ecma262/#sec-properties-of-the-array-prototype-object\" rel=\"nofollow noreferrer\"><code>Array.prototype</code></a> like <a href=\"https://tc39.es/ecma262/#sec-array.prototype.map\" rel=\"nofollow noreferrer\"><code>Array.prototype.map</code></a> or <a href=\"https://tc39.es/ecma262/#sec-array.prototype.join\" rel=\"nofollow noreferrer\"><code>Array.prototype.join</code></a>, and most importantly <a href=\"https://tc39.es/ecma262/#sec-array.prototype.reduce\" rel=\"nofollow noreferrer\"><code>Array.prototype.reduce</code></a>. In fact, there is a nifty little sketch of a proof on the Wikipedia page for <a href=\"https://wikipedia.org/wiki/Fold_(higher-order_function)#Universality\" rel=\"nofollow noreferrer\"><em>Fold</em></a> (which is the computer science name for <code>reduce</code>), which shows that <code>reduce</code> can do everything a loop can do. There's also <a href=\"https://tc39.es/ecma262/#sec-array.from\" rel=\"nofollow noreferrer\"><code>Array.from</code></a>, which is really powerful.</p>\n<p>Now that I have praised all of the powerful methods, I have a confession to make: the problem you have is actually a <a href=\"https://wikipedia.org/wiki/Prefix_sum\" rel=\"nofollow noreferrer\"><em>Prefix sum</em></a> which can be perfectly solved with the <code>scan</code> function. But … unfortunately, that specific method is missing from <code>Array.prototype</code>.</p>\n<p>If <code>scan</code> <em>did</em> exist, the solution would look something like this [I'll add a simplistic implementation of <code>scan</code> just to make it run]:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>Array.prototype.scan = \n function scan(f, z) {\n return this.reduce(\n (acc, el) =&gt; acc.concat([f(acc[acc.length - 1], el)]),\n [z]\n );\n }\n\nfunction splitString(str) {\n return Array.from(str.substring(1)).\n scan(\n (a, b) =&gt; `${a}.${b}`,\n str.charAt(0)\n );\n}\n\nconsole.log(splitString(\"abcdebfkj\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>[Here you can see it in action in the programming language <a href=\"https://scala-lang.org/\" rel=\"nofollow noreferrer\">Scala</a>, which does have <code>scan</code> in its standard library: <a href=\"https://scastie.scala-lang.org/JoergWMittag/lGpk4P66SZOovCV5o6jt1Q/19%5D\" rel=\"nofollow noreferrer\">https://scastie.scala-lang.org/JoergWMittag/lGpk4P66SZOovCV5o6jt1Q/19]</a></p>\n<p>Unfortunately, without <code>scan</code>, we have to do a bit more work.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function splitString(str) {\n return Array.from(\n { length: str.length },\n (_, i) =&gt;\n Array.from(\n str.substring(0, i + 1)\n ).\n join(\".\")\n );\n}\n\nconsole.log(splitString(\"abcdebfkj\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>The outer <code>Array.from</code> creates an <code>Array</code> of length <code>str.length</code>, and it uses the return value of the arrow function as each element.</p>\n<p>The arrow function gets the current index as its argument, it uses the <a href=\"https://tc39.es/ecma262/#sec-string.prototype.substring\" rel=\"nofollow noreferrer\"><code>String.prototype.substring</code></a> method to grab the first <code>i</code> characters of the string, converts that substring into an array of characters using the above-mentioned very versatile <code>Array.from</code>, and then <code>join</code>s the characters back together with a <code>&quot;.&quot;</code>.</p>\n<p>We can try and more directly re-implement <code>scan</code>:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function splitString(str) {\n return Array.from(str.substring(1)).\n reduce(\n (acc, c) =&gt; acc.concat([`${acc.slice(-1)}.${c}`]),\n [str.charAt(0)]\n );\n}\n\nconsole.log(splitString(\"abcdebfkj\"));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>This is essentially an inlined version of the above solution using <code>scan</code> and the simple definition of <code>scan</code>.</p>\n<p>So, the main trick is to use the methods that ECMAScript provides us, in particular the ones provided on <code>Array</code> and <code>Array.prototype</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:24:49.260", "Id": "528133", "Score": "0", "body": "Don't you think reduce method is designed to make an array to single value? Just clarifying things. Your code works superb and I really understand every piece of it. Also, we are making two array one is from `Array.from` and another one for `acc` which take more memory?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T09:12:59.493", "Id": "528143", "Score": "0", "body": "\"Don't you think reduce method is designed to make an array to single value?\" – Yes, that's what `reduce` does: apply a binary operation between all elements of a collection to reduce the collection to a single value. In my case, the single value just happens to be an array itself. There's nothing in the type signature of `reduce` that forbids that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T18:28:38.440", "Id": "267800", "ParentId": "267788", "Score": "1" } } ]
{ "AcceptedAnswerId": "267800", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T11:33:01.543", "Id": "267788", "Score": "0", "Tags": [ "javascript", "performance" ], "Title": "Build list of prefixes, including the whole string" }
267788
<p>I am attempting to make a simple Portal wrapper that does the following.</p> <ol> <li>Can render multiple portals on the same view</li> <li>Can render multiple portals by targeting parent ids. This cannot be done by passing a ref into the component since the container may live anywhere.</li> <li>Can render multiple portal without any parent targets</li> </ol> <p>This is what I came up with this morning. The code works exactly how I want it to work. It creates portals with or without a parent target and cleans up completely. However React says not to call hooks from conditions, which you can see I have done here by calling useRef within a ternary. I have not seen any warnings or errors but I am also developing this code in a custom setup with Webpack and Typescript. I have not pushed this code to NPM to see what happens when I import the library into a project. My guess is there's going to be issues. Is there a better way to do this?</p> <p>Thanks in advance.</p> <p><em><strong>Calling Component:</strong></em></p> <pre><code>&lt;div&gt; {open1 &amp;&amp; ( &lt;Portal parentId=&quot;panel-1&quot;&gt; &lt;Panel title=&quot;Poopster&quot; onClose={handleClose1}&gt; &lt;div&gt;Panel&lt;/div&gt; &lt;/Panel&gt; &lt;/Portal&gt; )} {open2 &amp;&amp; ( &lt;Portal&gt; &lt;Panel onClose={handleClose2}&gt; &lt;div&gt;Panel&lt;/div&gt; &lt;/Panel&gt; &lt;/Portal&gt; )} &lt;div&gt; </code></pre> <p><em><strong>Portal Component</strong></em></p> <pre><code>import * as React from 'react'; import { createPortal } from 'react-dom'; export interface PortalProps { children: React.ReactElement; parentId?: string; } export const Portal = ({ children, parentId }: PortalProps): React.ReactElement =&gt; { let ref = !parentId ? React.useRef(document.createElement('div')) : React.useRef(document.getElementById(parentId)); React.useEffect((): VoidFunction =&gt; { return (): void =&gt; { if (ref) { document.body.removeChild(ref.current); } ref = null; }; }, []); React.useEffect(() =&gt; { if (!parentId &amp;&amp; ref.current) { document.body.appendChild(ref.current); } }, [ref, parentId]); return createPortal(children, ref.current); }; export default Portal; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:24:21.580", "Id": "528132", "Score": "0", "body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to **simply state the task accomplished by the code**. Please see [**How do I ask a good question?**](https://CodeReview.StackExchange.com/help/how-to-ask)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T13:55:56.677", "Id": "528199", "Score": "1", "body": "@Aaron If you dislike any of the rules on our site then you can post on [Meta](https://codereview.meta.stackexchange.com/) saying why we should change them. However I recommend you don't voice false or accusatory statements if you decide to." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T14:03:58.690", "Id": "267792", "Score": "0", "Tags": [ "javascript", "react.js", "typescript" ], "Title": "How can I call React useRef conditionally in a Portal wrapper?" }
267792
<p>How should I structure this code to create a maze, solve it with breath-first-search (BFS) and to provide basic navigation movements by 1 step within maze with number of moves required to navigate? Use move along the path, Up, Left, Right, Down.</p> <p>Below is some code that I mangled together on how to think / approach and figure how to structure python for this BFS algorithm code.</p> <p>Is anyone open to mentoring on this BFS algorithm navigation maze python structure or provide another more suitable approach to BFS algorithm maze navigation?</p> <pre><code>import sys def parse_map(filename): with open(filename, &quot;r&quot;) as f: return [[char for char in line] for line in f.read().rstrip(&quot;\n&quot;).split(&quot;\n&quot;)][3:] def count_x(house_map): return sum([ row.count('p') for row in house_map ] ) def printable_house_map(house_map): return &quot;\n&quot;.join([&quot;&quot;.join(row) for row in house_map]) def add_x(house_map, row, col): return house_map[0:row] + [house_map[row][0:col] + ['p',] + house_map[row][col+1:]] + house_map[row+1:] def successors(house_map): return [ add_x(house_map, r, c) for r in range(0, len(house_map)) for c in range(0,len(house_map[0])) if house_map[r][c] == '.' ] def is_goal(house_map, k): return count_x(house_map) == k def bfs_graph_search(house_map): fringe = [initial_house_map] if house_map.goal_test(node.state): return fringe fringe = deque([house_map]) visited = set() while fringe: fringe = fringe.popleft() visited.add(node.state) for child in node.expand(problem): if child.state not in fringe and child not in visited: if house_map.goal_test(child.state): return child fringe.append(child) return None def solve(initial_house_map,k): fringe = [initial_house_map] while len(fringe) &gt; 0: for new_house_map in successors( fringe.pop() ): if is_goal(new_house_map,k): return(new_house_map,True) fringe.append(new_house_map) if __name__ == &quot;__main__&quot;: house_map=parse_map('map1.txt') k = 2 print (&quot;Initial ]house map:\n&quot; + printable_house_map(house_map) + &quot;\n\nSearching for solution...\n&quot;) solution = solve(house_map,k) print (&quot;Found:&quot;) print (printable_house_map(solution[0]) if solution[1] else &quot;False&quot;) class Agent: def __init__(self, initial, goal=None): self.initial = initial self.goal = goal def actions(self, state): raise NotImplementedError def result(self, state, action): raise NotImplementedError def goal_test(self, state): if isinstance(self.goal, list): return is_in(state, self.goal) else: return state == self.goal def path_cost(self, c, state1, action, state2): return c + 1 def value(self, state): raise NotImplementedError class FringeGraph: def __init__(self, state, parent=None, action=None, path_cost=0): self.state = state self.parent = parent self.action = action self.path_cost = path_cost self.depth = 0 if parent: self.depth = parent.depth + 1 def path(self): node, path_back = self, [] while node: path_back.append(node) node = node.parent return list(reversed(path_back)) def solution(self): return [node.action for node in self.path()[1:]] def expand(self, agent): return [self.child_node(agent, action) for action in agent.actions(self.state)] def child_node(self, agent, action): next_state = agent.result(self.state, action) next_node = Node(next_state, self, action, problem.path_cost(self.path_cost, self.state, action, next_state)) return next_node </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T16:48:27.247", "Id": "528073", "Score": "0", "body": "Class Agent is showed twice (did you mean to subclass" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T19:42:30.797", "Id": "528091", "Score": "0", "body": "sorry bad copy / paste, yes just one Agent() class" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T21:29:35.447", "Id": "528256", "Score": "1", "body": "Does this code work? I'm seeing what should be a `NameError` in `bfs_graph_search` with `node`. It's not defined anywhere. I also don't see your classes explicitly used anywhere. Are you importing them or renaming them? It seems like your `Agent` and `FringeGraph` classes probably live in a separate module/file. Also, could you include an example of what `map1.txt` looks like?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T15:06:16.403", "Id": "267794", "Score": "1", "Tags": [ "python", "algorithm", "breadth-first-search" ], "Title": "How to create a maze solve search with BFS provide navigation movements" }
267794
<p>I am going through a course and after learning the theory I decided to implement the DS on my own. I write a few test cases and all operations seem to be working fine but once I tried to double check with the course's solution, it is not clear if I am missing anything since my logic is not line by line the same :(</p> <p>Resizing approach I took:</p> <ul> <li>Doubling once full capacity is reach</li> <li>Halving once number of items in the Queue decrease to 1/4 of capacity</li> </ul> <p>Operations:</p> <pre><code>public E dequeue() public void enqueue(E item) public int size() private boolean isFullCapacity() private boolean isFourthCapacity() private void resize(int newSize) public boolean isEmpty() </code></pre> <p>If anyone can point me to where I can more thoroughly test, I would also appreciate it. I could not find any test suite on the internet. Would also appreciate general good practices feed back :)</p> <pre><code>public class QueueResizingArray &lt;E&gt; implements Queue&lt;E&gt; { private E[] arr; private int size; private int front; private int end; private static final int INITIAL_CAPACITY = 6; private static final int INCREASE_FACTOR = 2; public QueueResizingArray(){ this.arr = (E[]) new Object[INITIAL_CAPACITY]; } @Override public void enqueue(E item) { if(item == null) throw new IllegalArgumentException(&quot;item entered cannot be null&quot;); this.arr[front] = item; this.front = getNextPointerInCircularArray(this.front); this.size ++; if(isFullCapacity()) resize(INCREASE_FACTOR * this.arr.length); } @Override public E dequeue() { if(this.isEmpty()) throw new NoSuchElementException(&quot;Queue is empty when trying to dequeue&quot;); E item = this.arr[end]; this.arr[end] = null; this.end = getNextPointerInCircularArray(this.end); this.size--; /* first condition added otherwise following will happen. , lets take as an example an array of length, arr.length = 3, and there is one item in array, size = 1, and we decide to dequeue this single item. size = 1 will decrement to 0 in the dequeue() method and the reach isFourthCapacity(). at this point, the following check occurs. if ( size == arr.length/4) in this case since size = 1 and arr.length = 4, the check evaluates to if ( 0 == 0), triggering a resize even with no items present. if (0 == 0) incorrectly triggering shrinking even with no items present 0 (size)/3 (array.length) = 0 ( */ if(this.size &gt; 0 &amp;&amp; isFourthCapacity()) resize(this.arr.length/2); return item; } @Override public boolean isEmpty() { return this.size == 0; } @Override public int size() { return this.size; } private boolean isFullCapacity(){ return this.size == this.arr.length; } private boolean isFourthCapacity(){ return this.size == this.arr.length/4; } private void resize(int newArrLength){ E[] newArr = (E[]) new Object[newArrLength]; int insertIndex = 0; int tempEnd = this.end; do{ newArr[insertIndex] = this.arr[tempEnd]; tempEnd = getNextPointerInCircularArray(tempEnd); insertIndex++; }while(this.front != tempEnd); //the reason why i move end is because if halving, end will lag front and we can increment end to touch all items we need to copy. I think we could also decrement front //TODO we need a do while to move end one away from front, below does not work because when full, end will equal front not triggering copying of elements // while(this.front != tempEnd){ // newArr[insertIndex] = this.arr[tempEnd]; // tempEnd = getNextPointerInCircularArray(tempEnd); // insertIndex++; // } //resetting indexes after resizing this.front = this.size; this.end = 0; //setting new array this.arr = newArr; } private int getNextPointerInCircularArray(int reference){ return (reference + 1) % this.arr.length; } } </code></pre> <p>Tests:</p> <pre><code>public class Test { @org.junit.Test public void testMyCircularResizingArraySolution(){ Queue&lt;Integer&gt; queue = new QueueResizingArray&lt;&gt;(); //enqueue queue.enqueue(1); //assert Assert.assertEquals(1, queue.size()); //dequeue int item1 = queue.dequeue(); Assert.assertEquals(1, item1); Assert.assertEquals(0, queue.size()); //6 enqueues queue.enqueue(1); queue.enqueue(1); queue.enqueue(1); queue.enqueue(-9); queue.enqueue(2); queue.enqueue(7); //last enqueue should have triggered doubling of circular array int item2 = queue.dequeue(); Assert.assertEquals(1, item2); Assert.assertEquals(5, queue.size()); int item3 = queue.dequeue(); Assert.assertEquals(1, item3); Assert.assertEquals(4, queue.size()); //will trigger halving int item4 = queue.dequeue(); Assert.assertEquals(1, item4); Assert.assertEquals(3, queue.size()); int item5 = queue.dequeue(); Assert.assertEquals(-9, item5); Assert.assertEquals(2, queue.size()); int item6 = queue.dequeue(); Assert.assertEquals(2, item6); Assert.assertEquals(1, queue.size()); int item7 = queue.dequeue(); Assert.assertEquals(7, item7); Assert.assertEquals(0, queue.size()); } } </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T17:22:16.197", "Id": "267796", "Score": "0", "Tags": [ "java", "algorithm", "queue", "circular-list" ], "Title": "Circular Resizing Array in Queue Impl" }
267796
<p>I would love some criticism on the design and get feedback on how easy the python library <a href="https://github.com/AxelGard/cira" rel="nofollow noreferrer">cira</a> is to use.</p> <p>Cira is a Façade library for simpler interaction with alpaca-trade-API from <a href="https://alpaca.markets/" rel="nofollow noreferrer">Alpaca Markets</a>.</p> <p>Cira is available on pip. <code>pip install cira</code></p> <p>I have made a <a href="https://github.com/AxelGard/cira/wiki/Tutorial" rel="nofollow noreferrer">tutorial</a></p> <p>but the example that I have used a lot is building a simple index fund in a few lines of python code.</p> <pre class="lang-py prettyprint-override"><code>import cira import random import time cira.alpaca.KEY_FILE = &quot;../mypath/key.json&quot; portfolio = cira.Portfolio() exchange = cira.Exchange() qty = 1 # choose how many stocks should be handled in one session while exchange.is_open: for stock in random.choices(exchange.stocks, k=qty): stock.buy(1) for stock in random.choices(portfolio.owned_stocks, k=qty): stock.sell(1) time.sleep(60*30) # 30 min timer </code></pre> <p>So reading this example do you understand what the code does and could you see how you would expand on this code to make your own trading algorithm.</p> <p><strong>edit</strong> All of the source code was requested but would recommend checking out the repo instead.</p> <pre class="lang-py prettyprint-override"><code>:::::::::::::: setup.py :::::::::::::: from setuptools import setup with open(&quot;README.md&quot;, &quot;r&quot;) as fh: long_description = fh.read() setup( name='cira', version='2.1.1', description='A simpler library for the alapaca trade api', url='https://github.com/AxelGard/cira', author='Axel Gard', author_email='', license='MIT', packages=['cira'], long_description=long_description, long_description_content_type=&quot;text/markdown&quot;, install_requires=['alpaca-trade-api'], extras_requires = { &quot;dev&quot;: [ &quot;pytest&quot; ] }, classifiers=[ &quot;Development Status :: 5 - Production/Stable&quot;, &quot;Topic :: Office/Business :: Financial&quot;, &quot;Programming Language :: Python :: 3.6&quot;, &quot;License :: OSI Approved :: MIT License&quot;, 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', 'Programming Language :: Python :: 3.8', ], ) :::::::::::::: temp.py :::::::::::::: import cira import random import time import operator cira.alpaca.KEY_FILE = &quot;../paper-trader/key.json&quot; portfolio = cira.Portfolio() exchange = cira.Exchange() print(exchange.is_open) for stk in exchange.stocks[:3]: for op in (operator.add, operator.sub, operator.mul, operator.truediv, operator.floordiv): assert op(stk, 2) == op(stk.price, 2), f&quot;test of op {op}&quot; stk = cira.Stock(&quot;TSLA&quot;) print(stk.price) :::::::::::::: cira/alpaca.py :::::::::::::: import json import alpaca_trade_api as tradeapi import os &quot;&quot;&quot; This function let's you interact with the Alpaca trade API &quot;&quot;&quot; KEY_FILE = &quot;&quot; # user key file path APCA_API_KEY_ID = &quot;&quot; APCA_API_SECRET_KEY = &quot;&quot; def authentication_header(): &quot;&quot;&quot; get's key and returns key in json format &quot;&quot;&quot; with open(KEY_FILE, &quot;r&quot;) as file: header = json.load(file) return header def api(): &quot;&quot;&quot; returns object for api &quot;&quot;&quot; global KEY_FILE global APCA_API_KEY_ID global APCA_API_SECRET_KEY if &quot;APCA_ID&quot; in os.environ: APCA_ID = os.environ[&quot;APCA_ID&quot;] APCA_KEY = os.environ[&quot;APCA_KEY&quot;] elif KEY_FILE: auth_header = authentication_header() APCA_ID = str(auth_header[&quot;APCA-API-KEY-ID&quot;]) APCA_KEY = str(auth_header[&quot;APCA-API-SECRET-KEY&quot;]) else: APCA_ID = APCA_API_KEY_ID APCA_KEY = APCA_API_SECRET_KEY # Open the API connection api = tradeapi.REST(APCA_ID, APCA_KEY, &quot;https://paper-api.alpaca.markets&quot;) # Get account info api.get_account() return api :::::::::::::: cira/config.py :::::::::::::: &quot;&quot;&quot; This files keeps the varibale that is used for configuration cross cira. &quot;&quot;&quot; # logging IS_LOGGING = False LOG_FILE = &quot;&quot; # debugging DEBUG = False :::::::::::::: cira/exchange.py :::::::::::::: from . import alpaca from . import stock class Exchange: &quot;&quot;&quot; This is the class instence of the Exchange. This class is used for interaction with the exchanges, for exampel NYSE. The exchange returns data and list of Stocks. &quot;&quot;&quot; def __init__(self): self.name = &quot;&quot; self.exchanges = [ &quot;NASDAQ&quot;, &quot;NYSE&quot;, &quot;ARCA&quot;, &quot;BATS&quot;, ] # list of stock exchanges that is supported by alpaca self._is_open = False self._assets = [] self._symbols = [] # [&quot;sym&quot;, ... ] self._stocks = [] # [Stock(sym), ... ] obj self._historical_data = {} @property def is_open(self): &quot;&quot;&quot; returns if exchange is open &quot;&quot;&quot; self._is_open = alpaca.api().get_clock().is_open return self._is_open def assets_raw(self): &quot;&quot;&quot; returns a list of all avilabel stocks in exchanges list &quot;&quot;&quot; all_assets = [] active_assets = alpaca.api().list_assets(status=&quot;active&quot;) for exchange in self.exchanges: all_assets += [a for a in active_assets if a.exchange == exchange] self._assets = all_assets return self._assets @property def symbols(self): &quot;&quot;&quot; returns a list of all symbols &quot;&quot;&quot; self._symbols = [] for asset in self.assets_raw(): self._symbols.append(asset.__dict__[&quot;_raw&quot;][&quot;symbol&quot;]) return self._symbols @property def stocks(self): &quot;&quot;&quot; returns a list of objects Stocks &quot;&quot;&quot; self._stocks = [] for sym in self.symbols: self._stocks.append(stock.Stock(sym)) return self._stocks @property def historical_data(self): &quot;&quot;&quot; gathers all historical data on all stocks, {&quot;sym&quot;:[data]} &quot;&quot;&quot; self._historical_data = {} for stk in self.stocks: self._historical_data[stk.symbol] = stk.historical_data() return self._historical_data:::::::::::::: cira/__init__.py :::::::::::::: &quot;&quot;&quot; Cira A simpler libray for alpaca-trade-api from Alpaca Markets. &quot;&quot;&quot; import alpaca_trade_api as tradeapi from . import alpaca from . import config from . import util from . import logging from .exchange import Exchange from .stock import Stock from .portfolio import Portfolio __version__ = &quot;2.1.1&quot; __author__ = &quot;Axel Gard&quot; __credits__ = &quot;alpaca.markets&quot; :::::::::::::: cira/logging.py :::::::::::::: import csv from . import config import time &quot;&quot;&quot; This functions is logging trades &quot;&quot;&quot; def format_log_action(act:str, sym:str, qty:int): &quot;&quot;&quot; formats info for logging &quot;&quot;&quot; time_ = time.strftime(&quot;%Y-%m-%d %H:%M&quot;, time.gmtime()) log_data = [act, sym, qty, time_] return log_data def log(log_data): &quot;&quot;&quot; writes log data to file &quot;&quot;&quot; with open(config.LOG_FILE, &quot;a&quot;) as file: # fd.write(log_data) writer = csv.writer(file) writer.writerow(log_data) return None :::::::::::::: cira/portfolio.py :::::::::::::: from . import alpaca from . import util from . import stock class Portfolio: &quot;&quot;&quot; The class Portfolio, is for interacting with your own protfolio. &quot;&quot;&quot; def __init__(self): self.equity = 0 self._list_orders = [] self._owned_stocks = [] self._position = [] @property def orders(self): &quot;&quot;&quot; returns a list of all open orders with all diffult args &quot;&quot;&quot; self._list_orders = alpaca.api().list_orders() return self._list_orders @property def position(self): # PREV: get_position &quot;&quot;&quot; create a list of all owned position &quot;&quot;&quot; portfolio = alpaca.api().list_positions() self._position = [] for position in portfolio: position_dict = util.reformat_position(position) position_dict[&quot;symbol&quot;] = position.symbol self._position.append(position_dict) return self._position def owned_stock_qty(self, stock): # maby shuld be in stock.Stock &quot;&quot;&quot; returns quantity of owned of a stock Stock (obj) &quot;&quot;&quot; position = util.reformat_position(stock.position) return position[&quot;qty&quot;] @property def owned_stocks(self): &quot;&quot;&quot; returns a list of owned stocks &quot;&quot;&quot; lst = self.position self._owned_stocks = [] for dict_ in lst: self._owned_stocks.append(stock.Stock(dict_[&quot;symbol&quot;])) return self._owned_stocks def sell_list(self, lst): &quot;&quot;&quot; takes a list of Stocks and sells all stocks in that list &quot;&quot;&quot; for stock_ in lst: qty = self.owned_stock_qty(stock_) # if not stock.symbol == 'GOOGL': # # BUG: fix, google has problem selling! stock_.sell(qty) def __repr__(self): return f&quot;portfolio({self.equity})&quot; def __str__(self): return f&quot;{self.position}&quot; :::::::::::::: cira/stock.py :::::::::::::: # import alpaca_trade_api as tradeapi from . import config from . import alpaca from . import logging from . import util class Stock: &quot;&quot;&quot; This is the class instence of a Stock. This class is for interaction of a Stock &quot;&quot;&quot; def __init__(self, symbol:str): self.symbol = symbol self._price = 0 self._value = 0 self._is_shortable = False self._can_borrow = False self._barset = None self._week_pl_change = 0 self._is_tradable = False self._position = None self._today_plpc = 0 self._plpc = 0 self._is_open = False @property def price(self) -&gt; float: # PREV: current_price &quot;&quot;&quot; returns the current price of given symbol (str) &quot;&quot;&quot; if not self.exchange_is_open: self._price = self.value else: # OBS: due to API change no diffrence btween price and value self._price = self.barset(1)[self.symbol][0].c return self._price @property def value(self) -&gt; float: # prev: value_of_stock &quot;&quot;&quot; takes a string sym. Gets and returns the stock value at close &quot;&quot;&quot; nr_days = 1 bars = self.barset(nr_days) if bars is None: self._value = 0.0 else: self._value = bars[self.symbol][0].c # get stock at close return self._value def buy(self, qty: int): &quot;&quot;&quot; buys a stock. Takes int qty and a string sym &quot;&quot;&quot; order_ = self.order(qty, &quot;buy&quot;) if config.IS_LOGGING: logging.log(logging.format_log_action(&quot;buy&quot;, self.symbol, qty)) return order_ def sell(self, qty: int): &quot;&quot;&quot; sells a stock. Takes int qty and a string sym&quot;&quot;&quot; order_ = self.order(qty, &quot;sell&quot;) if config.IS_LOGGING: logging.log(logging.format_log_action(&quot;sell&quot;, self.symbol, qty)) return order_ def order(self, qty: int, beh: str) -&gt; float: &quot;&quot;&quot; submit order and is a template for order &quot;&quot;&quot; if not self.is_tradable: raise Exception(f&quot;Sorry, {self.symbol} is currantly not tradable on https://alpaca.markets/&quot;) else: order = alpaca.api().submit_order( symbol=self.symbol, qty=qty, side=beh, type=&quot;market&quot;, time_in_force=&quot;gtc&quot; ) return order @property def is_shortable(self) -&gt; bool: &quot;&quot;&quot; checks if stock can be shorted &quot;&quot;&quot; self._is_shortable = alpaca.api().get_asset(self.symbol).shortable return self._is_shortable @property def can_borrow(self) -&gt; bool: &quot;&quot;&quot;check whether the name is currently available to short at Alpaca&quot;&quot;&quot; self._can_borrow = alpaca.api().get_asset(self.symbol).easy_to_borrow return self._can_borrow def barset(self, limit:int): &quot;&quot;&quot; returns barset for stock for time period lim &quot;&quot;&quot; self._barset = alpaca.api().get_barset(self.symbol, &quot;minute&quot;, limit=int(limit)) return self._barset def historical_data(self, nr_days=1000): &quot;&quot;&quot;returns a list of the stocks closing value, range of 1 to 1000 days&quot;&quot;&quot; lst = [] nr_days = max(1, min(nr_days, 1000)) for bar in self.barset(nr_days)[self.symbol]: lst.append(bar.c) return lst @property def week_pl_change(self): &quot;&quot;&quot; Percentage change over a week &quot;&quot;&quot; nr_days = 5 bars = self.barset(nr_days) week_open = bars[self.symbol][0].o week_close = bars[self.symbol][-1].c self._week_pl_change = (week_close - week_open) / week_open return self._week_pl_change @property def is_tradable(self): &quot;&quot;&quot; return if the stock can be traded &quot;&quot;&quot; self._is_tradable = alpaca.api().get_asset(self.symbol).tradable return self._is_tradable @property def position(self): &quot;&quot;&quot; returns position of stock &quot;&quot;&quot; pos = alpaca.api().get_position(self.symbol) self._position = util.reformat_position(pos) return self._position @property def today_plpc(self): &quot;&quot;&quot; stock today's profit/loss percent &quot;&quot;&quot; self._today_plpc = util.reformat_position(self.position)[ &quot;unrealized_intraday_plpc&quot; ] return self._today_plpc @property def plpc(self): &quot;&quot;&quot; stock sym (str) Unrealized profit/loss percentage &quot;&quot;&quot; self._plpc = util.reformat_position(self.position)[&quot;unrealized_plpc&quot;] return self._plpc @property def exchange_is_open(self) -&gt; bool: &quot;&quot;&quot; returns if exchange is open &quot;&quot;&quot; self._is_open = alpaca.api().get_clock().is_open return self._is_open def __repr__(self): return f&quot;{self.symbol}@(${self.price})&quot; def __str__(self): return f&quot;{self.symbol}&quot; # Operators def __eq__(self, other): if isinstance(other,(int,float)): return self.price == other return self.price == other.price def __ne__(self, other): if isinstance(other,(int,float)): return self.price != other return self.price != other.price def __lt__(self, other): if isinstance(other,(int,float)): return self.price &lt; other return self.price &lt; other.price def __le__(self, other): if isinstance(other,(int,float)): return self.price &lt;= other return self.price &lt;= other.price def __gt__(self, other): if isinstance(other,(int,float)): return self.price &gt; other return self.price &gt; other.price def __ge__(self, other): if isinstance(other,(int,float)): return self.price &gt;= other return self.price &gt;= other.price # Arithmetic Operators def __add__(self, other): if isinstance(other,(int,float)): return self.price + other return self.price + other.price def __radd__(self, other): return self.price + other def __sub__(self, other): if isinstance(other,(int,float)): return self.price - other return self.price - other.price def __rsub__(self, other): return self.price - other def __mul__(self, other): if isinstance(other,(int,float)): return self.price * other return self.price * other.price def __rmul__(self, other): return self.price * other def __truediv__(self, other): if isinstance(other,(int,float)): return self.price / other return self.price / other.price def __rdiv__(self, other): return self.price / other def __floordiv__(self, other): if isinstance(other,(int,float)): return self.price // other return self.price // other.price def __rfloordiv__(self, other): return self.price // other # Type Conversion def __abs__(self): # dose not rely makes sense should not be able to # be neg but might be good to have return abs(self.price) def __int__(self): return int(self.price) def __float__(self): return float(self.price) def __round__(self, nDigits): return round(self.price, nDigits) :::::::::::::: cira/util.py :::::::::::::: def reformat_position(position): &quot;&quot;&quot; reformat position to be float values &quot;&quot;&quot; raw_position = vars(position)[&quot;_raw&quot;] position_dict = {} for key in raw_position.keys(): try: position_dict[key] = float(raw_position[key]) except ValueError: continue return position_dict :::::::::::::: tests/__init__.py :::::::::::::: :::::::::::::: tests/test_cira.py :::::::::::::: &quot;&quot;&quot; Tests for cira pkg. for dev &quot;&quot;&quot; import pytest import cira import os import operator if 'APCA_ID' in os.environ and 'APCA_KEY' in os.environ: # github action cira.alpaca.APCA_API_KEY_ID = os.environ['APCA_ID'] cira.alpaca.APCA_API_SECRET_KEY = os.environ['APCA_KEY'] cira.alpaca.KEY_FILE = &quot;&quot; else: cira.alpaca.KEY_FILE = &quot;../paper-trader/key.json&quot; def test_setup(): &quot;&quot;&quot; Ensure that position is predictable for testing &quot;&quot;&quot; portfolio = cira.Portfolio() exchange = cira.Exchange() if exchange.is_open: pass # portfolio.sell_list(portfolio.owned_stocks) # clear portfolio #assert portfolio.owned_stocks == [] :::::::::::::: tests/test_setup.py :::::::::::::: :::::::::::::: tests/test_stock.py :::::::::::::: &quot;&quot;&quot; Tests for cira class Stock. &quot;&quot;&quot; import pytest import cira import os import operator def test_stock(): &quot;&quot;&quot; test relatied to the stock class &quot;&quot;&quot; portfolio = cira.Portfolio() exchange = cira.Exchange() stk = cira.Stock(&quot;PYPL&quot;) assert stk.is_shortable == True assert stk.can_borrow == True assert stk.is_tradable == True assert stk + 2 == stk.price + 2 assert stk - 2 == stk.price - 2 assert stk * 2 == stk.price * 2 for op in (operator.add, operator.sub, operator.mul, operator.truediv, operator.floordiv): assert op(stk, 2) == op(stk.price, 2), f&quot;test of op {op}&quot; </code></pre> <p>when a new file starts it is denoted with</p> <pre><code>:::::::::::::: file name :::::::::::::: </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T20:07:31.450", "Id": "528092", "Score": "0", "body": "Okej, thanks! Will edit the post with the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T17:39:58.537", "Id": "528291", "Score": "1", "body": "Just a thought... Perhaps if you had a time-limited or demo key, maybe that would lower the barrier of entry for this question? Having to sign up to a service to obtain a key before running the example might be a bit more than what most people are willing to do (unless they already have a key/keen about finance/trading). Thanks AxelG" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T18:41:38.740", "Id": "528377", "Score": "1", "body": "@C.Harley Yes that would be nice, but that I don't see a simple way of doing that. I am not affiliated with Alpaca.markets in any way those I would need to make some proxy and somehow generate keys by that proxy. But it would be nice. thanks for the suggestion." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T18:55:35.107", "Id": "528378", "Score": "0", "body": "@mdfst13 have added all the code, but it a bash more for all the different fiels" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T18:26:25.590", "Id": "267799", "Score": "1", "Tags": [ "python", "python-3.x" ], "Title": "Building a simple index fund using Cira" }
267799
<p>I just finished my Tic-tac-toe AI, and would be very grateful for opinions and comments on that project. I would like to add it to my 'entry level Python developer portfolio'.</p> <p>README:</p> <p>Simple AI that plays tic-tac-toe with itself. At the beginning it choses moves to play randomly, every possible move has the same probability of being played. Sequences of moves that lead to victory get points, thus there will be a higher chance of choosing those moves in the future games. Accordingly moves that ended in a losing state will be chosen less frequently. After about 200 000 games there will be more than 99% of draws - both players will not make single mistake in more than 99% of games.</p> <p>Main Class:</p> <pre><code>import rules #main game loop. Number of repetition defines how many games are played for i in range (1): #these two lists are used to store moves used in each game moves_X = [] moves_O = [] #creation of an empty board, flags move_X and move_O are used to define whether it is Xs or Os move at the moment board = [{'number': 100000, 'board': [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '], 'value': 100}] move_X = True move_O = False #change flag is the cap that prevents the game to be played for longher than 9 moves change = 0 #this loop goes on until Os or Xs wins or it is a draw while True: if move_X and change &lt;= 4: #to define new board after Xs move we use function called draw() defined in the rules module board = rules.draw(0, change, board) moves_X.append(board) #to visualize the game we use draw_board() function defined in rules module print(rules.draw_board(board)) move_X = False move_O = True #using iswin function from rules() we check if Xs have alredy won if (rules.iswin(board[0]['board'], 'X')): print(rules.draw_board(board)) print('X won!') #if Xs won we add points to all of Xs moves from that game #and take points from Os moves for move in moves_X: move[0]['value'] += 1 for move in moves_O: if move[0]['value'] &gt; 1: move[0]['value'] -= 1 break #next O play its move elif move_O and change&lt;4: board = rules.draw(1, change, board) print(rules.draw_board(board)) moves_O.append(board) move_X = True move_O = False change += 1 if (rules.iswin(board[0]['board'], 'O')): print(rules.draw_board(board)) print('O won!') for move in moves_O: move[0]['value'] += 1 for move in moves_X: if move[0]['value'] &gt; 1: move[0]['value'] -= 1 break #if the board is full and neither of the players won else: print('Draw!') break #after compliton of the main game loop we save the results rules.save() </code></pre> <p>all_data Class:</p> <pre><code>import itertools #used to create list of all combinations of ' ', X and O. Each combination have its number and value #that list will be filtered and sorted in the data_base module def board_init(): move_number = [] for b,i in enumerate(itertools.product(' XO', repeat=9)): if b==100000: break else: move_n_number = {'number': b, 'board': i, 'value': 100} move_number.append(move_n_number) return move_number </code></pre> <p>data_base Class:</p> <pre><code>import all_data import json #board_sort module sorts and filters list created with board_init() in the all_data module def board_sort(move_n): #move_list_X and move_list_O are used to sort moves by sign and number, from first to fifth in Xs and fourth in Os. move_list_X=[[], [], [], [], []] move_list_O=[[], [], [], []] move_list = (move_list_X, move_list_O) for i in move_n: if i.get('board').count('X')==1 and i.get('board').count('O')==0: move_list_X[0].append(i) elif i.get('board').count('X')==1 and i.get('board').count('O')==1: move_list_O[0].append(i) elif i.get('board').count('X')==2 and i.get('board').count('O')==1: move_list_X[1].append(i) elif i.get('board').count('X')==2 and i.get('board').count('O')==2: move_list_O[1].append(i) elif i.get('board').count('X')==3 and i.get('board').count('O')==2: move_list_X[2].append(i) elif i.get('board').count('X')==3 and i.get('board').count('O')==3: move_list_O[2].append(i) elif i.get('board').count('X')==4 and i.get('board').count('O')==3: move_list_X[3].append(i) elif i.get('board').count('X')==4 and i.get('board').count('O')==4: move_list_O[3].append(i) elif i.get('board').count('X')==5 and i.get('board').count('O')==4: move_list_X[4].append(i) else: continue return move_list def save(move_list): with open('all_moves.txt', 'w') as f: json.dump(move_list, f) </code></pre> <p>rules Class:</p> <pre><code>import random import json import all_data import data_base #if there is no file 'all_moves.txt' it is is created try: with open('all_moves.txt') as json_file: move_list = json.load(json_file) except IOError: move_n = all_data.board_init() move_list = data_base.board_sort(move_n) #iswin function is used to check if Xs or Os have alredy won def iswin(board, letter='X'): if board[0]==letter and board[1]==letter and board[2]==letter: return True elif board[3]==letter and board[4]==letter and board[5]==letter: return True elif board[6] == letter and board[7] == letter and board[8] == letter: return True elif board[0] == letter and board[3] == letter and board[6] == letter: return True elif board[1] == letter and board[4] == letter and board[7] == letter: return True elif board[2] == letter and board[5] == letter and board[8] == letter: return True elif board[0] == letter and board[4] == letter and board[8] == letter: return True elif board[6] == letter and board[4] == letter and board[2] == letter: return True else: return False #draw function is used to draw a move from a list of possible moves #the probability of each choice is dependent on previous results def draw(letter, number, board): possible_moves=[] move = move_list[letter][number] for i in move: sum=0 for z, g in zip(i['board'], board[0]['board']): if z==g: continue else: sum += 1 if sum==1: possible_moves.append(i) else: continue return(random.choices(possible_moves, weights=[i['value'] for i in possible_moves], k = 1)) #saves changes made in the 'all_moves.txt' file def save(): with open('all_moves.txt', 'w') as f: json.dump(move_list, f) #function used to visualize present state of the board def draw_board(board): return( ''' {} {} {} '''.format(board[0]['board'][:3], board[0]['board'][3:6], board[0]['board'][6:]) ) </code></pre> <p><a href="https://github.com/jaskrawo/tic-tac-toe" rel="nofollow noreferrer">Github link</a></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T22:12:44.667", "Id": "528110", "Score": "4", "body": "Looking at your GitHub link it doesn't look like you have too much more code in this project, I would consider adding that to your question too so you can get a more rounded review. For example `rules.iswin` makes sense to me but `rules.draw_board` seems like an odd responsibility for a module with that name. At the moment however you haven't provided the code for that module for review. If there are specific aspects you'd like advice on then you can add some questions too if you like, or just let reviewers come up with whatever they can think of." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T23:20:37.997", "Id": "528173", "Score": "4", "body": "@Greedo maybe you already saw but in case not- OP added more code 11 hours ago" } ]
[ { "body": "<p>Thanks Jacek for your post. Let's make a quick summary of the most obvious issues and we'll go over them:</p>\n<ul>\n<li>number of files</li>\n<li>the functions in certain files belong in other files due to their naming</li>\n<li>clear dependencies for functions in other files</li>\n<li>redundant comments</li>\n<li>code formatting (empty lines, not using PEP8, using doc-string for multi-line print, not using f-strings)</li>\n<li>many functions are too long and can be refactored</li>\n<li>use of break and continue (spaghetti code)</li>\n<li>no entry point, the script runs as soon as it's imported</li>\n<li>lots of hard-coding of strings, numbers, structure indexes, etc.</li>\n</ul>\n<h1>Number of files</h1>\n<p>I can understand breaking up the files, but some of them only have one or two functions. If you were writing the operating system for the Space Shuttle, there is a good reason to do so, but the domain problem is playing tic-tac-toe - not enough to warrant splitting them so. This splitting leads into the next issue:</p>\n<h1>Function Dependencies</h1>\n<p>As described above, each file needed to import a few functions from other files, which means each file is dependent on another in the same domain.</p>\n<p>Let me describe the loading, hopefully you see why it's unnecessary:</p>\n<pre><code>run main -&gt; opens rules -&gt; loads random, json, all_data -&gt; \nopens all_data -&gt; loads intertools -&gt; returns to rules -&gt; \nopens data_base -&gt; opens all_data -&gt; loads itertools/cached -&gt; \nreturns to data_base -&gt; loads json/cached -&gt; returns to rules -&gt; \nloads data_base/cached.\n</code></pre>\n<p>In large projects, files are split along modules/activities, losing a file/folder would break specific functionality, but the program &quot;could&quot; still run (i.e. &quot;module not found, cannot access accounting function&quot;). Everything, however, in your tic-tac-toe project is required and needed to run. Doesn't make sense to split them up.</p>\n<p>There is also an obvious case of duplicating the <code>save()</code> function. You have the exact same code in 2 different files. This would be a clear bug if everything was in a single file.</p>\n<h1>Function Naming</h1>\n<p>When other programmers look at your code, they don't know/understand the coded solution, but will, through how you express the intent of variables by their name.</p>\n<p>Part of proper naming of variables is explaining to the reader what your function does. In <code>all_data</code>, the <code>board_init()</code> function name is noun-verb. <code>initialise_playing_board()</code> is verb-noun, longer, and so descriptive that it leaves no other interpretation to what it does.<br>However, looking into the comment at the top of <code>all_data</code>, it doesn't do that at all. It builds 100,000 variants of possible combinations of tic-tac-toe board layouts. So <code>board_init()</code> doesn't initialise a board at all, and <code>all_data</code> isn't data, but derived possibilities of a tic-tac-toe board.</p>\n<p>Does that explain the point? I've had to read your code, line by line, to understand the variables aren't the truth of the action. Which leads into the next section:</p>\n<h1>Redundant Comments</h1>\n<p>The comment at the top of <code>all_data</code> explained what the code does. Then I read the code and saw that the comment matched. So one of these two needs to be deleted, which should it be? Obviously the comment - otherwise the code wouldn't exist anymore.<br><br>Comments are used to explain the &quot;why&quot; of a function. If you had a function that did a very-specific formatting but appears it is never run, you'd go and ask a team member &quot;why does this function exist?&quot; Perhaps they know, perhaps they don't, so you ask another colleague and so on, until you find someone that says &quot;Oh yeah, we had a client that wanted their report formatted that way.&quot; Do we have that client anymore? &quot;No, they closed a few years ago.&quot; There you go, you can delete that code and push your changes to the code repository. <br>Why did I give you that example? Well, <strong>if</strong> there was a function comment <code>&quot;&quot;&quot;For Client X-Y-Z report format&quot;&quot;&quot;</code> (in this example), then you could have searched the customer database to see if that client exists, learning the truth that it's time to delete that function.<br>Delete the code??? Shouldn't you keep it? Well, no, that's what the code repository is for, all the historical code changes are tracked there.<br>Comments lie. Comments cause bugs. Over time, the code changes, so what <em>was</em> the &quot;how&quot; 2 years ago, might not be the &quot;how&quot; <em>today</em>. If you get a new and eager-beaver developer, they might read your comment, see that the code doesn't do that, and rewrite the code so that it matches the comment (I've seen that happen).</p>\n<h1>Code formatting</h1>\n<p>The PEP8 formatting style is mentioned alot when you're coding Python, so many developers expect you to format your code to follow that standard. Many IDEs have automated style formatting (such as PyCharm (Menu item 'Code'-&gt; 'Reformat Code')) which can save your time.<br>\nPEP257 discusses what a Docstring is and where you should use it. Whilst yes, it's possible to use it as a string representation, you should be using a string with &quot;\\n&quot; to denote a line break, and instead of .format(var), using f-strings which have been available since Python 3.6. <br>Please research PEP8, PEP257 and f-strings to help improve your code formatting.<br>\nIf your IDE doesn't help with all of this, you can install pylint (<code>pip install pylint</code>) to help locate issues in your code. Here is pylint in action:</p>\n<pre><code>************* Module all_data\nall_data.py:9:8: C0103: Variable name &quot;b&quot; doesn't conform to snake_case naming style (invalid-name)\nall_data.py:11:8: R1723: Unnecessary &quot;else&quot; after &quot;break&quot; (no-else-break)\n************* Module data_base\ndata_base.py:7:0: C0301: Line too long (119/100) (line-too-long)\ndata_base.py:8:4: C0103: Variable name &quot;move_list_X&quot; doesn't conform to snake_case naming style (invalid-name)\ndata_base.py:9:4: C0103: Variable name &quot;move_list_O&quot; doesn't conform to snake_case naming style (invalid-name)\ndata_base.py:50:9: W1514: Using open without explicitly specifying an encoding (unspecified-encoding)\ndata_base.py:50:39: C0103: Variable name &quot;f&quot; doesn't conform to snake_case naming style (invalid-name)\ndata_base.py:1:0: W0611: Unused import all_data (unused-import)\ndata_base.py:2:0: C0411: standard import &quot;import json&quot; should be placed before &quot;import all_data&quot; (wrong-import-order)\n************* Module main\nmain.py:12:0: C0301: Line too long (121/100) (line-too-long)\nmain.py:13:0: C0301: Line too long (106/100) (line-too-long)\nmain.py:25:0: C0301: Line too long (108/100) (line-too-long)\nmain.py:38:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)\nmain.py:67:0: C0325: Unnecessary parens after 'if' keyword (superfluous-parens)\nmain.py:75:0: W0311: Bad indentation. Found 28 spaces, expected 24 (bad-indentation)\nmain.py:9:8: C0103: Variable name &quot;moves_X&quot; doesn't conform to snake_case naming style (invalid-name)\nmain.py:10:8: C0103: Variable name &quot;moves_O&quot; doesn't conform to snake_case naming style (invalid-name)\nmain.py:14:8: C0103: Variable name &quot;move_X&quot; doesn't conform to snake_case naming style (invalid-name)\nmain.py:15:8: C0103: Variable name &quot;move_O&quot; doesn't conform to snake_case naming style (invalid-name)\nmain.py:34:16: C0103: Variable name &quot;move_X&quot; doesn't conform to snake_case naming style (invalid-name)\nmain.py:35:16: C0103: Variable name &quot;move_O&quot; doesn't conform to snake_case naming style (invalid-name)\nmain.py:6:4: R1702: Too many nested blocks (6/5) (too-many-nested-blocks)\nmain.py:63:16: C0103: Variable name &quot;move_X&quot; doesn't conform to snake_case naming style (invalid-name)\nmain.py:64:16: C0103: Variable name &quot;move_O&quot; doesn't conform to snake_case naming style (invalid-name)\nmain.py:6:4: R1702: Too many nested blocks (6/5) (too-many-nested-blocks)\nmain.py:6:8: W0612: Unused variable 'i' (unused-variable)\nmain.py:4:0: R0912: Too many branches (13/12) (too-many-branches)\n************* Module rules\nrules.py:8:53: C0303: Trailing whitespace (trailing-whitespace)\nrules.py:67:0: C0325: Unnecessary parens after 'return' keyword (superfluous-parens)\nrules.py:11:9: W1514: Using open without explicitly specifying an encoding (unspecified-encoding)\nrules.py:23:4: R1705: Unnecessary &quot;elif&quot; after &quot;return&quot; (no-else-return)\nrules.py:21:0: R0911: Too many return statements (9/6) (too-many-return-statements)\nrules.py:54:8: W0622: Redefining built-in 'sum' (redefined-builtin)\nrules.py:56:12: C0103: Variable name &quot;z&quot; doesn't conform to snake_case naming style (invalid-name)\nrules.py:56:15: C0103: Variable name &quot;g&quot; doesn't conform to snake_case naming style (invalid-name)\nrules.py:58:12: R1724: Unnecessary &quot;else&quot; after &quot;continue&quot; (no-else-continue)\nrules.py:73:9: W1514: Using open without explicitly specifying an encoding (unspecified-encoding)\nrules.py:73:39: C0103: Variable name &quot;f&quot; doesn't conform to snake_case naming style (invalid-name)\n</code></pre>\n<h1>Code Refactoring</h1>\n<p>Pieces of code like:</p>\n<pre><code> for move in moves_X:\n move[0]['value'] += 1\n\n for move in moves_O:\n if move[0]['value'] &gt; 1:\n move[0]['value'] -= 1\n \n</code></pre>\n<p>and</p>\n<pre><code> for move in moves_O:\n move[0]['value'] += 1\n\n for move in moves_X:\n if move[0]['value'] &gt; 1:\n move[0]['value'] -= 1\n \n</code></pre>\n<p>are identical except for the iterator. This could be refactored into:</p>\n<pre><code> def calculate_points(first, second):\n for move in first:\n move[0]['value'] += 1\n\n for move in second:\n if move[0]['value'] &gt; 1:\n move[0]['value'] -= 1\n</code></pre>\n<p>and complete the process by issuing 2 statements in their place:</p>\n<pre><code> calculate_points(moves_X, moves_O)\n calculate_points(moves_O, moves_X) \n</code></pre>\n<h1>Use of break and continue</h1>\n<p>Spaghetti code is the name given to code that doesn't complete the block fully, jumping out into another section of code. Ways to avoid this:</p>\n<ul>\n<li>ensuring you limit the number of iterations a loop performs by having the iterator as a function, or</li>\n<li>having a variable that is set to <code>False</code> inside the block, allowing the loop to exit when it returns to be evaluated before the next loop.</li>\n<li>refactoring the code into a function, and using return to leave the function when a condition is satisfied</li>\n</ul>\n<p>As an example:</p>\n<pre><code>playing = True\nwhile playing:\n ...\n if player.is_dead:\n playing = False\n else:\n ...do regular stuff...\n \n</code></pre>\n<p>or</p>\n<pre><code>while all_players_are_alive():\n ...do regular stuff...\n \ndef all_players_are_alive():\n for player in game_engine.players():\n if player.is_dead:\n return False\n return True\n \n</code></pre>\n<h1>Entry point</h1>\n<p>As we're writing a script for execution, and not as a library, the entry point <code>if __name__ == &quot;__main__&quot;:</code> should be used.<br>For example, if you pushed your script into the code repository, and a code documentor such as Sphinx ran over it, it would freeze because it would start playing the game. This is because the code begins running as soon as Python loads it, when the goal of the documentor was just to analyse the code.<br><br>Here is the process in action:</p>\n<pre><code>ch@ubuntu:~/PycharmProjects/testing/tic-tac-toe-main$ python\nPython 3.8.3 (default, Sep 9 2020, 15:01:52) \n[GCC 7.5.0] on linux\nType &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n&gt;&gt;&gt; import main\n\n[' ', ' ', ' ']\n['X', ' ', ' ']\n[' ', ' ', ' ']\n...etc...\n\n\nch@ubuntu:~/PycharmProjects/testing/tic-tac-toe-main$ nano main.py \n\nimport rules\n\ndef play_game():\n #main game loop. Number of repetition defines how many games are played\n for i in range (1):\n....\n....\n #after compliton of the main game loop we save the results\n rules.save()\n\nif __name__ == &quot;__main__&quot;:\n play_game()\n</code></pre>\n<p>and now, into Python again:</p>\n<pre><code>ch@ubuntu:~/PycharmProjects/testing/tic-tac-toe-main$ python\nPython 3.8.3 (default, Sep 9 2020, 15:01:52) \n[GCC 7.5.0] on linux\nType &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information.\n&gt;&gt;&gt; import main\n&gt;&gt;&gt; \n</code></pre>\n<p>See? it didn't execute automatically. If you want to run it directly, with <code>python main.py</code>, that would begin the execution phase, playing the game.</p>\n<h1>Hard-coding of values/strings/indexes</h1>\n<p>When you hard-code strings, numbers, or the index numbers of lists, if something changes in your code, you need to find all the statements and change them. Take for instance, the example function above, in the section <strong>Code Refactoring</strong>.</p>\n<p>If you had to find all instances of <code>move[0]['value']</code> and change the value of <code>0</code> into <code>1</code>, you'd spend quite some time to do it, and to verify every change was actually made, you'd need to look at every single line of code, or run the game quite a few times and look carefully for mistakes.</p>\n<p>If, however, you replaced all those &quot;magic&quot; numbers and strings with a single variable, only a single change in a single location should be needed, and all the numbers or strings would be changed automatically. <br>If you need more clarification on this principle, look at Wikipedia for &quot;Magic number (programming)&quot;.</p>\n<h1>Final Note</h1>\n<p>This was quite a challenge to review your code, and I hope you spend some time learning about all the items mentioned above. I wanted to also demonstrate code for a tic-tac-toe game - not exactly the same as yours - this is a single player version (no weighting or 100,000 loops). If you read the code carefully, it should also introduce you into some new ways of writing code.<br>The input system is very simple, using co-ordinates to select the cell.</p>\n<p>I hope this review helps you with your code, good luck for any future programming.</p>\n<pre><code>import random\nfrom enum import Enum\nfrom itertools import product\n\n\nclass Tile(Enum):\n Empty = 0\n X = 1\n O = 2\n\n\nclass Board:\n def __init__(self):\n self._board = {f&quot;{x},{y}&quot;: Tile.Empty for x, y in\n product(range(3), range(3))}\n self._game_over = False\n self._winning_combinations = (\n (&quot;0,0&quot;, &quot;0,1&quot;, &quot;0,2&quot;), (&quot;1,0&quot;, &quot;1,1&quot;, &quot;1,2&quot;), (&quot;2,0&quot;, &quot;2,1&quot;, &quot;2,2&quot;),\n (&quot;0,0&quot;, &quot;1,0&quot;, &quot;2,0&quot;), (&quot;0,1&quot;, &quot;1,1&quot;, &quot;2,1&quot;), (&quot;0,2&quot;, &quot;1,2&quot;, &quot;2,2&quot;),\n (&quot;0,0&quot;, &quot;1,1&quot;, &quot;2,2&quot;), (&quot;0,2&quot;, &quot;1,1&quot;, &quot;2,0&quot;))\n self._winner = &quot;&quot;\n\n def pick_cell(self, address, tile, name):\n print(f&quot;{name} has picked cell {address} for {tile.name}&quot;)\n current_tile = self.layout[address]\n if current_tile != Tile.Empty:\n print(f&quot;Cannot change that cell ({address}). Already chosen: &quot;\n &quot;{current_tile.name}&quot;)\n else:\n self.layout[address] = tile\n if self.check_for_winner():\n self._game_over = True\n print(f&quot;Game is over! {self._winner} has won!&quot;)\n\n @property\n def game_over(self):\n return self._game_over\n\n @property\n def layout(self):\n return self._board\n\n def display_board(self):\n print(&quot;*&quot; * 50)\n for counter, (address, status) in enumerate(self.layout.items()):\n char = &quot;?&quot; if status.name == &quot;Empty&quot; else status.name\n print(f&quot;{char:5} &quot;, end=&quot;&quot;)\n if counter in (2, 5):\n print(&quot;&quot;)\n print(&quot;\\n&quot;)\n\n def check_for_winner(self):\n for tile in (Tile.O, Tile.X):\n for group in self._winning_combinations:\n a = self.layout[group[0]] == tile\n b = self.layout[group[1]] == tile\n c = self.layout[group[2]] == tile\n if a == b == c and a:\n self._winner = tile.name\n return True\n\n @staticmethod\n def available_cells():\n return [f&quot;{address}&quot; for address, status in board.layout.items() if\n status == Tile.Empty]\n\n\ndef get_user_selection(params, display_params=&quot;&quot;):\n is_a_valid_choice = False\n if display_params == &quot;&quot;:\n display_params = params\n while not is_a_valid_choice:\n choice = input(f&quot;\\nPlease select a choice ({display_params}): &quot;)\n if choice.isalpha():\n choice = choice.lower()\n if choice.isnumeric():\n choice = int(choice)\n if choice in params:\n return choice\n\n print(f&quot;That's unfortunately not a selection you can make. Please &quot;\n f&quot;select one of these: {display_params}&quot;)\n\n\nif __name__ == &quot;__main__&quot;:\n board = Board()\n print(&quot;Who are you playing? Noughts or Crosses? (o/x)?&quot;)\n choice = get_user_selection([&quot;x&quot;, &quot;o&quot;])\n player = Tile.X\n computer = Tile.O\n if choice == &quot;o&quot;:\n player = Tile.O\n computer = Tile.X\n\n while not board.game_over and len(board.available_cells()):\n board.display_board()\n selection = get_user_selection(board.available_cells())\n board.pick_cell(selection, player, &quot;Player&quot;)\n board.display_board()\n if not board.game_over and len(board.available_cells()):\n selection = random.choice(board.available_cells())\n board.pick_cell(selection, computer, &quot;Computer&quot;)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-16T22:54:12.610", "Id": "268066", "ParentId": "267807", "Score": "2" } } ]
{ "AcceptedAnswerId": "268066", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T20:51:55.203", "Id": "267807", "Score": "3", "Tags": [ "python", "tic-tac-toe" ], "Title": "Python tic-tac-toe AI" }
267807
<p>In the book they recommend to utilize an Array, but I think that it's easier to use an ArrayList instead, is there any problem with that? Is this code well designed?</p> <pre><code>package com.company; import java.util.ArrayList; import java.util.NoSuchElementException; import java.util.Random; public class RandomQueue&lt;Item&gt;{ private ArrayList&lt;Item&gt; a; private int size; Random r; public RandomQueue(){ a = new ArrayList&lt;Item&gt;(); size = 0; } public int size(){ return size; } public boolean isEmpty(){ return size == 0; } public void enqueue(Item item){ a.add(item); size++; } public Item dequeue(){ if(isEmpty()){ throw new NoSuchElementException(&quot;Queue is empty&quot;); }else { r = new Random(); int randomIndex = r.nextInt(size); Item item = a.get(randomIndex); a.remove(randomIndex); size--; return item; } } public Item sample(){ r = new Random(); if(isEmpty()){ throw new IndexOutOfBoundsException(); } int index = r.nextInt(size); return a.get(index); } } </code></pre>
[]
[ { "body": "<p>You should document the reason why <code>Random r</code> is package private. At the moment the reason is not clear, but if you fix the &quot;perpetual reinstantiation&quot; by initializing the <code>r</code> variable in the constructor, then you can take advantage of the package private visibility in unit tests by replacing the random number generator with a non-random Random implementation (because unit testing random behaviour is pretty much impossible).</p>\n<p>If you go with the <code>static Random</code> as suggested by @mdfst13, then you should use <code>ThreadLocalRandom</code> so that different threads that use the class do not interfere with each other.</p>\n<p>It is customary in Java that generic types are defined using single capital letters. Using a name that resembles a class name (<code>&lt;Item&gt;</code>) can be confusing as in a cursory glance it suggests that a specific <code>Item</code> class should be used. This increases cognitive load, which makes following the code more difficult.</p>\n<p>Beyond generic types, single letter names should be avoided. Use names that describe the purpose of the field. Non-descriptive field names again increase the cognitive load on the reader.</p>\n<p>The two instances of generating a random index should be refactored to an internal method.</p>\n<pre><code>public class RandomQueue&lt;T&gt; {\n \n private final List&lt;T&gt; data = new ArrayList&lt;&gt;();\n \n /**\n * Package private so that it can be overridden in unit tests.\n */\n Random rand = new Random();\n \n private int randomIndex() {\n return rand.nextInt(data.size());\n }\n\n ....\n}\n</code></pre>\n<p>Because this is Java and the class implements a collection of objects, you should see if it would make sense to implement the <code>Collection</code> interface. This might make the class more versatile.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T06:00:02.003", "Id": "267816", "ParentId": "267809", "Score": "5" } }, { "body": "<p>This is in addition to Torben's answer.</p>\n<h2>Java Collections Framework</h2>\n<p>It was a good idea to replace the original array with an <code>ArrayList</code>, but you can get even more benefit from that replacement.</p>\n<p>Your <code>size</code> field isn't necessary any more, as there is a size() method in the collections framework, and what you count yourself is exactly the size of your list, so you can use that method and delete the <code>size</code> field.</p>\n<p>You declare the list as</p>\n<pre><code> private ArrayList&lt;Item&gt; a;\n</code></pre>\n<p>It's recommended to declare fields and variables with the least specific interface type that matches your needs. Candidates are <code>Collection</code> and <code>List</code>. <code>Collection</code> doesn't support the indexed access that you need, so you should write</p>\n<pre><code> private List&lt;Item&gt; a;\n</code></pre>\n<p>or even include the initialization there instead of the constructor:</p>\n<pre><code> private List&lt;Item&gt; a = new ArrayList&lt;&gt;();\n</code></pre>\n<p>This way, it's easier to later change e.g. from an <code>ArrayList</code> to a <code>LinkedList</code> if you see a benefit, or want to do performance comparisons. As both classes fully comply with the <code>List</code> interface, no other line of code has to be touched for that change.</p>\n<p>You might even decide to make your own class conform to the Collections framework by declaring to implement <code>Collection</code> or one of its sub-interfaces. This makes such a queue class much more useful than its &quot;isolated&quot; counterpart.</p>\n<p>But be warned that there is some complexity in implementing a compliant <code>Collection</code> from scratch, so the recommended way would be to extend some existing class, maybe <code>AbstractList</code> or <code>AbstractQueue</code>.</p>\n<h2>Style</h2>\n<p>Your indentation is perfect.</p>\n<p>Your naming can be improved (see Torben's answer).</p>\n<p>Your usage of spaces is a bit inconsistent and not following the conventions we all are used to see, e.g. in</p>\n<pre><code> }else {\n</code></pre>\n<p>Your IDE surely has a function for re-formatting your code (if not, switch to decent one, e.g. Eclipse), and you should make it a habit to let it do its job regularly.</p>\n<h2>Documentation</h2>\n<p>This class could well become part of a useful library. Then it's important to let your fellow developers know what the various methods do. While it's quite possible to guess what <code>enqueue()</code> and <code>dequeue()</code> do (good naming!), at least your <code>sample()</code> method isn't self-explanatory from its name, and deserves a documentation.</p>\n<p>You should make it a habit to write Javadoc-formatted comments for classes, constructors and public methods so others can read what they are meant for, without having to dive into your source code. The Javadoc format is well supported in all decent IDEs, e.g. showing up as a tooltip on method names.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T19:50:48.737", "Id": "528254", "Score": "0", "body": "Thank you for the detailed explanation as well" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T09:24:22.373", "Id": "267854", "ParentId": "267809", "Score": "1" } } ]
{ "AcceptedAnswerId": "267816", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-08T21:26:30.417", "Id": "267809", "Score": "5", "Tags": [ "java", "performance", "random", "queue" ], "Title": "Randomized Queue with ArrayList from Princeton's Algorithm Book" }
267809
<p>I'm always down to learn better ways of doing thing and I wanted to see if I can get an input from the community to see if there is a way that I can improve this function:</p> <pre class="lang-php prettyprint-override"><code>function pardot_dashboard_query() { $args = [ 's' =&gt; '&lt;!-- wp:acf/pardot-form ', 'sentence' =&gt; 1, 'post_type' =&gt; [ 'post', 'page' ], ]; $pardot_posts = get_posts($args); if (!$pardot_posts) { echo 'There are no active Pardot Forms.'; return; } echo '&lt;p&gt;The Pardot Form is active on the following pages/posts:&lt;/p&gt;'; ?&gt; &lt;ul&gt; &lt;?php foreach ($pardot_posts as $post): ?&gt; &lt;li&gt;&lt;a href=&quot;&lt;?= $post-&gt;guid ?&gt;&quot;&gt;&lt;?= $post-&gt;post_title ?: 'No title available' ?&gt;&lt;?= ' (' . ucfirst($post-&gt;post_type) . ')' ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; &lt;?php } </code></pre> <p>If there are other means of outputs and or ways to shrink it down - All help will be appreciated!</p>
[]
[ { "body": "<p>I generally don't advocate for printing any content from within a function, but I'll not dwell on this because it is a somewhat common practice for WordPressers.</p>\n<ul>\n<li>Name your function to clearly express what it does. Please greater importance on clarity than brevity.</li>\n<li>declare the return value as <code>void</code> to help you and your IDE to better understand the function's behavior.</li>\n<li>avoid single-use variable declarations unless they are valuably self-documenting.</li>\n<li>I don't see you using excessive spacing like many WP devs, so kudos for that.</li>\n<li>I prefer curly brace syntax for language construct looping. I don't personally find the verbose loop end to be valuable.</li>\n<li>use <code>printf()</code> and <code>sprintf()</code> to elegantly marry variables and expressions into a template string. This is easier to read than a bunch of concatenation and interpolation.</li>\n<li>I prefer not to jump in and out of php tags, so I'll demonstrate staying inside of PHP the whole time.</li>\n<li>I'm not sold on that <code>href</code> value being legit. Is that value actually a valid url?</li>\n</ul>\n<p>Code:</p>\n<pre><code>function printPardotDashboardItems(): void\n{\n $pardot_posts = get_posts([\n 's' =&gt; '&lt;!-- wp:acf/pardot-form ',\n 'sentence' =&gt; 1,\n 'post_type' =&gt; [\n 'post',\n 'page'\n ],\n ]);\n if (!$pardot_posts) {\n echo '&lt;p&gt;There are no active Pardot Forms.&lt;/p&gt;';\n } else {\n $items = [];\n foreach ($pardot_posts as $post) {\n $items[] = sprintf(\n '&lt;li&gt;&lt;a href=&quot;%s&quot;&gt;%s (%s)&lt;/a&gt;&lt;/li&gt;',\n $post-&gt;guid,\n $post-&gt;post_title ?: 'No title available',\n ucfirst($post-&gt;post_type)\n );\n }\n printf(\n '&lt;p&gt;The Pardot Form is active on the following pages/posts:&lt;/p&gt;&lt;ul&gt;%s&lt;/ul&gt;',\n implode(&quot;\\n&quot;, $items)\n );\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T12:08:23.123", "Id": "528145", "Score": "0", "body": "This works flawlessly! Thanks @mickmackusa, I learned something new with this technique - Surprisingly, the href actually does come back as an accurate return." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T10:34:42.567", "Id": "267823", "ParentId": "267813", "Score": "0" } } ]
{ "AcceptedAnswerId": "267823", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T02:53:21.457", "Id": "267813", "Score": "1", "Tags": [ "php", "html" ], "Title": "Output results of a search for usage of a pardot-form" }
267813
<p>I'm implementing row-level-locking on a MS SQL Server. The function I created below works, but even with a very small data set, it takes a significant amount of time to return the results.</p> <p>If I were to code this in VBA for example, I would call the username() function only once and store the result. Can this be done in a table-valued function?</p> <p><strong>How can I improve this function to perform faster?</strong></p> <pre><code>CREATE Function [compliance].[fn_AllowActivity] (@ActivityID sysname) returns table with schemabinding as return select 1 as [fn_AllowActivity_result] from compliance.tbl_Users join compliance.tbl_Activity on compliance.tbl_Users.UnitID=compliance.tbl_Activity.UnitID where @ActivityID=compliance.tbl_Activity.ActivityID and compliance.tbl_Users.Active=1 and compliance.tbl_Users.Windows_ID=substring(user_name(),CHARINDEX('\',user_name())+1,10) or compliance.tbl_Users.Windows_ID = substring(user_name(),CHARINDEX('\',user_name())+1,10) and compliance.tbl_Users.Active=1 and compliance.tbl_Users.RoleID&gt;=3 GO </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T07:36:16.973", "Id": "528137", "Score": "1", "body": "Are tbl_Users.UnitID and tbl_Activity.ActivityID primary keys? Are tbl_Activity.UnitID, tbl_Users.Active and tbl_Users.RoleID indexed? Also, you check compliance.tbl_Users.Active=1 twice." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T07:55:57.090", "Id": "528140", "Score": "0", "body": "tbl_Users.UnitID and tbl_Activity.ActivityID are primary keys. None of the other columns are indexed. The reason i'm checking activity twice is that there are two types of conditions i'm checking... hence the OR clause... but I guess you are saying that is not what i'm doing!?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T09:13:35.000", "Id": "528144", "Score": "0", "body": "I have added indexes on the columns you suggested as well as other ones that are refrenced. It has helped to greatly speed up execution time. Although, there are still some queries that are very slow. I'm now analyzing these with the 'execution planer'." } ]
[ { "body": "<p>Based on Pavlov's comment I added indexs to my tables and altered the fuction as follows:</p>\n<pre><code>ALTER Function [compliance].[fn_AllowActivity] (@ActivityID sysname)\nreturns table\nwith schemabinding\nas\nreturn select 1 as [fn_AllowActivity_result]\nfrom \ncompliance.tbl_Users left join compliance.tbl_Activity on compliance.tbl_Users.UnitID=compliance.tbl_Activity.UnitID\nwhere compliance.tbl_Users.Active=1 and compliance.tbl_Users.Windows_ID = substring(user_name(),CHARINDEX('\\',user_name())+1,10) and \n (@ActivityID=compliance.tbl_Activity.ActivityID or compliance.tbl_Users.RoleID&gt;=3)\nGO\n</code></pre>\n<p>Performance is now within what is expected. Many thanks!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T12:23:33.823", "Id": "267825", "ParentId": "267817", "Score": "0" } }, { "body": "<p>Aside from the indexes (which is important), you can improve the query by storing the username in a variable and adding the username condition in the join, which would simplify the query and improve the join performance :</p>\n<pre><code>CREATE Function [compliance].[fn_AllowActivity] (@ActivityID sysname)\nRETURNS TABLE\nWITH schemabinding\nAS\n\n DECLARE @UserName VARCHAR(250) = SUBSTRING(user_name(), CHARINDEX('\\', user_name() ) + 1 , 10)\n \nRETURN SELECT 1 AS [fn_AllowActivity_result]\nFROM \n compliance.tbl_Users \nJOIN compliance.tbl_Activity \n ON compliance.tbl_Users.UnitID = compliance.tbl_Activity.UnitID \n AND compliance.tbl_Users.Windows_ID = @UserName\n AND compliance.tbl_Users.Active = 1 \nWHERE \n @ActivityID = compliance.tbl_Activity.ActivityID \nAND compliance.tbl_Users.Active = 1 \nOR compliance.tbl_Users.RoleID &gt;= 3\nGO\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-19T08:15:06.087", "Id": "268137", "ParentId": "267817", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T07:25:33.077", "Id": "267817", "Score": "0", "Tags": [ "performance", "sql", "sql-server" ], "Title": "Table-Value Function with row-level-locking" }
267817
<p>I have an array <code>requestArr</code> in which there are objects with two values, also I have an array with objects <code>itemsArr</code> keys which is 'id' and the value of the array with numbers.</p> <p>Task like this: To map array of <code>itemsArr</code> and to compare key of object in it with value of an id in array <code>requestArr</code> if they coincide, it is necessary to delete from value of object of array <code>itemsArr</code> number corresponding to value count in array <code>requestArr</code> and at the same time to add it to absolutely new array <code>itemToSave</code>.</p> <p>At the end of the search, check if there is at least one number in the beta from the array of <code>itemsArr</code> in the array of numbers, if not add it to a completely new array <code>itemToDelete</code>.</p> <p>Below is the code that works the way I need it, but I'm sure there's a better solution than the one I got.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>const itemToDelete = []; const itemToSave = []; const requestArr = [{ id: 15, count: 25 }]; const itemsArr = [ { '15': [25, 26, 31, 33] }, { '21': [25, 26, 616, 617] } ]; itemsArr.map((item) =&gt; { const itemId = Number(Object.keys(item)[0]); item[itemId].map((itemArrCounts, i) =&gt; { requestArr.map((requestItem) =&gt; { if (requestItem.count === itemArrCounts &amp;&amp; requestItem.id === itemId) { itemToDelete.push({ id: itemId, teamId: itemArrCounts }); item[itemId].splice(i, 1); } }); item[itemId].length === 0 &amp;&amp; itemToSave.push({ id: itemId }); }); }); console.log(itemToDelete, itemToSave);</code></pre> </div> </div> </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T07:34:30.803", "Id": "267818", "Score": "0", "Tags": [ "javascript", "array" ], "Title": "Create a new array of an array of numbers and an array of objects whose key is used for search" }
267818
<p>I have written some code to determine an interpolation matrix over a grid of points. I originally wrote the code in matlab, where under the specified parameters it took just over 2 minutes. The equivalent code in Python however takes 40minutes!</p> <p>I was expecting Python to be slower, but not be such an amount! Any feedback on the code is much appreciated.</p> <pre><code>import numpy as np from numpy import linalg as LA def g(x, y): gx = -x * (x ** 2 + y ** 2) gy = -y * (x ** 2 + y ** 2) return np.array((gx, gy)) def wendland(r): if r &lt; 1: return ((1-r)**4)*(4*r+1) else: return 0 def make_collocation_points(h, x1, x2, y1, y2): i = 0 x = [] y = [] for j in range(x1,x2+1): for k in np.arange(y1, y2, h): if LA.norm(g(j*h, k*h) - (j*h, k*h)) &gt; 0.00001: # Don't accept values on the chain recurrent set! x.append(j*h) y.append(k*h) i += 1 return x, y, i def get_aij(x, y, n): a = np.zeros((n,n)) for j in range(0, n): for k in range(0, n): a[j, k] = ( wendland(LA.norm(g(x[j], y[j]) - g(x[k], y[k]))) - wendland(LA.norm(g(x[j], y[j]) - np.array([x[k], y[k]]))) - wendland(LA.norm([x[j], y[j]] - g(x[k], y[k]))) + wendland(LA.norm(np.array([x[j], y[j]]) - np.array([x[k], y[k]]))) ) return a if __name__ == &quot;__main__&quot;: h = 0.11 x1, x2 = -15, 15 y1, y2 = -15, 15 x, y, n = make_collocation_points(h, x1, x2, y1, y2) a = get_aij(x, y, n) </code></pre>
[]
[ { "body": "<p>In both Matlab and Numpy, your indexed loops are not the right way to express vectorized operations. You should adopt a strong bias against loops and individual element indexing, learn how broadcasting works, and pass around <code>ndarray</code>s instead of lists.</p>\n<p>Based on the above, a potential vectorized solution - with a regression test to ensure that the results have not changed - is</p>\n<pre class=\"lang-py prettyprint-override\"><code>from numbers import Real\nfrom typing import Sequence, Union\n\nimport numpy as np\nfrom numpy.linalg import norm\nfrom scipy.stats import describe\n\n\nEPSILON = 1e-12\n\n\ndef g(xy: np.ndarray) -&gt; np.ndarray:\n return -xy * np.sum(xy**2, axis=0)\n\n\ndef wendland(r: np.ndarray) -&gt; np.ndarray:\n r = norm(r, axis=0)\n out = (1 - r)**4 * (1 + 4*r)\n out[r &gt;= 1] = 0\n return out\n\n\ndef make_collocation_points(h: Real, x1: int, x2: int, y1: int, y2: int) -&gt; np.ndarray:\n j = np.arange(x1, x2+1)\n k = np.arange(y1, y2, h)\n jk = np.stack(np.meshgrid(k, j)) * h\n\n # Don't accept values on the chain recurrent set!\n g_norm = norm(g(jk) - jk, axis=0)\n jk = jk[::-1, g_norm &gt; 1e-5]\n\n return jk\n\n\ndef get_aij(xy: np.ndarray) -&gt; np.ndarray:\n # broadcast to get the effect of xj, xk, yj, yk\n xyj, xyk = np.broadcast_arrays(\n xy[:, np.newaxis, :],\n xy[:, :, np.newaxis],\n )\n\n gj = g(xyj)\n gk = g(xyk)\n\n return (\n + wendland(gj - gk) - wendland(xyj - gk)\n - wendland(gj - xyk) + wendland(xyj - xyk)\n )\n\n\ndef assert_close(\n a: Union[Real, np.ndarray],\n b: Union[Real, Sequence[Real]],\n) -&gt; None:\n assert np.all(np.isclose(a, b, rtol=0, atol=EPSILON))\n\n\ndef regression_test() -&gt; None:\n h = 0.11\n n = 2 # 15 is way too slow\n x1, x2 = -n, n\n y1, y2 = -n, n\n\n xy = make_collocation_points(h, x1, x2, y1, y2)\n assert xy.shape == (2, 185)\n stats = describe(xy.T)\n assert_close(stats.minmax[0], (-0.22, -0.22))\n assert_close(stats.minmax[1], (+0.22, +0.2156))\n assert_close(stats.mean, (0, -2.2e-3))\n assert_close(stats.variance, (0.02433152173913048, 0.016781450543478273))\n\n a = get_aij(xy)\n assert a.shape == (185, 185)\n stats = describe(a.flatten())\n assert_close(stats.minmax[0], -0.17266964737638246)\n assert_close(stats.minmax[1], +1.10925185890418380)\n assert_close(stats.mean, 0.11771392866408713)\n assert_close(stats.variance, 0.061445578720171375)\n\n\ndef demo() -&gt; None:\n h = 0.11\n n = 10\n x1, x2 = -n, n\n y1, y2 = -n, n\n\n xy = make_collocation_points(h, x1, x2, y1, y2)\n print(describe(xy.T))\n\n a = get_aij(xy)\n print(describe(a.flatten()))\n\n\nif __name__ == &quot;__main__&quot;:\n regression_test()\n demo()\n</code></pre>\n<p>I don't have a whole lot of patience for long execution runs, but for n=10 the demo finishes in about five seconds even though it produces 14,607,684 elements. A quick-and-dirty <code>timeit</code> produces:</p>\n<pre><code>old, n=2: 1.433 s\nnew, n=2: 0.007 s\nold, n=3: 6.206 s\nnew, n=3: 0.035 s\nold, n=4: 18.033 s\nnew, n=4: 0.099 s\nold, n=5: 43.935 s\nnew, n=5: 0.224 s\nold, n=6: 90.451 s\nnew, n=6: 0.459 s\nold, n=7: 161.559 s\nnew, n=7: 0.878 s\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T02:55:24.400", "Id": "267844", "ParentId": "267824", "Score": "4" } } ]
{ "AcceptedAnswerId": "267844", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T12:07:12.563", "Id": "267824", "Score": "2", "Tags": [ "python", "python-3.x", "numpy" ], "Title": "Calculating a function over a large array" }
267824
<p>There is a function that draws triangles on the canvas area in each lines:</p> <pre><code>function DivotTemplate(divot, canvas) { if (divot === void 0) { divot = defaultConfig; } var config = __assign(__assign({}, defaultConfig), divot); var ctx = canvas.getContext('2d'); if (!ctx) throw Error('Canvas context error'); var width = canvas.width; var height = canvas.height; var step = config.step, radius = config.radius, strokeStyle = config.strokeStyle, triangleWidth = config.triangleWidth; var x = [1, 1, triangleWidth + 1]; var y = [1, triangleWidth, triangleWidth / 2]; var context = canvas.getContext('2d'); if (!context) throw Error('Canvas context error'); /* Рисуем три точки для первого треугольника */ for (var c = 0; c &lt; height; c++) { if (c % 2 === 0) { x[0] = triangleWidth + 1; x[1] = triangleWidth + 1; x[2] = 1; } else { var s = step / 2; x = [1 + s, 1 + s, triangleWidth + 1 + s]; } for (var i = 0; i &lt; width; i = i + step) { context.beginPath(); context.arc(x[0], y[0], radius, 0, 2 * Math.PI, false); context.strokeStyle = strokeStyle; context.stroke(); context.beginPath(); context.arc(x[1], y[1], radius, 0, 2 * Math.PI, false); context.strokeStyle = strokeStyle; context.stroke(); context.beginPath(); context.arc(x[2], y[2], radius, 0, 2 * Math.PI, false); context.strokeStyle = strokeStyle; context.stroke(); /* Соединяем две точки из трех */ context.beginPath(); context.moveTo(x[2], y[2]); context.lineTo(x[0], y[0]); context.strokeStyle = strokeStyle; context.stroke(); context.beginPath(); context.moveTo(x[2], y[2]); context.lineTo(x[1], y[1]); context.strokeStyle = strokeStyle; context.stroke(); x[0] = x[0] + step; x[1] = x[1] + step; x[2] = x[2] + step; } x = [1, 1, triangleWidth + 1]; y[0] = y[0] + step; y[1] = y[1] + step; y[2] = y[2] + step; } return canvas; } </code></pre> <p>I measured the performance of this function and get bad indicators (pic. 1)</p> <p><a href="https://i.stack.imgur.com/pISVM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pISVM.png" alt="Timeline display for code" /></a></p> <p>How it can be improved?</p> <p>Why <code>context.strokeStyle = strokeStyle;</code> takes over 4 seconds?</p> <p>Maybe pull out <code>context.beginPath();</code> outside of loop? Or combine some operators? How to optimize canvas drawing?</p>
[]
[ { "body": "<h2>2D canvas performance</h2>\n<p>You are running on a VERY slow system. Make sure you are not running any extension when measuring performance.</p>\n<h3>Avoid GPU state changes</h3>\n<p>The biggest performance penalty when using the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D\" rel=\"noreferrer\">2D canvas API</a> are state changes.</p>\n<p>State changes are when you change rendering settings (state) such as the color. The state needs to be moved from the CPU to the GPU which means shutting down many systems so that the main Address and Data Bus can communicate with the GPU Address and Data Bus. Not only does this slow your code, but all processes are effected.</p>\n<p>You can see the penalty on lines 44, 48, 52, 58, and 63, where you set <code>context.strokeStyle = strokeStyle;</code> (approx 400ms) This penalty is forced as your styles are all identical (The 2D API does not check if the style needs to be changed)</p>\n<p>The most basic fix is to batch all render calls using the same style as one path operation. <code>ctx.beginPath(); /* ... build path ... */; ctx.stroke();</code></p>\n<p>Note that building a path does not require GPU communication until the render function is called. <code>ctx.stroke</code> or <code>ctx.fill</code></p>\n<h3>Avoid exceptions.</h3>\n<p>Using <code>try</code>, <code>catch</code>, or <code>throw</code> in JS will mark the code (and any code called, or in the same scope) as <code>Do not optimise</code>. Meaning that the optimiser does not get to improve the performance.</p>\n<h3>Avoid arrays</h3>\n<p>Indexing into arrays is slower than using variables directly.</p>\n<p>Creating an array is much slower than assigning variables directly. Up to a point, for 3 items its best to use variables, for 12 items then an array is better, but still avoid creating a new array, reuse the existing array.</p>\n<h3>General points</h3>\n<p>Avoid repeated calculations. Especially true if you have the code marked <code>Do not optimise</code></p>\n<p>Examples...</p>\n<ul>\n<li><p><code>x = [1, 1, triangleWidth + 1];</code> at bottom of outer loop is not needed.</p>\n</li>\n<li><p><code>context.arc(x[2], y[2], radius, 0, 2 * Math.PI, false);</code> Pre-calculate 2.PI. Use the defaults, eg the last argument <code>false</code> is the default and thus not needed.</p>\n</li>\n<li><p>You get the 2D context twice. Only needed once.</p>\n</li>\n<li><p>For <code>ctx.arc</code> if <code>radius</code> is less than 2px use <code>ctx.rect(x - radius. y- radius, diameter, diameter)</code> where <code>diameter</code> is calculated outside the loops as <code>const diameter = radius * 2</code></p>\n<p><code>ctx.rect</code> is much quicker than <code>ctx.arc</code> and at &lt;2px radius they a visually very similar. Note when using <code>ctx.rect</code> reducing the radius by <code>0.8</code> will more closely approximate the visual density of the arc.</p>\n</li>\n<li><p>You are rendering 2 connected line segments using two <code>moveTo</code> calls. They are connected and as such only need one <code>moveTo</code> (see rewrite)</p>\n</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The following rewrite will be a huge improvement in performance. My estimate is at least twice as fast.</p>\n<pre><code>function DivotTemplate(divot = {}, canvas) {\n const TAU = 2 * Math.PI;\n const config = {\n ...defaultConfig,\n ... divot\n };\n const ctx = canvas.getContext('2d');\n const width = canvas.width, height = canvas.height;\n const step = config.step;\n const radius = config.radius;\n const strokeStyle = config.strokeStyle;\n const triangleWidth = config.triangleWidth;\n \n var x0 = 1, x1 = 1, x2 = triangleWidth + 1;\n var y0 = 1, y1 = triangleWidth, y2 = triangleWidth / 2;\n var c, s, i;\n \n /* One state change */\n ctx.strokeStyle = strokeStyle;\n \n /* Build one path */\n ctx.beginPath();\n\n for (c = 0; c &lt; height; c++) {\n if (c % 2 === 0) {\n x0 = triangleWidth + 1;\n x1 = triangleWidth + 1;\n x2 = 1;\n } else {\n s = step / 2;\n x0 = 1 + s;\n x1 = 1 + s;\n x2 = triangleWidth + 1 + s;\n }\n for (i = 0; i &lt; width; i += step) {\n ctx.moveTo(x0 + radius, y0); \n ctx.arc(x0, y0, radius, 0, TAU);\n\n ctx.moveTo(x1 + radius, y1);\n ctx.arc(x1, y1, radius, 0, TAU);\n\n ctx.moveTo(x2 + radius, y2);\n ctx.arc(x2, y2, radius, 0, TAU);\n\n ctx.moveTo(x0, y0);\n ctx.lineTo(x1, y1);\n ctx.lineTo(x2, y2);\n\n x0 += step;\n x1 += step;\n x2 += step;\n }\n \n y0 + =step;\n y1 += step;\n y2 += step;\n }\n \n /* One render call */\n ctx.stroke();\n return canvas;\n}\n</code></pre>\n<h2>Multiple calls</h2>\n<p>If the function <code>DivotTemplate</code> is called many times (with the same settings) move setup, <code>beginPath</code>, and <code>stroke</code> out of the function and build one path for the many <code>DivotTemplate</code> calling stroke when all done.</p>\n<h2>Render pixels directly</h2>\n<p>It is unclear what the various values of <code>divot</code> are but if <code>step</code> is near 1 px then the whole function should write pixels via a buffer and avoid the 2D context path calls altogether.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T19:01:21.093", "Id": "267835", "ParentId": "267830", "Score": "5" } } ]
{ "AcceptedAnswerId": "267835", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T16:04:29.737", "Id": "267830", "Score": "2", "Tags": [ "javascript", "performance", "canvas" ], "Title": "Draw triangles on the HTML canvas optimization" }
267830
<p>I recently crafted <a href="https://puzzling.stackexchange.com/questions/111576/a-pretty-binary-grid">a binary word search puzzle</a> using HTML, CSS and JavaScript to dynamically build grids within a grid:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var board = document.getElementById('board'); var characters = [ 'H','U','O','M','S','F','I','R','E','I', 'P','O','B','P','O','S','P','K','K','A', 'S','E','P','T','E','M','B','E','R','F', 'Y','T','A','E','W','D','T','I','O','T', 'W','W','N','S','R','A','I','E','B','E', 'X','E','H','P','T','A','Y','Z','S','R', 'S','L','X','G','Y','E','T','U','F','N', 'K','F','D','R','E','Q','R','I','X','O', 'Y','T','H','Q','Z','H','X','N','O','O', 'L','H','Z','D','F','O','U','R','T','N' ]; for (var iCharacters = 0; iCharacters &lt; characters.length; iCharacters++) { var binary = '0' + characters[iCharacters].charCodeAt(0).toString(2); var square = '&lt;div class="square"&gt;'; for (var iBinary = 0; iBinary &lt; binary.length; iBinary++) { if (iBinary == 4) { square += '&lt;div class="empty"&gt;&lt;/div&gt;'; square += '&lt;div&gt;' + binary.charAt(iBinary) + '&lt;/div&gt;'; } else square += '&lt;div&gt;' + binary.charAt(iBinary) + '&lt;/div&gt;'; } board.innerHTML += square + '&lt;/div&gt;'; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>html, body { background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%); } .board { width: 800px; height: 800px; display: grid; grid-template-columns: repeat(10, 10%); grid-template-rows: repeat(10, 10%); grid-gap: 5px; border-radius: 5px; } .square { display: grid; grid-template-columns: repeat(3, 33%); grid-template-rows: repeat(3, 33%); border-radius: 5px; background-color: #fff7; } .square div { display: flex; align-content: center; justify-content: center; font-size: 15px; color: #444; } .square div:nth-child(1) { border-top-left-radius: 5px; } .square div:nth-child(3) { border-top-right-radius: 5px; } .square div:nth-child(7) { border-bottom-left-radius: 5px; } .square div:nth-child(9) { border-bottom-right-radius: 5px; } .square .empty { background-color: #0003; border-radius:5px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="board" class="board"&gt;&lt;/div&gt;</code></pre> </div> </div> </p> <p>Since I don't use HTML, CSS and JavaScript as often as I used to, it would be nice to have someone review my code to answer the following questions:</p> <ul> <li>Is my code legible?</li> <li>Are there more efficient methods I could have used?</li> </ul> <p><sub><em><strong>Note</strong>: The use of Hungarian notation isn't something I typically do, however in the case where I have multiple iteration variables, I utilize the notation to help denote that the variable I'm working with is, an iteration variable. As such <code>iBinary</code> does not mean that it is an integer, but rather an iteration variable. To me, this is easier to follow when it doesn't make sense to use <code>x,y,z</code> or <code>i,j,k</code>.</em></sub></p>
[]
[ { "body": "<p>Answering to your first question your code is certainly legible, I would modify your main structure (I'm copying just the first two rows for brevity):</p>\n<pre><code>var characters = ['H','U','O','M','S','F','I','R','E','I',\n 'P','O','B','P','O','S','P','K','K','A',\n];\n</code></pre>\n<p>You could separate the two rows in your matrix with a clean cut using differents strings for every row and with <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join?retiredLocale=it#select-language\" rel=\"nofollow noreferrer\"><code>join</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split\" rel=\"nofollow noreferrer\"><code>split</code></a> methods:</p>\n<pre><code>const characters = ['HUOMSFIREI','POBPOSPKKA'].join('').split('');\n</code></pre>\n<p>I saw you used only <code>var</code> in your code, this is legitimate but if you have the possibility better use <code>let</code> and <code>const</code> instead of it for a better clarity of your code and to avoid problems related to the scope, see <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var?retiredLocale=it\" rel=\"nofollow noreferrer\"><code>var</code></a> for more informations.</p>\n<p>About your loop:</p>\n<pre><code>for (var iCharacters = 0; iCharacters &lt; characters.length; iCharacters++) {\n var binary = '0' + characters[iCharacters].charCodeAt(0).toString(2);\n var square = '&lt;div class=&quot;square&quot;&gt;';\n for (var iBinary = 0; iBinary &lt; binary.length; iBinary++) {\n if (iBinary == 4) {\n square += '&lt;div class=&quot;empty&quot;&gt;&lt;/div&gt;';\n square += '&lt;div&gt;' + binary.charAt(iBinary) + '&lt;/div&gt;';\n }\n else\n square += '&lt;div&gt;' + binary.charAt(iBinary) + '&lt;/div&gt;';\n }\n board.innerHTML += square + '&lt;/div&gt;';\n}\n</code></pre>\n<p>The line <code>square += '&lt;div&gt;' + binary.charAt(iBinary) + '&lt;/div&gt;';</code> is present in both the two branches of your if-else statement, you can rewrite it like below :</p>\n<pre><code>if (iBinary === 4) {\n square += '&lt;div class=&quot;empty&quot;&gt;&lt;/div&gt;';\n}\nsquare += '&lt;div&gt;' + binary.charAt(iBinary) + '&lt;/div&gt;';\n</code></pre>\n<p>You can also use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of?retiredLocale=it\" rel=\"nofollow noreferrer\"><code>for...of</code></a> statement and rewrite your loop in this way:</p>\n<pre><code>for (const character of characters) {\n const binary = '0' + character.charCodeAt(0).toString(2);\n let square = '&lt;div class=&quot;square&quot;&gt;';\n\n for (let iBinary = 0; iBinary &lt; binary.length; ++iBinary) {\n if (iBinary === 4) {\n square += '&lt;div class=&quot;empty&quot;&gt;&lt;/div&gt;';\n }\n square += '&lt;div&gt;' + binary.charAt(iBinary) + '&lt;/div&gt;';\n }\n board += square + '&lt;/div&gt;';\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T10:52:01.617", "Id": "267856", "ParentId": "267833", "Score": "2" } }, { "body": "<p>For the first question, i.e.</p>\n<blockquote>\n<p><em>Is my code legible?</em></p>\n</blockquote>\n<p>It is somewhat legible. I can understand what it is doing. Bearing in mind you stated you don't typically use Hungarian notation I'd point out that the naming could be improved. For e</p>\n<p>Have you seen <a href=\"https://stackoverflow.com/a/111972/1575353\">the accepted answer</a> to <a href=\"https://stackoverflow.com/q/111933/1575353\">the SO post <em>Why shouldn't I use &quot;Hungarian Notation&quot;?</em></a> as well as other answers? The accepted answer points out that often Apps Hungarian is used instead of (non-Apps) Hungarian.</p>\n<p>When I see a variable name like <code>iCharacters</code> my first thought might be that it holds the total number of characters in the array. However I can see that it is used as a counter variable incremented from 0 to one less than the total number of characters in the array. A more appropriate name might be something like <code>iCharacterIndex</code> or <code>iCurrentCharacterIndex</code>.</p>\n<p>Then variables like <code>board</code>, <code>characters</code>, etc. don't use Hungarian notation (which I prefer). It is better to either exclusively use it or not.</p>\n<p>The spacing is consistent with idiomatic JavaScript.</p>\n<hr />\n<p>For the second question, i.e.</p>\n<blockquote>\n<p><em>Are there more efficient methods I could have used?</em></p>\n</blockquote>\n<p>Just as I mentioned in <a href=\"https://codereview.stackexchange.com/a/262781/120114\">this answer</a> it is wise to <a href=\"https://developers.google.com/speed/docs/insights/browser-reflow\" rel=\"nofollow noreferrer\">Minimize browser reflows</a>. That means instead of adding elements to the DOM in a loop - e.g. appending to <code>board.innerHTML</code> at the end of the outer <code>for</code> loop, add elements to a <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/DocumentFragment\" rel=\"nofollow noreferrer\">documentFragment</a> or temporary element and then add the contents of that element in a single step.</p>\n<p>In the past there were <a href=\"https://stackoverflow.com/q/16696632/1575353\">discussions about the most efficient way to concatenate strings</a>. Browsers have come a long way in the past decade and that may not really be a major concern anymore, especially since this code likely only runs once when the page loads. Also, <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals\" rel=\"nofollow noreferrer\">Ecmascript 6 template literals</a> can help.</p>\n<p>Another option might be using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template\" rel=\"nofollow noreferrer\"><code>&lt;template&gt;</code></a> tag to create elements without an inner loop.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T12:39:24.700", "Id": "267861", "ParentId": "267833", "Score": "2" } }, { "body": "<h2>Review</h2>\n<p>You code looks very old school. Use modern JavaScript that simplifies common tasks and helps improve performance.</p>\n<h3>General points</h3>\n<ul>\n<li>Use constants for variables that do not change. <code>characters</code>, <code>board</code>, <code>binary</code> should all be <code>const</code></li>\n<li>Names are a little long. Use common abbreviations when possible. eg for programmers <code>characters</code> is written <code>chars</code>, <code>binary</code> is <code>bin</code>. Loop index's are short <code>iBinary</code> can just be <code>i</code>, <code>idx</code>, or <code>j</code></li>\n<li>Use <code>for of</code> when you don't need the indexes.</li>\n<li>Avoid writing markup to the page. It is very slow compared to using the DOM API. see rewrite</li>\n<li>Use <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Strict equality\">=== (Strict equality)</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Equality\">== (Equality)</a>. Same for <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Strict inequality\">!== (Strict inequality)</a> rather than <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Inequality\">!= (Inequality)</a></li>\n<li>Dont repeat code. The two statement blocks inside the loop both end in the same line. Remove the <code>else</code> and the line <code>square += '&lt;div&gt;' + binary.charAt(iBinary) + '&lt;/div&gt;';</code> need only be written once.</li>\n<li>ALWAYS delimit code blocks. eg never do <code>else foo = 0;</code> always <code>else { foo = 0; }</code> same with <code>if</code>, <code>for</code>, <code>while</code>, etc..</li>\n</ul>\n<h2>Rewrite</h2>\n<p>The rewrite does not resemble your code at all as it uses modern JavaScript.</p>\n<p>The code is packed into a function as you should never write code outside a function.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>;(() =&gt; {\n \"use strict\";\n const tag = (tag, props = {}) =&gt; Object.assign(document.createElement(tag), props);\n const append = (par, ...sibs) =&gt; sibs.reduce((p, sib) =&gt; (p.appendChild(sib), p), par);\n const rows = [\n 'HUOMSFIREI',\n 'POBPOSPKKA',\n 'SEPTEMBERF',\n 'YTAEWDTIOT',\n 'WWNSRAIEBE',\n 'XEHPTAYZSR',\n 'SLXGYETUFN',\n 'KFDREQRIXO',\n 'YTHQZHXNOO',\n 'LHZDFOURTN'\n ];\n const char2BinArr = c =&gt; [...c.charCodeAt(0).toString(2).padStart(8, \"0\")];\n function addBin(bit, i) {\n const res = [tag(\"div\", {textContent: bit})];\n i === 4 &amp;&amp; res.unshift(tag(\"div\", {className: \"empty\"}));\n return res;\n }\n function createBoard(rows) {\n append(board, \n ...rows.map(row =&gt; [...row].map(char =&gt; {\n return append(\n tag(\"div\", {className: \"square\"}),\n ...char2BinArr(char).map(addBin).flat()\n );\n })).flat()\n );\n }\n createBoard(rows);\n})();</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html, body {\n background: linear-gradient(90deg, #00C9FF 0%, #92FE9D 100%);\n}\n.board {\n width: 800px;\n height: 800px;\n display: grid;\n grid-template-columns: repeat(10, 10%);\n grid-template-rows: repeat(10, 10%);\n grid-gap: 5px;\n border-radius: 5px;\n}\n.square {\n display: grid;\n grid-template-columns: repeat(3, 33%);\n grid-template-rows: repeat(3, 33%);\n border-radius: 5px;\n background-color: #fff7;\n}\n.square div {\n display: flex;\n align-content: center;\n justify-content: center;\n font-size: 15px;\n color: #444;\n}\n.square div:nth-child(1) { border-top-left-radius: 5px; }\n.square div:nth-child(3) { border-top-right-radius: 5px; }\n.square div:nth-child(7) { border-bottom-left-radius: 5px; }\n.square div:nth-child(9) { border-bottom-right-radius: 5px; }\n.square .empty {\n background-color: #0003;\n border-radius:5px;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div id=\"board\" class=\"board\"&gt;&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<h2>References</h2>\n<p>Reference to features used in the rewrite.</p>\n<ul>\n<li><p>JS objects and function calls</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array map\">Array.map</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array flat\">Array.flat</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Array reduce\">Array.reduce</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. Object assign\">Object.assign</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript global objects reference. String padStart\">String.padStart</a></li>\n</ul>\n</li>\n<li><p>JS operators</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Spread syntax\">... (Spread syntax)</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript operator reference. Strict equality\">=== (Strict equality)</a></li>\n</ul>\n</li>\n<li><p>JS misc</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\" title=\"MDN JavaScript Functions Arrow functions\">=&gt; (Arrow functions)</a></li>\n</ul>\n</li>\n<li><p>Browser API's</p>\n<ul>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Document createElement\">Document.createElement</a></li>\n<li><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild\" rel=\"nofollow noreferrer\" title=\"MDN Web API's Node appendChild\">Node.appendChild</a></li>\n</ul>\n</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T22:47:38.977", "Id": "267905", "ParentId": "267833", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T17:46:13.033", "Id": "267833", "Score": "4", "Tags": [ "javascript", "performance", "html", "css" ], "Title": "Creating a binary word search " }
267833
<p>I wanted to get some feedback on a fluent unit testing framework I’ve written. I call the project Fluent VBA. You can find a link to the project on GitHub <a href="https://github.com/b-gonzalez/Fluent-VBA" rel="nofollow noreferrer">here</a></p> <p><strong>Motivation</strong></p> <p>This project was inspired when I read about Fluent Assertions in C# as I was reading a book on unit testing.</p> <p><strong>Usage</strong></p> <p>Fluent frameworks are intended to be read like natural language. So instead of having something like:</p> <pre><code>Dim result = returnsFive() ‘returns the number 5 Dim Assert as cUnitTester Set Assert = New cUnitTester Assert.Equal(Result,5) </code></pre> <p>You can have code that reads more naturally like so:</p> <pre><code>Dim Result as cFluent Set Result = new cFluent Result.TestValue = ReturnsFive() Result.Should.Be.EqualTo(5) </code></pre> <p><strong>High level overview</strong></p> <p>Fluent VBA is broken down into 13 class modules: Nine classes and four interfaces. All of the class modules have an instancing property of PublicNotCreatable. So the project can be referenced in an external testing project. To do that, you’d just need to create an instance of cFluent using the MakeFluent() method in the mInit module. But you don’t have to do that if you don’t want to. You can also write your testing code in the cFluent project.</p> <p>The project has a few main components: A Should component, a Be component, and a Have component. I also have components for their opposite: A ShouldNot component, and NotBe component, and a NotHave component. These various components are implemented in the project using composition.</p> <p>Since the project is a unit-testing framework, I can use the project to test itself. So in the mTests module, I have a procedure called MetaTests where I do this. The meta tests mainly use the Fluent.Should.Be.EqualTo method with debug.assert to do this. Since all other methods rely on this method, I test this test extensively. I also test its opposite (i.e. Fluent.ShouldNot.Be.EqualTo) to ensure that it contains the expected value. In addition to these MetaTests, I also have lots of different examples showing how you can use this framework in a variety of different ways.</p> <p><strong>Detailed overview</strong></p> <p><strong>Interfaces</strong>:</p> <p><strong>The IShould Interface:</strong></p> <p>This interface contains the following procedures:</p> <pre><code>Public Property Get Be() As IBe End Property Public Property Get Have() As IHave End Property Public Function Contain(value As Variant) As Boolean End Function Public Function StartWith(value As Variant) As Boolean End Function Public Function EndWith(value As Variant) As Boolean End Function </code></pre> <p>It is implemented by both the cShould and cShouldNot classes.</p> <p><strong>The IBe interface:</strong></p> <p>This interface contains the following procedures:</p> <pre><code>Public Function GreaterThan(value As Variant) As Boolean End Function Public Function LessThan(value As Variant) As Boolean End Function Public Function EqualTo(value As Variant) As Boolean End Function </code></pre> <p>It is implemented by both the cBe and cNotBe classes.</p> <p><strong>The IHave interface</strong></p> <p>This interface contains the following procedures:</p> <pre><code>Public Function LengthOf(value As Double) As Boolean End Function Public Function MaxLengthOf(value As Double) As Boolean End Function Public Function MinLengthOf(value As Double) As Boolean End Function </code></pre> <p>It is implemented by both the cHave and cNotHave classes.</p> <p><strong>The ISetExpression interface:</strong></p> <p>This interface implements the following procedure:</p> <pre><code>Public Property Set setExpr(value As cExpressions) End Property </code></pre> <p>It is implemented by the cBe, cNotBe, cHave, cNotHave, cShould, and cShouldNot classes.</p> <p><strong>Classes</strong></p> <p><strong>The cFluent class</strong></p> <p>The highest level object in the project. It is responsible for accepting the initial test value. From the client, you can access the cMeta class to access meta-level test properties. And you can use the cShould and cShouldNot classes to access additional classes to be described.</p> <p>This is the code in the cFluent class:</p> <pre><code>Option Explicit Private pShould As cShould Private pShouldSet As ISetExpression Private pShouldNot As cShouldNot Private pShouldNotSet As ISetExpression Private pExpressions As cExpressions Private pMeta As cMeta Private pMetaSet As ISetExpression Public Property Let TestValue(value As Variant) pExpressions.TestValue = value End Property Public Property Get TestValue() As Variant TestValue = pExpressions.TestValue End Property Public Property Get Should() As IShould If pShould Is Nothing Then Set pShould = New cShould End If Set pShouldSet = pShould Set pShouldSet.setExpr = pExpressions Set Should = pShouldSet End Property Public Property Get ShouldNot() As IShould If pShouldNot Is Nothing Then Set pShouldNot = New cShouldNot End If Set pShouldNotSet = pShouldNot Set pShouldNotSet.setExpr = pExpressions Set ShouldNot = pShouldNotSet End Property Public Property Get Meta() As cMeta Set Meta = pMeta End Property Private Sub Class_Initialize() Set pExpressions = New cExpressions Set pMeta = New cMeta Set pExpressions.setMeta = pMeta End Sub </code></pre> <p><strong>The cMeta class</strong></p> <p>This object is responsible for some test-related settings. These are both implemented as properties which both implement setters and getters. The PrintResult property is a Boolean property. If the property is set to true, results of the results are printed in the immediate window. The second is the TestName field. If it’s given a value, that value is printed to the immediate window when the PrintResults property is set to true.</p> <p>This is the code in the cMeta class:</p> <pre><code>Option Explicit Private pPrintResults As Boolean Private pTestName As String Public Property Let TestName(value As String) pTestName = value End Property Public Property Get TestName() As String TestName = pTestName End Property Public Property Let PrintResults(value As Boolean) pPrintResults = value End Property Public Property Get PrintResults() As Boolean PrintResults = pPrintResults End Property </code></pre> <p><strong>The cExpressions class</strong></p> <p>This object is responsible for the evaluation and printing of all expressions. It contains all methods for evaluation. It also uses an instance of cMeta to determine if and how tests are to be printed. And it contains the TestValue value which the tests are to be evaluated against.</p> <p>This is the code in the cExpressions class:</p> <pre><code>Option Explicit Private pTestValue As Variant Private pMeta As cMeta Public Property Let TestValue(value As Variant) pTestValue = value End Property Public Property Get TestValue() As Variant TestValue = pTestValue End Property Public Property Set setMeta(value As cMeta) Set pMeta = value End Property Public Function GreaterThan(OrigVal As Variant, NewVal As Variant, Optional NegateValue As Boolean = False) As Boolean GreaterThan = (OrigVal &gt; NewVal) If pMeta.PrintResults Then If NegateValue Then NegateValue = Not GreaterThan PrintEval (NegateValue) Else PrintEval (GreaterThan) End If End If End Function Public Function LessThan(OrigVal As Variant, NewVal As Variant, Optional NegateValue As Boolean = False) As Boolean LessThan = (OrigVal &lt; NewVal) If pMeta.PrintResults Then If NegateValue Then NegateValue = Not LessThan PrintEval (NegateValue) Else PrintEval (LessThan) End If End If End Function Public Function EqualTo(OrigVal As Variant, NewVal As Variant, Optional NegateValue As Boolean = False) As Boolean EqualTo = (OrigVal = NewVal) If pMeta.PrintResults Then If NegateValue Then NegateValue = Not EqualTo PrintEval (NegateValue) Else PrintEval (EqualTo) End If End If End Function Public Function Contain(OrigVal As Variant, NewVal As Variant, Optional NegateValue As Boolean = False) As Boolean If OrigVal Like &quot;*&quot; &amp; NewVal &amp; &quot;*&quot; Then Contain = True End If If pMeta.PrintResults Then If NegateValue Then NegateValue = Not Contain PrintEval (NegateValue) Else PrintEval (Contain) End If End If End Function Public Function StartWith(OrigVal As Variant, NewVal As Variant, Optional NegateValue As Boolean = False) As Boolean Dim valLength As Long valLength = Len(NewVal) If Left(OrigVal, valLength) = CStr(NewVal) Then StartWith = True End If If pMeta.PrintResults Then If NegateValue Then NegateValue = Not StartWith PrintEval (NegateValue) Else PrintEval (StartWith) End If End If End Function Public Function EndWith(OrigVal As Variant, NewVal As Variant, Optional NegateValue As Boolean = False) As Boolean Dim valLength As Long valLength = Len(NewVal) If Right(OrigVal, valLength) = CStr(NewVal) Then EndWith = True End If If pMeta.PrintResults Then If NegateValue Then NegateValue = Not EndWith PrintEval (NegateValue) Else PrintEval (EndWith) End If End If End Function Public Function LengthOf(OrigVal As Double, NewVal As Double, Optional NegateValue As Boolean = False) As Boolean LengthOf = (Len(CStr(OrigVal)) = NewVal) If pMeta.PrintResults Then If NegateValue Then NegateValue = Not LengthOf PrintEval (NegateValue) Else PrintEval (LengthOf) End If End If End Function Public Function MaxLengthOf(OrigVal As Double, NewVal As Double, Optional NegateValue As Boolean = False) As Boolean MaxLengthOf = (Len(CStr(OrigVal)) &lt;= NewVal) If pMeta.PrintResults Then If NegateValue Then NegateValue = Not MaxLengthOf PrintEval (NegateValue) Else PrintEval (MaxLengthOf) End If End If End Function Public Function MinLengthOf(OrigVal As Double, NewVal As Double, Optional NegateValue As Boolean = False) As Boolean MinLengthOf = (Len(CStr(OrigVal)) &gt;= NewVal) If pMeta.PrintResults Then If NegateValue Then NegateValue = Not MinLengthOf PrintEval (NegateValue) Else PrintEval (MinLengthOf) End If End If End Function Friend Sub PrintEval(ByVal value As Boolean) Dim Result As String Dim TestPassed As Boolean Result = &quot;&quot; TestPassed = value If TestPassed Then Result = &quot;Passed&quot; If pMeta.TestName &lt;&gt; Empty Then Debug.Print pMeta.TestName &amp; Result Else Debug.Print &quot;Passed: &quot; &amp; Result End If Else Result = &quot;Failed&quot; If pMeta.TestName &lt;&gt; Empty Then Debug.Print pMeta.TestName &amp; Result Else Debug.Print &quot;Failed: &quot; &amp; Result End If End If End Sub </code></pre> <p><strong>The cShould class</strong></p> <p>Responsible for creating instances of the Have and Be classes. Also responsible for testing a few methods described in the IShould interface. These methods use methods implemented by the cExpressions object under the hood.</p> <p>This is the code in the cShould class:</p> <pre><code>Option Explicit Implements IShould Implements ISetExpression Private pShouldVal As Variant Private pBe As cBe Private pBeSet As ISetExpression Private pHave As cHave Private pHaveSet As ISetExpression Private pExpressions As cExpressions Public Property Set ISetExpression_setExpr(value As cExpressions) Set pExpressions = value pShouldVal = pExpressions.TestValue End Property Public Property Get IShould_Have() As IHave If pHave Is Nothing Then Set pHave = New cHave End If Set pHaveSet = pHave Set pHaveSet.setExpr = pExpressions Set IShould_Have = pHaveSet End Property Public Property Get IShould_Be() As IBe If pBe Is Nothing Then Set pBe = New cBe End If Set pBeSet = pBe Set pBeSet.setExpr = pExpressions Set IShould_Be = pBeSet End Property Public Function IShould_Contain(value As Variant) As Boolean IShould_Contain = pExpressions.Contain(pShouldVal, value) End Function Public Function IShould_StartWith(value As Variant) As Boolean IShould_StartWith = pExpressions.StartWith(pShouldVal, value) End Function Public Function IShould_EndWith(value As Variant) As Boolean IShould_EndWith = pExpressions.EndWith(pShouldVal, value) End Function </code></pre> <p><strong>The cBe class</strong></p> <p>Responsible for implementing and executing the methods described earlier in the IBe interface. These methods use methods implemented by the cExpressions object under the hood.</p> <p>This is the code in the cBe class:</p> <pre><code>Option Explicit Implements IBe Implements ISetExpression Private pExpressions As cExpressions Private pBeValue As Variant Public Property Set ISetExpression_setExpr(value As cExpressions) Set pExpressions = value pBeValue = pExpressions.TestValue End Property Public Function IBe_GreaterThan(value As Variant) As Boolean IBe_GreaterThan = pExpressions.GreaterThan(pBeValue, value) End Function Public Function IBe_LessThan(value As Variant) As Boolean IBe_LessThan = pExpressions.LessThan(pBeValue, value) End Function Public Function IBe_EqualTo(value As Variant) As Boolean IBe_EqualTo = pExpressions.EqualTo(pBeValue, value) End Function </code></pre> <p><strong>The cHave class</strong></p> <p>Responsible for implementing and executing the methods described earlier in the IHave interface. These methods use methods implemented by the cExpressions object under the hood.</p> <p>This is the code in the cHave class:</p> <pre><code>Option Explicit Implements IHave Implements ISetExpression Private pExpressions As cExpressions Private pHaveVal As Variant Public Property Set ISetExpression_setExpr(value As cExpressions) Set pExpressions = value pHaveVal = pExpressions.TestValue End Property Public Function IHave_LengthOf(value As Double) As Boolean IHave_LengthOf = pExpressions.LengthOf(CDbl(pHaveVal), value) End Function Public Function IHave_MaxLengthOf(value As Double) As Boolean IHave_MaxLengthOf = pExpressions.MaxLengthOf(CDbl(pHaveVal), value) End Function Public Function IHave_MinLengthOf(value As Double) As Boolean IHave_MinLengthOf = pExpressions.MinLengthOf(CDbl(pHaveVal), value) End Function </code></pre> <p><strong>The Not classes (cShouldNot,cNotBe, cNotHave)</strong> Responsible for implementing and executing the methods in their respective interfaces (i.e. IShould, IBe, and IHave) For the implementation of the various methods, they use the same methods in the cExpessions object as their non-negated counterparts. The only difference is that these methods are negated with a not operator to get the opposite result.</p> <p><strong>The cShouldNot class</strong></p> <p>This is the code in the cShouldNot class:</p> <pre><code>Option Explicit Implements IShould Implements ISetExpression Private pNotBe As cNotBe Private pNotBeSet As ISetExpression Private pNotHave As cNotHave Private pNotHaveSet As ISetExpression Private pExpressions As cExpressions Private pShouldNotVal As Variant Public Property Set ISetExpression_setExpr(value As cExpressions) Set pExpressions = value pShouldNotVal = pExpressions.TestValue End Property Public Property Get IShould_Have() As IHave If pNotHave Is Nothing Then Set pNotHave = New cNotHave End If Set pNotHaveSet = pNotHave Set pNotHaveSet.setExpr = pExpressions Set IShould_Have = pNotHaveSet End Property Public Property Get IShould_Be() As IBe If pNotBe Is Nothing Then Set pNotBe = New cNotBe End If Set pNotBeSet = pNotBe Set pNotBeSet.setExpr = pExpressions Set IShould_Be = pNotBeSet End Property Public Function IShould_Contain(value As Variant) As Boolean IShould_Contain = Not pExpressions.Contain(pShouldNotVal, value, True) End Function Public Function IShould_StartWith(value As Variant) As Boolean IShould_StartWith = Not pExpressions.StartWith(pShouldNotVal, value, True) End Function Public Function IShould_EndWith(value As Variant) As Boolean IShould_EndWith = Not pExpressions.EndWith(pShouldNotVal, value, True) End Function </code></pre> <p><strong>The cNotBe class</strong></p> <p>This is the code in the cNotBe class:</p> <pre><code>Option Explicit Implements IBe Implements ISetExpression Private pNotBeValue As Variant Private pBe As IBe Private pExpressions As cExpressions Public Property Set ISetExpression_setExpr(value As cExpressions) Set pExpressions = value pNotBeValue = pExpressions.TestValue End Property Public Function IBe_GreaterThan(value As Variant) As Boolean IBe_GreaterThan = Not pExpressions.GreaterThan(pNotBeValue, value, True) End Function Public Function IBe_LessThan(value As Variant) As Boolean IBe_LessThan = Not pExpressions.LessThan(pNotBeValue, value, True) End Function Public Function IBe_EqualTo(value As Variant) As Boolean IBe_EqualTo = Not pExpressions.EqualTo(pNotBeValue, value, True) End Function </code></pre> <p><strong>The cNotHave class</strong></p> <p>This is the code in the cNotHave class:</p> <pre><code>Option Explicit Implements IHave Implements ISetExpression Private pNotHaveVal As Variant Private pExpressions As cExpressions Public Property Set ISetExpression_setExpr(value As cExpressions) Set pExpressions = value pNotHaveVal = pExpressions.TestValue End Property Public Function IHave_LengthOf(value As Double) As Boolean IHave_LengthOf = Not pExpressions.LengthOf(CDbl(pNotHaveVal), value, True) End Function Public Function IHave_MaxLengthOf(value As Double) As Boolean IHave_MaxLengthOf = Not pExpressions.MaxLengthOf(CDbl(pNotHaveVal), value, True) End Function Public Function IHave_MinLengthOf(value As Double) As Boolean IHave_MinLengthOf = Not pExpressions.MinLengthOf(CDbl(pNotHaveVal), value, True) End Function </code></pre> <p><strong>Final notes</strong></p> <p>After LOTS of changes to the API, I think I finally have a design I’m satisfied with. I’d appreciate any feedback.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T22:20:04.033", "Id": "528169", "Score": "1", "body": "You need lots lots lots more examples demonstrating how your code works and a detailed help file explaining what each of your classes does/ how it should be used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T02:10:11.110", "Id": "528177", "Score": "0", "body": "In terms of testing, I have over 500 lines of code relating to tests. The MetaTests procedure details usage of every method in the API. You can see that in the mTests.bas file I have on github here: https://github.com/b-gonzalez/Fluent-VBA/blob/main/Source/mTests.bas\n\nThe API as used by the client when an instance is created is pretty simple and well explained by the tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T02:17:41.183", "Id": "528178", "Score": "0", "body": "I do agree that some of the methods in cExpressions can be explained in better detail. So I'll focus on adding comments detailing what those methods do." } ]
[ { "body": "<p>Really great stuff!</p>\n<p><strong>PredeclaredIds</strong></p>\n<p>It might be useful to consider declaring many of your classes with their <code>VB_PredeclaredId</code> attribute set to <code>True</code>. Doing so makes each class essentially 'static' (a default instance will always exist). The <em>static</em> instance can act as a class factory and enforce the required <code>cExpressions</code> instance/dependency in a single statement. I would point you <a href=\"https://rubberduckvba.wordpress.com/2016/01/11/oop-in-vba-immutability-the-factory-pattern/\" rel=\"nofollow noreferrer\">here</a> for a more in-depth explanation.</p>\n<p>As an example, this would allow changing:</p>\n<pre><code>'From the cFluent class\nPublic Property Get Should() As IShould\n If pShould Is Nothing Then\n Set pShould = New cShould\n End If\n Set pShouldSet = pShould\n Set pShouldSet.setExpr = pExpressions\n Set Should = pShouldSet\nEnd Property\n</code></pre>\n<p>To become:</p>\n<pre><code>Public Property Get Should() As IShould\n If pShould Is Nothing Then\n Set pShould = cShould.Create(pExpressions)\n End If\n Set Should = pShould\nEnd Property\n</code></pre>\n<p>The <code>cShould</code> class would need a new <code>Public</code> factory/constructor function like:</p>\n<pre><code>Public Function Create(ByVal testExpression As cExpressions) As IShould\n Dim newShould As ISetExpression\n Set newShould = new cShould\n Set newShould.setExpr = testExpression\n Set Create = newShould\nEnd Function\n</code></pre>\n<p><strong>One more class?</strong></p>\n<p>When considering the example:</p>\n<pre><code>Dim Result as cFluent\nSet Result = new cFluent\nResult.TestValue = ReturnsFive()\nResult.Should.Be.EqualTo(5)\n</code></pre>\n<p>It seemed to me that setting the <code>TestValue</code> property detracted a little bit from the general 'fluency' of the API.</p>\n<p>Initializing <code>cFluent</code> with a test result seems to be largely driven by limitations of VBA compared to advantages of other languages. For example, in C#, Extension methods allows expressions like the one below where the test result is part of the fluent expression (the example is from <a href=\"https://fluentassertions.com/introduction\" rel=\"nofollow noreferrer\">here</a> ):</p>\n<pre><code>string actual = &quot;ABCDEFGHI&quot;;\nactual.Should().StartWith(&quot;AB&quot;).And.EndWith(&quot;HI&quot;).And.Contain(&quot;EF&quot;).And.HaveLength(9);\n</code></pre>\n<p>Although VBA does not support Extension methods, it might also be interesting to explore adding one additional layer prior to <code>cFluent</code>, like <code>cFluentTestResult</code>. Doing so could result expressions like:</p>\n<pre><code>Dim testResult as cFluentTestResult\nSet testResult = new cFluentTestResult\ntestResult.Of(ReturnsFive()).Should.Be.EqualTo(5)\n</code></pre>\n<p>The test result is simply passed from class to class. Consequently, <code>cFluentTestResult</code> can be a stateless class that simply initiates the assert expression. So, by setting <code>cFluentTestResult's</code> VB_PredeclaredId attribute to <code>True</code>, the expression can become as terse as:</p>\n<pre><code>cFluentTestResult.Of(ReturnsFive()).Should.Be.EqualTo(5)\n</code></pre>\n<p>Using this additional layer with the C# example above</p>\n<pre><code>Dim actual As String\nactual = &quot;ABCDEFGHI&quot;\ncFluentTestResult.Of(actual).Should().StartWith(&quot;AB&quot;).And.EndWith(&quot;HI&quot;).And.Contain(&quot;EF&quot;).And.HaveLength(9);\n</code></pre>\n<p>Not quite as nice as C#, but now the test result is also built into the assert expression...food for thought.</p>\n<p>I'll also comment that the <code>cExpressions</code> class will need some further work especially in the <code>EqualTo</code> function. Passing values around as <code>Variant</code> is necessary because VBA supports neither generics nor method overloads. Still, comparing two <code>Variant</code> values using the <code>=</code> operator is insufficient in many cases. Comparisons depend greatly on the specific Type involved. As an example, when comparing <code>Doubles</code>, some type of tolerance parameter is needed. In some cases 4.6 = 4.56 returning <code>True</code>, is <em>good enough</em> ... and sometimes it's not. All the actual = expected comparisons in <code>cExpressions</code> need to be reviewed carefully for all potential VBA Types that can be encountered.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T17:45:13.657", "Id": "528465", "Score": "1", "body": "Minor point, but would probably go for `.AndAlso` in the API to avoid clashing with the protected keyword and to suggest you can short circuit the API by mimicking VB.Net naming - i.e. if one assert fails they all do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-18T00:31:58.133", "Id": "528668", "Score": "0", "body": "This is really great feedback. I'll look into implementing some of your suggestions." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T13:42:54.110", "Id": "267961", "ParentId": "267836", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-09T19:21:59.147", "Id": "267836", "Score": "3", "Tags": [ "vba" ], "Title": "A fluent unit testing framework in VBA" }
267836
<p>I have a little project, <a href="https://github.com/UltiRequiem/chuy" rel="nofollow noreferrer">chuy</a>, which is basically a copy of <a href="https://en.wikipedia.org/wiki/Make_(software)" rel="nofollow noreferrer">Make</a>.</p> <p>By request of users I have added support for <code>toml</code> configuration, since originally it only accepted <code>json</code>.</p> <p>The files that <code>chuy</code> have to check are: <code>[&quot;chuy.json&quot;,&quot;chuy.toml&quot;,&quot;pyproject.toml&quot;]</code>.</p> <p>The order of priority is the same order in which they are placed. (If it is true that <code>chuy.json</code> exists, it no longer matters whether<code> chuy.toml</code> or <code>pyproject.toml</code> exist.)</p> <p>So I wrote:</p> <pre class="lang-py prettyprint-override"><code>def get_config_file() -&gt; str: try: with open(&quot;chuy.json&quot;, mode=&quot;r&quot;, encoding=&quot;utf-8&quot;): return &quot;json&quot; except FileNotFoundError: try: with open(&quot;pyproject.toml&quot;, mode=&quot;r&quot;, encoding=&quot;utf-8&quot;): return &quot;pyproject&quot; except FileNotFoundError: try: with open(&quot;chuy.toml&quot;, mode=&quot;r&quot;, encoding=&quot;utf-8&quot;): return &quot;toml&quot; except FileNotFoundError: raise BaseException(&quot;I can't find your configuration file :(&quot;) </code></pre> <p>Which is horrible, some refactor later:</p> <pre class="lang-py prettyprint-override"><code>def get_config_file(posible_config_files = [&quot;chuy.json&quot;, &quot;chuy.toml&quot;, &quot;pyproject.toml&quot;])-&gt; str: for file in posible_config_files: try: with open(file, mode=&quot;r&quot;, encoding=&quot;utf-8&quot;): return file except FileNotFoundError: continue </code></pre> <p>Which is a bit better, but I still don't think it's a good solution.</p> <p>Any ideas?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T00:47:22.743", "Id": "528175", "Score": "2", "body": "It's preferable to use `pathlib` to find files. Read through [the pathlib documentation](https://pymotw.com/3/pathlib/) to understand some of the options. e.g. `p = pathlib.Path('touched')` `if p.exists():` etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T02:54:05.063", "Id": "528179", "Score": "3", "body": "@C.Harley please add an answer instead of a comment. Refer to the section **When _shouldn't_ I comment?** on [Comment everywhere](https://codereview.stackexchange.com/help/privileges/comment)." } ]
[ { "body": "<ul>\n<li>Don't <code>raise BaseException</code></li>\n<li>Typo: <code>posible</code> -&gt; <code>possible</code></li>\n<li>Don't type-hint a <code>list</code>; instead use <code>List[str]</code> in the case of your <code>posible_config_files</code></li>\n<li>Consider making a reusable solution that separates &quot;all existing config files&quot; from &quot;the first existing config file&quot;</li>\n</ul>\n<h2>Suggested</h2>\n<pre class=\"lang-py prettyprint-override\"><code>from pathlib import Path\nfrom typing import Iterable\n\n\ndef config_files() -&gt; Iterable[Path]:\n for name in (&quot;chuy.json&quot;, &quot;chuy.toml&quot;, &quot;pyproject.toml&quot;):\n path = Path(name)\n if path.is_file():\n yield path\n\n\ndef config_file() -&gt; Path:\n try:\n return next(config_files())\n except StopIteration:\n raise FileNotFoundError('No configuration file was found')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T16:50:27.380", "Id": "267867", "ParentId": "267841", "Score": "3" } }, { "body": "<p>Thanks Eliaz for your question, I'll give you a few pointers to help you. These are pretty standard boiler-plate code patterns in any Python project. For example:</p>\n<ul>\n<li>For configuration files, you should utilise ConfigParser.</li>\n<li>Using argparse for user input or default choices like with unattended script running</li>\n<li>Using logging to help figure out what happens during execution (maybe it loaded a different file to what they expected?).</li>\n</ul>\n<p>You might be wondering why I'm giving all these additions to your question - and that's because your question actually is very common as a software developer.</p>\n<p>If you try using this in your github project, you will see how it can remove a lot of code used for printing status updates (such as changing the logging level for screen (warning/info) verses for file (debug)) and argparse and configparser makes life easier to manage input and standardise config files.</p>\n<p>This will allow use-cases where they have two or more config files, but they wish to use a specific config file for a particular run/exec.</p>\n<h1>Entry Point</h1>\n<p>This is the start of the logic for your script, and it helps other coders to understand what your program does, and how it does it. Let's establish the program flow to make it clear to the readers of your code what the script is doing:</p>\n<pre><code>if __name__ == &quot;__main__&quot;:\n log = activate_logging()\n log.debug('Log activated')\n params = parse_command_line()\n log.debug(f&quot;Received these options: {params.file_list}&quot;)\n config_file = load_first_config(params)\n log.debug(f&quot;Selected config file: {config_file}&quot;)\n</code></pre>\n<p>That makes it quite clear what it's attempting to do. Enabling logging, reading the parameters from the command line, then loading the appropriate config file.</p>\n<h1>Logging</h1>\n<p>I've found that using logging rather than step-by-step debugging is faster because the system will tell you what it's doing (as long as you write the correct statements). It saves a lot of time, and removes the questions like &quot;how did that happen?&quot;\nThis is a standard logging pattern, and it will log to the screen when it runs. If you refer to the Python documentation, you can modify this to make it log to a file and screen, or only to a file.</p>\n<pre><code>def activate_logging():\n logger = logging.getLogger()\n handler = logging.StreamHandler()\n formatter = logging.Formatter(&quot;%(asctime)s %(name)-12s %(levelname)-8s %(message)s&quot;)\n handler.setFormatter(formatter)\n logger.addHandler(handler)\n logger.setLevel(logging.DEBUG)\n return logger\n</code></pre>\n<h1>Parsing Choices</h1>\n<p>One way to get user input is via the command line, but you can have some defaults, like what you've done. So we use <code>argparse</code> to handle user choices or make our own selection from the default items we specified. Here is another standard coding pattern:</p>\n<pre><code>def parse_command_line():\n desc = &quot;Chuy: Set alias to long commands and speed up your workflow.&quot;\n parser = argparse.ArgumentParser(description=desc)\n\n parser.add_argument(&quot;-f&quot;, &quot;--file&quot;, action=&quot;store&quot;, dest=&quot;file_list&quot;,\n type=str, nargs=&quot;*&quot;,\n default=[&quot;chuy.json&quot;, &quot;pyproject.toml&quot;, &quot;chuy.toml&quot;],\n help=&quot;Examples: -i chuy.json pyproject.toml, -i chuy.toml&quot;)\n args = parser.parse_args()\n log.debug(f&quot;List of items: {args.file_list}&quot;)\n return args\n</code></pre>\n<p>argparse is great because it can do a lot of boilerplate things such as automatic help:</p>\n<pre><code>ch@ubuntu:~/PycharmProjects/testing$ python chuy.py -h\n2021-09-11 03:22:19,612 root DEBUG Log activated\nusage: chuy.py [-h] [-f [FILE_LIST [FILE_LIST ...]]]\n\nChuy: Set alias to long commands and speed up your workflow.\n\noptional arguments:\n -h, --help show this help message and exit\n -f [FILE_LIST [FILE_LIST ...]], --file [FILE_LIST [FILE_LIST ...]]\n Examples: -f chuy.json pyproject.toml, -f chuy.toml\n</code></pre>\n<h1>Configuration Selection</h1>\n<p>Finally, we use <code>configparser</code> to handle looking for the choices, and returning the first choice.</p>\n<pre><code>def load_first_config(args):\n parser = ConfigParser()\n candidates = args.file_list\n found = parser.read(candidates)\n missing = set(candidates) - set(found)\n log.debug(f&quot;Found config files: {found}&quot;)\n log.debug(f&quot;Missing files : {missing}&quot;)\n if found:\n return found[0]\n return None\n</code></pre>\n<p>If you're using an <code>[ini]</code> style config file, configparser can also read those and return a config object (more information can be found in the documentation).</p>\n<h1>Running The Code</h1>\n<p>Including the imports at the top of the file:</p>\n<pre><code>import logging\nimport argparse\nfrom configparser import ConfigParser\n</code></pre>\n<p>We can then run it:</p>\n<pre><code>2021-09-11 03:19:51,510 root DEBUG Log activated\n2021-09-11 03:19:51,511 root DEBUG List of items: ['chuy.json', 'pyproject.toml', 'chuy.toml']\n2021-09-11 03:19:51,511 root DEBUG Received these options: ['chuy.json', 'pyproject.toml', 'chuy.toml']\n2021-09-11 03:19:51,511 root DEBUG Found config files: []\n2021-09-11 03:19:51,511 root DEBUG Missing files : ['chuy.json', 'chuy.toml', 'pyproject.toml']\n2021-09-11 03:19:51,511 root DEBUG Selected config file: None\n</code></pre>\n<p>Now we create a dummy file chuy.toml (<code>touch chuy.toml</code>) and re-run the app:</p>\n<pre><code>2021-09-11 03:20:04,702 root DEBUG Log activated\n2021-09-11 03:20:04,703 root DEBUG List of items: ['chuy.json', 'pyproject.toml', 'chuy.toml']\n2021-09-11 03:20:04,703 root DEBUG Received these options: ['chuy.json', 'pyproject.toml', 'chuy.toml']\n2021-09-11 03:20:04,703 root DEBUG Found config files: ['chuy.toml']\n2021-09-11 03:20:04,703 root DEBUG Missing files : ['chuy.json', 'pyproject.toml']\n2021-09-11 03:20:04,703 root DEBUG Selected config file: chuy.toml\n</code></pre>\n<p>We can also use command lines:</p>\n<pre><code>ch@ubuntu:~/PycharmProjects/testing$ python chuy.py -f pyproject.toml\n2021-09-11 03:32:00,024 root DEBUG Log activated\n2021-09-11 03:32:00,025 root DEBUG List of items: ['pyproject.toml']\n2021-09-11 03:32:00,025 root DEBUG Received these options: ['pyproject.toml']\n2021-09-11 03:32:00,025 root DEBUG Found config files: []\n2021-09-11 03:32:00,025 root DEBUG Missing files : {'pyproject.toml'}\n2021-09-11 03:32:00,026 root DEBUG Selected config file: None\n</code></pre>\n<p>I hope this helps - please drop any questions below in the comments. Cheers!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T00:57:22.867", "Id": "267878", "ParentId": "267841", "Score": "1" } } ]
{ "AcceptedAnswerId": "267878", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T00:03:36.683", "Id": "267841", "Score": "2", "Tags": [ "python", "python-3.x", "array", "file", "file-system" ], "Title": "Send an array of files and return the first one that exists" }
267841
<p>Need help to optimize the following code for lower time complexity:</p> <pre><code>arrayMultiply(ipnArray: number[]): number[] { let outArray = []; for (let i=0; i&lt;ipnArray.length; i++){ let currentNum = ipnArray[i]; let newArr = ipnArray.filter(nub =&gt; nub !== currentNum); let tempValue; for (let j=0; j&lt;newArr.length; j++ ){ if (tempValue) { tempValue = tempValue * newArr[j]; }else{ tempValue = newArr[j]; } } outArray.push(tempValue); } return outArray; } </code></pre> <p>This method takes an input of an array of numbers and returns the array where each element is a product of the other elements even if it has duplicate values. For Example: [1,2,3] becomes [6,3,2] Example 2: [1, 2, 2, 3] will be [12, 6, 6, 4]</p> <p>Edit: My bad. the return should be [6, 3, 2] instead of the previous typo.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T17:55:56.387", "Id": "528212", "Score": "0", "body": "I'm sorry, but your script does not return `[12, 6, 6, 4]` for `[1, 2, 2, 3]`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:03:44.397", "Id": "529377", "Score": "0", "body": "The filter function will filter out all instances of an array value. So if your array is [12,2,2,4], eventually filter will return the array [12,4]. Did you mean for this to happen?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:57:48.343", "Id": "529385", "Score": "0", "body": "Admittedly, I'm not sure how to interpret this problem." } ]
[ { "body": "<p>I haven't written JavaScript in years, so won't attempt a coded response.</p>\n<p>If you ran your code and showed us the output, there wouldn't be typos, and it would show that you've actually tested your code.</p>\n<p>Your solution unnecessarily creates temporary arrays, when it could simply omit the relevant cell from the calculation. That would speed things up a little.</p>\n<p>(Note: I'm not sure your filter would work correctly with repeated values. If I understand it, it would change the results of your second example. Edit: I've checked and I'm fairly confident - your filter discards duplicated values, so your second example doesn't work.)</p>\n<p>However, I think we can do this in two passes, provided the numbers are small enough that we won't hit arithmetic overflow (and that's a potential problem with any solution).</p>\n<p>If P is the product of all values in ipnArray, then outArray[n] is P/ipnArray[n]. Two simple passes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T06:13:17.793", "Id": "267849", "ParentId": "267846", "Score": "0" } }, { "body": "<p>The solution you proposed consisted of two nested loops: First loop iterates <code>n</code> time. Inside that, you have a <code>filter</code> and a second loop for all the elements except the <code>currentNum</code>, which is <code>n - 1</code> time. Therefore time complexity is <span class=\"math-container\">\\$\\mathcal{O}(n ( (n - 1)+n )) = \\mathcal{O}(n^2)\\$</span></p>\n<p>If you want to iterate over all the elements in an array except for one, a better approach can be skipping the loop with <code>continue</code> when index counter is equal to that index.</p>\n<p>An alternative solution for this problem can be based on the product of all numbers in the list. &quot;Each element is the product of all the elements except itself&quot;, means by dividing each element from the total product you can eliminate the effect of current element in the product.\nThis approach will be <span class=\"math-container\">\\$\\mathcal{O}(n + n) = \\mathcal{O}(n)\\$</span>: one iteration over all elements to get the product and another to calculate the values.</p>\n<p>In case you want to return a new array with the results (just as what it states in the function signature), space complexity will be of <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>, but you can modify the same array, therefore <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span>.</p>\n<p><strike>One special case for this scenario is zero: When the product of all elements in zero, return an array with the same length of input as zero.</strike> Note that it will only work for an array of non-zero elements.</p>\n<p>This is what it would look like</p>\n<pre><code>function nonZeroArrayMultiply(list: number[]): number[] {\n const allProd = list.reduce((prod, cur) =&gt; prod * cur)\n let result = []\n for (let n of list)\n result.push(allProd / n)\n return result\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T09:51:40.950", "Id": "528185", "Score": "0", "body": "How well does this approach work in the presence of zeros?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T16:05:14.753", "Id": "528202", "Score": "0", "body": "@mdfst13 Thank you for your comment. This was the first type I was contributing here, and apparently my answer wasn't exactly the way it was expected to be. I completely edited my answer to comply with CodeReview community guidelines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T16:06:21.133", "Id": "528203", "Score": "0", "body": "@TobySpeight If the result of multiplication is zero, return an array with the same length filled with zeros." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T07:38:53.260", "Id": "528832", "Score": "0", "body": "I don't see how this version does that; am I missing something?. If that _is_ what it does (please explain what I'm missing), then it's wrong anyway (when exactly one input element is zero, then the corresponding output entry should be non-zero)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-21T08:51:25.043", "Id": "528844", "Score": "0", "body": "@TobySpeight You're right, this does not work for arrays with zeros. We can consider the special case of zero with counting them (More than one zero, return array of zeros, if only one zero, return product of all for this index), but it won't be a pleasant solution. Other solutions do not have this issue. I will update the answer. Thanks." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T07:06:36.683", "Id": "267851", "ParentId": "267846", "Score": "1" } }, { "body": "<p>That takes quadratic time. I'd say the intended/standard way is to compute prefix products and suffix products and for any number, multiply its prefix product with its suffix product. That's linear time. And unlike the divide-the-whole-product-by-the-number approach it doesn't have an issue with zeros or with the whole-array product being too large.</p>\n<p>Example:</p>\n<pre><code>Input: [2, 3, 5, 7]\nPrefix products: [1, 2, 6, 30] (computed forwards)\nSuffix products: [105, 35, 7, 1] (computed backwards)\nResult: [1*105, 2*35, 6*7, 30*1]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T14:52:50.293", "Id": "529376", "Score": "0", "body": "Hi. I've been doing this exact problem. Could you please explain how you would do this in TypeScript?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:34:19.690", "Id": "529381", "Score": "0", "body": "@moonman239 I'd probably do it the same way. Is there something special about TypeScript? I'm not familiar with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T15:56:38.300", "Id": "529384", "Score": "0", "body": "I guess what I'm wondering is - what's a prefix product and suffix product, and how do you compute it? Are you saying that OP really can't improve the time complexity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:00:33.697", "Id": "529386", "Score": "0", "body": "@moonman239 Hmm? In my answer I say they *can* improve the time complexity (and how). Prefix product is the product of a prefix. See [this](https://en.wikipedia.org/wiki/Prefix_sum#Scan_higher_order_function) for example." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:09:42.920", "Id": "529387", "Score": "0", "body": "OK. I think I'm doing something like that already: function replaceWithProduct(array: number[])\n{\n for (let i=0; i<array.length; i++)\n {\n let arrayWithoutElement = array.slice(0,i).concat(array.slice(i+1,array.length));\n array[i] = productOfArray(arrayWithoutElement);\n }\n return array;\n}" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-27T16:22:18.597", "Id": "529389", "Score": "0", "body": "@moonman239 Doesn't look like it. Looks like brute force instead. I added an example to the answer now." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T09:14:23.150", "Id": "267853", "ParentId": "267846", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T04:27:18.930", "Id": "267846", "Score": "1", "Tags": [ "javascript", "performance", "array", "typescript" ], "Title": "Replace array values with product of all other values" }
267846
<p>In my learning course, I've implemented a message queue to which data gets pushed by some thread and later gets processed by some other thread. My implementation isn't that efficient as it involves creating minimum three copies of the same data which is not acceptable. So is there any way to avoid these unnecessary copies? This is my sample working code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;list&gt; #include &lt;thread&gt; #include &lt;mutex&gt; #include &lt;condition_variable&gt; struct Data { std::string topic {}; std::string msg {}; Data(const std::string&amp; topic, const std::string&amp; msg) { this-&gt;topic = topic; this-&gt;msg = msg; } }; std::mutex net_mutex {}; std::mutex pro_mutex {}; std::condition_variable net_cond_var {}; std::condition_variable pro_cond_var {}; std::list&lt;Data&gt; net_list; std::list&lt;Data&gt; pro_list; void pro_thread() { while (true) { std::unique_lock&lt;std::mutex&gt; ul(pro_mutex); pro_cond_var.wait(ul, [] () { return not pro_list.empty(); }); Data data = pro_list.front(); // third copy pro_list.pop_front(); ul.unlock(); // do processing } } void relay_thread() { while (true) { // relays received network data to different processing threads based upon topic std::unique_lock&lt;std::mutex&gt; ul(net_mutex); net_cond_var.wait(ul, [] () { return not net_list.empty(); }); Data data = net_list.front(); // second copy net_list.pop_front(); ul.unlock(); if (data.topic == &quot;A&quot;) { // push data into pro_list queue pro_mutex.lock(); pro_list.emplace_back(data); pro_cond_var.notify_one(); pro_mutex.unlock(); } } } void net_thread() { while (true) { // receives data from socket and pushes into net_list queue Data data(&quot;A&quot;, &quot;Hello, world!&quot;); net_mutex.lock(); net_list.emplace_back(data); // first copy net_cond_var.notify_one(); net_mutex.unlock(); } } int main() { std::thread net(net_thread); std::thread relay(relay_thread); std::thread pro(pro_thread); net.join(); relay.join(); pro.join(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T10:14:22.753", "Id": "528187", "Score": "0", "body": "This doesn't really seem to do much? (Well, it crashes due to popping from the wrong list in `relay_thread`). Otherwise this seems like a question about how to do something (avoid copies), which isn't really on topic here: https://codereview.stackexchange.com/help/on-topic" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T10:15:35.543", "Id": "528188", "Score": "0", "body": "To give you a hint though, you should use `std::move`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T10:51:30.570", "Id": "528190", "Score": "0", "body": "Sorry for that, it was a typo. I've corrected it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T11:01:51.373", "Id": "528191", "Score": "0", "body": "I've a doubt since `struct Data` doesn't implement neither move constructor nor move assignment operator. Does `std::move` make any sense?" } ]
[ { "body": "<h1>Create a <code>class</code> that implements the thread-safe queue</h1>\n<p>Your program has two queues, and already you see a lot of code duplication. It would be great to create a class that implements everything necessary for a thread-safe queue. For example:</p>\n<pre><code>template &lt;typename T&gt;\nclass ThreadSafeQueue {\n std::mutex mutex;\n std::condition_variable cond_var;\n std::queue&lt;T&gt; queue;\n\npublic:\n void push(T&amp;&amp; item) {\n {\n std::lock_guard lock(mutex);\n queue.push(item);\n }\n\n cond_var.notify_one();\n }\n\n T&amp; front() {\n std::unique_lock lock(mutex);\n cond_var.wait(lock, [&amp;]{ return !queue.empty(); });\n return queue.front();\n }\n\n void pop() {\n std::lock_guard lock(mutex);\n queue.pop(item);\n }\n};\n</code></pre>\n<p>This way, the rest of the code now simplifies a lot:</p>\n<pre><code>ThreadSafeQueue&lt;Data&gt; net_queue;\nThreadSafeQueue&lt;Data&gt; pro_queue;\n...\nvoid relay_thread() {\n while (true) {\n Data &amp;data = net_queue.front(); // no copy, just a reference\n\n if (data.topic == &quot;A&quot;) {\n pro_queue.push(std::move(data)); // move the data to the other queue\n }\n\n net_queue.pop();\n }\n}\n</code></pre>\n<p>There are a few other improvements I've put into the above code, which I'll discuss below.</p>\n<h1>Use <code>std::queue</code> for queues</h1>\n<p>The STL provides a type for queues: <a href=\"https://en.cppreference.com/w/cpp/container/queue\" rel=\"nofollow noreferrer\"><code>std::queue</code></a>. Prefer to use that one over a &quot;raw&quot; <code>std::list</code> or other container. In particular, it enforces the properties of a queue: things can only be pushed in one end and popped from the other end.</p>\n<h1>Don't <code>pop()</code> a queue item until after you used it</h1>\n<p>In order to avoid copies, don't pop items from the queue until you've fully used them. <a href=\"https://en.cppreference.com/w/cpp/container/queue/front\" rel=\"nofollow noreferrer\"><code>front()</code></a> returns a reference, so you can access the item that way. The only drawback of this approach is that this only allows one consumer thread per queue.</p>\n<p>Alternatively, you could <code>std::move()</code> the item out of the queue, like so:</p>\n<pre><code>Data data = std::move(pro_list.front()); // move constructor used if available\n</code></pre>\n<p>Or if you use a <code>std::list</code> to store the queue items, you could use <a href=\"https://en.cppreference.com/w/cpp/container/list/splice\" rel=\"nofollow noreferrer\"><code>splice()</code></a> to move a list entry to a temporary list; this will even work with types that can neither be copied nor moved. For example:</p>\n<pre><code>std::list&lt;Data&gt; temp_list;\n\n{\n std::unique_lock lock(pro_mutex);\n pro_cond_var.wait(...);\n temp_list.splice(temp_list.begin(), pro_list, pro_list.begin());\n // no need to pop()\n}\n\nData &amp;data = temp_list.front();\n// do processing\n</code></pre>\n<h1>Call <code>notify_one()</code> without the mutex locked</h1>\n<p>It is generally more efficient to call <a href=\"https://en.cppreference.com/w/cpp/thread/condition_variable/notify_one\" rel=\"nofollow noreferrer\"><code>notify_one()</code></a> without the mutex being locked, otherwise the notified thread could be woken and immediately attempt to lock the still locked mutex as well.</p>\n<h1>Ensure the threads can terminate gracefully</h1>\n<p>Your <code>main()</code> function calls <code>join()</code> on all the threads it started, which is good, but unfortunately this means it will wait forever, since the threads themselves never return. In a real application you want to be able to terminate those threads gracefully. This requires waking up the threads that are blocked on <code>cond_var.wait()</code>, and having some way to signal that they should exit their loop, either using a separate flag, or by pushing a special item to the queue that signals that they should exit their loop.</p>\n<h1>Avoid manual locking of mutexes</h1>\n<p>I see you call <code>net_mutex.lock()</code> and <code>net_mutex.unlock()</code> in your code, but it's safer to use <code>std::lock_guard()</code>. You can limit the scope of the lock by using braces, like so:</p>\n<pre><code>Data data(&quot;A&quot;, &quot;Hello, world!&quot;);\n\n{\n std::lock_guard lock(net_mutex);\n net_list.emplace_back(data);\n}\n\nnet_cond_var.notify_one();\n</code></pre>\n<h1>When to use <code>emplace_back()</code></h1>\n<p>In see this in your code:</p>\n<pre><code>Data data(&quot;A&quot;, &quot;Hello, world!&quot;);\n...\nnet_list.emplace_back(data); // first copy\n</code></pre>\n<p>Indeed, <code>emplace_back()</code> makes a copy here. There's nothing special <code>emplace_back()</code> can do here, you can call <code>push_back()</code> instead and it would be just as efficient. If the <code>Data</code> type has a move constructor, then <code>push_back(std::move(data))</code> is also just as efficient as <code>emplace_back(std::move(data))</code>. Where <code>emplace_back()</code> shines is when you use it to construct the item directly in place, like so:</p>\n<pre><code>net_list.emplace_back(&quot;A&quot;, &quot;Hello, world!&quot;);\n</code></pre>\n<p>This is the most efficient way to add an item to the list, as not having to move at all is faster than moving (and of course much faster than copying).</p>\n<h1>Implicitly generated move constructors</h1>\n<p>From the comments:</p>\n<blockquote>\n<p>I've a doubt since <code>struct Data</code> doesn't implement neither move constructor nor move assignment operator. Does <code>std::move</code> make any sense?</p>\n</blockquote>\n<p>Yes, the compiler can generate implicit constructors, including <a href=\"https://stackoverflow.com/questions/13344800/can-a-move-constructor-be-implicit\">implicit move constructors</a>. Whether this is done depends on whether you did not declare or delete any copy or move constructors/assignment operators yourself, and whether all the member functions have move constructors (obviously). Your <code>struct Data</code> satisfies all the requirements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T18:49:47.877", "Id": "528213", "Score": "2", "body": "Just to add a little explanation on not locking mutexes manually: If you lock/unlock them manually, and any code throws an exception while it is locked, the mutex is left locked -- almost never the desired behavior. You could wrap it in a try block, but that's hard to remember and ugly. The C++ preferred approach is what G. Sliepen recommends, `lock_guard`. In the case of an exception, it is destroyed as the stack unwinds, having the desired effect *and* there is no way to make a mistake, as its only one line rather than two separate ones." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T12:12:02.330", "Id": "267859", "ParentId": "267847", "Score": "8" } } ]
{ "AcceptedAnswerId": "267859", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T04:56:01.837", "Id": "267847", "Score": "5", "Tags": [ "c++", "queue" ], "Title": "Thread-safe message queue" }
267847
<p>Challenge: find the top three most frequently used words in a string. Only imports from the <code>base</code> package are allowed (source: <a href="https://www.codewars.com/kata/51e056fe544cf36c410000fb" rel="nofollow noreferrer">codewars</a>)</p> <p>I'm looking for feedback on (1) readability, and (2) performance<br></p> <ul> <li>Was folding the string into &quot;frequency map&quot; a good choice?</li> <li>I have several small functions that I compose together. Are these abstraction layers helping or hurting readability?</li> <li>How are my functions names?</li> <li>Does the <code>base</code> package have any libraries that would make this code significantly easier to write?</li> <li>Could I benefit from using more pointfree style?</li> </ul> <pre><code>import qualified Data.Map as Map import Data.List import Data.Function import Data.Char import Data.Maybe top3 :: [Char] -&gt; [[Char]] top3 str = let wordFrequencyMap = foldr (Map.alter increment) Map.empty (normalizedWords str) sortedWordFrequencies = sortBy reverseBySecond (Map.toList wordFrequencyMap) in map fst (take 3 sortedWordFrequencies) where normalizedWords = filter containsAtLeastOneAlphaNumericChar . lowerCaseWords . map isLegalChar containsAtLeastOneAlphaNumericChar w = find isAlphaNum w /= Nothing lowerCaseWords = map (map toLower) . words isLegalChar c = if isAlphaNum c || c =='\'' then c else ' ' reverseBySecond x y = if snd x &lt; snd y then GT else LT increment Nothing = Just 1 increment (Just x) = Just (x + 1) </code></pre>
[]
[ { "body": "<p>I'd write</p>\n<pre><code>increment = (&lt;|&gt; (Just 1)) . fmap (+1)\n</code></pre>\n<p>You can probably also write</p>\n<pre><code>reverseBySecond = flip $ comparing snd\n</code></pre>\n<p>if you don't mind getting <code>EQ</code> for equal pairs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T00:41:54.180", "Id": "528229", "Score": "0", "body": "I like the use of `<|>`, I've never used it. I'll add it to my toolkit." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T09:08:52.643", "Id": "267852", "ParentId": "267848", "Score": "1" } }, { "body": "<p>i had already answered this from within my <a href=\"http://lynx.browser.org/\" rel=\"nofollow noreferrer\">http://lynx.browser.org/</a> unbloated hypertext browser within superfast <a href=\"http://www.washington.edu/alpine/\" rel=\"nofollow noreferrer\">http://www.washington.edu/alpine/</a> mail commander but <a href=\"http://stackexchange.com/\">http://stackexchange.com/</a> does not behave like written from humans for humans and rather unfortunately insists on a robot captcha unsolvable on a braille typewriter.</p>\n<p>i will recreate my first intuitive answer which goes more lambda calculus and less hoare calculus than your code to try</p>\n<pre><code>top3=map head.take 3.reverse.sortBy(comparing length).group.sort.words\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T08:31:32.190", "Id": "267885", "ParentId": "267848", "Score": "-1" } }, { "body": "<p>The frequency map is a good way to solve this. A nice trick to generate the frequency map is by creating a list of singleton maps and merging them all together:</p>\n<pre><code>wordFrequencyMap = Map.unionsWith (+) $ map (\\x -&gt; singleton x 1) $ normalizedWords str\n</code></pre>\n<p>I think this way is a bit more declarative which is what we aim for in Haskell.</p>\n<hr />\n<p>You could simplify:</p>\n<pre class=\"lang-hs prettyprint-override\"><code> containsAtLeastOneAlphaNumericChar w = find isAlphaNum w /= Nothing\n</code></pre>\n<p>to</p>\n<pre class=\"lang-hs prettyprint-override\"><code> containsAtLeastOneAlphaNumericChar = any isAlphaNum\n</code></pre>\n<p>At that point you might find it clearer to inline the definition:</p>\n<pre class=\"lang-hs prettyprint-override\"><code> normalizedWords = filter (any isAlphaNum) . lowerCaseWords . map isLegalChar\n</code></pre>\n<hr />\n<p>To sort in descending order, use <code>Down</code> from <code>Data.Ord</code>, this will reverse the ordering of whatever is passed into it, e.g. <code>Down 1 &gt; Down 2</code> is True.</p>\n<pre class=\"lang-hs prettyprint-override\"><code> sortedWordFrequencies = sortOn (Down . snd) (Map.toList wordFrequencyMap)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-11-26T08:30:41.747", "Id": "270409", "ParentId": "267848", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T05:38:39.237", "Id": "267848", "Score": "1", "Tags": [ "strings", "haskell", "functional-programming", "reinventing-the-wheel" ], "Title": "Word frequency finder" }
267848
<p>I've started to write my first APL project, so I would like to have general feedbacks on coding style, file organization, error handling and defensive programming, performance improvements, etc.</p> <p>The PNM format is handled by the following two functions:</p> <pre><code> ∇img←readpnm file;data;x;y;type;⎕IO ⎕IO←1 data←83 ¯1 ⎕MAP file type←(3 2⍴'P4P5P6')∧.=⎕UCS 2↑data →(~∨/type)⍴err data←3↓data x y←⌽⍎⎕UCS ¯1↓(⍳∘10↑⊢)data →type/pbm pgm ppm pbm: data←,⍉(8⍴2)⊤256|(⍳∘10↓⊢)data img←y(↑⍤1)(x,8×⌈8÷⍨y)⍴data →0 pgm: img←x y⍴256|(⍳∘10↓⊢)⍣2⊢data →0 ppm: img←(1⌽⍳3)⍉x y 3⍴256|(⍳∘10↓⊢)⍣2⊢data →0 err:'Unknown file magic' ∇ ∇img writepnm(spec file);hdr;dta;x;y;tie →((3 2⍴'P4P5P6')∧.=spec)/pbm pgm ppm 'Unknown file kind' →0 pbm: hdr←10,⍨⎕UCS(⍕x y←⌽⍴img) dta←,⍉(8×⌈8÷⍨x)↑⍉img dta←2⊥⍉((8÷⍨≢dta),8)⍴dta →fin pgm: hdr←10 50 53 53 10,⍨⎕UCS(⍕⌽⍴img) dta←,img →fin ppm: hdr←10 50 53 53 10,⍨⎕UCS(⍕x y←⌽1↓⍴img) dta←,y(3×x)⍴(¯1⌽⍳3)⍉img fin: tie←file(⎕NCREATE⍠'IfExists' 'Error')0 :Trap 0 tie ⎕ARBOUT(⎕UCS spec),10,hdr,dta :Else 'Error occured when write file' :EndTrap ⎕NUNTIE tie ∇ </code></pre> <p>The namespace <code>Bluenoise</code> contains a <code>mkda</code> function that generates a <code>,⍨2×r</code> shape &quot;dither array&quot; suitable for halftoning using functions in <code>Dither</code> namespace. Their usage summaries are <code>dither_array diffuse greyscale_image</code>(error diffusion halftoning), <code>dither_array dither greyscale_image</code> <code>dither_array (R G B colordither) greyscale_image</code> where <code>R G B</code> is a size 3 vector corresponding to the weight of each color channel.</p> <p>The <code>Blur</code> namespace has <code>radius boxblur image</code>, <code>(level radius) gblur image</code>, where <code>gblur</code> is approximate Gaussian blur.</p> <p>The <code>Interpol</code> namespace has <code>image nearest newsize</code>, which computes nearest neighbor interpolation.</p> <p>The project is at <a href="https://github.com/LdBeth/pnmaster" rel="noreferrer">https://github.com/LdBeth/pnmaster</a></p> <pre><code>:Namespace Image tiling←⊣⍴⊢/⍤⊣⍴⍤1⊢ quant←{⊃∘⍋⍤1⊢|⍵∘.-⍺} linear←{(1÷⍵-1)×⎕IO-⍨⍳⍵} :Namespace Bluenoise ∇da←mkda r ;m;g;s;gauss;cluster;void;imax ;l;v;bp;pt;rank;loc;all;⎕IO ⎕IO←0 m←,⍨2×r ⋄ bp←?m⍴2 gauss←{*-4.5÷⍨∘.+⍨2*⍨(⌽,1∘↓)⍳1+⍵} ⍝ use interger approximation s←⍴g←s⌿(s←0≠+/g)/g←⌊0.5+(⊢××/∘⍴)gauss r cluster←⊢×(-,⍨r)↓(,⍨r)↓{+/,g×⍵}⌺s∘(r⊖⍪⍨)∘(r⌽,⍨) void←cluster~ ⋄ imax←,⍳(⌈/⌈/) loop: l←imax cluster bp (l⌷,bp)←0 v←imax void bp (v⌷,bp)←1 →(l≠v)/loop pt←bp ⋄ da←m⍴0 ⋄ rank←¯1++/,bp :While rank≥0 loc←imax cluster pt (loc⌷,pt)←0 (loc⌷,da)←rank rank-←1 :EndWhile pt←bp ⋄ rank←+/,bp ⋄ all←×/m :While rank&lt;all loc←imax void pt (loc⌷,pt)←1 (loc⌷,da)←rank rank+←1 :EndWhile ∇ :EndNamespace :Namespace Dither diffuse←{ ⎕DIV←⎕IO←1 in←1-⍵÷255 g←1+∘.+⍨0 1 0 m←⍺ ##.tiling⍨⍴⍵ cvol←{+/,g×⍵}⌺3 3 ⊃{ b←0.5≤a←in×m=⍺ err←a-b c←err÷cvol m&gt;⍺ in+←cvol c b∨⍵}/(⌽⍳≢,⍺),0 } dither←{ (1-⍵÷255)≥(⍴⍵)##.tiling(0.5∘+÷≢∘,)⍺ } colordither←{ q←{⌊r×⌊(r←255÷⍺-1)÷⍨⍵} s←⍵+(255÷(0.5+≢,⍺)×⍺⍺-1)×⍤0 2⊢(⍴⍵)##.tiling ⍺ 255⌊⍺⍺(q⍤0 2)s } :EndNamespace :Namespace Blur boxblur←{⌊⍵÷⍥({+/,⍵}⌺(1+2×⍺ ⍺))1⍴⍨⍴⍵} gblur←{ ⎕IO←0 l rad←⍺ m←(⍴⍵)⍴1 box←{⍵÷⍥({+/,⍵}⌺(⍺ ⍺))m} bforg←{ wl←(⊢-(~2∘|))⌊0.5*⍨1+⍺÷⍨i←12×⍵*2 m←(⌊0.5+⊢)(¯4×1+wl)÷⍨i-+/(wl*2 1 0)×1 4 3×⍺ wl+2×m≤⍳⍺ } ⌊⊃box/(l bforg rad),⊂⍵ } :EndNamespace :Namespace Interpol nearest←{ ⍝ img←⍺ ⋄ x y←⍵ ⍺⌷⍨(⍴⍺)(##.quant⍥##.linear)¨⍵ } :EndNamespace :EndNamespace </code></pre>
[]
[ { "body": "<h1>Coding style</h1>\n<h2>Comment your code</h2>\n<p>My father brought be up with the principle that you should be able to reconstruct your code from your comments. Maybe that level of commenting isn't necessary, especially if you use well-chosen names, but at least comment your API functions with what they do, what the arguments are, and what the results are.</p>\n<h2>Adopt a naming convention</h2>\n<p>You make use of constants, variables, functions, and operators, but without any discernible naming convention other than namespaces being uppercased and everything else lowercased. Furthermore, multi-word names and abbreviations in names are all run together. This makes it hard for the human reader to parse your code and remember calling conventions. Consider adopting or adapting a naming convention and separating words and abbreviations with under_scores or camelCase. As an example, take <a href=\"https://abrudz.github.io/style#nc\" rel=\"nofollow noreferrer\">my personal naming conventions</a>.</p>\n<h2>Explain your names</h2>\n<p>Many of your names are very short. Consider adding a comment when such names are first used, explaining their mnemonic, as this will help the reader of your code.</p>\n<h2>Avoid excessive use of <code>⍨</code> to swap arguments</h2>\n<p>I'm a big proponent of <a href=\"https://abrudz.github.io/style/#pr\" rel=\"nofollow noreferrer\">using <code>⍨</code> to avoid parentheses</a>, however, if using <code>⍨</code> leads to the left argument needing a parenthesis then there is nothing to be gained. For example, <code>(r←255÷⍺-1)÷⍨⍵</code> can become <code>⍵÷r←255÷⍺-1</code> and <code>(¯4×1+wl)÷⍨i-+/(wl*2 1 0)×1 4 3×⍺</code> can be <code>(i-+/(wl*2 1 0)×1 4 3×⍺)÷¯4×1+wl</code>.</p>\n<h2>Use <code>⍨</code> to simplify code</h2>\n<p>Whether to use <code>⍨</code> in simple cases or not, is a matter of style. I personally do it, and I see you have too e.g. with <code>⍺ ##.tiling⍨⍴⍵</code>. However, I'd be consistent then and also do it with e.g. <code>(x,8×⌈8÷⍨y)⍴data</code> as <code>data⍴⍨x,8×⌈8÷⍨y</code> and <code>(⍴⍵)##.tiling ⍺</code> as <code>⍺ ##.tiling⍨ ⍴⍵</code> and <code>(⍴⍵)⍴1</code> as <code>1⍴⍨⍴⍵</code> although this latter example could also be written as <code>1⍨¨⍵</code>, utilising the &quot;Constant&quot; meaning of <code>⍨</code>.</p>\n<h2>Remove unnecessary parentheses</h2>\n<p>Besides for governing order of execution and binding, parentheses can clarify structure in the code. APL's very simple precedence rules means that there's no need for parentheses &quot;just to be sure&quot;. Even in the absence of a naming convention, primitives have a clear syntactic role, and thus things like <code>(##.quant⍥##.linear)¨</code> can be <code>##.quant⍥##.linear¨</code>. Alternatively, you could &quot;factor out&quot; the dotting into the parent space as <code>##.(quant⍥linear¨)</code> or <code>##.(quant⍥linear)¨</code>.</p>\n<p>There's no need for any parenthesis in <code>⎕UCS(⍕⌽⍴img)</code> and <code>⎕UCS(⍕x y←⌽1↓⍴img)</code>.</p>\n<p>Neither is there in <code>{+/,⍵}⌺(⍺ ⍺)</code> as stranding binds stronger than almost anything else.</p>\n<h2>Avoid old-school use of <code>→</code></h2>\n<p>Your uses of <code>→</code> can and should be replaced by proper control structures for clarity and to avoid coding errors. E.g. <code>loop:</code> … <code>→(l≠v)/loop</code> becomes <code>:Repeat</code> … <code>:Until l=v</code> and</p>\n<pre><code> →type/pbm pgm ppm\n pbm:\n data←,⍉(8⍴2)⊤256|(⍳∘10↓⊢)data\n img←y(↑⍤1)(x,8×⌈8÷⍨y)⍴data\n →0\n pgm:\n img←x y⍴256|(⍳∘10↓⊢)⍣2⊢data\n →0\n ppm:\n img←(1⌽⍳3)⍉x y 3⍴256|(⍳∘10↓⊢)⍣2⊢data\n →0\n</code></pre>\n<p>becomes</p>\n<pre><code> :Select type⍳1\n :Case 1 ⍝ pbm\n data←,⍉(8⍴2)⊤256|(⍳∘10↓⊢)data\n img←y(↑⍤1)(x,8×⌈8÷⍨y)⍴data\n :Case 2 ⍝ pgm\n img←x y⍴256|(⍳∘10↓⊢)⍣2⊢data\n :Case 3 ⍝ ppm\n img←(1⌽⍳3)⍉x y 3⍴256|(⍳∘10↓⊢)⍣2⊢data\n :EndSelect\n</code></pre>\n<p>Similarly in <code>writepnm</code>.</p>\n<h2>Be consistent in <code>⎕IO</code> usage</h2>\n<p>Some of your functions use <code>⎕IO</code> explicitly to be <code>⎕IO</code>-independent, some localise <code>⎕IO←0</code> and some <code>⎕IO←1</code>. Your code would be easier to follow if you settled on a specific value and set it once in the outermost namespace.</p>\n<p>Alternatively, use one main value and set the other locally when needed. With this usage, the main value is usually <code>1</code> and the local <code>0</code>.</p>\n<h2>Avoid inline anonymous multi-line functions</h2>\n<p>The inner multi-line dfn in <code>diffuse</code> is being used in exactly the same manner as <code>bforg</code> in <code>gblur</code>, yet isn't named and called separately:</p>\n<pre><code> ⊃{\n b←0.5≤a←in×m=⍺\n err←a-b\n c←err÷cvol m&gt;⍺\n in+←cvol c\n b∨⍵}/(⌽⍳≢,⍺),0\n</code></pre>\n<p>Using inline dfns like this is not only hard to read, it is also very confusing to trace through and debug because the flow is in the following order:</p>\n<pre><code> 7{\n 2\n 3\n 4\n 5\n 6 }/1\n</code></pre>\n<p>Give the function a proper name and use that.</p>\n<h2>Parenthesise multiple assignment</h2>\n<blockquote>\n<p>Dyalog recommends that the names (…) are enclosed in parentheses to reduce potential ambiguity in assignment statements. <sup><a href=\"https://help.dyalog.com/latest/#Language/Primitive%20Functions/Assignment.htm\" rel=\"nofollow noreferrer\">[source]</a></sup></p>\n</blockquote>\n<p>Thus, <code>l rad←</code> should be written as <code>(l rad)←</code> and <code>x y←</code> should be <code>(x y)←</code></p>\n<h2>Reverse order of variable names instead of reversing the data</h2>\n<p><code>x y←⌽</code> can be simplified to <code>y x←</code>.</p>\n<h2>Avoid unnecessary trains</h2>\n<p>Sometimes a plain explicit expression does the trick: <code>(⌊0.5+⊢)</code> can simply be <code>⌊0.5+</code> which will also run faster.</p>\n<h2>Functions should return a result</h2>\n<p>Though no result is needed from <code>writepnm</code>, it is still good practice to return a result. If you do not return a result, it is very awkward to use the function from inside dfns, or inline in expressions including trains. To prevent cluttering when used in an APL session, you can make the result shy by putting the result in braces in the function header: <code>{result}←img writepnm(spec file);hdr;dta;x;y;tie</code>. A possible sensible result could be the number of bytes written or <code>1</code> to indicate that all went well.</p>\n<h2>Use <code>⎕NAPPEND</code> rather than <code>⎕ARBOUT</code></h2>\n<p><code>⎕NAPPEND</code> is the normal way to write to binary files.</p>\n<h2>Unnecessary reshaping</h2>\n<p>As far as I can tell, the reshaping in <code>,y(3×x)⍴</code> is a no-op since the data is ravelled immediately afterwards.</p>\n<h2>Avoid reusing variable names for unrelated values</h2>\n<p>In the single expression <code>s←⍴g←s⌿(s←0≠+/g)/g←⌊0.5+(⊢××/∘⍴)gauss r</code> the variable name <code>s</code> is used for two unrelated values. This is bound to confuse the casual reader.</p>\n<h2>Make sure code is restartable</h2>\n<p>The code <code>s←⍴g←s⌿(s←0≠+/g)/g←⌊0.5+(⊢××/∘⍴)gauss r</code> changes the value of <code>g</code> and <code>s</code> twice. This means that if something goes wrong in this line, and you have to re-evaluate it, <code>g</code> and/or <code>s</code> may already have gone through their first transformation, and you'll have to back up until their initial assignment. Instead, consider breaking the expression into three lines, which also becomes much easier to read:</p>\n<pre><code>g←⌊0.5+(⊢××/∘⍴)gauss r\ns←0≠+/g\ns←⍴g←s⌿s/g\n</code></pre>\n<p>In fact, the refactoring might inspire you to make the filtering of <code>g</code> in-place:</p>\n<pre><code>g←⌊0.5+(⊢××/∘⍴)gauss r\ns←0≠+/g\ng/⍨←s ⋄ g⌿⍨←s\ns←⍴g\n</code></pre>\n<h2>Use <code>⍣</code> for more elegant code</h2>\n<p><code>imax←,⍳(⌈/⌈/)</code> can be written as <code>imax←,⍳⌈/⍣2</code> which hints at the rank too.</p>\n<h2>Use <code>∘</code> to simplify tacit functions</h2>\n<p>Thus <code>⊢-(~2∘|)</code> can be written as <code>⊢-∘~2∘|</code>.</p>\n<h1>File organization</h1>\n<p>You've organised all code into two scripted namespaces, which means that changing any code affects the source file for a lot of other code. Also, the casing of your file names does not match the casing of their contents.</p>\n<p>Instead, use <a href=\"https://github.com/Dyalog/link\" rel=\"nofollow noreferrer\">Link</a> and make every namespace and sub-namespace represented by a folder and subfolder, of matching name, in your repo. You can either choose to keep leaf namespaces scripted, or even break those up with one function/operator in each file.</p>\n<p>If you unscript everything your only source files will be .apln for functions and .aplo for operators. However, you will have to wrap tacit functions in tradfns covers, e.g.:</p>\n<pre><code>tiling←tiling\ntiling←⊣⍴⊢/⍤⊣⍴⍤1⊢\n</code></pre>\n<p>Either scheme will allow you to edit and track changes on a much more granular basis, will allow you to use file handling to move items around, and will allow you to edit multiple items simultaneously.</p>\n<h1>Error handling and defensive programming</h1>\n<h2>Raise proper errors rather than returning messages</h2>\n<p>Your PNM file handling functions return character vector messages, which are non-conforming results, rather than signalling proper errors when something goes wrong. This would make for rather awkward usage, as one has to check the return value rather than simply trapping errors. Read up on <a href=\"https://aplwiki.com/wiki/Error_trapping_with_Dyalog_APL\" rel=\"nofollow noreferrer\">error trapping with Dyalog APL</a> (note the list of external links at the bottom).</p>\n<p>Don't forget to untie the file if an error happens!</p>\n<h2>Assert valid input</h2>\n<p><code>readpnm</code> goes right ahead and attempts a <code>⎕MAP</code> without checking that the input is even a character vector or that the file exists. If fed an invalid array or even a filename for a file that doesn't exist, the user will see <code>readpnm</code> suspend into the tracer. Consider wrapping the code body in:</p>\n<pre><code>:If 1≥|≡file ⍝ vector\n:AndIf 0 2∊⍨10|⎕DR file ⍝ character\n:AndIf ⎕NEXISTS file\n</code></pre>\n<p> ⋮</p>\n<pre><code>:Else\n ⎕SIGNAL⊂('EN' 11)('Message' 'Invalid file name')\n:EndIf\n</code></pre>\n<p>Similar tests can be done for other API functions.</p>\n<h2>Avoid unnecessary option setting</h2>\n<p><code>⎕NCREATE</code> will error if you try to create a file that already exists, so there's no need to use variant in <code>(⎕NCREATE⍠'IfExists' 'Error')</code>.</p>\n<h2>Avoid dangerous usage of <code>⍎</code></h2>\n<p>The code <code>x y←⌽⍎</code> blindly executes part of the file contents, which should generally be avoided. Consider either filtering the file contents or using the safe <code>⎕VFI</code>: <code>y x←2↑⊃⊢⍤//⎕VFI</code> (The <code>2↑</code> here is to ensure we get exactly two dimensions and thus avoid a length error upon assignment.)</p>\n<h1>Performance improvements</h1>\n<h2>Use built-in type conversion rather than implementing it</h2>\n<p>As far as I can tell, <code>,⍉(8⍴2)⊤256|</code> converts signed 1-byte integers to signed 1-byte integers, and then further to individual bits. You can probably speed things up by only modifying the internal type (which doesn't actually change the data bits) rather than doing the computation: <code>11⎕DR⊃0 83⎕DR</code>. Note the <code>0 83⎕DR</code> which ensures the numbers are interpreted as unsigned integers even if they have been squeezed to Boolean (when all numbers are zeros and ones).</p>\n<h2>Use in-place changes to avoid memory copying</h2>\n<p>When reading a PBM file, <code>(x,8×⌈8÷⍨y)⍴data</code> reshapes <code>data</code> for creating <code>img</code> but <code>data</code> is never used again. Since the interpreter doesn't know that <code>data</code> won't be used, it has to keep its value available, and thus the reshaping requires copying the entire data in memory. If instead you do a modified assignment to perform the reshaping, it can be done in-place: <code>data⍴⍨←x,8×⌈8÷⍨y</code></p>\n<p>Similarly for PGM and PPM files, you might be able to avoid a memory copy by computing the amount of data to drop and then dropping it in-place: <code>data↓⍨←2⍳⍨+\\10=data</code> – however, be aware that this traverses the data in its entirety to finding all the <code>10</code> before it can identify the second <code>10</code>, so it might actually suffer in performance. Morale: Run some speed tests.</p>\n<h2>Avoid grade for finding the position of the smallest element</h2>\n<p><code>quant</code> uses <code>⊃∘⍋⍤1</code> to find the position of the smallest element in each row. Depending on your Dyalog version, you may find <code>(⊢⍳⌊/)⍤1</code> to be significantly faster.</p>\n<h2>Consider computing constants once</h2>\n<p>The constant <code>g←1+∘.+⍨0 1 0</code> will be recomputed every time <code>diffuse</code> is used. Consider defining it once in the namespace, or at least simplifying its definition to <code>g←3 3⍴1 2 1 2 3 2 1 2 1</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T01:29:22.080", "Id": "528318", "Score": "1", "body": "Adám, this is interesting to read. I had heard of APL, but not seen any longer bits of code until I ran into this question yesterday. Usually I can give comments on inefficient implementation of image processing functionality, even if written in a language I’ve never used. But this code really stumped me. I spent some time yesterday reading up on APL, and am quite curious about it now. I recognize some of the operators now, but a till, I think it would take a long time to read (just like a mathematical expression you haven’t seen before can take some time to parse and understand). (1/2)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T01:31:39.767", "Id": "528319", "Score": "1", "body": "Is my impression right, or do you eventually get used to language enough to be able to read it quickly like other languages? I did read a comment that it’s a “write-only language”, which would be surprising because nobody would use it, or?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T02:40:35.240", "Id": "528322", "Score": "0", "body": "@CrisLuengo It's almost like learning any other language. I'd say APL is one of the rare ones that actually tries to make its own style when most languages borrow from ALGOL's style or C. This make it stand out to most programmers, and when something looks unfamiliar, programmers have a bad habit of shunning it and calling it \"write-only\"." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T02:42:54.063", "Id": "528324", "Score": "0", "body": "@CrisLuengo If you'd like some more help on understanding APL, [The APL Orchard(SE chat)](https://apl.chat) is open to all." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:22:18.287", "Id": "528326", "Score": "0", "body": "`⊢⍤//⎕VFI` it seems you mean to take the second for the result from `⎕VFI`, but in this way the result is boxed so it doesn't make sense to `2↑`, I suggest using `⊃⌽⎕VFI`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:38:15.593", "Id": "528327", "Score": "0", "body": "@LdBeth Ah, right it needs to be disclosed: `2↑⊃⊢⍤//⎕VFI`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T23:12:57.003", "Id": "267934", "ParentId": "267857", "Score": "2" } } ]
{ "AcceptedAnswerId": "267934", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T10:52:30.473", "Id": "267857", "Score": "5", "Tags": [ "image", "apl" ], "Title": "Image processing using Dyalog APL" }
267857
<p>As the title suggests, I'm writing an x64 Code Emitter. Right now I've only encoded 1 instruction (The add instruction). I want to know if this API can be improved at all.</p> <p>This is how you I use it.</p> <pre class="lang-c prettyprint-override"><code>int main() { // The Operand type contains the type of the operand and a union with the contained value. // There are 4 types right now, NONE, REGISTER, MEMORY, and CONSTANT. Operand imm42 = (Operand) { OPERAND_CONSTANT, .Constant = 42 }; Operand imm256 = (Operand) { OPERAND_CONSTANT, .Constant = 256 }; // rax and r8 are constants defined in another file. // the emitAdd function for now simply prints the result to stdout. emitAdd(rax, imm42); // -&gt; 48 83 C0 2A emitAdd(rax, imm256); // -&gt; 48 05 00 01 00 00 emitAdd(r8, imm42); // -&gt; 49 83 C0 2A emitAdd(r8, imm256); // -&gt; 49 81 C0 00 01 00 00 } </code></pre> <p>I'm pretty happy with what I've done so far, and I've tested every variation of this instruction. i.e (add reg, imm add reg, reg) I haven't encoded memory variants yet though.</p> <p>This is the main code.</p> <pre class="lang-c prettyprint-override"><code>// Instruction.c // forward declaration for emitAdd #include &quot;Instruction.h&quot; #include &lt;stdio.h&gt; #include &lt;stdbool.h&gt; #include &lt;stddef.h&gt; #include &quot;types.h&quot; #include &quot;Encoding.h&quot; unsigned int registerToIndex(Register reg) { switch (reg) { case REGISTER_AL: case REGISTER_AX: case REGISTER_EAX: case REGISTER_RAX: return 0; case REGISTER_CL: case REGISTER_CX: case REGISTER_ECX: case REGISTER_RCX: return 1; case REGISTER_DL: case REGISTER_DX: case REGISTER_EDX: case REGISTER_RDX: return 2; case REGISTER_BL: case REGISTER_BX: case REGISTER_EBX: case REGISTER_RBX: return 3; case REGISTER_AH: case REGISTER_SPL: case REGISTER_SP: case REGISTER_ESP: case REGISTER_RSP: return 4; case REGISTER_CH: case REGISTER_BPL: case REGISTER_BP: case REGISTER_EBP: case REGISTER_RBP: return 5; case REGISTER_DH: case REGISTER_SIL: case REGISTER_SI: case REGISTER_ESI: case REGISTER_RSI: return 6; case REGISTER_BH: case REGISTER_DIL: case REGISTER_DI: case REGISTER_EDI: case REGISTER_RDI: return 7; case REGISTER_R8B: case REGISTER_R8W: case REGISTER_R8D: case REGISTER_R8: return 8; case REGISTER_R9B: case REGISTER_R9W: case REGISTER_R9D: case REGISTER_R9: return 9; case REGISTER_R10B: case REGISTER_R10W: case REGISTER_R10D: case REGISTER_R10: return 10; case REGISTER_R11B: case REGISTER_R11W: case REGISTER_R11D: case REGISTER_R11: return 11; case REGISTER_R12B: case REGISTER_R12W: case REGISTER_R12D: case REGISTER_R12: return 12; case REGISTER_R13B: case REGISTER_R13W: case REGISTER_R13D: case REGISTER_R13: return 13; case REGISTER_R14B: case REGISTER_R14W: case REGISTER_R14D: case REGISTER_R14: return 14; case REGISTER_R15B: case REGISTER_R15W: case REGISTER_R15D: case REGISTER_R15: return 15; } } static bool is8BitRegister(Register reg) { return reg &gt;= REGISTER_AL &amp;&amp; reg &lt;= REGISTER_R15B; } static bool is16BitRegister(Register reg) { return reg &gt;= REGISTER_AX &amp;&amp; reg &lt;= REGISTER_R15W; } static bool is32BitRegister(Register reg) { return reg &gt;= REGISTER_EAX &amp;&amp; reg &lt;= REGISTER_R15D; } static bool is64BitRegister(Register reg) { return reg &gt;= REGISTER_RAX &amp;&amp; reg &lt;= REGISTER_R15; } static bool needsREX(Register reg) { switch (reg) { case REGISTER_SPL: case REGISTER_BPL: case REGISTER_SIL: case REGISTER_DIL: case REGISTER_R8B: case REGISTER_R9B: case REGISTER_R10B: case REGISTER_R11B: case REGISTER_R12B: case REGISTER_R13B: case REGISTER_R14B: case REGISTER_R15B: case REGISTER_R8W: case REGISTER_R9W: case REGISTER_R10W: case REGISTER_R11W: case REGISTER_R12W: case REGISTER_R13W: case REGISTER_R14W: case REGISTER_R15W: case REGISTER_R8D: case REGISTER_R9D: case REGISTER_R10D: case REGISTER_R11D: case REGISTER_R12D: case REGISTER_R13D: case REGISTER_R14D: case REGISTER_R15D: case REGISTER_R8: case REGISTER_R9: case REGISTER_R10: case REGISTER_R11: case REGISTER_R12: case REGISTER_R13: case REGISTER_R14: case REGISTER_R15: return true; } return false; } static void printMemory(byte* memory, size_t length) { /* byte arr[] = {0x3, 0x4, 0x6, 0x5}; printMemory(arr, 4); -&gt; 03 04 06 05 */ for (size_t i = 0; i &lt; length; i++) { byte b = memory[i]; printf(&quot;%X%X &quot;, (b &amp; 0xF0) &gt;&gt; 4, b &amp; 0x0F); } printf(&quot;\n&quot;); } /* This function optimizes for instruction size, so instructions are encoded using the least amount of bytes possible. */ void emitAdd(Operand destination, Operand source) { // for now just assume the largest an x64 instruction can be. // I think it can be bigger, I haven't checked. byte instruction[14] = {}; unsigned int index = 0; if (destination.Type == OPERAND_REGISTER &amp;&amp; source.Type == OPERAND_CONSTANT) { Register reg = destination.Register; unsigned int registerCode = registerToIndex(reg); qword constant = source.Constant; if (reg == REGISTER_AL || reg == REGISTER_AX || reg == REGISTER_EAX || reg == REGISTER_RAX) { switch (reg) { case REGISTER_AL: { instruction[index++] = 0x4; *(byte*)(instruction + index++) = constant; } break; case REGISTER_AX: { instruction[index++] = 0x66; instruction[index++] = 0x5; *(word*)(instruction + index) = constant, index += 2; } break; case REGISTER_EAX: case REGISTER_RAX: { if (reg == REGISTER_RAX) instruction[index++] = REX_W; if (constant &lt;= 0xFF) { instruction[index++] = 0x83; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, 0, registerCode); *(byte*)(instruction + index++) = constant; } else { instruction[index++] = 0x5; *(dword*)(instruction + index) = constant, index += 4; } } break; } } else if (is8BitRegister(reg)) { if (needsREX(reg)) instruction[index++] = (reg &lt; REGISTER_R8B ? REX : REX_B); instruction[index++] = 0x80; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, 0, registerCode); *(byte*)(instruction + index++) = constant; } else if (is16BitRegister(reg)) { instruction[index++] = 0x66; if (constant &lt;= 0xFF) { if (needsREX(reg)) instruction[index++] = REX_B; instruction[index++] = 0x83; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, 0, registerCode); *(byte*)(instruction + index++) = constant; } else { if (needsREX(reg)) instruction[index++] = REX_B; instruction[index++] = 0x81; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, 0, registerCode); *(word*)(instruction + index) = constant, index += 2; } } else if (is32BitRegister(reg)) { if (constant &lt;= 0xFF) { if (needsREX(reg)) instruction[index++] = REX_B; instruction[index++] = 0x83; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, 0, registerCode); *(byte*)(instruction + index++) = constant; } else { if (needsREX(reg)) instruction[index++] = REX_B; instruction[index++] = 0x81; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, 0, registerCode); *(dword*)(instruction + index) = constant, index += 4; } } else { // must be a 64 bit register instruction[index++] = (reg &lt; REGISTER_R8 ? REX_W : REX_W | REX_B); if (constant &lt;= 0xFF) { instruction[index++] = 0x83; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, 0, registerCode); *(byte*)(instruction + index++) = constant; } else { instruction[index++] = 0x81; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, 0, registerCode); *(dword*)(instruction + index) = constant, index += 4; } } } else if (destination.Type == OPERAND_REGISTER &amp;&amp; source.Type == OPERAND_REGISTER) { Register dst = destination.Register; Register src = source.Register; unsigned int dstRegisterCode = registerToIndex(dst); unsigned int srcRegisterCode = registerToIndex(src); if (is8BitRegister(dst) &amp;&amp; is8BitRegister(src)) { if (needsREX(dst) || needsREX(src)) { unsigned int rexPrefixIndex = index++; instruction[rexPrefixIndex] = REX; instruction[rexPrefixIndex] |= (dst &gt;= REGISTER_R8B ? REX_B : 0); instruction[rexPrefixIndex] |= (src &gt;= REGISTER_R8B ? REX_R : 0); } instruction[index++] = 0x00; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, srcRegisterCode, dstRegisterCode); } else if (is16BitRegister(dst) &amp;&amp; is16BitRegister(src)) { instruction[index++] = 0x66; if (needsREX(dst) || needsREX(src)) { unsigned int rexPrexfixIndex = index++; instruction[rexPrexfixIndex] = REX; instruction[rexPrexfixIndex] |= (dst &gt;= REGISTER_R8W ? REX_B : 0); instruction[rexPrexfixIndex] |= (src &gt;= REGISTER_R8W ? REX_R : 0); } instruction[index++] = 0x1; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, srcRegisterCode, dstRegisterCode); } else if (is32BitRegister(dst) &amp;&amp; is32BitRegister(src)) { if (needsREX(dst) || needsREX(src)) { unsigned int rexPrefixIndex = index++; instruction[rexPrefixIndex] = REX; instruction[rexPrefixIndex] |= (dst &gt;= REGISTER_R8D ? REX_B : 0); instruction[rexPrefixIndex] |= (src &gt;= REGISTER_R8D ? REX_R : 0); } instruction[index++] = 0x1; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, srcRegisterCode, dstRegisterCode); } else if (is64BitRegister(dst) &amp;&amp; is64BitRegister(src)) { unsigned int rexPrefixIndex = index++; instruction[rexPrefixIndex] = REX_W; instruction[rexPrefixIndex] |= (dst &gt;= REGISTER_R8 ? REX_B : 0); instruction[rexPrefixIndex] |= (src &gt;= REGISTER_R8 ? REX_R : 0); instruction[index++] = 0x1; instruction[index++] = encodeModRM(REGISTER_ADDRESSING, srcRegisterCode, dstRegisterCode); } } printMemory(instruction, index); } </code></pre> <p>All the sources are here, it's mostly defining constants and forward declarations.</p> <pre><code>types.h: https://hastebin.com/pipuqezoxe.cpp Encoding.h: https://hastebin.com/esiciniwex.cpp Instruction.h: https://hastebin.com/refokaluka.cpp Instruction.c (where all the code emitting happens): https://hastebin.com/fuboqijedi.cpp </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T12:59:51.677", "Id": "528193", "Score": "4", "body": "IMO the API is still too small to give meaningful feedback about, especially because it doesn't include any interesting cases yet (eg memory operands and labels). Maybe someone else feels differently about that.." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T13:13:55.070", "Id": "528194", "Score": "2", "body": "Too long to include? If those 4 files cause you to go over the 64K limit we have here, then I suggest they probably need some splitting to make them more manageable." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T13:55:54.177", "Id": "528198", "Score": "0", "body": "@Toby Speight I've included the code in the main post if that helps, I originally excluded it for brevity, the emitAdd function is only ~150 lines." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T16:40:58.977", "Id": "528205", "Score": "1", "body": "If you look at other code reviews, you will see that the standard is to include all the code, so that people can run it. You should only work on brevity if the code is bigger than fits in a single question. You should always include enough code in the question so that people can run it, possibly in the form of unit tests. In any case, I would suggest that you try to include all four files. If it doesn't tell you that breaks the 64K limit, then you're good. If it does, then there might be more to consider." } ]
[ { "body": "<pre><code>// forward declaration for emitAdd\n#include &quot;Instruction.h&quot;\n</code></pre>\n<p>There's no declaration here. Do you mean it's in <code>Instruction.h</code>? I think you don't need this comment. When you include a header with the same name as the source file, everyone reading your code will assume it contains declarations of exported functions. If it doesn't, that might be worthy of comment.</p>\n<pre><code>unsigned int registerToIndex(Register reg) {\n switch (reg) {\n case REGISTER_AL:\n case REGISTER_AX:\n case REGISTER_EAX:\n case REGISTER_RAX: return 0;\n case REGISTER_CL:\n case REGISTER_CX:\n case REGISTER_ECX:\n case REGISTER_RCX: return 1;\n [...]\n</code></pre>\n<p>This is a lot of boilerplate, and mistakes could easily creep in. Aside from that, having an unordered enum for the registers is inconvenient for users of the library, who will probably want to mention them by number, not name, in most cases (when writing a register allocator, for instance).</p>\n<p>I would either separate the register type from the register index, storing the latter in some other field of the <code>Operand</code> struct, or else rearrange the enum so that this function can be something like</p>\n<pre><code>unsigned int registerToIndex(Register reg) {\n return (unsigned)reg % 16u;\n}\n</code></pre>\n<p>and document that.</p>\n<pre><code>static bool needsREX(Register reg) { [...] }\n</code></pre>\n<p>This returns false for registers like <code>rax</code> that normally need REX.W. It seems as though it's really testing for every need for REX other than REX.W, which is hard to capture in a function name.</p>\n<p>My advice is to handle prefixes in a different way. Instead of having custom logic to work out what prefixes you'll need up front, track it as you go, and emit the prefixes at the end. <code>encodeModRM</code> should set REX.RXB based on the arguments.</p>\n<pre><code>printf(&quot;%X%X &quot;, (b &amp; 0xF0) &gt;&gt; 4, b &amp; 0x0F);\n</code></pre>\n<p>That can just be <code>printf(&quot;%02X &quot;, b);</code>.</p>\n<pre><code>void emitAdd(Operand destination, Operand source) { [...] }\n</code></pre>\n<p>The length of this function and the amount of duplicated code worries me. You've got a <em>long</em> road ahead of you. You definitely don't want to be copy-and-pasting all of this code just so that you can change the opcode byte for other instructions.</p>\n<p>The 16-bit, 32-bit and 64-bit cases are almost identical, and I'd unify them.</p>\n<pre><code>unsigned int registerCode = registerToIndex(reg);\n</code></pre>\n<p>I wouldn't use &quot;code&quot; and &quot;index&quot; for the same property. Just call it &quot;index&quot;.</p>\n<pre><code>if (reg == REGISTER_AL || reg == REGISTER_AX || reg == REGISTER_EAX || reg == REGISTER_RAX) {\n</code></pre>\n<p>You may as well change this to <code>if (registerCode == 0) {</code>.</p>\n<pre><code>*(byte*)(instruction + index++) = constant;\n</code></pre>\n<p><code>instruction</code> is an array of <code>byte</code>, so I'd just say <code>instruction[index++] = constant;</code></p>\n<pre><code>*(word*)(instruction + index) = constant, index += 2;\n*(dword*)(instruction + index) = constant, index += 4;\n</code></pre>\n<p>These aren't portable; they assume that the machine is little-endian and supports unaligned stores. Even if you don't make them portable right now, you should move them into separate functions so that they aren't duplicated everywhere, and can be made portable later without search-and-replace.</p>\n<pre><code>if (constant &lt;= 0xFF) {\n</code></pre>\n<p>This test is wrong because byte immediates are sign extended. It should be something like <code>((dword)constant &lt;= 0x7Fu || (dword)constant &gt;= 0xFFFFFF80u)</code> (with obvious changes in the 16-bit case). Of course, this test should also be in its own function.</p>\n<pre><code>if (is8BitRegister(dst) &amp;&amp; is8BitRegister(src)) {\n if (needsREX(dst) || needsREX(src)) {\n</code></pre>\n<p>Some combinations of 8-bit registers aren't encodable, like <code>ah,r8b</code>. You emit incorrect code in this case.</p>\n<p>If you take my advice to work out prefixes as you go, you should have a &quot;invalid with REX&quot; flag that you set whenever you see ah/ch/dh/bh, and test it at the end and error out if necessary.</p>\n<pre><code>} else if (is64BitRegister(dst) &amp;&amp; is64BitRegister(src)) { [...] }\n</code></pre>\n<p>There's no default case in this if-else chain, so when the register types don't match you'll just silently emit no code. The same is true if the operand types are invalid or you just haven't implemented them yet.</p>\n<p>In general, be suspicious of if-else chains without a final else, and switch statements without a default case. You may want to add an explicit <code>// do nothing</code> case if doing nothing is really the right action.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T19:18:44.820", "Id": "267869", "ParentId": "267860", "Score": "3" } } ]
{ "AcceptedAnswerId": "267869", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T12:21:19.323", "Id": "267860", "Score": "2", "Tags": [ "c", "assembly", "native-code" ], "Title": "Writing an x64 Code Emitter to eventually make a full fledged Assembler like NASM" }
267860
<p>I'm trying to learn C++ with a background in python. This is my first program besides general practice. I wanted to remake the war game. I'm looking to get feedback on the C++ equivalent of its pythonicness. Some mistakes I believe I've made are possibly misusing the std functions, unnecessary type transformations, and unnecessary duplications of data, but I'm not sure where to begin.</p> <p>For an explanation of the code, I didn't initialize cards themselves, I just used a 1- 52 range to signify cards. To distribute the cards, I just thought it would be fun to try and use a random binary with a bitlength of 52 and distribute the cards from that. I was also hesitant on the <code>while(true)</code> loop, I wanted a different way to do it but it works as intended.</p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;random&gt; #include &lt;algorithm&gt; #include &lt;set&gt; using namespace std; int randNum(int min, int max) { random_device r; default_random_engine e1(r()); uniform_int_distribution&lt;int&gt; uniform_dist(min, max); int mean = uniform_dist(e1); return mean; } string toBinary(int n) { string r; while(n != 0) { r = (n % 2 == 0 ? &quot;0&quot; : &quot;1&quot;) + r; n /= 2; } return r; } string deckShuffleSeed() { string deck; // Decimals to make a binary w/ bit length of 26 // /2 # of cards in deck, therefore: consolidate 2, so we can use ints deck = toBinary(randNum(33554432, 67108863)) + toBinary(randNum(33554432, 67108863)); return deck; } int randSetChoice(const set&lt;int&gt; &amp;s) { auto ItRandChoice = std::next(s.begin(), randNum(0, int(s.size()))); return *ItRandChoice; } string war() { // hand initialization set&lt;int&gt; p1, p2; string deckDealingSeed = deckShuffleSeed(); for (int i = 1; i &lt;= 52; i++) { int convSeedIndex = deckDealingSeed[i] - '0'; if (convSeedIndex == 1) { p2.insert(i); } else { p1.insert(i); } } // game loop while (!p1.empty() || !p2.empty()) { int recursiveWarCount = 0; set&lt;int&gt; cardsOnTable; while(true) { // recursive war loop if (p1.size() &gt; 3 * recursiveWarCount &amp;&amp; p2.size() &gt; 3 * recursiveWarCount) { int p1RandChoice = randSetChoice(p1), p2RandChoice = randSetChoice(p2); // round loop if (p1RandChoice / 4 &gt; p2RandChoice / 4) { // p1 wins p1.insert(p2RandChoice); p2.erase(p2RandChoice); if (recursiveWarCount &gt; 0) { p1.insert(cardsOnTable.begin(), cardsOnTable.end()); for (int i = 1; i &lt; recursiveWarCount * 3; i++) { int randTableChoice = randSetChoice(p2); p1.insert(randTableChoice); p2.erase(randTableChoice); } } break; } else if (p1RandChoice / 4 &lt; p2RandChoice / 4) { // p2 wins p2.insert(p1RandChoice); p1.erase(p1RandChoice); if (recursiveWarCount &gt; 0) { p2.insert(cardsOnTable.begin(), cardsOnTable.end()); for (int i = 1; i &lt; recursiveWarCount * 3; i++) { int randTableChoice = randSetChoice(p1); p2.insert(randTableChoice); p1.erase(randTableChoice); } } break; } else { // war recursiveWarCount += 1; cardsOnTable.insert(p1RandChoice); cardsOnTable.insert(p2RandChoice); } } else { if (p1.size() &gt; p2.size()) { return &quot;p1&quot;; } else { return &quot;p2&quot;; } } } } if (p1.empty()) { return &quot;p2&quot;; } else if(p2.empty()) { return &quot;p2&quot;; } else { return &quot;Something is wrong!&quot;; } } int main() { cout &lt;&lt; war() &lt;&lt; endl; return 1; } </code></pre>
[]
[ { "body": "<h1>Representing decks of cards</h1>\n<p>The way you store decks of cards and shuffle them is really very strange.\nThere's the unnecessary conversion (even for Python) from numbers to strings and back.\nUsing <code>std::set</code> for a deck is wrong, because it doesn't preserve the order of the cards in the deck. Instead, I would use a <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>std::deque</code></a> (no pun intended); it is fast to insert and remove cards from either end, and preserves their order. To create a deck of 52 cards (and lets keep them represented using <code>int</code>s for now), you could write:</p>\n<pre><code>std::deque&lt;int&gt; deck(52);\nstd::iota(deck.begin(), deck.end(), 1);\n</code></pre>\n<p>Here I've used <a href=\"https://en.cppreference.com/w/cpp/algorithm/iota\" rel=\"nofollow noreferrer\"><code>std::iota()</code></a> to initialize the value of each card in the deck, although a regular for-loop would be fine too. To shuffle the cards, use <a href=\"https://en.cppreference.com/w/cpp/algorithm/random_shuffle\" rel=\"nofollow noreferrer\"><code>std::shuffle()</code></a>:</p>\n<pre><code>std::random_device rd;\nstd::default_random_engine rng(rd());\nstd::shuffle(deck.begin(), deck.end(), rng);\n</code></pre>\n<p>Then to split the deck evenly among the two players (as mentioned in the rules of <a href=\"https://en.wikipedia.org/wiki/War_(card_game)\" rel=\"nofollow noreferrer\">War</a>), just copy each half of the deck, using <code>std::deque</code>'s constructor that takes two iterators:</p>\n<pre><code>auto midpoint = std::advance(deck.begin(), deck.size() / 2);\nstd::deque&lt;int&gt; p1(deck.begin(), midpoint);\nstd::deque&lt;int&gt; p2(midpoint, deck.end());\n</code></pre>\n<p>Now you can just draw a card from the deck like so:</p>\n<pre><code>auto card = p1.front();\np1.pop_front();\n</code></pre>\n<p>And to push the card to the back of the deck you could write:</p>\n<pre><code>p1.push_back(card);\n</code></pre>\n<p>Note that we didn't need any random number generator after the initial shuffling anymore.</p>\n<p>You can also move multiple cards in one go using <a href=\"https://en.cppreference.com/w/cpp/container/deque/insert\" rel=\"nofollow noreferrer\"><code>insert()</code></a> and <a href=\"https://en.cppreference.com/w/cpp/container/deque/erase\" rel=\"nofollow noreferrer\"><code>erase()</code></a>. Instead of keeping track of <code>recursiveWarCount</code> and only moving cards when the war is resolved, consider moving cards from both player's decks to the deck on the table every step of the war.</p>\n<h1>Avoid repeating yourself</h1>\n<p>The code that deals with player 1 winning the war is almost identical to the one for player 2 winning the war, just with <code>p1</code> and <code>p2</code> reversed. Whenever you see yourself mostly duplicating the same lines of code, consider writing a function instead.</p>\n<p>You could also consider creating a function that moves a card from one deck to another, so you can just call that instead of explicitly taking a card from one deck and adding it to another.</p>\n<h1>Consider creating new types or type aliases</h1>\n<p>Explicitly writing <code>std::deque&lt;int&gt;</code> every time you declare a deck of cards is not great; it's quite long, you have to remember the correct type, and from the type it's not clear that it represents a deck of cards. Having a better name for a deck of cards would be great. You can create an alias for that type with the <a href=\"https://en.cppreference.com/w/cpp/language/type_alias\" rel=\"nofollow noreferrer\"><code>using</code> keyword</a>:</p>\n<pre><code>using Card = int;\nusing Deck = std::deque&lt;Card&gt;;\n</code></pre>\n<p>And then you can use it like so:</p>\n<pre><code>Deck p1, p2;\n</code></pre>\n<p>Another way would be to create <code>class Card</code> and <code>class Deck</code> that represent cards and decks of cards, and have member functions that perform typical operations on it, like <code>get_value()</code> for a <code>Card</code>, and <code>shuffle()</code>, <code>split()</code>, <code>draw()</code> and so on for a <code>Deck</code>. This is a bit more work up front, but it might make implementing the actual logic of the War game much easier.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T14:32:24.923", "Id": "267863", "ParentId": "267862", "Score": "4" } }, { "body": "<p><a href=\"https://codereview.stackexchange.com/a/267863/84364\">G. Sliepen's answer</a> already mentioned that there is a <a href=\"https://en.cppreference.com/w/cpp/algorithm/random_shuffle\" rel=\"nofollow noreferrer\"><code>std::shuffle</code> function</a>, but I wanted to point that out explicitly.</p>\n<p>I recommend, even to experienced developers, to read through the <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">algorithm</a> header once a year just to remind themselves what all is in it.</p>\n<p>As for learning the C++ idioms and best practices, I suggest watching the videos from the major C++ conferences on YouTube. CppCon had a <a href=\"https://www.youtube.com/playlist?list=PLHTh1InhhwT5o3GwbFYy3sR7HDNRA353e\" rel=\"nofollow noreferrer\">Back to Basics</a> track in 2020.</p>\n<hr />\n<p><a href=\"https://stackoverflow.com/questions/1452721\">Don’t</a> write <code>using namespace std;</code>.</p>\n<p>You can, however, in a CPP file (not H file) or inside a function put individual <code>using std::string;</code> etc. (See <a href=\"https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#sf7-dont-write-using-namespace-at-global-scope-in-a-header-file\" rel=\"nofollow noreferrer\">SF.7</a>.)</p>\n<hr />\n<pre><code> if (p1.size() &gt; p2.size()) {\n return &quot;p1&quot;;\n } else {\n return &quot;p2&quot;;\n }\n</code></pre>\n<p>You can just write: <code>return p1.size() &gt; p2.size() ? &quot;p1&quot; : &quot;p2&quot;;</code><br />\nThis is <strong>better</strong> not just shorter, as it states up front that you are returning something... then goes on to a level of detail that what you return this or that depending. As you wrote it, it's a general-purpose <code>if</code> statement and requires more cognitive overhead to figure out that both branches do <em>similar</em> things, and you <code>return</code> no matter what.</p>\n<hr />\n<p>I don't know why you are making random choices during game play: I thought the game is played by taking your next card in order, not a random card from those you hold.</p>\n<hr />\n<pre><code>int p1RandChoice = randSetChoice(p1), p2RandChoice = randSetChoice(p2);\n</code></pre>\n<p>I'd like to point out that it's good style in C++ to put one declaration per statement, and not gang them up like this.</p>\n<p>You should also make things <code>const</code> when you can.</p>\n<hr />\n<p>I think your use of a <code>set</code> (a non-ordered collection?) makes the code more complex. But even using a <a href=\"https://en.cppreference.com/w/cpp/container/deque\" rel=\"nofollow noreferrer\"><code>deque</code></a>, you can improve things by defining a function to deal out a card, as <em>seeing</em> the value of the next card and <em>removing it</em> from the collection are separate operations. (That makes sense for large complex types that you would want to avoid copying.)</p>\n<pre><code>// not shown: definition for card_t\nusing deck = std::deque&lt;card_t&gt;;\n\ncard_t draw (deck&amp; d)\n{\n const auto x = d.front();\n d.pop_front();\n return x;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T17:15:51.567", "Id": "528207", "Score": "0", "body": "I think the reason OP has for making a random choice is to simulate a shuffled deck of cards while using a `std::set` which naturally keeps them sorted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T17:18:16.573", "Id": "528208", "Score": "0", "body": "A slight inconsistency in your last bit of code: `card_t` has a `_t` suffix, but `deck` hasn't." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T17:22:54.863", "Id": "528209", "Score": "1", "body": "A nice introduction into algorithms is also this CppCon presentation from Jonathan Boccara: [The World Map of C++ STL Algorithms](https://www.youtube.com/watch?v=2olsGf6JIkU)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T17:51:25.627", "Id": "528210", "Score": "0", "body": "@G.Sliepen I figured I'd want to use a variable named `card` here and there, but the only instances of `deck` were the player's hands and possibly the discard pile used for wars." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T15:08:22.337", "Id": "267864", "ParentId": "267862", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T13:39:01.507", "Id": "267862", "Score": "4", "Tags": [ "c++", "beginner", "playing-cards" ], "Title": "War card game with random play" }
267862
<p>This is the code I've written that'll take a word as input and write all its anagrams to a file. The java compiler forces me to use try-catch statements every time I wish to do something with the file. I want to know if there's any way to make my code shorter and more readable in general. As you can see, inside the <code>write_anagram</code> function, where I want want to swap two indices <code>i</code> and <code>j</code>. The code's been long with so many instances of <code>substring</code> and <code>charAt</code> function. I want to use it for my school project so want it more readable for an examiner. Any improvements I can make? Is there any substitute for <code>FileWriter</code> so that I don't have to use try catch many times?</p> <pre><code>import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Anagrams { int count; FileWriter f; void write(String s) { try { f.write(s+&quot;\n&quot;); } catch (IOException e) { System.out.println(&quot;An error ocurred while writing to the file&quot;); System.exit(0); } } void write_anagrams(String s, int start) { int i, j; String n; for(i=start; i&lt;s.length(); i++) { for(j=i+1; j&lt;s.length(); j++) { n = s.substring(0,i)+s.charAt(j)+s.substring(i+1, j)+s.charAt(i)+s.substring(j+1); write(n); count++; write_anagrams(n, i+1); } } } void write_anagrams(String s) { try { f = new FileWriter(&quot;AnagramsByJava.txt&quot;); } catch (IOException e) { System.out.println(&quot;An error ocurred while opening the file&quot;); } count = 1; write(s); write_anagrams(s, 0); try { f.close(); } catch (IOException e) { System.out.println(&quot;An error ocurred while closing the file&quot;); } System.out.println(count+&quot; anagrams have been written to AnagramsByJava.txt&quot;); } public static void main() { Scanner sc = new Scanner(System.in); Anagrams object = new Anagrams(); System.out.print(&quot;Enter a word: &quot;); String s = sc.next(); object.write_anagrams(s); } } </code></pre>
[]
[ { "body": "<p><em>(I'm a little nervous about answering since you mention this is for an exam, but then again we're here to help you learn and it's up to you and your examiners to see that you do the right thing with any help you get.)</em></p>\n<p>Since you asked about the exceptions, the answer is that if you plan to just crash on exception, then just don't <code>catch</code> it and use <code>throws</code> instead. Catch it somewhere else, such as in <code>main</code>, if you want to display something in particular. But even that's optional - you can even just throw from <code>main</code>.</p>\n<p>You also should be using <code>close()</code> on your resources. You can use the &quot;try-with-resources&quot; pattern to do this for you. In my example, I use <code>try</code> only for this purpose - I'm still not <code>catch</code>ing anything.</p>\n<p>You should free up your anagram logic from knowing that it will be written to a file - if it just gets a <code>Writer</code> it can handle the case if we decide we want it written to a file, to the screen, to the internet, to a <code>String</code>, or anywhere else.</p>\n<p>Then just some minor fancy stuff to give you inspiration re: readability. Google anything you aren't familiar with (<code>StringBuilder</code>, <code>BufferedWriter</code>, <code>System.out.format</code>).</p>\n<p>I didn't touch your core anagram logic, though I did put it over several lines in an attempt to make it readable. To be honest it still confuses me how it works, but it does seem to work at least...!</p>\n<pre class=\"lang-java prettyprint-override\"><code>import java.io.BufferedWriter;\nimport java.io.FileWriter;\nimport java.io.IOException;\nimport java.io.Writer;\nimport java.util.Scanner;\n\npublic class Anagrams_mine {\n\n private static int write_anagrams(Writer f, String s, int start, int count)\n throws IOException {\n for (int i = start; i &lt; s.length(); i++) {\n for (int j = i + 1; j &lt; s.length(); j++) {\n String n = new StringBuilder(s.length())\n .append(s.substring(0, i))\n .append(s.charAt(j))\n .append(s.substring(i + 1, j))\n .append(s.charAt(i))\n .append(s.substring(j + 1))\n .toString();\n f.write(n + &quot;\\n&quot;);\n count = write_anagrams(f, n, i + 1, count + 1);\n }\n }\n return count;\n }\n\n static int write_anagrams(Writer f, String s) throws IOException {\n f.write(s + &quot;\\n&quot;);\n return write_anagrams(f, s, 0, 1);\n }\n\n public static void main(String[] args) throws IOException {\n try (Scanner scanner = new Scanner(System.in);\n Writer f = new BufferedWriter(new FileWriter(&quot;AnagramsByJava.txt&quot;))) {\n System.out.print(&quot;Enter a word: &quot;);\n int count = write_anagrams(f, scanner.next());\n f.flush();\n System.out.format(&quot;%s anagrams have been written.&quot;, count);\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T13:04:40.527", "Id": "528244", "Score": "0", "body": "Thanks a lot for this code. Hey this logic is simple. It is based on swapping indices. Say u have a word ABCD... We will swap 0 and 1 index then 0 and 2 index & so on... Now each of the swapped say BACD is swapped further from 1 index, i. e, we swap 1 and 2 index, 1 and 3 so on... So it goes on in a recursion until we've got all anagrams...!!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T10:33:37.793", "Id": "267888", "ParentId": "267866", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T16:28:32.133", "Id": "267866", "Score": "2", "Tags": [ "java" ], "Title": "Generate anagrams and write them to a file" }
267866
<pre><code>function transformXCoordinate(x, xOrigin, y, yOrigin, theta) { return xOrigin + (x - xOrigin) * Math.cos(theta) - (y - yOrigin) * Math.sin(theta); } function transformYCoordinate(x, xOrigin, y, yOrigin, theta) { return yOrigin - (x - xOrigin) * Math.sin(theta) + (y - yOrigin) * Math.cos(theta); } function computeBoundingBox(x, y, w, h, theta) { let xCenter = x + (w / 2); let yCenter = y + (h / 2); let transX1 = transformXCoordinate(x, xCenter, y, yCenter, theta); let transX2 = transformXCoordinate(x + w, xCenter, y, yCenter, theta); let transX3 = transformXCoordinate(x + w, xCenter, y + h, yCenter, theta); let transX4 = transformXCoordinate(x, xCenter, y + h, yCenter, theta); let transY1 = transformYCoordinate(x, xCenter, y, yCenter, theta); let transY2 = transformYCoordinate(x + w, xCenter, y, yCenter, theta); let transY3 = transformYCoordinate(x + w, xCenter, y + h, yCenter, theta); let transY4 = transformYCoordinate(x, xCenter, y + h, yCenter, theta); let min_x = Math.min(transX1, transX2, transX3, transX4); let max_x = Math.max(transX1, transX2, transX3, transX4); let min_y = Math.min(transY1, transY2, transY3, transY4); let max_y = Math.max(transY1, transY2, transY3, transY4); return { x: min_x, y: min_y, w: max_x - min_x, h: max_y - min_y }; } </code></pre> <p>Test fiddle here: <a href="https://jsfiddle.net/qdu8kmv9/" rel="nofollow noreferrer">https://jsfiddle.net/qdu8kmv9/</a></p> <p>I am looking to make this more efficient. I am using <a href="https://stackoverflow.com/questions/622140/calculate-bounding-box-coordinates-from-a-rotated-rectangle">this question</a> as a reference.</p> <p>I tried implementing Troubadour's answer like so:</p> <pre><code>function computeBoundingBox(x, y, w, h, theta) { let ct = Math.cos(theta); let st = Math.sin(theta); let hct = h * ct; let wct = w * ct; let hst = h * st; let wst = w * st; if (theta &gt; 0) { if (theta &lt; 1.5708) { // 0 &lt; theta &lt; 90 return { x1: x - hst, y1: y, x2: x + wct, y2: y + hct + wst }; } else { // 90 &lt;= theta &lt;= 180 return { x1: x - hst + wct, y1: y + hct, x2: x, y2: y + wst }; } } else { if (theta &gt; -1.5708) { // -90 &lt; theta &lt;= 0 return { x1: x, y1: y + wst, x2: x + wct - hst, y2: y + hct }; } else { // -180 &lt;= theta &lt;= -90 return { x1: x + wct, y1: y + wst + hct, x2: x - hst, y2: y }; } } } </code></pre> <p>But it gave incorrect results. Am I converting it wrong or is his answer wrong?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T21:31:37.410", "Id": "528219", "Score": "0", "body": "The second bit of code you translated from Troubadour's answer assumes the rotation is around the bottom-left corner. Hence `y_min = A_y;` for a rotation in 0-90 degrees. The other bit of code you wrote rotates around the center of the rectangle. Obviously you can reduce computation for your first bit of code, you repeatedly call `Math.cos(theta)` and `Math.sin(theta)` (the `Math.min()` and `Math.max()` calls are trivial in comparison). Knowing that all corners are transformed in a similar way (they're all at the same distance from the center), you can simplify a lot!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T21:34:54.587", "Id": "528220", "Score": "0", "body": "Ah, I see.. I'd prefer to get Troubadour's answer working since it seems much more efficient. I'm not exactly sure how to change his snippet to make the center the point of rotation instead of the bottom left though.. Is it hard to do?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T21:37:15.817", "Id": "528221", "Score": "0", "body": "I suggest you sit and work out the math. It's just trigonometry. It's a good exercise! Also, I highly recommend that you don't take pieces of code from SO without really understanding what they do. You should have worked out the math using the answer and code you found, so that you understood why it works, and then you wouldn't have been surprised at getting different answers." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T22:59:26.853", "Id": "528258", "Score": "0", "body": "@CrisLuengo I'm still having trouble. Math was always my worst subject by far, and this is giving me a lot of headache trying to get working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T21:25:37.000", "Id": "528305", "Score": "2", "body": "Fixing non-working code is off-topic for CR. Please see [on topic](https://codereview.stackexchange.com/help/on-topic). -- _\"Code Review aims to help improve working code. If you are trying to figure out why your program crashes or produces a wrong result, ask on Stack Overflow instead. Code Review is also not the place to ask for implementing new features.\"_" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-23T07:15:35.650", "Id": "528993", "Score": "0", "body": "(Wherever you present something to get help correcting results too far from what's wanted, be sure to include enough input to reproduce the problem.)" } ]
[ { "body": "<h2>Avoid numeric inaccuracies</h2>\n<p>You can use the vector along the x axis calculated as <code>ct</code>, <code>st</code> to deduce the quadrant rather than use <code>Math.PI / 2</code> or the approximation <code>1.5708</code>\n<code>ct &gt;= 0</code> for quads 1 &amp; 4 and <code>st &gt;= 0</code> for quads 2 &amp; 3</p>\n<h2>Reduce complexity</h2>\n<p>Rather than calculate the width <code>{wct: w * ct, wst: w * st}</code> and height <code>{hct: h * ct, hst: h * st}</code>vectors in the same direction you can calculate the height vector rotated 90 CW <code>{hct: -h * st, hst: h * ct}</code></p>\n<p>Thus all the calculations after that are all additions, and the code is a little easier to read and maintain.</p>\n<h2>Avoid redundant code</h2>\n<p>When a statement block returns it should not be followed by an else clause.</p>\n<p>eg</p>\n<pre><code>if (foo) { \n return bar; \n} else { \n return foo; \n}\n</code></pre>\n<p>should be</p>\n<pre><code>if (foo) { \n return bar; \n} \nreturn foo;\n</code></pre>\n<h2>Avoid repeated code</h2>\n<p>You return the same object 4 times. Use a function to create the return object. See rewrite;</p>\n<h2>Rewrite</h2>\n<ul>\n<li>Assuming that x Axis is along w and y axis is down along h.</li>\n<li>Lacking an origin will assume that the rotation is on the point x, y.</li>\n</ul>\n<pre><code>function computeBoundingBox(x, y, w, h, theta) {\n const result = (x1, x2, y1, y2) =&gt; ({x1, y1, x2, y2});\n const ux = Math.cos(theta); // unit vector along w\n const uy = Math.sin(theta);\n const wx = w * ux, wy = w * uy; // vector along w\n const hx = h *-uy, hy = h * ux; // vector along h\n\n if (ux &gt; 0) { \n return uy &gt; 0 ?\n result(x + hx, x + wx, y, y + hy + wy) :\n result(x, x + wx + hx, y + wy, y + hy); \n }\n return uy &gt; 0 ?\n result(x + hx + wx, x, y + hy, y + wy) :\n result(x + wx, x + hx, y + wy + hy, y); \n}\n</code></pre>\n<p>Using subtraction as it is a little bit quicker (No type check needed) and a little more compact.</p>\n<pre><code>function computeBoundingBox(x, y, w, h, theta) {\n const result = (x1, x2, y1, y2) =&gt; ({x1, y1, x2, y2});\n const ux = -Math.cos(theta); \n const ny = Math.sin(theta), uy = -ny;\n return ux &lt; 0 ? \n (uy &lt; 0 ?\n result(x - h*ny, x - w*ux, y, y - h*ux - w*uy) :\n result(x, x - w*ux - h*ny, y - w*uy, y - h*ux)) : \n (uy &lt; 0 ?\n result(x - h*ny - w*ux, x, y - h*ux, y - w*uy) :\n result(x - w*ux, x - h*ny, y - w*uy - h*ux, y));\n} \n</code></pre>\n<p>Or without the return function</p>\n<pre><code>function computeBoundingBox(x, y, w, h, theta) {\n const ux = -Math.cos(theta); \n const ny = Math.sin(theta), uy = -ny;\n return ux &lt; 0 ? \n (uy &lt; 0 ?\n {x1: x - h*ny, x2: x - w*ux, y1: y, y2: y - h*ux - w*uy} :\n {x1: x, x2: x - w*ux - h*ny, y1: y - w*uy, y2: y - h*ux}) : \n (uy &lt; 0 ?\n {x1: x - h*ny - w*ux, x2: x, y1: y - h*ux, y2: y - w*uy} :\n {x1: x - w*ux, x2: x - h*ny, y1: y - w*uy - h*ux, y2: y});\n} \n</code></pre>\n<h2>Example</h2>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const ctx = canvas.getContext(\"2d\");\nvar x = 90, y = 75, w = 70, h = 25;\nvar x1 = 210, y1 = 75;\nfunction computeBoundingBox(x, y, w, h, theta) {\n const result = (x1, x2, y1, y2) =&gt; ({x1, y1, x2, y2});\n const ux = Math.cos(theta); // unit vector along w\n const uy = Math.sin(theta);\n const wx = w * ux, wy = w * uy; // vector along w\n const hx = h *-uy, hy = h * ux; // vector along h\n\n if (ux &gt; 0) { \n return uy &gt; 0 ?\n result(x + hx, x + wx, y, y + hy + wy) :\n result(x, x + wx + hx, y + wy, y + hy); \n }\n return uy &gt; 0 ?\n result(x + hx + wx, x, y + hy, y + wy) :\n result(x + wx, x + hx, y + wy + hy, y); \n}\n\nfunction computeAABBCenter(x, y, w, h, theta) {\n const ux = Math.cos(theta) * 0.5; // half unit vector along w\n const uy = Math.sin(theta) * 0.5;\n const wx = w * ux, wy = w * uy; // vector along w\n const hx = h *-uy, hy = h * ux; // vector along h\n \n // all point from top left CW\n const x1 = x - wx - hx;\n const y1 = y - wy - hy;\n const x2 = x + wx - hx;\n const y2 = y + wy - hy;\n const x3 = x + wx + hx;\n const y3 = y + wy + hy;\n const x4 = x - wx + hx;\n const y4 = y - wy + hy;\n \n return {\n x1: Math.min(x1, x2, x3, x4),\n y1: Math.min(y1, y2, y3, y4),\n x2: Math.max(x1, x2, x3, x4),\n y2: Math.max(y1, y2, y3, y4),\n };\n}\n\n\n\nfunction draw(x,y,w,h,a) {\n ctx.setTransform(1,0,0,1,x,y);\n ctx.rotate(a);\n ctx.strokeRect(0, 0,w,h);\n ctx.setTransform(1,0,0,1,0,0);\n}\nfunction drawCentered(x,y,w,h,a) {\n ctx.setTransform(1,0,0,1,x,y);\n ctx.rotate(a);\n ctx.strokeRect(-w/2,-h/2,w,h);\n ctx.setTransform(1,0,0,1,0,0);\n}\nfunction drawBounds(bounds) {\n ctx.strokeRect(bounds.x1,bounds.y1, bounds.x2-bounds.x1, bounds.y2-bounds.y1);\n}\n\nrequestAnimationFrame(renderLoop);\nfunction renderLoop(time) {\n ctx.setTransform(1,0,0,1,0,0);\n ctx.clearRect(0, 0, 300, 150);\n const ang = time / 1000;\n ctx.strokeStyle = \"#F00\";\n drawBounds(computeBoundingBox(x, y, w, h, ang));\n drawBounds(computeAABBCenter(x1, y1, w, h, ang));\n ctx.strokeStyle = \"#000\";\n draw(x, y, w, h, ang);\n drawCentered(x1, y1, w, h, ang);\n requestAnimationFrame(renderLoop);\n\n}</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>canvas { border: 1px solid black }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;canvas id=\"canvas\"&gt;&lt;/canvas&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T22:37:31.133", "Id": "528257", "Score": "0", "body": "This is a good answer. Not sure who downvoted it but I assume the reason is that it still has the problem where it rotates around the bottom-left corner instead of the center, so it still has the same problems as the one in the original post." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T23:06:02.327", "Id": "528260", "Score": "0", "body": "@RyanPeschel Objects are normally rotated around an origin, in this case the origin is given by x, y. If the OP wants to rotate around any of the corners set the origin x, y to the corner Eg bottom right `computeBoundingBox(x + w, y + h, w, h, ang);` top right `computeBoundingBox(x + w, y , w, h, ang);` and so on" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T23:17:26.227", "Id": "528261", "Score": "0", "body": "Oh so if I want to get the bounding box of a rectangle rotated around its center I just do `computeBoundingBox(x + w / 2, y + h / 2, w / 2, h / 2, ang);` ? Also, your code is giving me some errors like `xax` and `xay` are undefined. Any idea what those should be?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T23:30:16.337", "Id": "528262", "Score": "0", "body": "@RyanPeschel My bad I changed names and forgot to copy that to the second snippet. xax and xay are the unit vector eg x Axis x and x Axis y. Will fix now" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T23:36:05.507", "Id": "528263", "Score": "0", "body": "Hey thanks for the fix. Was my most recent question about the bounding box correct though? Because I'm trying `computeBoundingBox(x + w / 2, y + h / 2, w / 2, h / 2, ang);` with your code and it's still not giving me the correct bounding box. Sorry but I'm just really struggling with this (trying to get the bounding box of a rectangle rotated around its center)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T00:27:58.347", "Id": "528264", "Score": "0", "body": "@RyanPeschel Please note this is code review. We review code and the rewrites will match the code given. You are asking for a fix which is off topic. The code in the answer will only work for origins at the extremas (one of four corners). The linked question at SO (accepted answer) shows how to get bounds for any origin. I have added in example how to get AABB when origin in at center (ONLY WORKS FOR CENTER!). To get AABB for any origin use the linked SO accepted answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T01:08:08.270", "Id": "528265", "Score": "0", "body": "Yeah, sorry about that. I initially didn't realize the limitations of Troubadour's answer because it was presented as if it were just a direct alternative, so I thought I was just doing something wrong. In any case, I _still_ am having trouble with your code snippet. Maybe I should just make a stackoverflow post at this point.. Here's my fiddle in case you can spot the error. If not I'll just make another post https://jsfiddle.net/yw6k0tvz/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T01:16:56.453", "Id": "528266", "Score": "0", "body": "Ended up just posting another question here since I realize this has gone off-topic. I'll accept your answer in the interim and give you an upvote as well since I think it's rude that you've been downvoted considering how much you've helped already https://stackoverflow.com/questions/69147768/efficient-way-to-calculate-the-bounding-box-of-a-rotated-rectangle" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T23:09:05.857", "Id": "267876", "ParentId": "267873", "Score": "4" } } ]
{ "AcceptedAnswerId": "267876", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T20:46:11.857", "Id": "267873", "Score": "-1", "Tags": [ "javascript", "performance", "algorithm" ], "Title": "Finding the minimum bounding box of a rotated rectangle" }
267873
<p>There are some image quality assessment methods for &quot;no-reference&quot; image quality analysis. Here, I am attempting to calculate the <a href="https://www.mathworks.com/help/images/ref/niqe.html" rel="nofollow noreferrer">NIQE score</a> and <a href="https://www.mathworks.com/help/images/ref/piqe.html" rel="nofollow noreferrer">PIQE score</a> for batch of images in Matlab. The file structure of test images and the experimental implementation are listed as below.</p> <ul> <li><p>File structure of test images</p> <p>The matlab code <code>.m</code> file is placed in the project root folder and there are multiple folders which is named by its data index number for placing test images. For example, there are <code>1/1.bmp</code>, <code>1/2.bmp</code>, <code>1/3.bmp</code>, ..., <code>2/1.bmp</code>, <code>2/2.bmp</code>, ... The results of NIQE score and PIQE score for the same data index are collected in a Excel file. For example, the results of images in folder <code>1/</code> are in <code>NIQE_PIQE_1.xlsx</code>.</p> <pre><code>- / | - NIQEPIQEcalculation.m | - 1/ | - 1.bmp | - 2.bmp | - 3.bmp | - 4.bmp ... </code></pre> </li> <li><p>NIQE score and PIQE score calculation (<code>NIQEPIQEcalculation.m</code>):</p> <pre><code>VideoLength = 1000; for DataIndex = 1:10 Index = zeros(1, VideoLength); NIQE_results = zeros(1, VideoLength); PIQE_results = zeros(1, VideoLength); for i = 1:VideoLength Index(i) = i; InputFileName = fullfile('.', num2str(DataIndex), [num2str(i), '.bmp']); if (~isfile(InputFileName)) fprintf(&quot;file: %s does not exist!\n&quot;, InputFileName); continue; end image = imread(InputFileName); NIQE_results(i) = niqe(image); [PIQE_results(i), activityMask, noticeableArtifactsMask, noiseMask] = piqe(image); end filename = fullfile('.', ['NIQE_PIQE_', num2str(DataIndex), '.xlsx']); writecell({&quot;Index&quot;}, filename, 'Sheet', 1, 'Range', 'A1'); %% Title writecell({&quot;NIQE_results&quot;}, filename, 'Sheet', 1, 'Range', 'B1'); %% Title writecell({&quot;PIQE_results&quot;}, filename, 'Sheet', 1, 'Range', 'C1'); %% Title writematrix(Index', filename, 'Sheet', 1, 'Range', 'A2'); writematrix(NIQE_results', filename, 'Sheet', 1, 'Range', 'B2'); writematrix(PIQE_results', filename, 'Sheet', 1, 'Range', 'C2'); end </code></pre> </li> </ul> <p><strong>Test Results</strong></p> <p>The test result as below is the NIQE values and PIQE values of image frames of <a href="https://peach.blender.org/" rel="nofollow noreferrer">Big Buck Bunny video</a> from index 1 to 30.</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: center;">Index</th> <th style="text-align: center;">NIQE_results</th> <th style="text-align: center;">PIQE_results</th> </tr> </thead> <tbody> <tr> <td style="text-align: center;">1</td> <td style="text-align: center;"></td> <td style="text-align: center;">100</td> </tr> <tr> <td style="text-align: center;">2</td> <td style="text-align: center;"></td> <td style="text-align: center;">100</td> </tr> <tr> <td style="text-align: center;">3</td> <td style="text-align: center;"></td> <td style="text-align: center;">100</td> </tr> <tr> <td style="text-align: center;">4</td> <td style="text-align: center;"></td> <td style="text-align: center;">100</td> </tr> <tr> <td style="text-align: center;">5</td> <td style="text-align: center;">12.2099094425521</td> <td style="text-align: center;">91.8023394419114</td> </tr> <tr> <td style="text-align: center;">6</td> <td style="text-align: center;">11.6193285900205</td> <td style="text-align: center;">89.3472471350986</td> </tr> <tr> <td style="text-align: center;">7</td> <td style="text-align: center;">10.8269712726979</td> <td style="text-align: center;">89.5699974060974</td> </tr> <tr> <td style="text-align: center;">8</td> <td style="text-align: center;">10.2604598394096</td> <td style="text-align: center;">78.2692546063272</td> </tr> <tr> <td style="text-align: center;">9</td> <td style="text-align: center;">9.41794970557878</td> <td style="text-align: center;">93.1639071925716</td> </tr> <tr> <td style="text-align: center;">10</td> <td style="text-align: center;">8.98879911222304</td> <td style="text-align: center;">89.6933273345099</td> </tr> <tr> <td style="text-align: center;">11</td> <td style="text-align: center;">7.83674635699391</td> <td style="text-align: center;">72.1679314095433</td> </tr> <tr> <td style="text-align: center;">12</td> <td style="text-align: center;">6.93615995922902</td> <td style="text-align: center;">71.1787240352723</td> </tr> <tr> <td style="text-align: center;">13</td> <td style="text-align: center;">6.25146723699582</td> <td style="text-align: center;">55.5303211057818</td> </tr> <tr> <td style="text-align: center;">14</td> <td style="text-align: center;">5.95755729784091</td> <td style="text-align: center;">49.3978064822725</td> </tr> <tr> <td style="text-align: center;">15</td> <td style="text-align: center;">5.8969449994385</td> <td style="text-align: center;">32.1378553044025</td> </tr> <tr> <td style="text-align: center;">16</td> <td style="text-align: center;">5.9352387933508</td> <td style="text-align: center;">28.0569685896641</td> </tr> <tr> <td style="text-align: center;">17</td> <td style="text-align: center;">5.84568114108705</td> <td style="text-align: center;">25.2654908924866</td> </tr> <tr> <td style="text-align: center;">18</td> <td style="text-align: center;">5.83724662032512</td> <td style="text-align: center;">27.3660487930311</td> </tr> <tr> <td style="text-align: center;">19</td> <td style="text-align: center;">5.77857438338826</td> <td style="text-align: center;">25.3675316576998</td> </tr> <tr> <td style="text-align: center;">20</td> <td style="text-align: center;">5.88214805832496</td> <td style="text-align: center;">20.2540102673404</td> </tr> <tr> <td style="text-align: center;">21</td> <td style="text-align: center;">5.84028592378761</td> <td style="text-align: center;">17.7404899333201</td> </tr> <tr> <td style="text-align: center;">22</td> <td style="text-align: center;">5.75832883896143</td> <td style="text-align: center;">15.3890486272598</td> </tr> <tr> <td style="text-align: center;">23</td> <td style="text-align: center;">5.88415908864208</td> <td style="text-align: center;">16.7476293145601</td> </tr> <tr> <td style="text-align: center;">24</td> <td style="text-align: center;">5.98381170240161</td> <td style="text-align: center;">13.8769349316869</td> </tr> <tr> <td style="text-align: center;">25</td> <td style="text-align: center;">5.73277852694226</td> <td style="text-align: center;">14.4188477587674</td> </tr> <tr> <td style="text-align: center;">26</td> <td style="text-align: center;">5.94560227365676</td> <td style="text-align: center;">12.3147528349809</td> </tr> <tr> <td style="text-align: center;">27</td> <td style="text-align: center;">6.02735742430951</td> <td style="text-align: center;">10.2252287321363</td> </tr> <tr> <td style="text-align: center;">28</td> <td style="text-align: center;">5.84366191580193</td> <td style="text-align: center;">10.1362182789466</td> </tr> <tr> <td style="text-align: center;">29</td> <td style="text-align: center;">5.82309621870735</td> <td style="text-align: center;">11.37956719739</td> </tr> <tr> <td style="text-align: center;">30</td> <td style="text-align: center;">5.86973169314128</td> <td style="text-align: center;">12.5193078645003</td> </tr> </tbody> </table> </div> <p>All suggestions are welcome.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-10T23:49:05.133", "Id": "267877", "Score": "0", "Tags": [ "performance", "excel", "file", "image", "matlab" ], "Title": "NIQE score and PIQE score calculation for batch of images in Matlab" }
267877
<p>I have the following code which works great to do what it is meant to do. It scrapes the bodies of all e-mails in the inbox at an e-mail address using IMAP and retrieves the unique code sent inside the body and stores it in a database with the amount paid. I'm hoping to make it so when a user purchases something they can send an Interac e-transfer and then enter the code that both of us receive via e-mail in the website and it will apply the credit of the e-transfer to their account/purchase.</p> <p>However, after setting it up on a cron job to cycle every few minutes so the content in the database stays fresh it eventually exceeds the bandwidth for the account within a day or so (not positive on how long it took but it didn't take long). Now, like I said the code works it's just very resource intensive apparently.</p> <p>I do not pipe the script because the e-mail account has already been set up a while ago and we do use the account for other e-transfers which I review manually for other transactions.</p> <ol> <li>Is there any way to clean it up so it works the same but uses less resources/bandwidth?</li> <li>Would it be better to run it when a user enters their payment code? Depending on the number of users running it this could also lead to bandwidth troubles.</li> <li>Are there any improvements or what ideas do you have?</li> </ol> <pre class="lang-php prettyprint-override"><code> define(&quot;MAX_EMAIL_COUNT&quot;, $_POST['maxcount']); /* took from https://gist.github.com/agarzon/3123118 */ function extractEmail($content) { $regexp = '/([a-z0-9_\.\-])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; preg_match_all($regexp, $content, $m); return isset($m[0]) ? $m[0] : array (); } function getAddressText(&amp;$emailList, &amp;$nameList, $addressObject) { $emailList = ''; $nameList = ''; foreach ($addressObject as $object) { $emailList .= ';'; if (isset($object-&gt;personal)) { $emailList .= $object-&gt;personal; } $nameList .= ';'; if (isset($object-&gt;mailbox) &amp;&amp; isset($object-&gt;host)) { $nameList .= $object-&gt;mailbox . &quot;@&quot; . $object-&gt;host; } } $emailList = ltrim($emailList, ';'); $nameList = ltrim($nameList, ';'); } function processMessage($mbox, $messageNumber) { global $db; // get imap_fetch header and put single lines into array $header = imap_rfc822_parse_headers(imap_fetchheader($mbox, $messageNumber)); $timestamp = strtotime($header-&gt;Date); $fromEmailList = ''; $fromNameList = ''; if (isset($header-&gt;from)) { getAddressText($fromEmailList, $fromNameList, $header-&gt;from); } $toEmailList = ''; $toNameList = ''; if (isset($header-&gt;to)) { getAddressText($toEmailList, $toNameList, $header-&gt;to); } $body = imap_fetchbody($mbox, $messageNumber, 1); //echo &quot;&lt;pre&gt;&quot;.print_r($body,true).&quot;&lt;/pre&gt;&quot;; /* Find Reference Number */ //echo &quot;&lt;pre style='background-color: #A2A2A2; border: 1px solid black'&gt;$body&lt;/pre&gt;&quot;; $searchfor = 'Reference Number'; // get the file contents, assuming the file to be readable (and exist) $contents = $body; // escape special characters in the query $pattern = preg_quote($searchfor, '/'); // finalise the regular expression, matching the whole line $pattern = &quot;/^.*$pattern.*\$/m&quot;; // search, and store all matching occurences in $matches if(preg_match_all($pattern, $contents, $matches)){ $reference = trim(str_replace('Reference Number : ','',$matches[0][0])); } else{ } /* Find Amount Paid */ //echo &quot;&lt;pre style='background-color: #A2A2A2; border: 1px solid black'&gt;$body&lt;/pre&gt;&quot;; $searchfor = 'has sent you a money transfer for the amount of'; // get the file contents, assuming the file to be readable (and exist) $contents = $body; // escape special characters in the query $pattern = preg_quote($searchfor, '/'); // finalise the regular expression, matching the whole line $pattern = &quot;/^.*$pattern.*\$/m&quot;; // search, and store all matching occurences in $matches if(preg_match_all($pattern, $contents, $matches)){ $amount = trim(preg_replace(&quot;/[^0-9\.]/&quot;, &quot;&quot;,$matches[0][0]),'.'); } else{ } $bodyEmailList = implode(';', extractEmail($body)); // Delete all messages older than one year (31557600 seconds). Divide it by two for six months. if($timestamp &lt; time()-31557600) { if(imap_delete($mbox,$messageNumber)) { /*echo &quot;&lt;strong&gt;&quot;; print_r($messageNumber . ' , ' . date(&quot;F j, Y g:i A&quot;,$timestamp).' , ' . 'Deleted' . &quot;\n&quot;); echo &quot;&lt;/strong&gt;&quot;;*/ } } else { if(!empty($reference) &amp;&amp; !empty($amount)) { if($fromNameList == &quot;catch@payments.interac.ca&quot; &amp;&amp; $toNameList!='etransfers@example.com') { $query = &quot;SELECT * FROM `&quot;.$db-&gt;prefix.&quot;payments_etransfer` WHERE `reference_id` = '&quot;.$reference.&quot;'&quot;; $select = $db-&gt;select($query); if($db-&gt;num_rows($select) &gt; 0) { } else { $do = $db-&gt;insert_sql(&quot;INSERT INTO `&quot;.$db-&gt;prefix.&quot;payments_etransfer` SET `email_id` = '&quot;.$messageNumber.&quot;', `timestamp` = '&quot;.$timestamp.&quot;', `reference_id` = '&quot;.$reference.&quot;', `amount` = '&quot;.$amount.&quot;', `sender` = '&quot;.$fromEmailList.&quot;'&quot;); if($do) { } else { echo &quot;Error&lt;br&gt;&lt;blockquote&gt;&lt;pre&gt;&quot;; print_r($messageNumber . ',' . $timestamp. ',' . $reference . ',$' . $amount . ',' . $fromEmailList . ',' . $fromNameList . ',' . $toEmailList . ',' . $toNameList . ',' . $bodyEmailList . &quot;\n&quot; ); echo &quot;&lt;/pre&gt;&lt;/blockquote&gt;&quot;; } } } } } } // imap_timeout(IMAP_OPENTIMEOUT, 300); // Open pop mailbox if (!$mbox = imap_open($_POST['mailbox'], $_POST['login'], $_POST['password'])) { die('Cannot connect/check pop mail! Exiting'); } if ($hdr = imap_check($mbox)) { $msgCount = $hdr-&gt;Nmsgs; } else { echo &quot;Failed to get mail&quot;; exit; } /* echo &quot;&lt;pre&gt;&quot;; echo 'emails count=' . $msgCount . &quot;\n\n\n&quot;; echo &quot;record number,from emails list,from names list,to emails list, to names list,extracted from body\n&quot;; */ /* might improve performance according to http://www.php.net/manual/en/function.imap-headerinfo.php#98809 imap_headers($mbox); */ for ($X = $msgCount; $X &gt; 0; $X--) { if($X &gt; 0) { processMessage($mbox, $X); } } /*echo &quot;&lt;/pre&gt;&quot;;*/ imap_expunge($mbox); imap_close($mbox); /* </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T11:23:17.450", "Id": "528271", "Score": "0", "body": "I have no idea what you are actually using this for, but to scrape financial details from within an e-mail box, which you do not own, seems a recipe for disaster. It sounds like it doesn't matter that this will be highly unreliable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T02:33:12.237", "Id": "528320", "Score": "0", "body": "@mdfst13 This is the entire code ran by cron. It circulates through all the e-mails in the inbox so yes, it reads all of them multiple times. Marks any that are 1 year old set for deletion. I could set that limit lower to a week or so. I could also do it so it deletes it right away but as I want a chance to view the actual e-mail before it removes it from the system." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T02:38:27.833", "Id": "528321", "Score": "0", "body": "@KIKOSoftware I do own the e-mail box and the e-mail box is on my server as part of my website (my domain). It is reliable and works great. It does exactly what I want except for running up the bandwidth and then shutting down the website due to that fact; which is why I posted here to see how I can improve on it.\n\nThere are a few unreliable areas that could potentially cause problems but at the moment I am not worried about those." } ]
[ { "body": "<h3>Only read new messages</h3>\n<p>From a <a href=\"https://codereview.stackexchange.com/questions/267879/scrape-e-mails-using-imap-from-cron?noredirect=1#comment528320_267879\">comment</a>:</p>\n<blockquote>\n<p>It circulates through all the e-mails in the inbox so yes, it reads all of them multiple times.</p>\n</blockquote>\n<p>I think that this is the source of your bandwidth problem. Either</p>\n<ol>\n<li>Turn down the cron frequency (easy but least effective).</li>\n<li>Track which emails you've already read and don't read them again.</li>\n<li>Change the program to only look at emails that arrived since you last looked (most difficult but also most efficient in terms of bandwidth).</li>\n</ol>\n<h3>Tracking seen messages</h3>\n<p>So in this code:</p>\n<blockquote>\n<pre><code> for ($X = $msgCount; $X &gt; 0; $X--) {\n if($X &gt; 0) {\n processMessage($mbox, $X);\n }\n\n }\n</code></pre>\n</blockquote>\n<p>First, it could just be</p>\n<pre><code> for ($X = $msgCount; $X &gt; 0; $X--) {\n processMessage($mbox, $X);\n }\n</code></pre>\n<p>The <code>if</code> doesn't do anything.</p>\n<p>But more importantly, you want to recognize if you've seen a message previously.</p>\n<pre><code> $seen = false;\n for ($X = $msgCount; !$seen &amp;&amp; ($X &gt; 0); $X--) {\n $seen = processMessage($mbox, $X);\n }\n</code></pre>\n<p>Then change <code>processMessage</code> to <code>return false;</code> at the end. And earlier, when you process an email, save the email identifier so that the next time you see that email, you can <code>return true</code>.</p>\n<blockquote>\n<pre><code> $header = imap_rfc822_parse_headers(imap_fetchheader($mbox, $messageNumber));\n</code></pre>\n</blockquote>\n<p>This could be simplified to</p>\n<pre><code> $header = imap_headerinfo($mbox, $messageNumber);\n</code></pre>\n<p>That will also give you access to <code>$header-&gt;message_id</code>, which is the thing that you can store to see if you've seen a message previously. Alternately, <code>imap_uid</code> also gives the message ID.</p>\n<h3>Move the message</h3>\n<p>Another simple option would be to move the message out of the inbox and into a separate folder. So messages in inbox need to be processed. Messages in the folder have already been processed. The <code>imap_mail_move</code> function moves messages.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T03:42:36.503", "Id": "267942", "ParentId": "267879", "Score": "2" } }, { "body": "<ol>\n<li><p><code>extractEmail()</code> is actually generating an array of email<strong>s</strong>, so the function name should be pluralized. <code>/[a-z0-9_]/i</code> is more simply expressed as <code>\\w</code>. Inside of a character class, a dot doesn't need to be escaped. If a hyphen is the first or final character in a character class or if it immediately follows a range of characters it does not need to be escaped. An <code>@</code> symbol is not a special character in regex, so it doesn't need escaping. You aren't using these captured substrings, so it seems logical to omit them or make them non-capturing where appropriate. Just so you know, there will be valid emails (fringe cases) that will not be matched by your email pattern. If this is sufficient for your project scope, then I suppose you don't need to spend anymore time on it -- just be careful where else you use this pattern.</p>\n<pre><code>function extractEmails(string $content): array {\n $regexp = '/[\\w.-]+@(?:[a-z\\d-]+\\.)+[a-z\\d]{2,4}+/i';\n return preg_match_all($regexp, $content, $m) ? $m[0] : [];\n}\n</code></pre>\n</li>\n<li><p>I find function name <code>getAddressText()</code> to be semantically misleading -- it is not &quot;getting&quot; anything, it is mutating the first two arguments which are reference variables. Rather than unconditionally wiping the data clean on the first two lines, then doing a bunch of string concatenation, then trimming the excess, I find it tidier to create arrays, then implode them. I suppose, if I am being honest, you never need to respect the data coming in via the first two parameters, so I think I'd just pass in <code>$addressObject</code> and return a two-element array.</p>\n<pre><code>function getAddressEmailsAndLists(array $addressObjects): array { \n $emails = [];\n $names = [];\n foreach ($addressObject as $object) {\n $emails[] = $object-&gt;personal ?? '';\n $names[] = isset($object-&gt;mailbox, $object-&gt;host)\n ? $object-&gt;mailbox . &quot;@&quot; . $object-&gt;host\n '';\n } \n return [implode(';', $emails), implode(';', $names)],\n}\n</code></pre>\n<p>One call of it would look like: <code>[$fromEmailList, $fromNameList] = getAddressText($header-&gt;from);</code></p>\n</li>\n<li><p>I am concerned by both occurrences of <code>$pattern = &quot;/^.*$pattern.*\\$/m&quot;;</code>. First, the escaping slash before <code>$</code> means that you are matching a literal dollar sign -- but your comment suggests you mean to mark the end of the line. Do you mean to remove the slash or match a literal dollar sign?</p>\n</li>\n<li><p><code>[^0-9\\.]</code> can be simplified to <code>[^\\d.]+</code> -- this will match the same list of characters, but it will make potentially longer matches and therefore fewer replacements.</p>\n</li>\n<li><p>Your sql does not look stable or secure to me because you are not using prepared statements with placeholders. This looks like a major problem for your database query wrappers.</p>\n</li>\n<li><p>I agree with @mdfst13's assessment of your <code>for()</code> loop logic.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:14:19.070", "Id": "267945", "ParentId": "267879", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T02:54:32.107", "Id": "267879", "Score": "4", "Tags": [ "php", "email" ], "Title": "Scrape E-Mails using IMAP from cron" }
267879
<p>I'm new to programming and was tasked with programming a generic circular FIFO queue, without using anything but an underlying array and self-programmed methods. I still don't know how to approach bigger projects like this yet. I managed to program something that technically works, but I need someone brutal to really tear this apart and let me know how I can improve. I try to practice when I can, but I still miss so many obvious things and get stuck constantly. I already submitted this work, but you can refrain from explicit answers anyway. Any tips at all are very much appreciated.</p> <p>The array needs to be able to double or be halved as needed for more memory or to take up less memory. Then it needs to be able to print everything out.</p> <pre><code>public class FloatingQueue&lt;T&gt; { private T[] theArray; private static final int initialCap = 10; private int capacity = initialCap; private int theHead = 0; private int theTail = -1; private int size; FloatingQueue() { theArray = (T[]) new Object[ initialCap ]; } //adds object to the end of the queue and returns true if array is now changed successfully public boolean offer ( T newData ) { boolean hasChanged = false; String changeCheck = this.toString(); size++; theTail++; if ( size &gt; capacity ) { this.doubleUp(); hasChanged = true; } if ( size &gt; 1 &amp; theTail == theHead | theArray[0] == null ) { theTail = returnNullIndex(); } theArray[theTail] = newData; if ( this.toString() != changeCheck ) { hasChanged = true; } return hasChanged; } //removes and returns first object in the queue public T poll() { if ( size == 0 ) { return null; } T temp = theArray[theHead]; theArray[theHead] = null; size--; if ( this.size() &gt; 0 ) theHead++; if ( size != 0 &amp; theArray[theHead] == null ) { theHead = returnNonNullIndex(); if ( returnNullIndex() &gt; 0 &amp; returnNullIndex() &lt; theTail ) { theHead = 0; } if ( size &lt; capacity / 4 &amp;&amp; capacity != 10 ) { this.downSize(); } } return temp; } //returns the first object and does not remove it public T peek() { T temp; if ( isEmpty() == false ) { temp = theArray[theHead]; return temp; } return null; } //Return number of objects in queue public int size() { return size; } //returns true if queue is empty public boolean isEmpty() { boolean noElements = false; if ( size() == 0 ) noElements = true; return noElements; } //empties the queue public void clear() { for ( int i = 0; i &lt; theArray.length; i++ ) { if ( theArray == null ) break; theArray[i] = null; } size = 0; theHead = 0; theTail = -1; } //should hopefully print out the strings in order public String toString() { String allElements = &quot;[&quot;; if ( size &gt; 0 ) allElements += theArray[theHead].toString() + &quot;,&quot;; for ( int i = 0; i &lt; capacity; i++ ) { if ( theArray[i] != null &amp;&amp; theArray[i] != theArray[theHead] &amp;&amp; theArray[i] != theArray[theTail] ) { allElements += theArray[i].toString() + &quot;,&quot;; } } if ( size &gt; 1 ) allElements += theArray[theTail] + &quot;,&quot;; allElements = (size() == 0) ? allElements : allElements.substring(0, allElements.length()-1); allElements += &quot;]&quot;; return allElements; } //doubles array size and copies into bigger array private void doubleUp ( ) { capacity *= 2; T[] biggerArray = (T[]) new Object[ capacity ]; for (int i = 0; i &lt; theArray.length; i++) { biggerArray[i] = theArray[i]; } theArray = biggerArray; } //halves underlying array and copies over private void downSize ( ) { capacity /= 2; int smallArrayIndex = 0; T[] smallerArray = (T[]) new Object[ capacity ]; for ( int i = theHead; i &lt;= theTail; i++ ) { smallerArray[smallArrayIndex] = theArray[i]; smallArrayIndex++; } theHead = 0; theTail = size - 1; theArray = smallerArray; } //finds first null index private int returnNullIndex () { for (int i = 0; i &lt; theArray.length-1; i++) { if ( theArray[i] == null ) { return i; } } return -1; } //finds non null index private int returnNonNullIndex () { for (int i = 0; i &lt; theArray.length-1; i++) { if ( theArray[i] != null ) { return i; } } return -1; } </code></pre>
[]
[ { "body": "<p><strong>Advice 1</strong></p>\n<p>In Java Collection Framework (the data structure framework residing in <code>java.util.*</code>), the item type is denoted by <code>E</code>, and not <code>T</code>. I suggest you do this:</p>\n<pre><code>public class FloatingQueue&lt;E&gt; {\n ... E here and there.\n}\n</code></pre>\n<p><strong>Advice 2</strong></p>\n<pre><code>FloatingQueue() {\n ....\n}\n</code></pre>\n<p>You are clearly missing the <code>public</code> keyword here; without it, only the code in the same package can construct your queue. Declare like this</p>\n<pre><code>public FloatingQueue() {\n ....\n}\n</code></pre>\n<p><strong>Advice 3</strong></p>\n<p><code>FloatingQueue</code> is a strange name for your class. What is <code>Floating</code>? Consider <code>ArrayFIFOQueue</code> instead to denote that it's a FIFO queue implemented via arrays (and not linked lists).</p>\n<p><strong>Advice 4</strong></p>\n<pre><code>theArray = (T[]) new Object[ initialCap ];\n</code></pre>\n<p>According to common Java programming conventions, there should not be spaces within the square brackets <code>[]</code>. Instead, write like this:</p>\n<pre><code>theArray = (T[]) new Object[initialCap];\n</code></pre>\n<p><strong>Advice 5</strong></p>\n<p>Also, private static constants should be named using uppercase SNAKE_CASE:</p>\n<pre><code>private static final int INITIAL_CAPACITY = 10;\n</code></pre>\n<p><strong>Advice 6</strong></p>\n<p>Write always <code>if ( condition ) {</code> as <code>if (condition) {</code>.</p>\n<p><strong>Advice 7</strong></p>\n<pre><code>private int theHead = 0;\nprivate int theTail = -1;\n</code></pre>\n<p>Consider the following instead:</p>\n<pre><code>private int headIndex = 0;\nprivate int tailIndex = 0;\n</code></pre>\n<p><strong>Advice 8</strong></p>\n<p>The <code>offer</code> method is overkilling it in my opinion. Consider this:</p>\n<pre><code>public void offer(E item) {\n if (shouldExtendArray()) {\n extendArray();\n }\n \n array[tailIndex++] = item;\n size++;\n \n if (tailIndex == array.length) {\n tailIndex = 0;\n }\n}\n</code></pre>\n<p><strong>Advice 9</strong></p>\n<p>Your <code>poll</code> method requires some comment explanation on what is being done their. Looks like you degrade it to linear time (instead of possible constant time) using the <code>returnNullIndex</code> and <code>returnNonNullIndex</code>.</p>\n<p><strong>Advice 10</strong></p>\n<pre><code>if ( size != 0 &amp; theArray[theHead] == null ) {\n</code></pre>\n<p>While <code>&amp;</code> is not a bit operand in this context, it differs from conventional <code>&amp;&amp;</code> in that it <em>does not short-circuit</em>. For example <code>getFalse() &amp; getTrue()</code> will evaluate both the calls even if the first <code>getFalse()</code> returns <code>false</code>. You don't need this. Use <code>&amp;&amp;</code> and <code>||</code> instead of <code>&amp;</code> and <code>|</code>, respectively.</p>\n<p><strong>Summa summarum</strong></p>\n<p>All in all, I thought about the following rewrite:</p>\n<pre><code>public class ArrayFIFOQueue&lt;E&gt; {\n\n private static final int INITIAL_CAPACITY = 10;\n\n private E[] array;\n private int headIndex;\n private int tailIndex;\n private int size;\n\n public ArrayFIFOQueue() {\n this.array = (E[]) new Object[INITIAL_CAPACITY];\n }\n\n public void offer(E item) {\n if (shouldExtendArray()) {\n extendArray();\n }\n\n array[tailIndex++] = item;\n size++;\n\n if (tailIndex == array.length) {\n tailIndex = 0;\n }\n }\n\n public E peek() {\n return size == 0 ? null : array[headIndex];\n }\n\n public int size() {\n return size;\n }\n\n public boolean isEmpty() {\n return size == 0;\n }\n\n public void clear() {\n // Help garbage collector:\n for (int i = 0; i &lt; size; i++) {\n int index = (headIndex + i) % array.length;\n array[index] = null;\n }\n\n size = 0;\n }\n\n public E poll() {\n if (size == 0) {\n return null;\n }\n\n E returnValue = array[headIndex];\n array[headIndex++] = null;\n\n if (headIndex == array.length) {\n headIndex = 0;\n }\n\n size--;\n\n if (shouldContract()) {\n contractArray();\n }\n\n return returnValue;\n }\n\n private boolean shouldExtendArray() {\n return size == array.length;\n }\n\n private boolean shouldContract() {\n return size * 4 &lt;= array.length &amp;&amp; array.length &gt;= 4 * INITIAL_CAPACITY;\n }\n\n private void extendArray() {\n assert size == array.length;\n E[] newArray = (E[]) new Object[2 * array.length];\n\n for (int i = 0; i &lt; array.length; i++) {\n newArray[i] = array[(headIndex + i) % array.length];\n }\n\n this.array = newArray;\n this.headIndex = 0;\n this.tailIndex = size;\n }\n\n private void contractArray() {\n assert size &lt;= array.length / 4;\n E[] newArray = (E[]) new Object[array.length / 4];\n\n for (int i = 0; i &lt; size; i++) {\n newArray[i] = array[(headIndex + i) % array.length];\n }\n\n this.array = newArray;\n this.headIndex = 0;\n this.tailIndex = size;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T08:07:55.077", "Id": "528232", "Score": "0", "body": "Advice-6 might be redundant might be using some sort of formatter" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T05:48:11.933", "Id": "267883", "ParentId": "267880", "Score": "4" } }, { "body": "<p>Here are a couple details from a quick glance at the code:</p>\n<ul>\n<li><p>If you are implemented a queue, consider actually implementing the Java <a href=\"https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Queue.html\" rel=\"nofollow noreferrer\">Queue</a> interface: <code>FloatingQueue implements Queue</code></p>\n</li>\n<li><p>Check you usage of booleans:</p>\n</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>if (isEmpty() == false) {\n ...\n}\n</code></pre>\n<p>Is written in a more readable way as:</p>\n<pre class=\"lang-java prettyprint-override\"><code>if (!isEmpty()) {\n ...\n}\n</code></pre>\n<p>Also, your <code>isEmpty</code> method is simply returning whether the <code>size</code> is zero. Then just do that, and remove the unneeded intermediate variable:</p>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean isEmpty() {\n return size() == 0;\n}\n</code></pre>\n<ul>\n<li>In your <code>offer</code> method, I'm not completely sure under which circumstances you would need to compare the queue to itself to check whether it has changed. If you added a new element to it, it definitely has changed. If what you want is to check the added element is not null, do that explicitly at the beginning of the method.</li>\n</ul>\n<pre class=\"lang-java prettyprint-override\"><code>public boolean offer ( T newData ) {\n // This already makes your offer method a O(N) time complexity in best case scenario\n String changeCheck = this.toString();\n ...\n if (this.toString() != changeCheck) {\n ...\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T07:10:50.240", "Id": "267884", "ParentId": "267880", "Score": "2" } }, { "body": "<p>When having no clue on how to resolve such a problem it often helps to go through a couple of examples or use cases.\nRe-using those later as test cases helps to ensure everything works as intended.</p>\n<p>Try to keep the cases as small as possible but just big enough.\nWhen choosing them consider the corner cases of how things operate.</p>\n<p>E.g. let's take a capacity of 3</p>\n<ul>\n<li>What if <code>theTail</code> is at the end of the array and your &quot;offer&quot;?</li>\n<li>What if <code>theTail</code> is at the middle (,start, end) of the array on expanding the size?</li>\n<li>What if <code>theHead</code> is at the end (,start, middle) of the array on shrinking the size?</li>\n</ul>\n<p>Observations on coderodde's solution.</p>\n<ul>\n<li>Polled data gets cleared to remove no longer needed data, this is not needed to have its solution correctly function. However as long as the array has the references to the data, the data cannot be garbage collected.</li>\n<li>It ensures that the <code>theHead</code> and <code>theTail</code> stay within the array.</li>\n<li>Some implementations have a <code>reserve(int)</code> function very similar to <code>extendArray</code> that allows to make the FIFO a certain size if such a size is expected to be useful (e.g. you know you will store lots of data).</li>\n</ul>\n<p>Observations on your solution:</p>\n<ul>\n<li>There is hysteresis between extending and reducing the array. (Offer followed by poll will not extend and reduce immediately after each other.)</li>\n</ul>\n<p>General:</p>\n<ul>\n<li>A stack is very common FIFO, where the offer operation is called push and the poll is called pop.</li>\n<li>Somehow I'm tempted to swap head and tail or would call them &quot;read&quot; and &quot;write&quot; pointer.</li>\n<li>It's possible to not track size but derive it from <code>Head</code> and <code>Tail</code>. (for indexing use them <code>% size</code>, store them with <code>% (2*size)</code>, and <code>Size=Tail-Head</code>, except if <code>Head&gt;Tail</code> in which case a small correction is needed.</li>\n<li>Lots of hardware prefers values with are <span class=\"math-container\">\\$2^n\\$</span> (e.g. 8 or 16) for the capacity because it simplifies calculations in binary numbers.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T02:42:34.570", "Id": "528323", "Score": "0", "body": "\"There is hysteresis between extending and reducing the array. (Offer followed by poll will not extend and reduce immediately after each other.)\" Note that this kind of hysteresis is *required* for resizable array data structures to achieve amortized constant time operation. If you use the same cutoff for growing and shrinking, you can get very bad performance if you wobble around the cutoff." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T11:15:18.510", "Id": "528338", "Score": "0", "body": "\"A stack is very common FIFO, where the offer operation is called push and the poll is called pop.\" - this is simply misinformation. A stack is LIFO (Last In First Out) which is a very different thing." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T16:03:12.967", "Id": "267894", "ParentId": "267880", "Score": "2" } } ]
{ "AcceptedAnswerId": "267883", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T04:13:16.133", "Id": "267880", "Score": "4", "Tags": [ "java", "array", "homework", "generics", "queue" ], "Title": "FIFO array/queue" }
267880
<p>I've been tasked with creating some way to encrypt arbitrary text for a .NET Core app, with the following requirements:</p> <ul> <li>Messages will be between 10 bytes and 1 kB.</li> <li>Boss doesn't want me to use AES-GCM (which I know would be the sensible option as it's already included in .NET Core and I've already read that implementing your own encryption is a bad idea) and wants me to come up with a custom implementation.</li> <li>This implementation will not be used too much, usually only at the app's startup.</li> </ul> <p>After some reading, I've come up with the following:</p> <p>Encryption:</p> <ol> <li>Convert message to UTF-8 bytes (<code>plaintext</code>)</li> <li>Generate a random <code>salt</code>.</li> <li>Using <code>salt</code>, derive enough material with PBKDF2 for an <code>aes_key</code> and an <code>hmac_key</code>.</li> <li>Generate a random <code>iv</code>.</li> <li>AES-CBC encrypt <code>plaintext</code> with <code>aes_key</code> and <code>iv</code> (<code>ciphertext</code>).</li> <li>Compute an HMAC-SHA-256 <code>hash</code> of <code>ciphertext||iv</code>.</li> <li>Return <code>salt||hash||iv||ciphertext</code> (<code>payload</code>).</li> </ol> <p>Decryption:</p> <ol> <li>Extract <code>salt</code>, <code>hash</code>, <code>iv</code>, <code>ciphertext</code> from <code>payload</code>.</li> <li>Using <code>salt</code>, derive enough material with PBKDF2 for an <code>aes_key</code> and an <code>hmac_key</code>.</li> <li>Compute an HMAC-SHA-256 <code>computed_hash</code> of <code>ciphertext||iv</code>.</li> <li>If <code>computed_hash</code> and <code>hash</code> are different, reject <code>payload</code>.</li> <li>AES-CBC decrypt <code>ciphertext</code> with <code>aes_key</code> and <code>iv</code> (<code>plaintext</code>).</li> <li>Convert <code>plaintext</code> to UTF-8 string (<code>message</code>).</li> <li>Return <code>message</code>.</li> </ol> <p>The implementation is as follows:</p> <pre class="lang-csharp prettyprint-override"><code>public class AuthenticatedEncryptionHelper { private const int _SALT_LENGTH = 16; private const int _KEY_DERIVATION_ITERATIONS = 100000; private const int _CRYPTO_KEY_LENGTH = 16; private const int _HMAC_KEY_LENGTH = 16; private const int _IV_LENGTH = 16; public byte[] Encrypt(string message, string password) { var salt = GenerateRandomBytes(_SALT_LENGTH); var (enc_key, hmac_key) = DeriveKeys(password, salt); var iv = GenerateRandomBytes(_IV_LENGTH); var plaintext = Encoding.UTF8.GetBytes(message); var ciphertext = AesEncrypt(plaintext, enc_key, iv); var hmac = ComputeHmac(ciphertext, iv, hmac_key); var payload = GeneratePayload(salt, hmac, iv, ciphertext); return payload; } public string Decrypt(byte[] payload, string password) { var (salt, hmac, iv, ciphertext) = ExplodePayload(payload); var (dec_key, hmac_key) = DeriveKeys(password, salt); var computed_hmac = ComputeHmac(ciphertext, iv, hmac_key); if (!AreHmacsEqual(hmac, computed_hmac)) { throw new Exception(); } var plaintext = AesDecrypt(ciphertext, dec_key, iv); var message = Encoding.UTF8.GetString(plaintext); return message; } private byte[] GenerateRandomBytes(int length) { var result = new byte[length]; using (var r = RandomNumberGenerator.Create()) { r.GetBytes(result); } return result; } private (byte[], byte[]) DeriveKeys(string password, byte[] salt) { var length = _CRYPTO_KEY_LENGTH + _HMAC_KEY_LENGTH; var result = new byte[length]; using (var pbkdf2 = new Rfc2898DeriveBytes(password, salt, _KEY_DERIVATION_ITERATIONS)) { result = pbkdf2.GetBytes(length); } var r1 = new byte[_CRYPTO_KEY_LENGTH]; var r2 = new byte[_HMAC_KEY_LENGTH]; Buffer.BlockCopy(result, 0, r1, 0, _CRYPTO_KEY_LENGTH); Buffer.BlockCopy(result, _CRYPTO_KEY_LENGTH, r2, 0, _HMAC_KEY_LENGTH); return (r1, r2); } private byte[] AesEncrypt(byte[] plaintext, byte[] key, byte[] iv) { byte[] ciphertext; using (var aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = key; aes.IV = iv; using (var encryptor = aes.CreateEncryptor()) { ciphertext = encryptor.TransformFinalBlock(plaintext, 0, plaintext.Length); } } return ciphertext; } private byte[] ComputeHmac(byte[] ciphertext, byte[] iv, byte[] key) { var input = new byte[iv.Length + ciphertext.Length]; Buffer.BlockCopy(iv, 0, input, 0, iv.Length); Buffer.BlockCopy(ciphertext, 0, input, iv.Length, ciphertext.Length); byte[] result; using (var hash = new HMACSHA256(key)) { result = hash.ComputeHash(input); } return result; } private byte[] GeneratePayload(byte[] salt, byte[] hmac, byte[] iv, byte[] ciphertext) { var result = new byte[salt.Length + hmac.Length + iv.Length + ciphertext.Length]; var curr_index = 0; Buffer.BlockCopy(salt, 0, result, curr_index, salt.Length); curr_index += salt.Length; Buffer.BlockCopy(hmac, 0, result, curr_index, hmac.Length); curr_index += hmac.Length; Buffer.BlockCopy(iv, 0, result, curr_index, iv.Length); curr_index += iv.Length; Buffer.BlockCopy(ciphertext, 0, result, curr_index, ciphertext.Length); return result; } private (byte[], byte[], byte[], byte[]) ExplodePayload(byte[] payload) { var salt = new byte[_SALT_LENGTH]; var hmac = new byte[32]; var iv = new byte[_IV_LENGTH]; var ciphertext = new byte[payload.Length - (_SALT_LENGTH + 32 + _IV_LENGTH)]; var curr_index = 0; Buffer.BlockCopy(payload, curr_index, salt, 0, _SALT_LENGTH); curr_index += _SALT_LENGTH; Buffer.BlockCopy(payload, curr_index, hmac, 0, 32); curr_index += 32; Buffer.BlockCopy(payload, curr_index, iv, 0, _IV_LENGTH); curr_index += _IV_LENGTH; Buffer.BlockCopy(payload, curr_index, ciphertext, 0, ciphertext.Length); return (salt, hmac, iv, ciphertext); } private bool AreHmacsEqual(byte[] hmac, byte[] computedHmac) { var result = true; if (hmac.Length != computedHmac.Length) { result = false; } for (int i = 0; i &lt; hmac.Length; i++) { if (hmac[i] != computedHmac[i]) { result = false; } } return result; } private byte[] AesDecrypt(byte[] ciphertext, byte[] key, byte[] iv) { byte[] plaintext; using (var aes = Aes.Create()) { aes.Mode = CipherMode.CBC; aes.Padding = PaddingMode.PKCS7; aes.Key = key; aes.IV = iv; using (var decryptor = aes.CreateDecryptor()) { plaintext = decryptor.TransformFinalBlock(ciphertext, 0, ciphertext.Length); } } return plaintext; } } </code></pre> <p>Any criticism of this code (or the algorithm) will be greatly appreciated.</p>
[]
[ { "body": "<h2>Cryptography</h2>\n<p>Yes, CBC followed by HMAC is fine (also known as encrypt-then-MAC), and you include the IV into the calculations, which is great. You indeed do not have to include the salt and iteration count into the HMAC calculation as they already influence the key being used. You may need to review this choice if you switch to GCM though - including more in the validated parameters never hurts.</p>\n<hr />\n<p>You are using a cryptographically secure random number generator, so kudos there.</p>\n<hr />\n<p>Beware that password based encryption still very much depends on the password strength. A password of 40 bit strength won't get anywhere near 128 bit strength, even with a key stretching algorithm such as PBKDF2.</p>\n<hr />\n<p>You are using the terribly named <code>Rfc2898DeriveBytes</code> class, which implements PBKDF2. This is not top of class algorithm (see e.g. Argon2) but it may suffice. This is presuming that you require a password in the first place of course; if you can perform encryption without requiring passwords then that's always better.</p>\n<hr />\n<p>If you don't call the method more than once, then <code>100_000</code> iterations may be on the low side. Especially for weak passwords: the higher the value the better. You may want to make this value dynamic so that you can choose a higher value when time progresses.</p>\n<hr />\n<p>16 bytes of secure random salt is precisely on the mark.</p>\n<hr />\n<p>One ugly problem with PBKDF2 / <code>Rfc2898DeriveBytes</code> is that it performs all the iterations again for each hash size required, standardizing on SHA-1 / 20 bytes. You are in this case better off specifying SHA-256 or SHA-512, otherwise you are having to perform more iterations than a possible attacker (who has enough with 1 key).</p>\n<hr />\n<p>HMAC-SHA-256 kinda defaults to a 256 bit key. Using 16 bytes / 128 bits is not <em>bad</em> in any sense, but there's that (this is also why specifying SHA-512 for PBKDF2 may be beneficial).</p>\n<hr />\n<p>You are using a (presumably) time-constant compare for the HMAC tag, nice, that would be one of the major issues when people just look at the methods, as Microsoft never indicates that you <em>should</em> use a time constant compare.</p>\n<h2>Code</h2>\n<p>See the question / answer <a href=\"https://stackoverflow.com/q/242534/589259\">at StackOverflow sister site</a> about naming conventions, especially regarding constant values: those should not start with an underscore.</p>\n<hr />\n<p>The block copy after PBKDF2 / function is not needed:</p>\n<blockquote>\n<p>The <code>Rfc2898DeriveBytes</code> class implements PBKDF2 functionality by using a pseudorandom number generator based on HMACSHA1. The Rfc2898DeriveBytes class takes a password, a salt, and an iteration count, and then generates keys through calls to the <code>GetBytes</code> method. <strong>Repeated calls to this method will not generate the same key</strong>; instead, appending two calls of the <code>GetBytes</code> method with a <code>cb</code> parameter value of <code>20</code> is the equivalent of calling the <code>GetBytes</code> method once with a <code>cb</code> parameter value of <code>40</code>.</p>\n</blockquote>\n<hr />\n<p>Later versions of C# allow for underscores in literals. <code>100_000</code> is a more readable version of <code>100000</code>.</p>\n<hr />\n<pre><code>aes.Padding = PaddingMode.PKCS7;\n</code></pre>\n<p>Although this is the default, I applaude you for setting it anyway; not all readers may <em>know</em> it is the default - crypto experts are not always also language/runtime specialists.</p>\n<h2>Design</h2>\n<p>You could use a version indicator before your ciphertext. In that case you can upgrade your algorithms and or iteration count when required (your boss may be corrected by a subject expert).</p>\n<hr />\n<p>Having small messages kind of obsoletes the need for streaming, but personally I'd still use streaming, especially since the .NET API seems to have been build around those. In this case all the byte arrays and whatnot won't matter much though.</p>\n<hr />\n<pre><code> curr_index += 32;\n</code></pre>\n<p>Use a constant here, e.g. <code>HMACSHA256_OUTPUT_SIZE = 32</code> or you'll be in trouble if somebody decides on using a different hash.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:01:00.713", "Id": "267923", "ParentId": "267881", "Score": "3" } } ]
{ "AcceptedAnswerId": "267923", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T04:35:38.517", "Id": "267881", "Score": "1", "Tags": [ "c#", "encryption" ], "Title": "Manual authenticated encryption on .NET Core" }
267881
<p>I am a newbie in Ruby. I want to learn Ruby and I want to learn clear code in Ruby. I coded a number guessing game but my code is smelling bad. How I can do better code?</p> <pre><code>class NumberGuess attr_accessor :num_of_guess, :random_num, :name def initialize(random_num, num_of_guess, name) @name = name @random_num = random_num @num_of_guess = num_of_guess end def start while num_of_guess &lt; 10 puts &quot;&quot; puts &quot;1 ile 100 arasında sayı tut&quot; guess_number = gets.to_i @num_of_guess += 1 guesses_left = (10 - @num_of_guess) if random_num &gt; guess_number puts &quot;#{@name}, Tahminin tutulan sayıdan daha düşük. Kalan hakkin #{guesses_left} &quot; elsif guess_number &gt; random_num puts &quot;#{@name}, Tahminin tutulan sayıdan daha büyük. Kalan hakkin #{guesses_left} &quot; end break if guess_number == random_num end if guess_number == random_num puts &quot;Tebrikler #{@name}! #{num_of_guess} denemede bildin&quot; else puts &quot;Üzgünüm #{@name}! Cevap: #{random_num} &quot; end end end puts (&quot;Merhaba,Ismini ogrenebilir miyim?&quot;) name = gets.chomp.capitalize game = NumberGuess.new(rand(100), 0, name) game.start </code></pre>
[]
[ { "body": "<p>I'm not a Ruby programmer, but there are a couple of general improvements I can think of for this code:</p>\n<ul>\n<li><strong>Better initialization</strong>: There is no need to pass the random number and <code>num_of_guess</code> to the class.\nGenerating a random number is part of the core definition of this game, and I will put it in the class.\nFor <code>num_of_guess</code>, just set it to zero. There's no need to pass it to class constructor.</li>\n<li>I try to <strong>avoid conditional statements</strong> as much as possible. They make the code hard to read.\nSo in the loop, instead of <code>break</code> when you find the solution, print the success message and return.\nIn this way, after the loop, you know that the player didn't find the answer, and you just print a failure message.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T08:33:52.807", "Id": "267886", "ParentId": "267882", "Score": "2" } }, { "body": "<h1>Consistency</h1>\n<p>Sometimes you use accessor methods, sometimes you access instance variables directly. Sometimes you use parentheses around message send arguments, sometimes you don't.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>Most communities have developed standardized community style guides. In Ruby, there are multiple such style guides. They all agree on the basics (e.g. indentation is 2 spaces), but they might disagree on more specific points (single quotes or double quotes).</p>\n<p>In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing <em>IFF</em> you actually <em>want</em> to convey some extra information.</p>\n<p>For example, some people always use parentheses for defining and calling purely functional side-effect free methods, and never use parentheses for defining and calling impure methods. That is a <em>good</em> reason to use two different styles (parentheses and no parentheses) for doing the same thing (defining methods).</p>\n<h1>Single-quoted strings</h1>\n<p>If you don't use string interpolation, it is helpful if you use single quotes for your strings. That way, it is immediately obvious that no string interpolation is taking place.</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>&quot;Merhaba,Ismini ogrenebilir miyim?&quot;\n</code></pre>\n<p>should instead be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>'Merhaba,Ismini ogrenebilir miyim?'\n</code></pre>\n<p>Note that it is perfectly fine to use double quoted strings if you otherwise needed to use escapes, e.g. here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>&quot;Congratulations, you've guessed the word!&quot;\n</code></pre>\n<p>reads much better than</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>'Congratulations, you\\'ve guessed the word!'\n</code></pre>\n<h1>Frozen string literals</h1>\n<p>Immutable data structures and purely functional code are always preferred, unless mutability and side-effects are required for clarity or performance. In Ruby, strings are always mutable, but there is a <a href=\"https://bugs.ruby-lang.org/issues/8976\" rel=\"nofollow noreferrer\">magic comment</a> you can add to your files (also available as a command-line option for the Ruby engine), which will automatically make all literal strings immutable:</p>\n<pre class=\"lang-rb prettyprint-override\"><code># frozen_string_literal: true\n</code></pre>\n<p>It is generally preferred to add this comment to all your files.</p>\n<h1>No space before argument list</h1>\n<p>In a message send, there should be no whitespace between the message and the argument list, e.g. this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts (&quot;Merhaba,Ismini ogrenebilir miyim?&quot;)\n</code></pre>\n<p>should be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts(&quot;Merhaba,Ismini ogrenebilir miyim?&quot;)\n</code></pre>\n<p>This will bite you as soon as you have more than one argument. Ruby allows you to write the argument list to a message send without parentheses like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>foo.bar baz, quux\n</code></pre>\n<p>instead of</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>foo.bar(baz, quux)\n</code></pre>\n<p>The problem arises because the whitespace triggers the first mode, so</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>foo.bar (baz, quux)\n</code></pre>\n<p>is <em>not</em> interpreted as <em>two</em> arguments <code>baz</code> and <code>quux</code> but as passing arguments with whitespace <em>instead of parentheses</em> and thus as a <em>single argument</em> <code>(baz, quux)</code>. Except <code>(baz, quux)</code> is not legal Ruby code, and thus you get an error.</p>\n<h1>Linting</h1>\n<p>You should run some sort of linter or static analyzer on your code. <a href=\"https://www.rubocop.org/\" rel=\"nofollow noreferrer\">Rubocop</a> is a popular one, but there are others.</p>\n<p>Rubocop was able to detect all of the style violations I pointed out above (plus some more), and also was able to autocorrect all of the ones I listed.</p>\n<p>Let me repeat that: I have just spent two pages pointing out how to correct tons of stuff that you can <em>actually</em> correct within milliseconds at the push of a button. I have set up my editor such that it automatically runs Rubocop with auto-fix as soon as I hit &quot;save&quot;.</p>\n<p>In particular, running Rubocop on your code, it detects 9 offenses, of which it can automatically correct 6.</p>\n<p>Here's what the result of the auto-fix looks like:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code># frozen_string_literal: true\n\nclass NumberGuess\n attr_accessor :num_of_guess, :random_num, :name\n\n def initialize(random_num, num_of_guess, name)\n @name = name\n @random_num = random_num\n @num_of_guess = num_of_guess\n end\n\n def start\n while num_of_guess &lt; 10\n puts ''\n puts '1 ile 100 arasında sayı tut'\n guess_number = gets.to_i\n @num_of_guess += 1\n guesses_left = (10 - @num_of_guess)\n\n if random_num &gt; guess_number\n puts &quot;#{@name}, Tahminin tutulan sayıdan daha düşük. Kalan hakkin #{guesses_left} &quot;\n elsif guess_number &gt; random_num\n puts &quot;#{@name}, Tahminin tutulan sayıdan daha büyük. Kalan hakkin #{guesses_left} &quot;\n end\n break if guess_number == random_num\n end\n\n if guess_number == random_num\n puts &quot;Tebrikler #{@name}! #{num_of_guess} denemede bildin&quot;\n else\n puts &quot;Üzgünüm #{@name}! Cevap: #{random_num} &quot;\n end\n end\nend\n\nputs('Merhaba,Ismini ogrenebilir miyim?')\nname = gets.chomp.capitalize\ngame = NumberGuess.new(rand(100), 0, name)\ngame.start\n</code></pre>\n<p>And here are the offenses that Rubocop could not automatically correct:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Inspecting 1 file\nC\n\nOffenses:\n\nnumber_guess.rb:3:1: C: Style/Documentation: Missing top-level class documentation comment.\nclass NumberGuess\n^^^^^\nnumber_guess.rb:12:3: C: Metrics/AbcSize: Assignment Branch Condition size for start is too high. [&lt;3, 16, 11&gt; 19.65/17]\n def start ...\n ^^^^^^^^^\nnumber_guess.rb:12:3: C: Metrics/MethodLength: Method has too many lines. [18/10]\n def start ...\n ^^^^^^^^^\n\n1 file inspected, 3 offenses detected\n</code></pre>\n<p>Similar to Code Formatting, it is a good idea to set up your tools such that the linter is automatically run when you paste code, edit code, save code, commit code, or build your project, and that passing the linter is a criterium for your CI pipeline.</p>\n<p>In my editor, I actually have multiple linters and static analyzers integrated so that they automatically always analyze my code, and also as much as possible automatically fix it while I am typing. This can sometimes be annoying (e.g. I get almost 30 notices for your original code, lots of which are duplicates because several different tools report the same problem), but it is in general tremendously helpful. It can be overwhelming when you open a large piece of code for the first time and you get dozens or hundreds of notices, but if you start a new project, then you can write your code in a way that you never get a notice, and your code will usually be better for it.</p>\n<h1>Print empty line</h1>\n<p>The idiomatic way of printing an empty line is just</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts\n</code></pre>\n<p>instead of</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts ''\n</code></pre>\n<h1>Unnecessary parentheses</h1>\n<p>There is no need for these parentheses:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>guesses_left = (10 - num_of_guess)\n</code></pre>\n<p>It should just be</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>guesses_left = 10 - num_of_guess\n</code></pre>\n<h1>Inconsistent use of parentheses for message send argument lists</h1>\n<p>You are sometimes using parentheses around arguments to message sends, and sometimes not. Remember what I wrote in the beginning: if you use different styles to write the same thing, people will assume that you want to draw attention to some sort of difference. So, you should only do this in case you actually <em>want</em> to point out some difference.</p>\n<p>For example, there are actually a couple of style conventions around parentheses for argument lists. One style convention is to use parentheses for purely functional methods and no parentheses for impure procedural methods. Another convention is to use parentheses for almost all methods, and no parentheses for &quot;global&quot; kernel procedures that aren't really used as methods at all (e.g. <a href=\"https://ruby-doc.org/core/Kernel.html#method-i-puts\" rel=\"nofollow noreferrer\"><code>Kernel#puts</code></a> or <a href=\"https://ruby-doc.org/core/Kernel.html#method-i-require\" rel=\"nofollow noreferrer\"><code>Kernel#require</code></a>), or for methods that feel like language keywords (<a href=\"https://ruby-doc.org/core/Module.html#method-i-include\" rel=\"nofollow noreferrer\"><code>Module#include</code></a> or <a href=\"https://ruby-doc.org/core/Module.html#method-i-attr_accessor\" rel=\"nofollow noreferrer\"><code>Module#attr_accessor</code></a>).</p>\n<p>But in your case you are, for example, using no parentheses here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts '1 ile 100 arasında sayı tut'\n</code></pre>\n<p>but you are using parentheses here:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>puts('Merhaba,Ismini ogrenebilir miyim?')\n</code></pre>\n<h1>Inconsistent use of attribute methods and instance variables</h1>\n<p>You are sometimes accessing instance variables directly e.g. here</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>@num_of_guess += 1\n</code></pre>\n<p>and sometimes you use the attribute method, e.g. here</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>while num_of_guess &lt; 10\n</code></pre>\n<p>This is inconsistent. Choose one or the other.</p>\n<p>I personally prefer to always use the attribute methods, because methods are more flexible: they can be overridden in subclasses or their implementation can be changed, without having to change any of the client code.</p>\n<p>So, you should either change the second example to</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>while @num_of_guess &lt; 10\n</code></pre>\n<p>or (my preference) the first example to</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>self.num_of_guess += 1\n</code></pre>\n<p>and the same in a couple of other places.</p>\n<h1><code>attr_reader</code> vs. <code>attr_accessor</code></h1>\n<p>In your original code, you are never writing to any of your attributes, so they should all be <a href=\"https://ruby-doc.org/core/Module.html#method-i-attr_reader\" rel=\"nofollow noreferrer\"><code>Module#attr_reader</code></a>s instead of <a href=\"https://ruby-doc.org/core/Module.html#method-i-attr_accessor\" rel=\"nofollow noreferrer\"><code>Module#attr_accessor</code></a>s:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>attr_reader :num_of_guess, :random_num, :name\n</code></pre>\n<p>However, if you follow my suggestion above, and always use the writers as well, then they need to stay accessors.</p>\n<h1>Access Restrictions</h1>\n<p>None of your attribute accessors are intended to be used by other objects. In fact, they <em>shouldn't</em> be used by other objects! They are the private internal state of the number guesser object. Therefore, they should not be part of the public API, they should be <a href=\"https://ruby-doc.org/core/Module.html#method-i-private\" rel=\"nofollow noreferrer\"><code>private</code></a>:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>private\n\nattr_accessor :num_of_guess, :random_num, :name\n</code></pre>\n<h1>Inconvenient API</h1>\n<p>The API of your object places a lot of unnecessary burden on the client. For example: why is it the client's responsibility to pass in the random number? Why is it the client's responsibility to pass in <code>0</code> to initialize <code>num_of_guess</code>? Your object should be able to do that on its own.</p>\n<h1>Unnecessary instance variables</h1>\n<p>The instance variables <code>@random_num</code> and <code>@num_of_guess</code> are only ever used in one method. They should be local variables instead.</p>\n<h1>Overcomplicated logic</h1>\n<p>As I mentioned above, the linters and static analyzers are still complaining about some stuff. Mostly, they are complaining about the length and the complexity of the <code>start</code> method.</p>\n<p>However, there is one specific complaint by <a href=\"https://github.com/troessner/reek\" rel=\"nofollow noreferrer\">Reek</a>:</p>\n<blockquote>\n<p>[30, 33]:<a href=\"https://github.com/troessner/reek/blob/master/docs/Duplicate-Method-Call.md\" rel=\"nofollow noreferrer\">DuplicateMethodCall</a>: NumberGuess#start calls 'guess_number == random_num' 2 times</p>\n</blockquote>\n<p>The simplest possible way to get rid of this warning would be to assign the result of <code>guess_number == random_num</code> to a variable (for example <code>won</code>) and use it in both places.</p>\n<p>However, this actually hints at some greater simplification that we can do: not only remove the duplicated expression <code>guess_number == random_num</code> but actually remove the duplicated check altogether! If we return from the whole method from inside the loop as soon as we know the player has won, there is no need to check again after the loop.</p>\n<p>And since we are now checking for equality earlier, we don't need to check for both greater-than and less-than. One of the two is enough.</p>\n<h1>Iterators</h1>\n<p>In Ruby, you almost never use loops. You would normally use <em>at least</em> an low-level iterator such as <a href=\"https://ruby-doc.org/core/Kernel.html#method-i-loop\" rel=\"nofollow noreferrer\"><code>Kernel#loop</code></a>, <code>#each</code>, or <a href=\"https://ruby-doc.org/core/Integer.html#method-i-times\" rel=\"nofollow noreferrer\"><code>Integer#times</code></a>. Really, you want to use higher-level iterators such as <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-map\" rel=\"nofollow noreferrer\"><code>Enumerable#map</code></a>, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-select\" rel=\"nofollow noreferrer\"><code>Enumerable#select</code></a>, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-group_by\" rel=\"nofollow noreferrer\"><code>Enumerable#group_by</code></a>, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-flat_map\" rel=\"nofollow noreferrer\"><code>Enumerable#flat_map</code></a>, <a href=\"https://ruby-doc.org/core/Enumerable.html#method-i-inject\" rel=\"nofollow noreferrer\"><code>Enumerable#inject</code></a>, etc.</p>\n<p>In this case, we are going to use <a href=\"https://ruby-doc.org/core/Integer.html#method-i-upto\" rel=\"nofollow noreferrer\"><code>Integer#upto</code></a> for the loop.</p>\n<p>The method now looks like this:</p>\n<pre class=\"lang-ruby prettyprint-override\"><code>def start\n random_num = rand(100)\n\n 1.upto(10) do |num_of_guess|\n puts\n puts '1 ile 100 arasında sayı tut'\n guess_number = gets.to_i\n guesses_left = 10 - num_of_guess\n\n if guess_number == random_num\n puts &quot;Tebrikler #{name}! #{num_of_guess} denemede bildin&quot;\n return\n end\n\n if random_num &gt; guess_number\n puts &quot;#{name}, Tahminin tutulan sayıdan daha düşük. Kalan hakkin #{guesses_left} &quot;\n else\n puts &quot;#{name}, Tahminin tutulan sayıdan daha büyük. Kalan hakkin #{guesses_left} &quot;\n end\n end\n\n puts &quot;Üzgünüm #{name}! Cevap: #{random_num} &quot;\nend\n</code></pre>\n<h1>Naming</h1>\n<p>There are a number of names that are somewhat confusing, misleading, or could be expressed better.</p>\n<p>For example, <code>random_num</code> doesn't really tell us what this variable is for. It tells us that it is a random number, but what does it <em>do</em>? I would name this <code>target</code>, for example, since it is the target the player is trying to hit.</p>\n<p><code>guess_number</code> can be just <code>guess</code>. We know it's a number guessing game, so we can probably assume that the user's guess is a number. <code>num_of_guess</code> could be just <code>try</code>. <code>guesses_left</code> would then be <code>tries_left</code>.</p>\n<p>Also, the <code>start</code> method does a lot more than just start the game. It <em>is</em> the game. So, it should probably be called <code>game</code>.</p>\n<h1>Magic numbers</h1>\n<p>There are some hard-coded magic numbers in your code, which show up multiple times. If you ever want to change those magic numbers, you will need to change them in multiple places, and you might forget one. (This actually happened to me: I wanted to be able to test the game faster, so I reduced the number of tries and the bound of the target number, but I forgot one place.)</p>\n<p>The two magic numbers are <code>10</code>, the maximum number of tries, and <code>100</code> the upper bound of the target number. We could make those constants of the class, attributes, or something else.</p>\n<h1>Complexity</h1>\n<p>Your <code>start</code> method does <em>a lot</em> of work. In particular, it doesn't actually do what it claims it does: it doesn't just <em>start</em> the game, it <em>is</em> the entire game.</p>\n<p>It also mixes input/output with computation. It is generally a good idea to separate input/output from computation. One obvious advantage is that you can test your computation by simply calling methods and passing arguments instead of having to type inputs and read outputs.</p>\n<p>We should probably break this up in some smaller methods.</p>\n<p>I would suggest, for example, a method for the actual game loop, a method for asking for input, a method for determining the result, and some methods for printing the result.</p>\n<h1>Proposal</h1>\n<pre class=\"lang-ruby prettyprint-override\"><code># frozen_string_literal: true\n\nclass NumberGuess\n private\n\n DEFAULT_TRIES = 10\n private_constant :DEFAULT_TRIES\n\n attr_accessor :name, :tries, :bound, :target\n\n def initialize(name, tries: DEFAULT_TRIES, bound: tries**2, target: rand(bound))\n self.name = name\n self.tries = tries\n self.bound = bound\n self.target = target\n end\n\n public\n\n def game\n 1.upto(tries) do |try|\n case result(ask)\n when :high\n high(try)\n when :low\n low(try)\n when :won\n return won(try)\n end\n end\n\n lost\n end\n\n private\n\n def ask\n puts\n puts &quot;1 ile #{bound} arasında sayı tut&quot;\n gets.to_i\n end\n\n def result(guess)\n if guess &gt; target\n :high\n elsif guess &lt; target\n :low\n else\n :won\n end\n end\n\n def high(try)\n puts &quot;#{name}, Tahminin tutulan sayıdan daha büyük. Kalan hakkin #{tries_left(try)}&quot;\n end\n\n def low(try)\n puts &quot;#{name}, Tahminin tutulan sayıdan daha düşük. Kalan hakkin #{tries_left(try)}&quot;\n end\n\n def won(try)\n puts &quot;Tebrikler #{name}! #{try} denemede bildin&quot;\n end\n\n def lost\n puts &quot;Üzgünüm #{name}! Cevap: #{target}&quot;\n end\n\n def tries_left(try)\n tries - try\n end\nend\n\nputs 'Merhaba,Ismini ogrenebilir miyim?'\nname = gets.chomp.capitalize\ngame = NumberGuess.new(name)\ngame.game\n</code></pre>\n<p>There are still two complaints by our static analyzer tools, unfortunately:</p>\n<ol>\n<li>There is no documentation.</li>\n<li>The <code>game</code> method is still too long.</li>\n</ol>\n<p>#1 can easily be fixed. (I will leave that up to you.) #2 would require some more extensive refactoring of the game logic, and maybe also some rethinking: for example, why limit the number of tries at all? With an upper bound of 100, for example, a clever player will need at most 7 tries to guess the number. So, we could just let them play until their guess is correct. Or, we allow them to abort the game at any point.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T15:08:30.537", "Id": "267893", "ParentId": "267882", "Score": "2" } } ]
{ "AcceptedAnswerId": "267893", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T05:15:33.187", "Id": "267882", "Score": "2", "Tags": [ "beginner", "game", "ruby", "number-guessing-game" ], "Title": "Number guessing game in Ruby" }
267882
<pre><code>print(&quot;Welcome to the Sieve of Eratosthenes, where you can generate prime numbers from 1 to n : &quot;) n = int(input(&quot;Enter your n : &quot;)) y = [y for y in range(1,n) if y*y &lt; n] primes = [p for p in range(2,n+1)] length = len(primes) print(primes) for p in range(2,len(y)+2): for i in range(2,length+1): if(i%p == 0 and i != p ): if(i in primes): primes.remove(i) print(primes) &quot;&quot;&quot; 1.)A range //0 to 100 .x 2.)Multiples can be found using 1 to sqrt(n) .x 3.)Now eliminate all multiples. x &quot;&quot;&quot; </code></pre> <p>OUTPUT</p> <blockquote> <p>Enter your n : 20<br /> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]<br /> [1, 2, 3, 5, 7, 11, 13, 17, 19]</p> </blockquote> <p>So I did this by my own and also I need some suggestions on what can I do to improve the code and can you tell me how good it is?.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T09:24:26.363", "Id": "528235", "Score": "0", "body": "i've updated the code,could you recheck it again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T10:31:22.063", "Id": "528237", "Score": "1", "body": "This always returns that the last number is prime. E.g. n=125 or n=102 return 125 and 102 as prime respectively. No numbers that end in 2 or 5 are prime except 2 and 5 themselves." } ]
[ { "body": "<h2>Stylistic improvements</h2>\n<ul>\n<li>You create a list <code>y</code>, and only use it to have an upper bound for the first loop. The bound should be the square root of <code>n</code>, you can compute that directly.\nSo <code>for p in range(2, math.ceil(n**0.5) + 1)</code> instead of <code>for p in range(2, len(y)+2)</code>.</li>\n<li>In Python you don't need (and shouldn't use) parenthesis for <code>if</code> statements. <code>if i in prime</code> is the same thing as <code>if (i in prime)</code>.</li>\n<li>If you look closely, you will notice that <code>length</code> is just the same as <code>n-1</code>. That's actually an error, as you include the number <code>n</code> into list <code>primes</code> of potential prime numbers. E.g. if <code>n = 99</code>, it will not eliminate <code>99</code> because of that. Anyway, you can just use <code>n</code> instead of <code>length</code>.</li>\n</ul>\n<p>After those suggestions, and bug fixes you end up with the following code:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nn = int(input())\n\nprimes = [p for p in range(2, n + 1)]\nfor p in range(2, math.ceil(n**0.5) + 1):\n for i in range(2, n + 1):\n if i % p == 0 and i != p:\n if i in primes:\n primes.remove(i)\n\nprint(primes)\n</code></pre>\n<h2>Algorithmic improvements</h2>\n<p>Lets first run the program for <code>n = 100 000</code>. On my laptop the code takes about 2.5 minutes to run.</p>\n<p>One big mistake is, that you use a list to store the potential prime numbers. If you maintain the potential numbers on paper, it's actually pretty quick to look up if a number is in the list, because the numbers are ordered increasingly. Also it's easy to remove a number. E.g. if you want to remove the number 4 from the list, you know that it's right at the beginning and you can just cross it out with a pen.\nHowever Python doesn't know that this list is monotonically increasing. If you want to remove the number 4 from the list of 100 000 numbers, then it has to check all 100 000 numbers, as any of those could be a 4. So you waste a lot of time. In terms of complexity, both looking up numbers (<code>if i in primes</code>) and removing a number <code>primes.remove(i)</code> is O(n)).</p>\n<p>There are other data structures, that can do both operations a lot faster. The easiest is just to use a Python <code>set</code>. A <code>set</code> is just a data structure that can hold a bunch of different numbers. It doesn't care about the order or how often you insert a number (<code>{1, 2} == {2, 1, 1}</code> is <code>True</code> in Python), however you can make lookups really fast and can also remove values really fast. Both in O(1) in Python.</p>\n<p>And as a side note. <code>if i in primes: primes.remove(i)</code> is the same as <code>primes.discard(i)</code>. <code>discard</code> removes an element from a set if it is there, and does nothing if it isn't there.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nn = int(input())\n\nprimes = set(range(2, n + 1))\nfor p in range(2, math.ceil(n**0.5) + 1):\n for i in range(2, n + 1):\n if i % p == 0 and i != p:\n primes.discard(i)\n\nprint(sorted(primes))\n</code></pre>\n<p>Notice that we sort the remaining numbers at the end, as a set in Python doesn't keep the data in sorted order (at least it's not guaranteed).</p>\n<p>For the same input (<code>n = 100 000</code>), the code runs in about 2.7 seconds now. Almost speedup of 60x.</p>\n<hr />\n<p>If you study the Sieve of Eratosthenes a bit, you will realize that you only need to cross out multiples of prime numbers.\nE.g. we <code>i == 6</code> you don't need to cross out any multiples of <code>6</code> any more, because we crossed them out already when we crossed out multiples of <code>2</code> (and in fact a second time when we crossed out multiples of <code>3</code>).</p>\n<p>That means we can do the following optimization:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nn = int(input())\n\nprimes = set(range(2, n + 1))\nfor p in range(2, math.ceil(n**0.5) + 1):\n if p in primes:\n for i in range(2, n + 1):\n if i % p == 0 and i != p:\n primes.discard(i)\n\nprint(sorted(primes))\n</code></pre>\n<p>For the input <code>n = 100 000</code> this runs now in just 0.7 seconds.</p>\n<hr />\n<p>Another optimization could be the following.\nCurrently you run <code>i</code> over all numbers, and check if they are multiples of <code>p</code>. But you can also just iterate over all multiples of <code>p</code> directly. Since we know that all multiples of <code>p</code> are <code>2*p, 3*p, 4*p, 5*p, ...</code>, you can just run the following:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import math\nn = int(input())\n\nprimes = set(range(2, n + 1))\nfor p in range(2, math.ceil(n**0.5) + 1):\n if p in primes:\n for k in range(2, n // p + 1):\n primes.discard(k * p)\n\nprint(sorted(primes))\n</code></pre>\n<p>This now runs in just 0.12 seconds for the input <code>n = 100 000</code>.\nA total speedup of over 1000x starting from the initial code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T19:09:25.887", "Id": "267900", "ParentId": "267887", "Score": "1" } }, { "body": "<blockquote>\n<pre><code>print(&quot;Welcome to the Sieve of Eratosthenes, where you can generate prime numbers from 1 to n : &quot;)\n</code></pre>\n</blockquote>\n<p>This is not a <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes</a>. It is a prime sieve in the sense that it takes a list of numbers and removes (or sieves) out those that aren't prime. But it does not follow the algorithm of the Sieve of Eratosthenes.</p>\n<p>Here's what the Sieve of Eratosthenes looks like:</p>\n<pre><code>primes = [p for p in range(2, n + 1)]\n\nfor p in primes:\n if p &gt; n / p:\n break\n\n for i in range(p * p, n + 1, p):\n if i in primes:\n primes.remove(i)\n</code></pre>\n<p>This is not necessarily the optimal version (for example, it might be better to compare <code>p</code> to the square root of <code>n</code> rather than do the <code>n / p</code> each time; or it may be better to use a set rather than a list). Nor is it likely to be the most Pythonic. I don't do Python development, so you should not take anything I suggest as being Pythonic.</p>\n<p>Some things that this does that your version does not:</p>\n<ol>\n<li>It only works on numbers that are prime. The initial loop may look like it is iterating over the entire range. But it actually only iterates over the primes, because the non-primes have been removed before it reaches them (I tested and unlike PHP, Python iterates over the current version of the array, not a copy of the original). It starts with 2 and eliminates all the even numbers.</li>\n<li>It does no trial division. Instead, it uses the Eratosthenes method of taking multiples of the current prime.</li>\n</ol>\n<p>That piece about multiplying rather than dividing is what I would describe as the central principle of the Sieve of Eratosthenes algorithm. So when I say that your version is not a Sieve of Eratosthenes, I mean that it doesn't do that.</p>\n<p>Note: there is nothing wrong with implementing a different sieve. It's possible to write a better one (although I'm not convinced that this is better). The Sieve of Eratosthenes is notable for being relatively good as well as comprehensible with moderate effort. It's not the best performing sieve. I'm just saying that you shouldn't call your version a Sieve of Eratosthenes, as it isn't one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T06:56:47.653", "Id": "528268", "Score": "0", "body": "I like how your SoE code removes values from the list while you're iterating it. Setting a good example here :-)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T21:43:43.480", "Id": "267903", "ParentId": "267887", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T08:47:28.460", "Id": "267887", "Score": "0", "Tags": [ "python", "primes" ], "Title": "My prime sieve using Python" }
267887
<p>My code is working perfectly fine, except for one-thing. The performance is not up-to the mark. What I am trying to achieve is I have an image with a few circles (each circle has a border with different color than circle fill color). When the user touches any circle, I want to change the border color of the selected circle. That's working fine, but what isn't working up-to expectation is that we have a table in the UI from which the user can select multiple circles, like 6-12 circles at max. In this 2nd scenario, the implementation is taking 3-4 seconds. Below I am sharing the code snippet I am using, if anything wrong found please guide me.</p> <p><strong>NOTE:</strong> I have 2 Images: <strong>Front</strong> and <strong>Back</strong>, front image is displayed to the user and upon user's interaction with the front image, the color of the touched point is taken from the back image and if that touched point is any of the circle on the image, then the <code>replaceColor</code> method gets called.</p> <pre><code>func replaceColor(sourceColor: [UIColor], withDestColor destColor: UIColor, tolerance: CGFloat) -&gt; UIImage { // This function expects to get source color(color which is supposed to be replaced) // and target color in RGBA color space, hence we expect to get 4 color components: r, g, b, a // assert(sourceColor.cgColor.numberOfComponents == 4 &amp;&amp; destColor.cgColor.numberOfComponents == 4, // &quot;Must be RGBA colorspace&quot;) // *** Allocate bitmap in memory with the same width and size as destination image or back image *** // let backImageBitmap = self.backImage!.cgImage! // Back Image Bitmap let bitmapByteCountBackImage = backImageBitmap.bytesPerRow * backImageBitmap.height let rawDataBackImage = UnsafeMutablePointer&lt;UInt8&gt;.allocate(capacity: bitmapByteCountBackImage) // A pointer to the memory block where the drawing is to be rendered /// *** A graphics context contains drawing parameters and all device-specific information needed to render the paint on a page to a bitmap image *** // let contextBackImage = CGContext(data: rawDataBackImage, width: backImageBitmap.width, height: backImageBitmap.height, bitsPerComponent: backImageBitmap.bitsPerComponent, bytesPerRow: backImageBitmap.bytesPerRow, space: backImageBitmap.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue) // Draw bitmap on created context contextBackImage!.draw(backImageBitmap, in: CGRect(x: 0, y: 0, width: backImageBitmap.width, height: backImageBitmap.height)) // Allocate bitmap in memory with the same width and size as source image or front image let frontImageBitmap = self.frontImage!.cgImage! // Front Image Bitmap let bitmapByteCountFrontImage = frontImageBitmap.bytesPerRow * frontImageBitmap.height let rawDataFrontImage = UnsafeMutablePointer&lt;UInt8&gt;.allocate(capacity: bitmapByteCountFrontImage) // A pointer to the memory block where the drawing is to be rendered let contextFrontImage = CGContext(data: rawDataFrontImage, width: frontImageBitmap.width, height: frontImageBitmap.height, bitsPerComponent: frontImageBitmap.bitsPerComponent, bytesPerRow: frontImageBitmap.bytesPerRow, space: frontImageBitmap.colorSpace ?? CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue) // Draw bitmap on created context contextFrontImage!.draw(frontImageBitmap, in: CGRect(x: 0, y: 0, width: frontImageBitmap.width, height: frontImageBitmap.height)) // *** Get color components from replacement color *** \\ let destinationColorComponents = destColor.cgColor.components let r2 = UInt8(destinationColorComponents![0] * 255) let g2 = UInt8(destinationColorComponents![1] * 255) let b2 = UInt8(destinationColorComponents![2] * 255) let a2 = UInt8(destinationColorComponents![3] * 255) // Prepare to iterate over image pixels var byteIndex = 0 while byteIndex &lt; bitmapByteCountBackImage { // Get color of current pixel let red = CGFloat(rawDataBackImage[byteIndex + 0]) / 255 let green = CGFloat(rawDataBackImage[byteIndex + 1]) / 255 let blue = CGFloat(rawDataBackImage[byteIndex + 2]) / 255 let alpha = CGFloat(rawDataBackImage[byteIndex + 3]) / 255 let currentColorBackImage = UIColor(red: red, green: green, blue: blue, alpha: alpha); // Compare two colors using given tolerance value if sourceColor.contains(currentColorBackImage) { // If the're 'similar', then replace pixel color with given target color rawDataFrontImage[byteIndex + 0] = r2 rawDataFrontImage[byteIndex + 1] = g2 rawDataFrontImage[byteIndex + 2] = b2 rawDataFrontImage[byteIndex + 3] = a2 } byteIndex = byteIndex + 4; } // Retrieve image from memory context let imgref = contextFrontImage!.makeImage() let result = UIImage(cgImage: imgref!) // Clean up a bit rawDataBackImage.deallocate() rawDataFrontImage.deallocate() return result } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T15:12:59.447", "Id": "528246", "Score": "0", "body": "This function is taking 3-4 seconds to run? Did you profile your code? Or are you assuming that this is the slow bit? I don’t know Swift, so can’t do a review, but I’m sure you can do the comparison of pixel values without dividing every value by 255, that seems wasteful. Not 3-4 seconds wasteful, though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T21:15:48.287", "Id": "528255", "Score": "0", "body": "@CrisLuengo - Yep, the division and multiplication by 255 adds a little overhead, but it is inconsequential to the overhead of the `contains` call and the `UIColor` conversion. As you point out, the “Time Profiler” brings the real issues into stark relief." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T23:04:27.893", "Id": "528259", "Score": "0", "body": "@Rob Wow! Now I’m really curious what happens in that `UIColor` constructor. Nice answer BTW." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T08:18:11.370", "Id": "528334", "Score": "0", "body": "@CrisLuengo I had few leaks and performance issues in my code which got resolved by below answer of Rob" } ]
[ { "body": "<p>There are two issues.</p>\n<ol>\n<li><p>The process of converting to and from <code>UIColor</code> objects is very expensive.</p>\n</li>\n<li><p>The process of calling <a href=\"https://developer.apple.com/documentation/swift/array/2945493-contains\" rel=\"nofollow noreferrer\"><code>contains</code></a> on an <code>Array</code> is O(n).</p>\n</li>\n</ol>\n<p>The time profiler will show you this:</p>\n<p><a href=\"https://i.stack.imgur.com/qLpqs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/qLpqs.png\" alt=\"enter image description here\" /></a></p>\n<p>FWIW, I used a points of interest <code>OSLog</code>:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>import os.log\n\nprivate let log = OSLog(subsystem: Bundle.main.bundleIdentifier!, category: .pointsOfInterest)\n</code></pre>\n<p>And logged the range:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>@IBAction func didTapProcessButton(_ sender: Any) {\n os_signpost(.begin, log: log, name: #function)\n let final = replaceColor(frontImage: circleImage, backImage: squareImage, sourceColor: [.blue], withDestColor: .green, tolerance: 0.25)\n os_signpost(.end, log: log, name: #function)\n processedImageView.image = final\n}\n</code></pre>\n<p>Then I could easily zoom into just that interval in my code using the “Points of Interest&quot; tool. And having done that, I can switch to the “Time Profiler” tool, and it shows that 49.3% of the time was spent in <code>contains</code> and 24.9% of the time was spent in <code>UIColor</code> initializer.</p>\n<p>I can also double click on the the <code>replaceColor</code> function in the above call tree, it will show this to me in my code (for debug builds, at least). This is another way of seeing the same information shown above:</p>\n<p><a href=\"https://i.stack.imgur.com/fgdmk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/fgdmk.jpg\" alt=\"enter image description here\" /></a></p>\n<p>So, regarding <code>UIColor</code> issue, in <a href=\"https://stackoverflow.com/a/31661519/1271826\">Change color of certain pixels in a UIImage</a>, I explicitly use <code>UInt32</code> representation of the color (and have a <code>struct</code> to provide user-friendly interaction with this 32-bit integer). I do this to enjoy efficient integer processing, and avoiding <code>UIColor</code>. In that case, processing colors in a 1080×1080 px image takes 0.03 seconds (avoiding the <code>UIColor</code> to-and-fro for each pixel).</p>\n<p>The bigger issue is that <code>contains</code> is very inefficient. If you must use <code>contains</code> sort of logic (once you are using <code>UInt32</code> representations of your colors), I would suggest using a <code>Set</code>, with <a href=\"https://developer.apple.com/documentation/swift/set/1540013-contains\" rel=\"nofollow noreferrer\">O(1) performance</a>, rather than <code>Array</code> (with <a href=\"https://developer.apple.com/documentation/swift/array/2945493-contains\" rel=\"nofollow noreferrer\">O(n) performance</a>).</p>\n<p>But even with that <code>contains</code> is inefficient approach. (In my example, my array had only one item.) I see an unused <code>tolerance</code> parameter, and wonder if you might consider doing this mathematically rather than looking up colors in some collection.</p>\n<hr />\n<p>Unrelated to your performance issue, you have a very serious memory problem here. The provided code snippet is calculating <code>bitmapByteCountFrontImage</code> and <code>bitmapByteCountBackImage</code> as width × height, but it should be width × height <strong>× 4</strong>. Your context uses 4 bytes per pixel, so make sure you allocate your buffer accordingly.</p>\n<p>Personally, I get out of the business of manually allocating buffers, and let <code>CGContext</code> do that for me:</p>\n<pre><code>let bitmapInfo: UInt32 = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue\n\nlet contextFrontImage = CGContext(data: nil,\n width: frontImageBitmap.width,\n height: frontImageBitmap.height,\n bitsPerComponent: 8, // eight bits per component, not source image bits per component\n bytesPerRow: frontImageBitmap.width * 4, // explicitly four bytes per pixel, not source image bytes per row\n space: CGColorSpaceCreateDeviceRGB(), // explicit color space, not source image color space\n bitmapInfo: bitmapInfo)\n\nguard let dataFrontImage = contextFrontImage?.data else {\n print(&quot;unable to get front image buffer&quot;)\n return nil\n}\nlet rawDataFrontImage = dataFrontImage.assumingMemoryBound(to: UInt8.self)\n</code></pre>\n<p>And, when you do this, it frees you from manually deallocating later (which, when you start passing around images, gets very complicated very quickly).</p>\n<p>I would also advise against referencing the source image’s bytes per row, bits per component, and color space. The whole purpose of creating and drawing in this new context and grabbing its buffer, is to get a new, known, and predetermined format, not relying on the original image parameters. This obviates the <code>assert</code> logic that you have commented out at the start of your routine, as we no longer care about the format of the original images.</p>\n<hr />\n<p>For example, here is a rendition that uses 32 bit integers for colors and replaces the <code>contains</code> logic with an arithmetic calculation and it processes a 1080×1080 px image on simulator in a release build in 0.01 seconds:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>/// Replace colors in “front” image on the basis of colors within in the “back” image matching a requested color within a certain tolerance.\n///\n/// - Parameters:\n/// - frontImage: This is the image that will be used for the basis of the returned image (i.e. where `searchColor` was not found in `backImage`.\n/// - backImage: The image in which we're going to look for `searchColor`.\n/// - searchColor: The color we are looking for in the backImage.\n/// - replacementColor: The color we are going to replace it with if found within the specified `tolerance`.\n/// - tolerance: The tolerance (in `UInt8`) to used when looking for `searchColor`. E.g. a `tolerance` of 5 when\n/// - Returns: The resulting image.\n\nfunc replaceColor(frontImage: UIImage, backImage: UIImage, searchColor: UIColor, replacementColor: UIColor, tolerance: UInt8) -&gt; UIImage? {\n guard\n let backImageBitmap = backImage.cgImage,\n let frontImageBitmap = frontImage.cgImage\n else {\n print(&quot;replaceColor: Unable to get cgImage&quot;)\n return nil\n }\n\n let searchColorRGB = RGBA32(color: searchColor)\n let (searchColorMin, searchColorMax) = searchColorRGB.colors(tolerance: tolerance)\n let replacementColorRGB = RGBA32(color: replacementColor)\n\n /// Graphics context parameters\n\n let bitsPerComponent = 8\n let colorspace = CGColorSpaceCreateDeviceRGB()\n let bitmapInfo = RGBA32.bitmapInfo\n let width = backImageBitmap.width\n let height = backImageBitmap.height\n\n // back image\n\n let backImageBytesPerRow = width * 4\n let backImagePixelCount = width * height\n let contextBackImage = CGContext(data: nil,\n width: width,\n height: height,\n bitsPerComponent: bitsPerComponent,\n bytesPerRow: backImageBytesPerRow,\n space: colorspace,\n bitmapInfo: bitmapInfo)\n\n guard let dataBackImage = contextBackImage?.data else {\n print(&quot;replaceColor: Unable to get back image buffer&quot;)\n return nil\n }\n let bufferBackImage = dataBackImage.bindMemory(to: RGBA32.self, capacity: width * height)\n contextBackImage!.draw(backImageBitmap, in: CGRect(x: 0, y: 0, width: width, height: height))\n\n // front image\n\n let contextFrontImage = CGContext(data: nil,\n width: width,\n height: height,\n bitsPerComponent: bitsPerComponent,\n bytesPerRow: width * 4,\n space: colorspace,\n bitmapInfo: bitmapInfo)\n\n guard let dataFrontImage = contextFrontImage?.data else {\n print(&quot;replaceColor: Unable to get front image buffer&quot;)\n return nil\n }\n let bufferFrontImage = dataFrontImage.bindMemory(to: RGBA32.self, capacity: width * height)\n contextFrontImage!.draw(frontImageBitmap, in: CGRect(x: 0, y: 0, width: width, height: height))\n\n // Prepare to iterate over image pixels\n\n for offset in 0..&lt;backImagePixelCount {\n let color = bufferBackImage[offset]\n\n // Compare two colors using given tolerance value\n\n if color.between(searchColorMin, searchColorMax) {\n bufferFrontImage[offset] = replacementColorRGB\n }\n }\n\n // Retrieve image from memory context\n\n return contextFrontImage?.makeImage().flatMap {\n UIImage(cgImage: $0)\n }\n}\n</code></pre>\n<p>Where</p>\n<pre class=\"lang-swift prettyprint-override\"><code>struct RGBA32: Equatable {\n private var color: UInt32\n\n var redComponent: UInt8 {\n return UInt8((color &gt;&gt; 24) &amp; 255)\n }\n\n var greenComponent: UInt8 {\n return UInt8((color &gt;&gt; 16) &amp; 255)\n }\n\n var blueComponent: UInt8 {\n return UInt8((color &gt;&gt; 8) &amp; 255)\n }\n\n var alphaComponent: UInt8 {\n return UInt8((color &gt;&gt; 0) &amp; 255)\n }\n\n init(red: UInt8, green: UInt8, blue: UInt8, alpha: UInt8) {\n let red = UInt32(red)\n let green = UInt32(green)\n let blue = UInt32(blue)\n let alpha = UInt32(alpha)\n color = (red &lt;&lt; 24) | (green &lt;&lt; 16) | (blue &lt;&lt; 8) | (alpha &lt;&lt; 0)\n }\n\n init(color: UIColor) {\n var red: CGFloat = .zero\n var green: CGFloat = .zero\n var blue: CGFloat = .zero\n var alpha: CGFloat = .zero\n\n color.getRed(&amp;red, green: &amp;green, blue: &amp;blue, alpha: &amp;alpha)\n\n self.color = (UInt32(red * 255) &lt;&lt; 24) | (UInt32(green * 255) &lt;&lt; 16) | (UInt32(blue * 255) &lt;&lt; 8) | (UInt32(alpha * 255) &lt;&lt; 0)\n }\n\n func colors(tolerance: UInt8) -&gt; (RGBA32, RGBA32) {\n let red = redComponent\n let green = greenComponent\n let blue = blueComponent\n let alpha = alphaComponent\n\n let redMin = red &lt; tolerance ? 0 : red - tolerance\n let greenMin = green &lt; tolerance ? 0 : green - tolerance\n let blueMin = blue &lt; tolerance ? 0 : blue - tolerance\n let alphaMin = alpha &lt; tolerance ? 0 : alpha - tolerance\n\n let redMax = red &gt; (255 - tolerance) ? 255 : red + tolerance\n let greenMax = green &gt; (255 - tolerance) ? 255 : green + tolerance\n let blueMax = blue &gt; (255 - tolerance) ? 255 : blue + tolerance\n let alphaMax = alpha &gt; (255 - tolerance) ? 255 : alpha + tolerance\n\n return (RGBA32(red: redMin, green: greenMin, blue: blueMin, alpha: alphaMin),\n RGBA32(red: redMax, green: greenMax, blue: blueMax, alpha: alphaMax))\n }\n\n func between(_ min: RGBA32, _ max: RGBA32) -&gt; Bool {\n return\n redComponent &gt;= min.redComponent &amp;&amp; redComponent &lt;= max.redComponent &amp;&amp;\n greenComponent &gt;= min.greenComponent &amp;&amp; greenComponent &lt;= max.greenComponent &amp;&amp;\n blueComponent &gt;= min.blueComponent &amp;&amp; blueComponent &lt;= max.blueComponent\n }\n\n static let red = RGBA32(red: 255, green: 0, blue: 0, alpha: 255)\n static let green = RGBA32(red: 0, green: 255, blue: 0, alpha: 255)\n static let blue = RGBA32(red: 0, green: 0, blue: 255, alpha: 255)\n static let white = RGBA32(red: 255, green: 255, blue: 255, alpha: 255)\n static let black = RGBA32(red: 0, green: 0, blue: 0, alpha: 255)\n static let magenta = RGBA32(red: 255, green: 0, blue: 255, alpha: 255)\n static let yellow = RGBA32(red: 255, green: 255, blue: 0, alpha: 255)\n static let cyan = RGBA32(red: 0, green: 255, blue: 255, alpha: 255)\n\n static let bitmapInfo = CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Little.rawValue\n}\n</code></pre>\n<p>And you'd call it like so:</p>\n<pre class=\"lang-swift prettyprint-override\"><code>let resultImage = replaceColor(frontImage: frontImage, backImage: backImage, searchColor: .blue, replacementColor: .green, tolerance: 5)\n</code></pre>\n<p>Resulting in (with the front, back and resulting images, going left to right):</p>\n<p><a href=\"https://i.stack.imgur.com/quaGy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/quaGy.png\" alt=\"enter image description here\" /></a></p>\n<p>Clearly, you can implement the <code>tolerance</code> logic however you want, but hopefully this illustrates the idea that excising <code>UIColor</code> and collection searching can have a dramatic impact on performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T08:16:35.453", "Id": "528333", "Score": "0", "body": "thanks a lot for saving my time!! The way you described each and every issue and solution to that was more than amazing. Now my code is working like a charm after I followed your instructions and your code snippet." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T18:33:22.147", "Id": "267899", "ParentId": "267889", "Score": "3" } } ]
{ "AcceptedAnswerId": "267899", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T12:40:20.327", "Id": "267889", "Score": "1", "Tags": [ "performance", "image", "swift", "ios", "color" ], "Title": "Changing the color of some pixels in an image in Swift" }
267889
<p>I just started learning java and wrote this variable length array as my first program. I wanted people's opinion on how &quot;java&quot; this code is. For example coding conventions, idioms that I could have used or any improvements that could be made.</p> <p><strong>MyClass.java</strong>:</p> <pre><code>package myproject; public class MyClass { public static void main(String[] args) { MyArray array = new MyArray(); for (int i = 0; i &lt; 100; i++) array.Push(i); for (int i = 0; i &lt; array.Size(); i++) { System.out.println(array.Get()[i]); } } } </code></pre> <p><strong>MyArray.java</strong>:</p> <pre><code>package myproject; public class MyArray { public MyArray() { array = new int[size]; } public MyArray(int size) { this.size = size; array = new int[size]; } public int[] Get() { return array; } public void Push(int number) { if (currentIndex &gt;= size) { IncreaseArraySize(); } array[currentIndex] = number; currentIndex++; } int Size() { return currentIndex; } private void IncreaseArraySize(){ if (size == 0){ size++; } else { size *= 2; } int newArray[] = new int[size]; for (int i = 0; i &lt; array.length; i++) { newArray[i] = array[i]; } array = newArray; } private int size = 0; private int currentIndex = 0; private int[] array; } </code></pre> <p>I was also kind of sceptical of this line : <code>array = newArray;</code> at first but the program seems to work fine.</p>
[]
[ { "body": "<p><strong>Advice 1</strong></p>\n<pre><code>public MyArray() {\n array = new int[size];\n}\n</code></pre>\n<p>Above, <code>size</code> is 0, so you are allocating a zero-length array. Useless. Consider this:</p>\n<pre><code>private static final int INITIAL_CAPACITY = 10; // Or some other reasonable constant but 10.\n\npublic MyArray() {\n array = new int[INITIAL_CAPACITY];\n}\n</code></pre>\n<p><strong>Advice 2</strong></p>\n<pre><code> ...\n private int size = 0;\n private int currentIndex = 0;\n private int[] array;\n}\n</code></pre>\n<p>You put your fields after everything else. The conventional portion of a Java file for fields is right after static constants and right before constructors:</p>\n<pre><code>private static final int INITIAL_CAPACITY = 10;\n\nprivate int size = 0;\nprivate int currentIndex = 0;\nprivate int[] array;\n\npublic MyArray() {\n ...\n}\n</code></pre>\n<p><strong>Advice 3</strong></p>\n<p>Once again, the fields:</p>\n<pre><code>private int size = 0;\nprivate int currentIndex = 0;\nprivate int[] array;\n</code></pre>\n<p>JVM sets <code>int</code> fields to zero by default. Consider this:</p>\n<pre><code>private int size;\nprivate int currentIndex;\nprivate int[] array;\n</code></pre>\n<p><strong>Advice 4</strong></p>\n<pre><code>public int[] Get() {\n return array;\n}\n</code></pre>\n<p>Wrong. Please, don't expose data structure related internals to the outside world.</p>\n<p><strong>Advice 5</strong></p>\n<p>Method names must come in <code>camelCase</code>, not in <code>PascalCase</code>.</p>\n<p><strong>Advice 6</strong></p>\n<pre><code>public MyArray(int size) {\n this.size = size;\n array = new int[size];\n}\n</code></pre>\n<p>What?! Your MyArray (no pun intended) is of size of <code>size</code> at the very beginning? In the state where all the &quot;elements&quot; are 0?</p>\n<p><strong>Advice 7 (ignore)</strong></p>\n<p>Actually, it seems to me that you don't need to keep <code>size</code> at all. Judging from your implementation we have always <code>size == array.length</code>. Ditch the <code>size</code> and rely on <code>array.length</code>; much easier to follow.</p>\n<p><strong>Advice 8</strong></p>\n<p>I suggest you add a <code>get(int)</code> method for accessing the data.</p>\n<p><strong>Advice 9</strong></p>\n<p>In <code>IncreaseArraySize()</code>, you could use <code>System.arraycopy</code>. Most likely, it will copy faster on large arrays.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T15:24:42.880", "Id": "528247", "Score": "0", "body": "For advice 1, my intention was for the array to be empty if size isn't specified in the constructor and calling Push would increase the size anyways. I also don't understand advice 6, apart from the fact that it does actually makes sense to completely get rid of `size`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T17:06:57.813", "Id": "528250", "Score": "1", "body": "The array size needs to be tracked separately for `IncreaseArraySize` to work. Otherwise you have to resize the array every time an element is added or removed, which is very inefficient." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T17:12:12.813", "Id": "528251", "Score": "0", "body": "@EricStein In this program, array size is stored at `currentIndex`. The variable called `size` is actually the capacity, which is always the same as the `array.length`. I.e. your analysis is correct (you need two sizes), but due to bad naming, it doesn't apply here." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T14:39:16.833", "Id": "267891", "ParentId": "267890", "Score": "1" } }, { "body": "<blockquote>\n<pre><code> private int size = 0;\n private int currentIndex = 0;\n</code></pre>\n</blockquote>\n<p>Given how you use these, better names would be</p>\n<pre><code> private int capacity = 0;\n private int size = 0;\n</code></pre>\n<p>But as <a href=\"https://codereview.stackexchange.com/a/267891/71574\">@coderodde already noted</a>, it would make more sense to get the capacity from <code>array.length</code> rather than maintain it separately.</p>\n<p>I would also rename <code>array</code> to <code>data</code>, but that's a more arguable point.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T17:16:23.503", "Id": "267897", "ParentId": "267890", "Score": "4" } } ]
{ "AcceptedAnswerId": "267891", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T13:06:50.177", "Id": "267890", "Score": "2", "Tags": [ "java", "beginner" ], "Title": "Variable length array" }
267890
<p>I want to enable bitmask-like behavior (ie. overloaded <code>operator|</code>, <code>operator&amp;</code> and <code>operator^</code>) for some <code>enum class</code>es. This is what I came up with:</p> <pre class="lang-cpp prettyprint-override"><code>#pragma once #include &lt;type_traits&gt; /// \brief Marks an enum class as enabled for bitmask behavior. /// \param type The name of the enum for which to enable the bitmask. /// \details This macro works by specializing \see{is_bitmask}. #define ENABLE_BITMASK(type) template&lt;&gt; \ struct is_bitmask&lt;type&gt; { \ constexpr static bool value = true; \ private: \ is_bitmask() = delete; \ }; /// This is a marker struct to enable bitmask behavior for enum classes. Should be /// automatically specialized by using \see ENABLE_BITMASK. /// \tparam T The enum class for which to enable this behavior. template &lt;typename T&gt; struct is_bitmask final { constexpr static bool value = false; private: is_bitmask() = delete; }; template &lt;typename T&gt; concept is_enum_bitmask = std::is_enum_v&lt;T&gt; &amp;&amp; (is_bitmask&lt;T&gt;::value == std::true_type::value); /// Enables bitmask behavior for enum classes by overloading operator|, operator&amp;, operator^ and operator~. /// \tparam Bits The enum to turn into a bitmask. This template parameter is constrained by \see is_enum_bitmask. template &lt;is_enum_bitmask Bits&gt; struct EnumBitset { private: using Type = std::underlying_type_t&lt;Bits&gt;; Type bits_ = 0; constexpr EnumBitset(Type b) noexcept { bits_ = b; } public: constexpr EnumBitset(Bits bit) noexcept { bits_ = static_cast&lt;Type&gt;(bit); } constexpr EnumBitset() noexcept { bits_ = 0; } constexpr EnumBitset(const EnumBitset&amp; other) = default; constexpr EnumBitset(EnumBitset&amp;&amp; other) noexcept = default; constexpr EnumBitset&amp; operator=(const EnumBitset&amp; other) = default; constexpr EnumBitset&amp; operator=(EnumBitset&amp;&amp; other) noexcept = default; constexpr ~EnumBitset() noexcept = default; [[nodiscard]] constexpr inline EnumBitset&lt;Bits&gt; operator|(const EnumBitset&lt;Bits&gt;&amp; b) const noexcept { return EnumBitset{this-&gt;bits_ | b.bits_}; } [[nodiscard]] constexpr inline EnumBitset&lt;Bits&gt; operator&amp;(const EnumBitset&lt;Bits&gt;&amp; b) const noexcept { return EnumBitset{this-&gt;bits_ &amp; b.bits_}; } [[nodiscard]] constexpr inline EnumBitset&lt;Bits&gt; operator^(const EnumBitset&lt;Bits&gt;&amp; b) const noexcept { return EnumBitset{this-&gt;bits_ ^ b.bits_}; } constexpr inline void operator|=(const EnumBitset&lt;Bits&gt;&amp; b) noexcept { this-&gt;bits_ |= b.bits_; } constexpr inline void operator&amp;=(const EnumBitset&lt;Bits&gt;&amp; b) noexcept { this-&gt;bits_ &amp;= b.bits_; } constexpr inline void operator^=(const EnumBitset&lt;Bits&gt;&amp; b) noexcept { this-&gt;bits_ ^= b.bits_; } [[nodiscard]] constexpr inline bool operator==(const EnumBitset&lt;Bits&gt;&amp; b) const noexcept { return this-&gt;bits_ == b.bits_; } [[nodiscard]] constexpr inline bool operator!=(const EnumBitset&lt;Bits&gt;&amp; b) const noexcept { return this-&gt;bits_ != b.bits_; } constexpr inline EnumBitset&lt;Bits&gt; operator~() const noexcept { return EnumBitset{~this-&gt;bits_}; } constexpr inline operator bool() const noexcept { return bits_ != 0; } constexpr inline explicit operator Type() const noexcept { return bits_; } [[nodiscard]] constexpr inline Type getBits() const { return bits_; } }; template &lt;typename T, typename U&gt; requires (is_enum_bitmask&lt;T&gt; &amp;&amp; std::is_constructible_v&lt;EnumBitset&lt;T&gt;, U&gt;) constexpr auto operator|(T left, U right) -&gt; EnumBitset&lt;T&gt; { return EnumBitset&lt;T&gt;(left) | right; } template &lt;typename T, typename U&gt; requires (is_enum_bitmask&lt;T&gt; &amp;&amp; std::is_constructible_v&lt;EnumBitset&lt;T&gt;, U&gt;) constexpr auto operator&amp;(T left, U right) -&gt; EnumBitset&lt;T&gt; { return EnumBitset&lt;T&gt;(left) &amp; right; } template &lt;typename T, typename U&gt; requires (is_enum_bitmask&lt;T&gt; &amp;&amp; std::is_constructible_v&lt;EnumBitset&lt;T&gt;, U&gt;) constexpr auto operator^(T left, U right) -&gt; EnumBitset&lt;T&gt; { return EnumBitset&lt;T&gt;(left) ^ right; } </code></pre> <p>Here's how it's supposed to work:</p> <ul> <li>One can enable bitmask behavior by using <code>ENABLE_BITMASK(MyEnum)</code>. I'm really unsure if this is a good way of doing this or if there are better ways to tag an enum as &quot;bitmask enabled&quot;. I don't want to enable it for all enum classes since this would make <code>enum class</code>es pointless.</li> <li>All enum class constants can be used with each other, but we can't mix two enums.</li> <li>All operations should be <code>constexpr</code> so they can be optimized by the compiler.</li> <li>(Known Limitation): <code>std::is_enum_v&lt;T&gt;</code> works for both enum classes and enums, I'll fix this with C++23's <code>std::is_scoped_enum&lt;T&gt;</code> as soon as it's available.</li> </ul> <p>Here's some example code:</p> <pre class="lang-cpp prettyprint-override"><code>enum class BitmaskableEnum { kFirst = 1, kSecond = 2, kThird = 4, kFirstAndSecond = 3 }; ENABLE_BITMASK(BitmaskableEnum); enum class SecondBitmaskableEnum { kFirst = 1 }; ENABLE_BITMASK(SecondBitmaskableEnum); enum class RegularEnum { kFirstBit = 1, kSecondBit = 2, kBoth = 3 }; void tests() { // Should compile auto a = BitmaskableEnum::kFirst | BitmaskableEnum::kSecond ^ BitmaskableEnum::kThird; a ^= BitmaskableEnum::kThird; // Should be true assert(a == BitmaskableEnum::kFirstAndSecond); // Those should not compile: const auto b = RegularEnum::kFirstBit | RegularEnum::kSecondBit; const auto c = BitmaskableEnum::kFirst | SecondBitmaskableEnum::kFirst; } </code></pre> <p>I also have a minor question: I'll be using this in a larger project of mine and would like to put this in the <code>util</code> namespace. Would this work with ADL? If not: Which parts need to be kept in the global namespace?</p>
[]
[ { "body": "<h1>Simplify <code>is_bitmask</code></h1>\n<p>Since you are using C++20 anyway, you can avoid making <code>is_bitmask</code> a <code>struct</code>, and make it a <code>constexpr</code> template variable instead. This simplifies the first part of the code a lot:</p>\n<pre><code>#define ENABLE_BITMASK(type) template&lt;&gt; \\\ninline constexpr bool is_bitmask&lt;type&gt; = true;\n\ntemplate &lt;typename T&gt;\ninline constexpr bool is_bitmask = false;\n\ntemplate &lt;typename T&gt;\nconcept is_enum_bitmask = std::is_enum_v&lt;T&gt; &amp;&amp; is_bitmask&lt;T&gt;;\n</code></pre>\n<h1>Missing <code>[[nodiscard]]</code>s?</h1>\n<p>I see you use <code>[[nodiscard]]</code> for most of the operators. Of course it should not be used for <code>|=</code>, <code>&amp;=</code> and <code>^=</code>, but why not use it for <code>~</code>, <code>bool()</code> and <code>Type()</code> as well?</p>\n<h1>Missing global operators</h1>\n<p>You have a just three global operators overloaded for bitmasks, and they all result in an <code>EnumBitset&lt;T&gt;</code> result. But I would also like to be able to write:</p>\n<pre><code>auto x = BitmaskableEnum::kFirst; \nauto y = ~x; // no match for operator~\nauto z = !x; // no match for operator!\n</code></pre>\n<h1>Missing <code>noexcept</code></h1>\n<p>There are a few member functions that are missing <code>noexcept</code>. There's nothing that should be able to throw.</p>\n<h1>Unnecessary trailing return types</h1>\n<p>I don't see a reason for the trailing return types for the global operators. The leading <code>auto</code> return type will already do the right thing.</p>\n<h1>Putting it in a namespace</h1>\n<p>You can move everything into its own namespace, with some changes. First, preprocessor macros are expanded at the point they are used, so you have to make sure they declare <code>is_bitmask</code> in the right namespace:</p>\n<pre><code>namespace util {\n#define ENABLE_BITMASK(type) template&lt;&gt; \\\ninline constexpr bool util::is_bitmask&lt;type&gt; = true;\n...\n</code></pre>\n<p>Second, ADL is not the issue, but regular lookup is the problem. You have to tell the compiler that you want to search for functions inside the <code>util</code> namespace, either by doing:</p>\n<pre><code>using namespace util;\n</code></pre>\n<p>Or if you want to restrict it only to the operators, then you have to write:</p>\n<pre><code>using util::operator&amp;;\nusing util::operator|;\nusing util::operator^;\n...\n</code></pre>\n<p>Once the operators have been found and they return a <code>util::EnumBitset&lt;T&gt;</code>, the compiler already has the full name of the type and doesn't have to do any further lookups.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T23:01:03.617", "Id": "267906", "ParentId": "267902", "Score": "3" } } ]
{ "AcceptedAnswerId": "267906", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-11T21:36:29.087", "Id": "267902", "Score": "6", "Tags": [ "c++", "enum", "c++20", "constant-expression" ], "Title": "Enabling bitset-like behavior for enum classes (C++20)" }
267902
<p>This is one more implementation of <a href="https://en.wikipedia.org/wiki/Binary_search_tree" rel="nofollow noreferrer">Binary Search Tree</a> in C++. There are many such implementations, however they are typically long and complex, and also many of them rely on pointers to parent nodes for deletion (which isn't necessary). My goals were simplicity, clarity and conciseness, especially for the <code>erase</code> function. Performance wasn't my first priority, so you can see a number of places in this code, where the performance might be slightly improved.</p> <pre><code>#include &lt;cstdlib&gt; #include &lt;ctime&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;utility&gt; using std::cout; using std::endl; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// Node // //////////////////////////////////////////////////////////////////////////////// struct Node { Node() = delete; Node(std::string const&amp; K): _lPtr(nullptr), _rPtr(nullptr), _key(K) {} friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, const Node* const); friend std::pair&lt;Node**, bool&gt; Find(std::string const&amp;, Node** const); friend void Erase(Node** const); friend void Clear(const Node* const); private: friend Node** FindMin(Node** const); friend Node** FindMax(Node** const); Node* _lPtr; Node* _rPtr; std::string _key; }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; S, const Node* const N) // ------ in the subtree with the root N: // ------ recursively traverse this subtree with inorder keys output { if (N != nullptr) S &lt;&lt; '(' &lt;&lt; N-&gt;_lPtr &lt;&lt; N-&gt;_key &lt;&lt; N-&gt;_rPtr &lt;&lt; ')'; return S; } std::pair&lt;Node**, bool&gt; Find(std::string const&amp; K, Node** const P) // ------ in the subtree with the root *P: // ------ if the node with the key K exists, return pointer to pointer to it and the flag 'true', // ------ otherwise return pointer to pointer, where the new node should be linked, and the flag 'false' { const auto nodePtr = *P; if (nodePtr != nullptr) { if (K &lt; nodePtr-&gt;_key) { // ------ search in the left subtree return Find(K, &amp;nodePtr-&gt;_lPtr); } else if (K &gt; nodePtr-&gt;_key) { // ------ search in the right subtree return Find(K, &amp;nodePtr-&gt;_rPtr); } else { // ------ the node is found: return pointer to it return std::make_pair(P, true); } } else { // ------ the node isn't found return std::make_pair(P, false); } } void Erase(Node** const P) // ------ in the subtree with the root *P: // ------ recursively erase its root { const auto nodePtr = *P; if (nodePtr-&gt;_lPtr != nullptr &amp;&amp; nodePtr-&gt;_rPtr != nullptr) { // ------ the node has two children: find the closest node, copy its key and erase it // ------ closest left or right nodes are chosen randomly for symmetry const auto closestPtr = (std::rand() % 2 == 0) ? FindMax(&amp;nodePtr-&gt;_lPtr) : FindMin(&amp;nodePtr-&gt;_rPtr); nodePtr-&gt;_key = (*closestPtr)-&gt;_key; Erase(closestPtr); } else if (nodePtr-&gt;_lPtr != nullptr) { // ------ the node has only the left child *P = nodePtr-&gt;_lPtr; delete nodePtr; } else if (nodePtr-&gt;_rPtr != nullptr) { // ------ the node has only the right child *P = nodePtr-&gt;_rPtr; delete nodePtr; } else { // ------ the node doesn't have children *P = nullptr; delete nodePtr; } } void Clear(const Node* const N) // ------ in the subtree with the root N: // ------ recursively erase all this subtree { if (N != nullptr) { Clear(N-&gt;_lPtr); Clear(N-&gt;_rPtr); delete N; } } Node** FindMin(Node** const P) // ------ in the subtree with the root *P: // ------ return pointer to pointer to the node with a minimal key { const auto nodePtr = *P; return (nodePtr-&gt;_lPtr != nullptr) ? FindMin(&amp;nodePtr-&gt;_lPtr) : P; } Node** FindMax(Node** const P) // ------ in the subtree with the root *P: // ------ return pointer to pointer to the node with a maximal key { const auto nodePtr = *P; return (nodePtr-&gt;_rPtr != nullptr) ? FindMax(&amp;nodePtr-&gt;_rPtr) : P; } //////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////// BST // //////////////////////////////////////////////////////////////////////////////// struct BST { BST(): _rootPtr(nullptr) {std::srand(std::time(nullptr));} virtual ~BST() {this-&gt;clear();} friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp;, BST const&amp;); bool contains(std::string const&amp;) const noexcept; void insert(std::string const&amp;); void erase(std::string const&amp;) noexcept; void clear() noexcept; private: Node* _rootPtr; }; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; S, BST const&amp; T) { S &lt;&lt; T._rootPtr; return S; } bool BST::contains(std::string const&amp; K) const noexcept { return Find(K, const_cast&lt;Node**&gt;(&amp;_rootPtr)).second; } void BST::insert(std::string const&amp; K) { const auto res = Find(K, &amp;_rootPtr); if (not res.second) *res.first = new Node(K); } void BST::erase(std::string const&amp; K) noexcept { const auto res = Find(K, &amp;_rootPtr); if (res.second) Erase(res.first); } void BST::clear() noexcept { Clear(_rootPtr); _rootPtr = nullptr; } //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// main // //////////////////////////////////////////////////////////////////////////////// int main() { BST t; t.insert(&quot;50&quot;); t.insert(&quot;60&quot;); t.insert(&quot;40&quot;); t.insert(&quot;45&quot;); t.insert(&quot;43&quot;); t.insert(&quot;30&quot;); t.insert(&quot;35&quot;); // ---------------------------- traverse original tree cout &lt;&lt; t &lt;&lt; endl; // ------------------------------------------------ erase t.erase(&quot;50&quot;); // ------------------------ traverse after erasure cout &lt;&lt; t &lt;&lt; endl; } </code></pre> <p>Also I tried to use more references in function arguments to get rid of <code>*</code> and <code>&amp;</code> operators, but I didn't succeed. May be, this is example of a problem, where references aren't flexible enough comparing to pointers - what do you think?</p> <p>Please see a more complete implementation of the BST (templates, copy and move constructors and assignments) <a href="https://github.com/alekseYY/BST" rel="nofollow noreferrer">here</a>.</p>
[]
[ { "body": "<h1>Move <code>struct Node</code> inside <code>struct BST</code></h1>\n<p>A <code>Node</code> is just an implementation detail of a <code>BST</code>. Also, consider the scenario where you need multiple data types, like linked lists, hash maps and so on, you can't name everything <code>Node</code>. Moving <code>Node</code> into <code>BST</code> solves the problem neatly:</p>\n<pre><code>struct BST\n{\n struct Node {\n ...\n };\n ...\n};\n</code></pre>\n<h1>Make operations on the tree <code>private</code> members functions.</h1>\n<p>You have a lot of global functions that are just helper functions for the BST. Make them <code>private</code> member functions of <code>BST</code> or <code>Node</code>. This will avoid polluting the global namespace.</p>\n<h1>Use smart pointers to avoid manual memory management</h1>\n<p>Use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr\" rel=\"nofollow noreferrer\"><code>std::unique_ptr</code></a> for the child pointers in <code>Node</code>, and for the pointer to the root node in <code>BST</code>. This avoids you having to call <code>new</code> and <code>delete</code> manually. For example:</p>\n<pre><code>struct Node\n{\n ...\nprivate:\n std::unique_ptr&lt;Node&gt; _lPtr;\n std::unique_ptr&lt;Node&gt; _rPtr;\n ...\n};\n</code></pre>\n<p>When inserting a node, use <a href=\"https://en.cppreference.com/w/cpp/memory/unique_ptr/make_unique\" rel=\"nofollow noreferrer\"><code>std::make_unique</code></a> instead of <code>new</code>:</p>\n<pre><code>void BST::insert(std::string const&amp; K)\n{\n const auto res = Find(K, &amp;_rootPtr);\n if (not res.second)\n *res.first = std::make_unique&lt;Node&gt;(K);\n}\n</code></pre>\n<p>Note that this also requires you to update other functions that would return a <code>Node **</code> to return a <code>std::unique_ptr&lt;Node&gt; *</code>. But now deleting a subtree is very simple. You don't need to call <code>Clear()</code> anymore; assuming <code>_rootPtr</code> is also a <code>std::unique_ptr&lt;Node&gt;</code>, you can just write:</p>\n<pre><code>void BST::clear() noexcept\n{\n _rootPtr.reset();\n}\n</code></pre>\n<p>This will automatically <code>delete</code> the root node, and since class members are automatically destructed, <code>_leftPtr</code> and <code>_rightPtr</code> will also clean themselves up, which in turn will recurse to their children until everything has been deleted. You don't need to explicitly call <code>clear()</code> in the destructor of <code>BST</code> either.</p>\n<h1>Prefer <code>'\\n'</code> over <code>std::endl</code></h1>\n<p>Use <a href=\"https://stackoverflow.com/questions/213907/stdendl-vs-n\"><code>'\\n'</code> instead of <code>std::endl</code></a>; the latter is equivalent to the former but also forces the output to be flushed, which is usually not necessary and can impact performance.</p>\n<h1>References vs. pointers</h1>\n<p>You should be able to use references for function arguments, however references should always point to a valid object, you can't have a <code>nullptr</code> reference. This is a problem for the way you wrote some of the functions; for example naively trying to modify your <code>operator&lt;&lt;()</code> would look like:</p>\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; S, const Node&amp; N)\n{\n if (&amp;N != nullptr) S &lt;&lt; '(' &lt;&lt; *(N._lPtr) &lt;&lt; N._key &lt;&lt; *(N._rPtr) &lt;&lt; ')';\n return S;\n}\n</code></pre>\n<p>However, since the C++ standard says that references must always point to valid objects, most compilers will eliminate the check for <code>&amp;N != nullptr</code>. So instead you would have to rewrite it like so:</p>\n<pre><code>std::ostream&amp; operator&lt;&lt;(std::ostream&amp; S, const Node&amp; N)\n{\n S &lt;&lt; '(';\n if (N._lPtr) S &lt;&lt; *(N._lPtr);\n S &lt;&lt; N._key;\n if (N._rPtr) S &lt;&lt; *(N._rPtr);\n S &lt;&lt; ')';\n return S;\n}\n</code></pre>\n<p>Yes, that's more tedious, but that's the way you would have to do it if you want to use references. The same goes for other functions that currently take a pointer to a <code>Node</code> that might be <code>nullptr</code>.</p>\n<h1>Consider using Doxygen to document your code</h1>\n<p>I see you tried to document some of your functions with comments, which is great. Consider using the <a href=\"https://en.wikipedia.org/wiki/Doxygen\" rel=\"nofollow noreferrer\">Doxygen</a> standard to document your code; this allows the Doxygen tools to check that you documented everything, and can create nicely formatted PDF, HTML and other format documents from your code.</p>\n<h1>Drawback of lack of parent pointers</h1>\n<p>There is a drawback of not having parent pointers, which you will encounter if you would want to implement iterators for your binary search tree. With parent pointers, iterators only have to store the pointer to the node they are currently at; using the parent pointer and comparing whether they are at the left or right child of the parent they can correctly iterate to the next node. Without parent pointers you need to store a stack of parent pointers inside your iterator.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T18:40:17.157", "Id": "528292", "Score": "0", "body": "Thank you for your kind suggestions. I won't touch my question, however I'll try to implement them in my GitHub repository." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:10:04.157", "Id": "528354", "Score": "1", "body": "Note that using `unique_ptr` would give a recursive delete issue, causing excessive stack depth. OTOH, being a tree (rather than a single list) you might have that anyway as-written." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:13:32.440", "Id": "528355", "Score": "0", "body": "@JDługosz That's true, although it's not worse than OP's `Clear()` in that regard. I'm not sure how to address this issue efficiently in a tree without parent pointers, as again, iterating over it would require a stack as well, and unlike a linked list where you have only one child pointer, you can't use the trick where you move the child's child pointer into your own child pointer in a loop." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:28:45.483", "Id": "528356", "Score": "0", "body": "@G.Sliepen IIRC, the normal way is to maintain an \"end\" pointer and move the Right link to the end, sliding the end pointer down all the way to the left. Do that while deleting and advancing to the left in a non-recursive loop. Back in the old days, running out of stack space was a more serious issue." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T10:12:50.100", "Id": "267912", "ParentId": "267907", "Score": "3" } }, { "body": "<p>You can use inline initializers for class data members, and simplify the constructors.</p>\n<pre><code> ⋮\n Node* _lPtr = nullptr;\n Node* _rPtr = nullptr;\n ⋮\npublic:\n explicit Node(std::string const&amp; K) : _key{K} {}\n</code></pre>\n<p>Oh, and being a one-argument constructor, it should probably be <code>explicit</code>.</p>\n<p>The parameter, being a <code>string</code> by reference, is OK and normal. But it could be better: For strings in particular, prefer using <code>string_view</code> (as a value) instead for more flexibility and efficiency when calling with lexical string literals. But, being a constructor that will create a string value for its member, you can use the <em>sink</em> idiom instead:</p>\n<pre><code> explicit Node(std::string K/*sink*/) : _key{std::move(K)} {}\n</code></pre>\n<p>This will save another copy operation when a <code>string</code> had to be created in order to call the constructor.</p>\n<h2>pointers or references</h2>\n<p>In this case, you are dealing with pointers most explicitly, so using pointers is probably clearest. That way you don't get confused as to whether one or two dereferences are happening.</p>\n<h2>testing pointers</h2>\n<p>Don't write explicit tests against <code>nullptr</code>. Unlike in some other languages, <code>nullptr</code> is <code>false</code> and other pointer values are <code>true</code>. Just write <code>if(p)</code> or <code>if(!p)</code> when testing a pointer.</p>\n<p>(Historical note: this was an efficiency issue with smart pointers prior to C++11, and is established culture and idiom. It <em>is</em> less cognitive overhead and thus easier to read.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T15:14:22.977", "Id": "528448", "Score": "0", "body": "Thank you for curly braces `{K}` as well! The argument type will be not only the `std::string`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:25:28.250", "Id": "267967", "ParentId": "267907", "Score": "1" } } ]
{ "AcceptedAnswerId": "267912", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T03:47:29.260", "Id": "267907", "Score": "3", "Tags": [ "c++", "binary-search-tree" ], "Title": "Binary Search Tree in C++ without parent pointers" }
267907
<p>In my coding interview for a company, I got the question to write a Minesweeper game. I did not manage to finish the game in 1 hour at that time, so now I have written it again after the interview. Could you please help me to check if my code follows good practices for a game-program ? I appreciate any ideas.</p> <pre><code>import random import pdb from os import system from enum import Enum class GameStatus(Enum): PLAYING = 0 LOSE = 1 WIN = 2 class MineBoard(object): def __init__(self, w, h, k): # Create a new board with size w x h self.w = w self.h = h self.board = [[0 for i in range(w)] for j in range(h)] self.allocateMines(w, h, k) self.status = GameStatus.PLAYING self.cellsToOpen = w * h - k def allocateMines(self, w, h, numOfMines): allocIndexes = self.getRandomPos(w * h, numOfMines) for i in allocIndexes: self.setMine(int(i / w), i % h) self.setAdjacentMines(int(i / w), i % h) def printLayout(self): print(' ' * 7 + ''.join(map(lambda x : '{:^7d}'.format(x + 1), range(self.w)))) print(' ' * 7 + '-' * (self.w * 7)) for (i, row) in enumerate(self.board): print('{:^7d}'.format(i + 1) + '|' + ' |'.join(list(map(lambda x : '{:^5s}'.format(self.display(x)), row))) + ' | ') print(' ' * 7 + '-' * (self.w * 7)) def click(self, row, col): value = self.reveal(row, col) if value: self.cellsToOpen -= 1 if self.cellsToOpen == 0: self.status = GameStatus.WIN if self.hasMine(row, col): self.status = GameStatus.LOSE elif self.isBlank(row, col): for dr in range(row - 1, row + 2): for dc in range(col - 1, col + 2): self.click(dr, dc) def flag(self, row, col): if self.isValidCell(row, col) and self.isHidden(row, col): self.toggleFlag(row, col) def isValidCell(self, row, col): return row &gt;= 0 and row &lt; self.h and col &gt;= 0 and col &lt; self.w def getRandomPos(self, n, k): res = [] remains = [i for i in range(n)] while k &gt; 0: r = random.randint(0, len(remains) - 1) res.append(r) del remains[r] k -= 1 return res #Convention for cell values: # - 0 : Hidden Blank # - 10 : Revealed Blank # - -1 : Hidden Bomb # - 9 : Revealed Bomb # - 1 ~ 8 : number of adjacent bomb (hidden) # - 11 ~ 18 : adjacent bomb (revealed) # - x + 100 : Flagged # def setMine(self, row, col): self.board[row][col] = -1 def setAdjacentMines(self, row, col): for dr in range(row - 1, row + 2): for dc in range(col - 1, col + 2): if self.isValidCell(dr, dc) and not self.hasMine(dr, dc): self.board[dr][dc] += 1 def toggleFlag(self, row, col): if self.isFlagged(row, col): self.board[row][col] -= 100 else: self.board[row][col] += 100 # Open a cell and return its value def reveal(self, row, col): if not self.isValidCell(row, col) or not self.isHidden(row, col): return None if self.isFlagged(row, col): self.toggleFlag(row, col) self.board[row][col] += 10 return self.board[row][col] def isHidden(self, row, col): return self.board[row][col] &lt; 9 def hasMine(self, row, col): return self.board[row][col] % 10 == 9 def isBlank(self, row, col): return self.board[row][col] % 10 == 0 def isOver(self): return self.winGame() or self.loseGame() def loseGame(self): return self.status == GameStatus.LOSE def winGame(self): return self.status == GameStatus.WIN def isFlagged(self, row, col): return self.board[row][col] &gt; 90 def revealAll(self): for i in range(len(self.board)): for j in range(len(self.board[0])): self.reveal(i, j) def display(self, ip): if ip &gt; 90: return 'F' elif ip == 9: return '*' elif ip == 10: return '.' elif ip &gt; 10: return str(ip - 10) return '' def cls(): system('clear') def play(): w = int(input('Enter width of board: ')) h = int(input('Enter height of board: ')) m = int(input('Enter number of mines : ')) while m &gt;= w * h - 1: m = int(input('Too many mines. Enter again : ')) game = MineBoard(w, h, m) while not game.isOver(): cls() game.printLayout() command = nextCommand() splits = command.split(' ') row = int(splits[0]) - 1 col = int(splits[1]) - 1 if command[-1] == 'F': game.flag(row, col) else: game.click(row, col) game.revealAll() cls() game.printLayout() if game.loseGame(): print('You lose !!') elif game.winGame(): print('You win !!. Congradulations !!') def nextCommand(): instruction = 'Commands : \n&lt;row&gt; &lt;col&gt; : open cell\n&lt;row&gt; &lt;col&gt; F : flag cell\nq : quit\n' return input(instruction).strip() play() </code></pre>
[]
[ { "body": "<p>Generally the code shows a consistent style, so in that regard I think it looks good. I like the way the status is explicitly kept using the enum; it makes everything that more easy to follow.</p>\n<hr />\n<pre><code>def __init__(self, w, h, k):\n</code></pre>\n<p>I could guess the <code>w</code> and <code>h</code>, but how could a caller know that <code>k</code> is the number of mines? Please use descriptive variable names.</p>\n<hr />\n<pre><code>self.setAdjacentMines(int(i / w), i % h)\n</code></pre>\n<p>This goes entirely unexplained in the code. First you create a list of indices, set the mines and then.. <code>setAdjacentMines</code> - why?</p>\n<hr />\n<pre><code>def printLayout(self):\n</code></pre>\n<p>I would expect that a method called <code>printLayout</code> prints... just the layout. However, it seems that it prints the entire board &amp; board state. I think this may be a method that got expanded and never renamed.</p>\n<p>The literal <code>7</code> appears a few times in <code>printLayout</code>. Why not create a constant value such as <code>MARGIN</code> for it? At least I presume it is a margin of sorts.</p>\n<hr />\n<pre><code>def click(self, row, col):\n</code></pre>\n<p>It seems that a click is also opening mines around the clicked location. What I find strange is that it seems those clicks can also explode mines.</p>\n<p><code>click</code> is used as a method name. This becomes a bit troublesome if you also allow &quot;virtual clicks&quot;, as we find out later in the method. <code>probe</code> would maybe be a better name.</p>\n<pre><code>elif self.isBlank(row, col):\n</code></pre>\n<p>Personally I don't like it when <code>click</code> hides other functionality, I'd put that in a calling function. All in all, it doesn't adhere to the principle of least surprise to me.</p>\n<hr />\n<pre><code>def setAdjacentMines(self, row, col):\n</code></pre>\n<p>This method uses higher level functions to detect the state of a position, but then uses <code>+= 1</code> to set the state. I don't exactly get what it is supposed to do at first glance, even after looking at the conventions. I presume it is trying to count bombs.</p>\n<hr />\n<pre><code>#Convention for cell values:\n# - 0 : Hidden Blank\n# - 10 : Revealed Blank\n# - -1 : Hidden Bomb\n# - 9 : Revealed Bomb\n# - 1 ~ 8 : number of adjacent bomb (hidden)\n# - 11 ~ 18 : adjacent bomb (revealed)\n# - x + 100 : Flagged\n#\n</code></pre>\n<p>Beware that comments that are <em>somewhere</em> within the code tend to get lost. This is especially true for environments that allow for reordering or refactoring of methods. Generally I would make those specific to the class; you need this to understand most of the methods in it anyway.</p>\n<hr />\n<pre><code>def isOver(self):\n return self.winGame() or self.loseGame()\n\ndef loseGame(self):\n return self.status == GameStatus.LOSE\n\ndef winGame(self):\n return self.status == GameStatus.WIN\n</code></pre>\n<p>What's wrong with <code>getStatus</code>?</p>\n<hr />\n<pre><code>def loseGame(self):\n return self.status == GameStatus.LOSE\n\ndef winGame(self):\n return self.status == GameStatus.WIN\n</code></pre>\n<p>These methods should <em>definitely</em> be private. But I honestly don't see why they exist at all, in that case.</p>\n<hr />\n<pre><code>while m &gt;= w * h - 1:\n</code></pre>\n<p>Ow, I wonder how you would reveal those mines. Oh well, a bit of unfairness never hurt :)</p>\n<hr />\n<pre><code>while not game.isOver():\n</code></pre>\n<p>That one was expected after seeing <code>isOver</code> being defined. Try <code>while game.getStatus == Playing</code> Always try and use positive tests.</p>\n<hr />\n<pre><code>command = nextCommand()\nsplits = command.split(' ')\nrow = int(splits[0]) - 1\ncol = int(splits[1]) - 1\nif command[-1] == 'F':\n game.flag(row, col)\nelse:\n game.click(row, col)\n</code></pre>\n<p>This should definitely be in a separate method. I'd use regular expressions here, if just to weed out invalid commands. Then you can use groups 1, 2 and 3 to retrieve the values.</p>\n<hr />\n<pre><code>game.revealAll()\n</code></pre>\n<p>I like this, and the fact that you use a separate call to print the board.</p>\n<h2>About the design</h2>\n<p>As indicated in other questions: using a <code>position</code> type would make sense, e.g. by randomly &quot;allocating&quot; mines.</p>\n<p>The idea to have one board with an integer to represent states is a nice idea. However, it is also rather dangerous. For instance, it would allow you to flag already revealed positions, or maybe call <code>setMine</code> after the setup stage. It is therefore quite easy to move the board into an invalid state or to make invalid moves. In general I would prefer a game where the methods make sure you cannot cheat.</p>\n<p>Another method is to have multiple layers, e.g. one with mines (and mine counts, for convenience) and one layer that shows if the position has been revealed or flagged.</p>\n<p>I would certainly perform a clear split between setting up the board and playing the game. Factories, factory methods and/or private methods could play a role here. The split could be virtual (just private methods called when setting up the board, otherwise not separated) or explicit (a separate builder class).</p>\n<p>All that said, after I concluded the review I understood the class design and would be able to alter it. So it definitely passed that test. I'd have to print out the board to understand <code>printLayout</code> fully, but that's OK.</p>\n<h2>Congradulations</h2>\n<p>You're weldone!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T02:07:44.563", "Id": "528401", "Score": "0", "body": "Thank you for taking your time ! I love how you help to suggest some other names for my variables. I always struggle to name things while coding." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T13:06:01.593", "Id": "528428", "Score": "0", "body": "I got an edit request that fixed the misspelling of \"Congradulations\" & \"You're weldone\" which is of course a joke on the misspelling of \"Congratulations\" *in the code of the question*." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T12:48:26.507", "Id": "267919", "ParentId": "267908", "Score": "5" } }, { "body": "<h1>Linter, style checker, static analyzer, code formatter</h1>\n<p>You should use a linter and/or a static analyzer, preferably one with an auto-correct functionality. I actually have multiple linters and multiple static analyzers configured in my editor, and they are set up so that they analyze my code while I type, and automatically correct whatever they can auto-correct when I save.</p>\n<p>When I save your code into a file and open the file in my editor, I get a whopping</p>\n<ul>\n<li>157(!!!) Errors</li>\n<li>44 Warnings</li>\n<li>21 Infos</li>\n</ul>\n<p>Now, to be fair, a lot of these are duplicates, because as I mentioned, I have multiple linters and analyzers set up. Also, I have them set to pretty aggressive settings, which can sometimes be annoying and overwhelming if you work with code that you haven't freshly written yourself. (OTOH, it is tremendously helpful if you have them turned on from the start, since you will be immediately notified and can thus avoid letting the count ever get this high.)</p>\n<p>In particular, I have type checking turned on, and almost 130 of the Errors are from <a href=\"https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance\" rel=\"noreferrer\">Pylance</a> complaining it can't fully determine the static type of some variable, parameter, or function. Now, if you care about static type safety or not, that is a subjective opinion, so you may ignore these Errors.</p>\n<p>The nice thing about style checkers, linters, and static analyzers with auto-correction support, and automatic code formatters is that they do (part of) your work for you. For example, as mentioned, if I simply save your code into a file and open that file in an editor, I get 157 Errors, 44 Warnings, and 21 Infos.</p>\n<p>If, instead, I copy&amp;paste the code into my editor, even during the &quot;paste&quot; operation, it already starts automatically applying fixes, and I only get 139 Errors, 30 Warnings, and 21 Infos. And I get the code formatted according to my preferences (e.g. using <code>&quot;</code> instead of <code>'</code>).</p>\n<h1>Consistency</h1>\n<p>Sometimes, you use two blank lines between methods, sometimes only one.</p>\n<p>You should choose one style and stick with it. If you are editing some existing code, you should adapt your style to be the same as the existing code. If you are part of a team, you should adapt your style to match the rest of the team.</p>\n<p>In general, if you use two different ways to write the exact same thing, the reader will think that you want to convey a message with that. So, you should only use two different ways of writing the same thing IFF you actually want to convey some extra information.</p>\n<p>Note that PEP8 mandates two lines after classes, one line after methods and functions.</p>\n<h1>PEP8 violations</h1>\n<p>The standard community coding style for the Python community is defined in <a href=\"https://python.org/dev/peps/pep-0008/\" rel=\"noreferrer\">Python Enhancement Proposal 8 – <em>Style Guide for Python Code</em></a>. You should <em>always</em> follow the guidelines of PEP8. There are plenty of tools available that can flag and even auto-correct violations of PEP8.</p>\n<p>Here's just a couple that my editor flagged:</p>\n<ul>\n<li><em>No space before colon</em>: In some places, you have space before the colon that starts a new block. There should be no space.</li>\n<li><em>Line length</em>: PEP8 is rather strict about line length. Some of your lines are too long.</li>\n<li>Sometimes, you have 1 blank line after the function. There should be 2 blank lines after a function or class.</li>\n<li><em>Docstring</em>: All your public modules, classes, methods, and functions should have a docstring explaining their usage.</li>\n<li><em><code>snake_case</code> naming</em>: The standard naming convention in Python is <code>PascalCase</code> for classes, <code>snake_case</code> for modules, functions, methods, attributes, variables, and parameters, and <code>SCREAMING_SNAKE_CASE</code> for constants. You are using <code>camelCase</code> for functions, methods, attributes, variables, and parameters. Use <code>snake_case</code> instead. For example, <code>allocateMines</code> should be <code>allocate_mines</code>, and so on.</li>\n</ul>\n<p>Note that, if we ignore the afore-mentioned undefined types, then the naming accounts for a vast majority of the remaining issues my editor reports. So, let's fix those names.</p>\n<h1>Vertical whitespace</h1>\n<p>Your code is all bunched up together. Some empty lines would allow the code room to breathe, for example in the <code>play</code> function. The function is clearly separated into a series of steps: setup, game loop, finish. The same applies to the game loop itself, it also has distinct steps. Some whitespace would help draw attention to those steps:</p>\n<pre class=\"lang-py prettyprint-override\"><code> w = int(input(&quot;Enter width of board: &quot;))\n h = int(input(&quot;Enter height of board: &quot;))\n m = int(input(&quot;Enter number of mines : &quot;))\n while m &gt;= w * h - 1:\n m = int(input(&quot;Too many mines. Enter again : &quot;))\n\n game = MineBoard(w, h, m)\n\n while not game.isOver():\n cls()\n game.printLayout()\n\n command = nextCommand()\n\n splits = command.split(&quot; &quot;)\n row = int(splits[0]) - 1\n col = int(splits[1]) - 1\n\n if command[-1] == &quot;F&quot;:\n game.flag(row, col)\n else:\n game.click(row, col)\n\n game.revealAll()\n cls()\n game.printLayout()\n\n if game.loseGame():\n print(&quot;You lose !!&quot;)\n elif game.winGame():\n print(&quot;You win !!. Congradulations !!&quot;)\n</code></pre>\n<p>Actually, it would make even more sense to extract the various separate steps into separate functions.</p>\n<h1>Chained comparison</h1>\n<p>Python supports chained comparisons, i.e.</p>\n<pre class=\"lang-py prettyprint-override\"><code>a &lt; b and b &lt; c\n</code></pre>\n<p>can be written as</p>\n<pre class=\"lang-py prettyprint-override\"><code>a &lt; b &lt; c\n</code></pre>\n<p>You could use that here:</p>\n<pre class=\"lang-py prettyprint-override\"><code>return row &gt;= 0 and row &lt; self.h and col &gt;= 0 and col &lt; self.w\n</code></pre>\n<p>could be</p>\n<pre class=\"lang-py prettyprint-override\"><code>return 0 &lt;= row &lt; self.h and 0 &lt;= col &lt; self.w\n</code></pre>\n<h1>Unnecessary comprehension</h1>\n<pre class=\"lang-py prettyprint-override\"><code>remains = [i for i in range(n)]\n</code></pre>\n<p>is unnecessary. You can pass any iterable to the <code>list</code> constructor to create a list:</p>\n<pre class=\"lang-py prettyprint-override\"><code>remains = list(range(n))\n</code></pre>\n<h1>Unused <code>import</code></h1>\n<p>You <code>import pdb</code> but never use it. Remove the <code>import</code>.</p>\n<h1>Explicit inheritance from <code>object</code></h1>\n<p>Your <code>MineBoard</code> class explicitly inherits from <code>object</code>. That is unnecessary in Python 3. Python 2 is no longer supported since 1 January 2020 (i.e. over 1.5 years), and Python 3 has been supported since 3 Dec 2008 (i.e. over 12.5 years). There is absolutely no reason to use Python 2 for new code in 2021.</p>\n<p>So, your class declaration should just be</p>\n<pre class=\"lang-py prettyprint-override\"><code>class MineBoard:\n</code></pre>\n<h1>Unused variables</h1>\n<p>In one of your list comprehensions, you have unused variables:</p>\n<pre class=\"lang-py prettyprint-override\"><code>self.board = [[0 for i in range(w)] for j in range(h)]\n</code></pre>\n<p>Neither <code>i</code> nor <code>j</code> are used. They should be called <code>_</code> to make clear that they are deliberately ignored:</p>\n<pre class=\"lang-py prettyprint-override\"><code>self.board = [[0 for _ in range(w)] for _ in range(h)]\n</code></pre>\n<h1>No <code>else</code> / <code>elif</code> after <code>return</code></h1>\n<p>In this piece of code</p>\n<pre class=\"lang-py prettyprint-override\"><code>if ip &gt; 90:\n return &quot;F&quot;\nelif ip == 9:\n return &quot;*&quot;\nelif ip == 10:\n return &quot;.&quot;\nelif ip &gt; 10:\n return str(ip - 10)\nreturn &quot;&quot;\n</code></pre>\n<p>All the <code>elif</code>s can just be <code>if</code>s, since in all of the conditionals in this method, we either exit the method or the conditional was false. In other words: if we reach the <code>if</code> <em>at all</em>, we know that all the <code>if</code>s before it were false, because otherwise we would already have returned from the method.</p>\n<pre class=\"lang-py prettyprint-override\"><code>if ip &gt; 90:\n return &quot;F&quot;\nif ip == 9:\n return &quot;*&quot;\nif ip == 10:\n return &quot;.&quot;\nif ip &gt; 10:\n return str(ip - 10)\nreturn &quot;&quot;\n</code></pre>\n<h1>Naming</h1>\n<p>There are a couple of names in your code that could be clearer, for example <code>ip</code>, <code>m</code>, and <code>k</code>. In particular, it seems that the parameter <code>k</code> in <code>__init__</code>, the parameter <code>num_of_mines</code> in <code>allocate_mines</code>, and the local variable <code>m</code> in <code>play</code> mean the same thing, but the parameter <code>k</code> in <code>get_random_pos</code> does not mean the same thing as the parameter <code>k</code> in <code>__init__</code>.</p>\n<p>They should really have more intention-revealing names. A <em>good name</em> should be <em>intention-revealing</em>. They should convey <em>meaning</em>.</p>\n<p>I also noticed something strange about the <code>MineBoard</code>. It appears that <code>MineBoard</code> is not actually a board of mines. It is also a game of minesweeper. In fact, when you instantiate it, you actually assign it to a variable named <code>game</code>!</p>\n<p>So, this implies two things: one, the class should probably have a different name (e.g. <code>Game</code>). But more importantly, the reason why it is hard to give it a proper name is that it appears to be doing too much. In particular, it represents two totally different concepts: a map / board, and a game. It should probably be split into two classes.</p>\n<h1>Mixing I/O and computation</h1>\n<p>I am not a big fan of mixing I/O and computation.</p>\n<p>An example of what I mean is the <code>print_layout</code> method. It mixes responsibilities of <em>creating</em> the string representation and <em>printing</em> it. This makes it hard to reuse and hard to test. You can't just call it and check its result value in a test, for example, you actually have to capture the output from the terminal.</p>\n<p>Instead, this method should be split into two methods. One which just creates the string representation of the board, and a second one which prints it. The first one should probably just be <code>MineBoard</code>'s <code>__str__</code> method, and the second one should probably be part of the game logic rather than the board logic.</p>\n<p>Something like this:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def __str__(self) -&gt; str:\n return &quot;\\n&quot;.join(\n [\n &quot; &quot; * 7 + &quot;&quot;.join(map(lambda x: &quot;{:^7d}&quot;.format(x + 1), range(self.w))),\n &quot; &quot; * 7 + &quot;-&quot; * (self.w * 7),\n &quot;\\n&quot;.join(\n (\n &quot;{:^7d}&quot;.format(i + 1)\n + &quot;|&quot;\n + &quot; |&quot;.join(\n list(map(lambda x: &quot;{:^5s}&quot;.format(self.display(x)), row))\n )\n + &quot; | &quot;\n )\n + &quot;\\n&quot;\n + (&quot; &quot; * 7 + &quot;-&quot; * (self.w * 7))\n for (i, row) in enumerate(self.board)\n ),\n ]\n )\n</code></pre>\n<p>And then in <code>play</code>, the two calls to <code>game.print_layout()</code> can simply be replaced by <code>print(game)</code>.</p>\n<h1>Comments</h1>\n<p>Generally speaking, comments are a <a href=\"https://martinfowler.com/bliki/CodeSmell.html\" rel=\"noreferrer\"><em>code smell</em></a>. Mostly, comments should not exist:</p>\n<ul>\n<li>If your code is so complex that you need to explain it in a comment, you should rather try to refactor your code to be less complex so that it needs no explanation.</li>\n<li>If you have a comment that explains <em>what</em> something is, you can rather give it a name that tells the reader what the thing is.</li>\n<li>If you have a comment that explains <em>how</em> the code does something, just delete it: the code explains how the code does something.</li>\n</ul>\n<p>The only acceptable thing for a comment is to explain <em>why</em> the code does something in a specific non-obvious way. So, for example, there is an obvious way that looks like it <em>should</em> work, but you tried it and it didn't work for a non-obvious reason. Then you can add a comment explaining that you are specifically using solution B even though it looks like much simpler solution A should also work, but it actually doesn't work because of issue X. Ideally, you would add a link to the pull request / code review / bug ticket where this issue is discussed in greater detail and maybe a link to a wiki page with a detailed explanation.</p>\n<p>The major offender is this comment here:</p>\n<pre class=\"lang-py prettyprint-override\"><code># Convention for cell values:\n# - 0 : Hidden Blank\n# - 10 : Revealed Blank\n# - -1 : Hidden Bomb\n# - 9 : Revealed Bomb\n# - 1 ~ 8 : number of adjacent bomb (hidden)\n# - 11 ~ 18 : adjacent bomb (revealed)\n# - x + 100 : Flagged\n#\n</code></pre>\n<p>This comment is problematic for many reasons.</p>\n<p>For one, it is placed in an awkward sport, in the middle of the class. It should probably be part of the class documentation proper, i.e. of the docstring.</p>\n<p>However, it really should not exist at all. Such important information, and such an encoding should be <em>encapsulated</em> in an object. It looks like you are missing an <em>abstraction</em>, probably something like a <code>Cell</code> (which could be a <code>namedtuple</code> or a <code>dataclass</code>).</p>\n<p>This abstraction would also allow us to move some of the methods out of <code>MineBoard</code>. For example, <code>display</code> should be an instance method of <code>Cell</code>. In fact, it should probably be <code>Cell</code>'s <code>__str__</code> method instead.</p>\n<p>A big clue is the fact that you have multiple comments talking about &quot;cells&quot; but you have no abstraction called &quot;cell&quot; in your code. That is often a dead giveaway that you are missing an abstraction.</p>\n<h1><code>if __name__ == &quot;__main__&quot;:</code></h1>\n<p>It is generally recommended to guard your main entry point using the familiar <code>if __name__ == &quot;__main__&quot;:</code> construct. This way, the main entry point will only be automatically executed if the module is run as a script, but not if it is <code>import</code>ed:</p>\n<pre class=\"lang-py prettyprint-override\"><code>if __name__ == &quot;__main__&quot;:\n play()\n</code></pre>\n<h1>Shebang line</h1>\n<p>Since you intend to run this as a script, it should have a shebang line, something like this:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>#!/usr/bin/env python3\n</code></pre>\n<h1>(Interim) result</h1>\n<pre class=\"lang-py prettyprint-override\"><code>#!/usr/bin/env python3\n\nimport random\nfrom enum import auto, Enum\nfrom subprocess import run\nfrom textwrap import dedent\nfrom typing import Iterable, Optional\n\n\nclass GameStatus(Enum):\n PLAYING = auto()\n LOSE = auto()\n WIN = auto()\n\n\nclass MineBoard:\n status: GameStatus = GameStatus.PLAYING\n w: int\n h: int\n board: list[list[int]]\n cells_to_open: int\n\n def __init__(self, w: int, h: int, k: int) -&gt; None:\n # Create a new board with size w x h\n self.w = w\n self.h = h\n self.board = [[0 for _ in range(w)] for _ in range(h)]\n self.allocate_mines(w, h, k)\n self.cells_to_open = w * h - k\n\n def allocate_mines(self, w: int, h: int, num_of_mines: int) -&gt; None:\n alloc_indexes = self.get_random_pos(w * h, num_of_mines)\n for i in alloc_indexes:\n self.set_mine(int(i / w), i % h)\n self.set_adjacent_mines(int(i / w), i % h)\n\n def __str__(self) -&gt; str:\n return &quot;\\n&quot;.join(\n [\n &quot; &quot; * 7 + &quot;&quot;.join(map(lambda x: &quot;{:^7d}&quot;.format(x + 1), range(self.w))),\n &quot; &quot; * 7 + &quot;-&quot; * (self.w * 7),\n &quot;\\n&quot;.join(\n (\n &quot;{:^7d}&quot;.format(i + 1)\n + &quot;|&quot;\n + &quot; |&quot;.join(\n list(map(lambda x: &quot;{:^5s}&quot;.format(self.display(x)), row))\n )\n + &quot; | &quot;\n )\n + &quot;\\n&quot;\n + (&quot; &quot; * 7 + &quot;-&quot; * (self.w * 7))\n for (i, row) in enumerate(self.board)\n ),\n ]\n )\n\n def click(self, row: int, col: int) -&gt; None:\n value = self.reveal(row, col)\n if value:\n self.cells_to_open -= 1\n if self.cells_to_open == 0:\n self.status = GameStatus.WIN\n if self.has_mine(row, col):\n self.status = GameStatus.LOSE\n elif self.is_blank(row, col):\n for dr in range(row - 1, row + 2):\n for dc in range(col - 1, col + 2):\n self.click(dr, dc)\n\n def flag(self, row: int, col: int) -&gt; None:\n if self.is_valid_cell(row, col) and self.is_hidden(row, col):\n self.toggle_flag(row, col)\n\n def is_valid_cell(self, row: int, col: int) -&gt; bool:\n return 0 &lt;= row &lt; self.h and 0 &lt;= col &lt; self.w\n\n def get_random_pos(self, n: int, k: int) -&gt; Iterable[int]:\n res: list[int] = []\n remains = list(range(n))\n while k &gt; 0:\n r = random.randint(0, len(remains) - 1)\n res.append(r)\n del remains[r]\n k -= 1\n return res\n\n # Convention for cell values:\n # - 0 : Hidden Blank\n # - 10 : Revealed Blank\n # - -1 : Hidden Bomb\n # - 9 : Revealed Bomb\n # - 1 ~ 8 : number of adjacent bomb (hidden)\n # - 11 ~ 18 : adjacent bomb (revealed)\n # - x + 100 : Flagged\n\n def set_mine(self, row: int, col: int) -&gt; None:\n self.board[row][col] = -1\n\n def set_adjacent_mines(self, row: int, col: int) -&gt; None:\n for dr in range(row - 1, row + 2):\n for dc in range(col - 1, col + 2):\n if self.is_valid_cell(dr, dc) and not self.has_mine(dr, dc):\n self.board[dr][dc] += 1\n\n def toggle_flag(self, row: int, col: int) -&gt; None:\n if self.is_flagged(row, col):\n self.board[row][col] -= 100\n else:\n self.board[row][col] += 100\n\n # Open a cell and return its value\n def reveal(self, row: int, col: int) -&gt; Optional[int]:\n if not self.is_valid_cell(row, col) or not self.is_hidden(row, col):\n return None\n if self.is_flagged(row, col):\n self.toggle_flag(row, col)\n self.board[row][col] += 10\n return self.board[row][col]\n\n def is_hidden(self, row: int, col: int) -&gt; bool:\n return self.board[row][col] &lt; 9\n\n def has_mine(self, row: int, col: int) -&gt; bool:\n return self.board[row][col] % 10 == 9\n\n def is_blank(self, row: int, col: int) -&gt; bool:\n return self.board[row][col] % 10 == 0\n\n def is_over(self) -&gt; bool:\n return self.win_game() or self.lose_game()\n\n def lose_game(self) -&gt; bool:\n return self.status == GameStatus.LOSE\n\n def win_game(self) -&gt; bool:\n return self.status == GameStatus.WIN\n\n def is_flagged(self, row: int, col: int) -&gt; bool:\n return self.board[row][col] &gt; 90\n\n def reveal_all(self) -&gt; None:\n for i in range(len(self.board)):\n for j in range(len(self.board[0])):\n self.reveal(i, j)\n\n def display(self, ip: int) -&gt; str:\n if ip &gt; 90:\n return &quot;F&quot;\n if ip == 9:\n return &quot;*&quot;\n if ip == 10:\n return &quot;.&quot;\n if ip &gt; 10:\n return str(ip - 10)\n return &quot;&quot;\n\n\ndef cls() -&gt; None:\n run([&quot;/usr/bin/env&quot;, &quot;clear&quot;], check=True)\n\n\ndef play() -&gt; None:\n w = int(input(&quot;Enter width of board: &quot;))\n h = int(input(&quot;Enter height of board: &quot;))\n m = int(input(&quot;Enter number of mines : &quot;))\n while m &gt;= w * h - 1:\n m = int(input(&quot;Too many mines. Enter again : &quot;))\n\n game = MineBoard(w, h, m)\n\n while not game.is_over():\n cls()\n print(game)\n\n command = next_command()\n\n splits = command.split(&quot; &quot;)\n row = int(splits[0]) - 1\n col = int(splits[1]) - 1\n\n if command[-1] == &quot;F&quot;:\n game.flag(row, col)\n else:\n game.click(row, col)\n\n game.reveal_all()\n cls()\n print(game)\n\n if game.lose_game():\n print(&quot;You lose !!&quot;)\n elif game.win_game():\n print(&quot;You win !!. Congradulations !!&quot;)\n\n\ndef next_command() -&gt; str:\n instruction = dedent(\n &quot;&quot;&quot;\\\n Commands :\n &lt;row&gt; &lt;col&gt; : open cell\n &lt;row&gt; &lt;col&gt; F : flag cell\n q : quit\n &quot;&quot;&quot;\n )\n return input(instruction).strip()\n\n\nif __name__ == &quot;__main__&quot;:\n play()\n</code></pre>\n<p>Note: In order to make this answer useful for future readers, I have mostly assumed Python 3.10, which is about to be released soon. However, I don't think I have used anything that is not available in Python 3.9, and the code can be trivially made to work with at least Python 3.8.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:07:34.010", "Id": "528275", "Score": "0", "body": "Funny that we came to the dual layer / dual classes approach seperately. There must be something in that :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T10:37:12.893", "Id": "528337", "Score": "0", "body": "A minor comment: if you've ever worked with multilingual applications, `_` is conventionally used with [gettext](https://docs.python.org/3/library/gettext.html) (`_ = gettext.gettext`). By default, Pylint will ignore an unused variable called \"dummy\" or beginning with \"unused_\" (can be controlled with the \"dummy-variables-rgx\" setting)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T10:10:00.827", "Id": "528419", "Score": "0", "body": "I've always find it incredulous that comments are discouraged in a blanket fashion. You could certainly make a case that OP's code doesn't need comments, but that's not true in general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T11:25:07.890", "Id": "528422", "Score": "1", "body": "It's also possible to implement `is_valid_cell` as `return row in range(self.h) and col in range(self.w)`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-10-01T11:26:13.360", "Id": "529660", "Score": "0", "body": "That's great post but the task was for 1 hour. I don't know who can finish it that fast with the fixes." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T13:02:34.153", "Id": "267920", "ParentId": "267908", "Score": "21" } }, { "body": "<p>(I've taken the liberty of converting all identifiers to PEP8 style.)</p>\n<h1>Board state</h1>\n<p>The state of a cell on a board is encoded with a single integer, which combines the following information:</p>\n<ul>\n<li>Is this cell revealed?</li>\n<li>Does this cell have a mine?</li>\n<li>Does this cell have a flag?</li>\n<li>How many neighbours of this cell are mines?</li>\n</ul>\n<p>This results in complicated code to check those properties, numerous magic numbers, and a lot of crevices where bugs can creep in. On the upside, it's fairly space efficient, but unless you're planning on allowing giant boards, that shouldn't make much of a difference. Here's my proposal:</p>\n<pre><code>@dataclass\nclass Cell:\n revealed: bool = False\n has_mine: bool = False\n has_flag: bool = False\n neighbouring_mines: int = 0\n\n def is_blank(self) -&gt; bool:\n return not self.has_mine and self.neighbouring_mines == 0\n</code></pre>\n<p>(I like using dataclasses for things like this, but of course there are plenty of other options, like attrs or a plain Python class!)</p>\n<p>This allows you to make various <code>MineBoard</code> methods less complex, for example:</p>\n<pre><code>def toggle_flag(self, row, col):\n self.board[row][col].has_flag = not self.board[row][col].has_flag\n</code></pre>\n<h1><code>allocate_mines</code></h1>\n<p>In all other places, you use row and column indexing, but in this method you're using an index. For consistency, I'd use a list of tuples for the mine locations. Additionally, you don't need to generate this list yourself, you can use <a href=\"https://docs.python.org/3/library/random.html#random.sample\" rel=\"nofollow noreferrer\"><code>random.sample</code></a>:</p>\n<pre><code>def allocate_mines(self, width, height, number_of_mines):\n all_indices = [(row, col) for row in range(height) for col in range(width)]\n mines = random.sample(all_indices, number_of_mines)\n for row, col in mines:\n self.set_mine(row, col)\n self.set_adjacent_mines(row, col)\n</code></pre>\n<h1><code>is_valid_cell</code></h1>\n<p>You're using this method in several places inside loops. Instead of looping unnecessarily over out-of-bound cells, try instead adjusting the range boundaries:</p>\n<pre><code>def set_adjacent_mines(self, row, col):\n for dr in range(max(0, row - 1), min(self.height, row + 2)):\n for dc in range(max(0, col - 1), min(self.width, col + 2)):\n self.board[dr][dc].neighbouring_mines += 1\n</code></pre>\n<h1>Item access</h1>\n<p>This is just a spur-of-the-moment idea, but you could implement <code>__getitem__</code> for the <code>MineBoard</code> class. It could access <code>Cell</code> objects and -- when passed <code>slice</code>s --- could even return an iterable over the <code>Cell</code>s. For example:</p>\n<pre><code>def toggle_flag(self, row, col):\n self[row, col].has_flag = not self[row, col].has_flag\n\ndef set_adjacent_mines(self, row, col):\n for cell in self[row - 1:row + 2, col - 1:col + 2]:\n cell.neighbouring_mines += 1\n</code></pre>\n<p>... Suitable implementation of <code>__getitem__</code> left as an exercise for the reader.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T02:11:38.293", "Id": "528402", "Score": "0", "body": "I know that represent everything in just one single number makes things much more complex here. It must be the result of doing many leetcode exercises recently and I just tend to save memory anytime possible. Love the idea of 'Item access'. Thanks !!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:34:38.327", "Id": "267926", "ParentId": "267908", "Score": "3" } }, { "body": "<p>Thanks Felicity for your post. You wrote that you're going for coding interviews, so I'll focus on various aspects that will be looked at by interviewers rather than pieces of code which other respondents already have. This might be a little extensive, but it's good to make you aware of what could be covered when submitting code during the interview process.</p>\n<ul>\n<li><p>Python-specific</p>\n<ul>\n<li>Not using PEP8 naming conventions</li>\n<li>Not using the <code>__main__</code> entry point</li>\n<li>Not using f-string formatting</li>\n<li>pdb is not used, be aware of unused imports in the final version</li>\n</ul>\n</li>\n<li><p>Input validation</p>\n<ul>\n<li>No checking of inputs</li>\n<li>No catching/handling of exceptions raised e.g.:<code>IndexError list assignment index out of range</code></li>\n</ul>\n</li>\n<li><p>Coding Style</p>\n<ul>\n<li>Using <code>.strip()</code> on a string which is hard-coded</li>\n<li>Comments in the code explaining what the code does when the code expresses this already</li>\n<li>Classes exposing private attributes as public</li>\n<li>Variable naming</li>\n<li>Mixing game logic with board logic (and instantiating the board as <code>game</code> changing it's role)</li>\n<li>Enum for GameStatus but then not using the same logic with tile values?</li>\n<li>Returning values from functions that aren't used - but as a way to exit the function</li>\n<li>Duplicated code</li>\n<li>Violating &quot;tell-don't-ask&quot; with lots of <code>if</code> statements when (see the next point...)</li>\n<li>Not using a proper data structure to represent the tiles and their behaviour</li>\n<li>Spelling/Grammar mistakes in the information presented to the user</li>\n</ul>\n</li>\n<li><p>Game Itself</p>\n<ul>\n<li>Game not acting properly when flagging a single mine (3x3, 1 mine) - finishing automatically</li>\n<li>Game not acting properly when flagging a single mine (5x5, 1 mine) due to lower-case f</li>\n</ul>\n</li>\n</ul>\n<h1>Python Specific</h1>\n<p>These items are something you should be aware of when writing Python code.<br>\n<em>PEP8</em>: PEP8 talks about using snake_case for variable/function naming (whilst class naming is CamelCase) and a few other things. Be aware of the major standard for each language, and follow the style rules in each organisation.<br><br>\n<em>Entry point</em>: As we're writing a script for execution, and not as a library, the entry point <code>if __name__ == &quot;__main__&quot;:</code> should be used. For example, if you pushed your script into the repository, and a code documentor such as Sphinx ran over it, it would freeze because it would start playing the game. This is because the code begins running as soon as Python loads it, when the intent of the documentor was just to analyse the code.<br><br>\n<em>F-strings</em>: Python 3.6 and later have this capability; f-strings can make reading print statements much easier. It's recommended to use them when writing any string statement that contains variables.<br><br>\n<em>Imports</em>: Unused imports hint that perhaps you're not fully aware of all the actions of your scripts? If the IDE doesn't highlight these, possibly change your IDE.</p>\n<h1>Input Validation</h1>\n<p>Input validation is a very important topic in programming, due to all sorts of bugs and attacks like Cross-Site-Scripting (XSS) and SQL Injection. When needing user input, ensure it's specific, that it's limited, and that you give responses to assist the user to provide the correct input, or allow them to exit the stage where they are.<br>This will enable avoiding runtime errors which crash the program (such as <code>IndexError list assignment index out of range</code> which I encountered) and avoid having try/except/finally statements due to limiting possible inputs.</p>\n<h1>Coding Style</h1>\n<p><code>.strip()</code>: Normally <code>.strip()</code> is chained at the end of a string where the data can have extraneous spacing, but this one is your own string. A book called &quot;Code Complete&quot; can be useful in learning different patterns of common mistakes made by programmers, I recommend grabbing a copy.<br><br>\n<em>Code Comments</em>: Comments, if used at all, should be a &quot;why you're doing it this way&quot; and not a &quot;how you're doing this&quot;. The code already explains the &quot;how&quot;. The danger is when the code changes (due to bugs or requirement changes) from what the comment says, another coder who sees the code, and sees the comment, says &quot;The code doesn't do that, I'll be helpful and make it do that&quot; (I've seen this happen). <br><br>\n<em>Classes exposing private attributes as public</em>: Proper OOP ensures that the internals of how classes achieve their magic are hidden. Most other languages enforce this by statements such as <code>private</code> and <code>public</code> before their type and variable name. For classes, be aware of what variables which are internal/private, and place an underscore <code>_</code> before them. This is important because when you put out code for others to use, if they begin accessing/modifying internal class variables and you release a new version with modified internals, it will break their implementation.<br><br>\n<em>Variable Naming</em>: line 21 states <code>self.cellsToOpen = w * h - k</code>, but the comment says <code># Create a new board with size w x h</code>, and the caller is <code>MineBoard(w, h, m)</code>. So we have <code>w</code> <code>h</code> <code>k</code> <code>x</code> <code>m</code> variables here. Do you see how this might be confusing to someone that is reading your code? Always use words that explain to readers what the code does through proper variable names. Obviously I've read through your code several times and I understand what your code does - but I shouldn't have to read it more than once to fully comprehend the statements. Something like: <code>MineBoard(width, height, num_mines)</code> and <code>self.cellsToOpen = width * height - num_mines</code> is much easier to understand.<br><br>\n<em>Duplicated code</em>: I see multiple calls to <code>self.isValidCell</code> and other functions <em>inside the class</em>. Python famously has a concept of DRY (Don't Repeat Yourself), which means that when you're starting to see multiple calls to a function, or repeating the same lines, that there is an opportunity for refactoring. Refactoring covers not only lines of code into a function, but of data objects into different structures.<br><br>\n<em>Tell - Don't Ask</em>: When your code has a lot of <em>if-this, then-that</em> statements in it, it's clear the logic belongs with the data rather than continually asking the data &quot;are you this?&quot; &quot;oh you're not?&quot; &quot;what about, are you this instead?&quot; &quot;you are? okay, I'll do this action then&quot;. <br><br>\nA good example is a set of code checking every minute &quot;is it now 7am?&quot; (probably with a loop that blocks the rest of the code from running). Rather than doing that, the <code>set_alarm(self, hour, minute)</code> function would spawn a thread which waits for hour/minute and then activates a call-back to the <code>activate_alarm(self)</code> function. You <em>tell</em> the function when to do something, not <em>ask</em> it if it's ready to do it/if it has it.<br><br>\n<em>Tiles data structure</em>: Each tile on the board has multiple states (hidden/revealed/flagged) and data (empty/has mine) which is complicated behaviour. Coupled with tell-don't-ask, users perform actions to each tile that can alter the game state and surrounding tile states. It's clear that an enum for state and data is needed per tile, as well as the tile having the capability of call-backs into the board say when a mine was triggered. This point might be a little complicated, but patterns like Observer can simplify this process. Also, mentioning that you know one or two patterns during your interview (you should know them well enough to write them on a whiteboard) can make you stand out from the crowd.</p>\n<h1>Game Itself</h1>\n<p><em>Single mine flagging</em>: In typical minesweeper, even when there is one mine remaining (flagged or unflagged), tiles that are unclicked still require clicking. The game rushes to a finish when flagging the correct tile, it doesn't leave the user in suspense whether they have chosen correctly or not.<br><br>\n<em>Single mine flagging due to lower-case f</em>: I was surprised when I flagged a tile and the game ended with a mine going off. It took me a few seconds to understand that it required an upper-case F to correctly flag a tile. On subsequent games, I failed again because of this input-handling problem. Upper or lower case, it shouldn't matter.</p>\n<p><em><strong>The End</strong></em></p>\n<p>I hope the other answers as well as mine are enough to give you lots to study before your next interview. I wish you the best of luck with the interviewing process and hope you get the job. Cheers!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T02:16:22.507", "Id": "528403", "Score": "0", "body": "Thanks for taking your time to write such an detail answer. I learnt tons of things in just one single post. That was amazing !. Just a minor thing, the \"strip\" function I used is on the input from the user, not the 'instruction' itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T07:07:22.893", "Id": "528410", "Score": "1", "body": "Yes, you are correct. Looking at the line after having a coffee :) it's a good idea to separate the messge to the user (use print(msg)), and what input you're receiving (`input(\"row?\")`;`input(\"column?\")`). Makes it easier to obtain the choices. Good effort." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T17:18:11.993", "Id": "267929", "ParentId": "267908", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T04:23:14.330", "Id": "267908", "Score": "14", "Tags": [ "python", "minesweeper" ], "Title": "A simple Minesweeper in Python" }
267908
<p>I have an array wrapper class that I'd like to get reviewed.</p> <p>There are two differences with other common questions on this site. First, my class needs to be &quot;nullable&quot;, where a &quot;null array&quot; has a different meaning than an array of length zero.</p> <p>Second, I'm trying to test whether small size optimization (like gcc's std::string implementation) can improve performance of my application.</p> <p>Below is my implementation. I also have another nullable array wrapper class without SSO, but it is pretty similar.</p> <p>I want to know if my implementation is &quot;correct&quot; assuming up to C++14, but not C++17.</p> <p>And is using <code>std::numeric_limits::max</code> size value a reasonable approach as a flag for &quot;null array&quot;? I considered using <code>nullptr</code> as the null flag, but <code>allocate(0)</code> may also return nullptr (e.g. on MSVC).</p> <pre><code>#ifndef SMALL_NULLABLE_ARRAY_H #define SMALL_NULLABLE_ARRAY_H #include &lt;algorithm&gt; #include &lt;type_traits&gt; #include &lt;cstdlib&gt; #include &lt;cstring&gt; #include &lt;limits&gt; namespace sml { template&lt;class T, class Allocator = std::allocator&lt;T&gt;, class S = uint32_t, S stack_size = 20&gt; class SmallNullableArray { static_assert(std::is_pod&lt;T&gt;::value, &quot;SmallNullableArray type should be POD&quot;); public: typedef T value_type; typedef T* pointer_type; typedef T&amp; reference_type; typedef S size_type; static constexpr size_type nullsize = std::numeric_limits&lt;size_type&gt;::max(); private: struct Members : Allocator { // derive from Allocator to use empty base optimization pointer_type _data; size_type _size; value_type _stack[stack_size]; constexpr pointer_type stack_address() { return &amp;(this-&gt;_stack[0]); } inline pointer_type allocate_check_and_copy(value_type const * const data, const size_type size) { if(size == nullsize) { return this-&gt;stack_address(); } else if(size &lt;= stack_size) { pointer_type result = this-&gt;stack_address(); std::copy(data, data + size, result); return result; } else { pointer_type result = this-&gt;allocate(size); std::copy(data, data + size, result); return result; } } inline pointer_type allocate_check(const size_type size) noexcept { if((size == nullsize) || (size &lt;= stack_size)) { return this-&gt;stack_address(); } else { return this-&gt;allocate(size); } } inline void deallocate_check() { if((this-&gt;_size &gt; stack_size) &amp;&amp; (this-&gt;_size != nullsize)) { this-&gt;deallocate(this-&gt;_data, this-&gt;_size); } } Members(value_type const * const data, const size_type size) : _data(this-&gt;allocate_check_and_copy(data, size)), _size(size) {} Members(const size_type size) : _data(this-&gt;allocate_check(size)), _size(size) {} Members() : _data(stack_address()), _size(0) {} } m; friend void swap(SmallNullableArray &amp; first, SmallNullableArray &amp; second) noexcept { using std::swap; std::swap(first.m._data, second.m._data); std::swap(first.m._size, second.m._size); std::swap(first.m._stack, second.m._stack); if(first.m._size &lt;= stack_size) { first.m._data = first.m.stack_address(); } if(second.m._size &lt;= stack_size) { second.m._data = second.m.stack_address(); } } public: SmallNullableArray() : m() {} SmallNullableArray(value_type const * const data, const size_t size) : m(data, size) {} SmallNullableArray(const size_t size) : m(size) {} // Copy SmallNullableArray(SmallNullableArray const &amp; other) : m(other.m._data, other.m._size) {} // Move SmallNullableArray(SmallNullableArray &amp;&amp; other) noexcept : m() { swap(*this, other); } // &quot;copy and swap&quot; covers both move and copy assignment https://stackoverflow.com/q/3279543/2723734 SmallNullableArray &amp; operator=(SmallNullableArray other) { swap(*this, other); return *this; } // destructor ~SmallNullableArray() { m.deallocate_check(); } inline bool is_stack() const { return (m._size &lt;= stack_size) || (m._size == nullsize); } inline bool is_null() const { return m._size == nullsize; } void nullify() { m.deallocate_check(); m._data = m.stack_address(); m._size = nullsize; } // reset and resize are the same, but reset doesn't copy over old data // we don't have m._capacity so there is always a re-allocation void reset(const size_type size) { m.deallocate_check(); m._data = m.allocate_check(size); m._size = size; } void resize(const size_type size) { if(is_null()) { m._data = m.allocate_check(size); m._size = size; } else if(is_stack()) { pointer_type new_addr = m.allocate_check(size); std::memmove(new_addr, m._data, std::min(size, m._size) * sizeof(value_type)); // need memmove if new size is also stack allocated m._data = new_addr; m._size = size; } else { pointer_type new_addr = m.allocate_check(size); std::copy(m._data, m._data + std::min(size, m._size), new_addr); m.deallocate_check(); m._data = new_addr; m._size = size; } } size_type size() const { return m._size; } pointer_type data() const { return m._data; } reference_type operator[](size_type idx) const { return *(m._data + idx); } pointer_type begin() { return m._data; } pointer_type end() { return m._data + m._size; } }; } // end namespace #endif // include guard </code></pre>
[]
[ { "body": "<h1>Missing <code>#include &lt;memory&gt;</code></h1>\n<p>Since you use <a href=\"https://en.cppreference.com/w/cpp/memory/allocator\" rel=\"nofollow noreferrer\"><code>std::allocator</code></a>, you have to <code>#include &lt;memory&gt;</code>, otherwise your code might fail to compile.</p>\n<h1>Avoid unnecessary use of <code>this-&gt;</code></h1>\n<p>Your code is full of <code>this-&gt;</code>, but in C++ you almost never have to use that, unless you have local variables in a member function that shadow member variables.</p>\n<h1>Add empty lines to your code to visually separate functions</h1>\n<p>It would help the readability of your code if you added newlines around functions and in other places where it will make the structure of your code more clear.</p>\n<p>Also avoid multiple statements on one line. Just write out small functions like so:</p>\n<pre><code>bool is_null() const {\n return m._size == nullsize;\n}\n</code></pre>\n<h1>Unnecessary use of <code>inline</code></h1>\n<p>There is no need to make the member functions of explicitly <code>inline</code>. The compiler should inline them automatically where appropriate.</p>\n<h1>Use <code>std::size_t</code> for <code>size_type</code></h1>\n<p>I would strongly recommend just using <a href=\"https://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::size_t</code></a> to store sizes. It will do the right thing. You might not think someone will want to make an array of more than <span class=\"math-container\">\\$2^{32}\\$</span> elements, but that's probably a wrong assumption.</p>\n<h1>Unnecessary use of <code>stack_address()</code></h1>\n<p>You can just write <code>return _stack;</code>. Alternatively, use <code>std::array</code> for the stack:</p>\n<pre><code>std::array&lt;value_type, stack_size&gt; stack;\n</code></pre>\n<p>And then you can use <code>stack.data()</code> to get a pointer to the stack.</p>\n<h1>How to represent a &quot;null&quot; array</h1>\n<p>Using <code>std::numeric_limits::max</code> is one way, although then you'd have to think about what happens if someone wants to create an array with exactly <code>std::numeric_limits::max</code> elements. But another way would be to use zero is the length, and then use something that is unused when the length is zero to store whether it is an empty array or a &quot;null&quot; array. For example, the first element of <code>stack</code> could be used as a flag in this case.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T18:45:58.100", "Id": "528295", "Score": "1", "body": "Thank you! Btw, I believe `std::allocator<void>` is being deprecated not std::allocator in general." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T19:37:11.533", "Id": "528300", "Score": "0", "body": "Ah, I missed that. Indeed, then it's fine :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T11:15:51.993", "Id": "267913", "ParentId": "267910", "Score": "4" } } ]
{ "AcceptedAnswerId": "267913", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T08:41:35.487", "Id": "267910", "Score": "4", "Tags": [ "c++", "array", "c++14" ], "Title": "Nullable array wrapper class with small size optimization" }
267910
<p>In this post, I will present and compare two distinct algorithms for sieve of Eratosthenes:</p> <p><strong><code>com.github.coderodde.math.prime.PrimeFinder</code></strong></p> <pre><code>package com.github.coderodde.math.prime; import java.util.ArrayList; import java.util.BitSet; import java.util.List; /** * This abstract defines the API for finding prime numbers. * * @author Rodin &quot;rodde&quot; Efremov * @version 1.6 (Sep 12, 2021) * @since 1.6 (Sep 12, 2021) */ public abstract class PrimeFinder { /** * Finds all the primes no larger than {@code limit} and returns them in a * sorted list. * * @param limit the maximum allowed prime. * @return a list of primes. */ public abstract BitSet findPrimesUpTo(int limit); /** * Converts all the primes in {@code bitSet} to the list. * * @param bitSet the target bit set describing the primes. * @param numberOfBits the number of actual numbers in {@code bitSet}. * @return the prime list. */ public static List&lt;Integer&gt; primeBitSetToList( BitSet bitSet, int numberOfBits) { List&lt;Integer&gt; list = new ArrayList&lt;&gt;(bitSet.size()); for (int i = 0; i &lt; bitSet.size(); i++) { if (bitSet.get(i)) { list.add(i); } } return list; } protected void checkLimit(int limit) { if (limit &lt; 0) { throw new IllegalArgumentException(&quot;Negative limit: &quot; + limit); } } } </code></pre> <p><strong><code>com.github.coderodde.math.prime.impl.LinearithmicPrimeFinder</code></strong></p> <pre><code>package com.github.coderodde.math.prime.impl; import com.github.coderodde.math.prime.PrimeFinder; import java.util.BitSet; /** * This class implements the basic sieve of Eratosthenes running in * {@code O(n log n)} time. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 12, 2021) * @since 1.6 (Sep 12, 2021) */ public final class LinearithmicPrimeFinder extends PrimeFinder { /** * {@inheritDoc } */ @Override public BitSet findPrimesUpTo(int limit) { checkLimit(limit); if (limit &lt; 2) { return new BitSet(limit); } if (limit == 2) { BitSet bitSet = new BitSet(3); bitSet.set(2); return bitSet; } BitSet bitSet = new BitSet(limit + 1); bitSet.set(0, bitSet.size(), true); bitSet.clear(0); bitSet.clear(1); // Deal with powers of two: for (int i = 4; i &lt;= limit; i += 2) { bitSet.set(i, false); } // Deal with powers of odd primes: for (int primeCandidate = 3; primeCandidate &lt;= limit; primeCandidate += 2) { if (bitSet.get(primeCandidate)) { for (int i = 2 * primeCandidate; i &lt;= limit; i += primeCandidate) { bitSet.set(i, false); } } } return bitSet; } } </code></pre> <p><strong><code>com.github.coderodde.math.prime.impl.FasterPrimeFinder</code></strong></p> <pre><code>package com.github.coderodde.math.prime.impl; import com.github.coderodde.math.prime.PrimeFinder; import java.util.BitSet; /** * This class implements a sieve of Eratosthenes prime finder described in * &lt;a href=&quot;https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Pseudocode&quot;&gt; * Wikipedia&lt;/a&gt;. Runs in {@code O(n log log n)} time. * * @author Rodion &quot;rodde&quot; Efremov * @version 1.6 (Sep 12, 2021) * @since 1.6 (Sep 12, 2021) */ public final class FasterPrimeFinder extends PrimeFinder { @Override public BitSet findPrimesUpTo(int limit) { checkLimit(limit); if (limit &lt; 2) { return new BitSet(limit); } if (limit == 2) { BitSet bitSet = new BitSet(3); bitSet.set(2); return bitSet; } BitSet bitSet = new BitSet(limit + 1); bitSet.set(0, bitSet.size(), true); bitSet.clear(0); bitSet.clear(1); for (int i = 2, end = (int)(Math.sqrt(limit)) + 1; i &lt; end; i++) { if (bitSet.get(i)) { for (int j = i * i; j &lt;= limit; j += i) { bitSet.clear(j); } } } return bitSet; } } </code></pre> <p><strong><code>com.github.coderodde.math.prime.Demo</code></strong></p> <pre><code>package com.github.coderodde.math.prime; import com.github.coderodde.math.prime.impl.FasterPrimeFinder; import com.github.coderodde.math.prime.impl.LinearithmicPrimeFinder; import java.util.BitSet; import java.util.List; public final class Demo { private static final int MAX_PRIME = 300_000_000; public static void main(String[] args) { PrimeFinder primeFinder1 = new LinearithmicPrimeFinder(); PrimeFinder primeFinder2 = new FasterPrimeFinder(); List&lt;Integer&gt; list1 = getPrimeList(MAX_PRIME, primeFinder1); List&lt;Integer&gt; list2 = getPrimeList(MAX_PRIME, primeFinder2); System.out.println(&quot;Agreed: &quot; + list1.equals(list2)); } private static List&lt;Integer&gt; getPrimeList(int limit, PrimeFinder finder) { long startTime = System.currentTimeMillis(); BitSet primeSieve = finder.findPrimesUpTo(limit); long endTime = System.currentTimeMillis(); long duration = endTime - startTime; System.out.println( finder.getClass().getSimpleName() + &quot; in &quot; + duration + &quot; milliseconds.&quot;); List&lt;Integer&gt; list = PrimeFinder.primeBitSetToList(primeSieve, limit + 1); return list; } } </code></pre> <p><strong>Critique request</strong></p> <p>Please, tell me anything that comes to mind. Especially, I am concerned with class and method naming.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T12:19:35.933", "Id": "528272", "Score": "0", "body": "(While the title is spot-on, I don't think you *wish to know which of the solutions you presented is best (and why)*.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T21:19:01.760", "Id": "528304", "Score": "0", "body": "Does Java Bitset not have a find-next-set interface? You really have to query bits one at a time? If the actual implementation is a bit-array / bitmap, searching for next set could be much faster if there was an API for it. I checked, there is an API: [`nextSetBit(int)`](https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html#nextSetBit(int))" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T22:34:40.213", "Id": "528306", "Score": "0", "body": "@PeterCordes I checked half a day earlier - don't expect \"the candidate check\" to take a significant part of the time, and don't expect significant improvement given the average gap. Any benchmarkers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T22:54:05.373", "Id": "528307", "Score": "0", "body": "@greybeard: Yeah, that conversion is cheap compared to sieving, but it could still be improved, especially since it's a separately reusable function. Also approximating the number of primes <= n to avoid over-allocating a huge ArrayList is not a bad idea. I added an answer." } ]
[ { "body": "<p>Just a few stabs:</p>\n<ul>\n<li><p>Why an <code>abstract class</code>? You could even have static method members in <code>interface</code>s.</p>\n</li>\n<li><p><code>/* Finds all the primes no larger than {@code limit} and returns them in a * sorted list.</code> I read <code>BitSet findPrimesUpTo(int limit)</code></p>\n</li>\n<li><p><code>PrimeFinder.primeBitSetToList()</code> - what is the relation to primes?<br />\nWhy convert in the first place?<br />\nWhy not to <code>Set&lt;&gt;</code>?</p>\n</li>\n<li><p>While <code>PrimeFinder</code> does look the place for <code>checkLimit()</code>, it does not seem the proper place for <em>other stuff shared by sieves</em>. The two presented deserve one.</p>\n</li>\n<li><p><code>bitSet.set(2, bitSet.size());</code> ((version 1.6:) did you convert from an implementation in a different language?)</p>\n</li>\n<li><p><code>// Deal with powers of two:</code> I read <em>multiples</em>?!</p>\n</li>\n<li><p><code>end = (int)(Math.sqrt(limit))</code> shouldn't <em>floor</em> be sufficient?</p>\n</li>\n<li><p>I'm struggling with &quot;the main loop&quot; - no special casing 2, &quot;no&quot; checking of even numbers.<br />\nMight be less cumbersome in a generic wheel implementation.</p>\n<ul>\n<li>I'm doubtful of termination with <code>limit</code> near <code>Integer.MAX_VALUE</code><br />\n(Doesn't even reach &quot;the loops&quot; with 1.8, but fails when trying to set a range up to -2^31 - the return value of <code>.size()</code>. And fails for negative <code>j += i</code> after circumventing this <code>util.BitSet</code> peculiarity.)<br />\nSuggestion: document to work up to <code>Integer.MAX_VALUE - 2 * Character.MAX_VALUE - 2</code>, update <code>checkLimit()</code> accordingly.</li>\n</ul>\n<p>Currently at</p>\n<pre><code>final int end = (int)(Math.floor(Math.sqrt(limit))) + 1; // limit for Basic?\nfor (int i = 2, inc = 1; i &lt; end; i += inc, inc = 2)\n</code></pre>\n<p>Alternatively, drop <code>end</code> at the cost of legibility:</p>\n<pre><code> for (int i = 2, inc = 1 ; ; i += inc, inc = 2)\n if (pPrimes.get(i)) {\n int j = i * i;\n if (limit &lt; j)\n return pPrimes;\n do {\n pPrimes.clear(j);\n j += i+i; // *full* map *is* kind of weird \n } while (j &lt;= limit); // &amp;&amp; 0 &lt; j?\n }\n</code></pre>\n</li>\n</ul>\n<p><em>Naming</em> is important - and difficult. With derivation/<code>extends</code>, I'd rather not repeat the base name. With <code>implements</code>, I'm not so sure.<br />\nI think I'd go for <code>BasicEratosthenes</code>.<br />\n(I have no misgivings whatsoever with the names <code>Demo</code> and <code>main()</code>.<br />\n<code>getPrimeList()</code> does more than to expect from its name. (<code>handle…()</code> is <em>lame</em>.))<br />\n(for comparison:)</p>\n<pre><code> // Deal with odd multiples of odd primes:\n for (int primeCandidate = 3;\n primeCandidate &lt;= limit; \n primeCandidate += 2) {\n if (pPrimes.get(primeCandidate)) {\n for (int prime2 = primeCandidate * 2,\n i = primeCandidate * 3; // not fixable with 0 &lt;= i &amp;&amp;\n i &lt;= limit; \n i += prime2) {\n pPrimes.set(i, false);\n }\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T12:14:18.260", "Id": "267915", "ParentId": "267911", "Score": "5" } }, { "body": "<h2>Class naming</h2>\n<p>The names you used are fine IMO. You could prefix <code>PrimeFinder</code> with <code>Abstract</code>, but that's personal preference. Even Java's builtin classes aren't consistent with it (see <code>Reader</code> vs. <code>AbstractSet&lt;E&gt;</code>, both are abstract).<br />\nI've also seen the <code>Base</code> suffix (e.g. <code>PrimeFinderBase</code>), but not very often.</p>\n<h2>Method naming</h2>\n<p><code>findPrimesUpTo()</code> could be shortened to <code>findPrimes()</code>. Any IDE should show you the signature on hover or while typing AND there's a javadoc comment describing the parameter (also displayed by the IDE).</p>\n<p>Adding to that, there are methods like <code>Random.nextInt()</code> and <code>String.substring()</code>. Changing the method names to explain the arguments only adds length to the name while not giving any further information:</p>\n<pre><code>Random.nextIntSmallerThan(int bound);\nRandom.nextInt(int bound); // actual method\n\nString.substringBetween(int start, int end);\nString.substring(int start, int end); // actual method\n\nPrimeFinder.findPrimesUpTo(int limit);\nPrimeFinder.findPrimes(int limit); // ???\n</code></pre>\n<p><del>There may be cases where choosing the longer name is better, but I'd argue against it in this case.</del></p>\n<p>UPDATE: See comments on further arguments pro/con shortening.</p>\n<h2>Static</h2>\n<p>Both classes should only have static methods. They're a collection of methods for a purpose, a service provider, which doesn't need to be instatiated. Currently, you create an object every time you want to find primes, which is weird to read, weird to write/use and possibly bad for performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T13:13:16.957", "Id": "528273", "Score": "0", "body": "`[The classes are something] which doesn't need to be [instantiated]` have a look at `Demo.getPrimeList()`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T20:56:43.027", "Id": "528301", "Score": "1", "body": "\"*`findPrimesUpTo()` should be shortened to `findPrimes()`.*\" I disagree. Code like `findPrimesUpTo(42)` is clear and self-documenting, whereas the meaning of the argument in `findPrimes(42)` is completely obscure if you see it outside the IDE (like, say, in a Stack Exchange post)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T23:52:40.277", "Id": "528311", "Score": "0", "body": "@IlmariKaronen I'm undecided. With \"naked code\", I prefer \"reads unequivocally\". Using an IDE, I prefer short names and useful pop-ups on \"mouse\" hovers like `BitSet findPrimes(int upToIncluding);` - with useful interpretation of, say, *doc comments* I might move `Including` there (if free to modify the interface, I'm leaning towards `Object findPrimes(int below, util.Collection accumulator);`(& 1-parameter overload).) (Every now&then, I wish I knew English.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T11:23:40.887", "Id": "528529", "Score": "0", "body": "Concerning the shortening if `findPrimesUpTo`, I was undecided if I should write *should* or *could*. I'll update the answer to reflect this." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T12:45:44.570", "Id": "267918", "ParentId": "267911", "Score": "2" } }, { "body": "<p>This probably isn't a significant portion of the <em>total</em> time including sieving, but converting a bitset to an array / ArrayList of integers can be done more efficiently by <strong>searching for the next set bit</strong> with <a href=\"https://docs.oracle.com/javase/7/docs/api/java/util/BitSet.html#nextSetBit(int)\" rel=\"nofollow noreferrer\"><code>i = bitset.nextSetBit(i);</code></a>, rather than querying every bit separately. (It returns <code>-1</code> for not found.)</p>\n<p>It may avoid branch mispredicts when the next set bit is in the same machine word of the underlying bitmap, hopefully taking advantage of machine instructions that scan an integer for the lowest set bit (after right-shifting or masking to remove the bits below the start position in this integer chunk of the bitmap).</p>\n<p>It may well be slower when set bits are close together, but once you get to reasonable sizes and primes get farther apart, a fast search for the next set bit is hopefully good. For large distances, you'd expect a good implementation to be checking at least 64 bits at a time to see if they contain a non-zero bit, only then bit-scanning within that integer.</p>\n<hr />\n<h3>Size your allocation to the expected number of primes <code>&lt;= n</code></h3>\n<pre><code> List&lt;Integer&gt; list = new ArrayList&lt;&gt;(bitSet.size());\n</code></pre>\n<p><strong>That's a significant over-allocation.</strong> The exact size is <code>bitSet.cardinality()</code>, but that would have to popcount your bitset. Instead probably better to slightly over-estimate and then trim the array. The number of primes &lt;= n can be approximated as <code>n / log(n)</code>, which under-estimates by 11% for n=10^4, or by 5% for n=10^9.</p>\n<pre><code> // This is an over-estimate for large n, maybe an under-estimate for small n.\n // ArrayList can grow if needed, and that's cheap for small a ArrayList.\n int approxPrimeCount = (int)(bitSet.size() * 1.10 / Math.log(bitSet.size()));\n List&lt;Integer&gt; list = new ArrayList&lt;&gt;(approxPrimeCount + 20);\n // fixed + 20 to make sure it's sane at small size, and we can use a smaller scale factor\n</code></pre>\n<p>(If your bitset only represents odd numbers, it's about twice as dense, so multiply by 2.2 instead of 1.1)</p>\n<p>In terms of space savings, for n=10^9, you'd allocate space for 1 billion ints (4 GB ~= 3.72 GiB). But exact Pi(10^9) = 50,847,534, so you only need space for ~51M. (195 MiB). That's 19.67 times as much space needed for the naive allocation. (ln(1e9) = 20.7). My over-estimation approximation gives <code>53080436 + 20</code> elements, taking 202.4 MiB of space, still a factor of 18.8 vs. the size of the naive allocation.</p>\n<p>So that's huge, unless elements of an ArrayList you only reserve capacity for but don't touch are cheap. (e.g. if the implementation doesn't zero them, so any fresh pages it got from the OS remain untouched, never page-faulted.)</p>\n<p><strong>Or instead of calling <code>log</code></strong>, use <code>31 - Integer.numberOfLeadingZeros( size )</code> as <a href=\"https://stackoverflow.com/questions/3305059/how-do-you-calculate-log-base-2-in-java-for-integers\">an approximation for integer log2</a>. If over-estimating the space required is not costly (e.g. if we can resize the ArrayList to just the used space after filling it), we can do <code>n / ilog2(n) * 3 / 2 + 20</code> or something. Dividing by log2(n) instead of ln(n) will give smaller results, so we're rolling that into our scale factor with <code>3/2</code> as a quick hack. ilog2 will over estimate for numbers that aren't powers of 2, e.g. log2(255) is 7.994, but ilog2(255) = 7.</p>\n<p>Or log2(10^9) ~= 29.89, so ilog2(10^9) is 29. That rounding down in the divisor can lead to a fairly large over-allocation in absolute terms, but being fast for small N can be worth it.</p>\n<hr />\n<p><strong>When you're done, you can trim the ArrayList capacity to its size with <code>.trimToSize()</code></strong>, giving back any reserved space you didn't end up needing. Unless of course you expect to be appending more numbers later.</p>\n<hr />\n<p>In your loop limit calculation, <strong>there's a lot going on in one line.</strong></p>\n<pre><code>// FasterPrimeFinder\n for (int i = 2, end = (int)(Math.sqrt(limit)) + 1; i &lt; end; i++) {\n ...\n }\n</code></pre>\n<p>I think it would be preferable to have <code>int end = ...</code> <em>outside</em> the for loop, even though that means it's still in scope after the loop. This is inside a relatively small function so it's fine. I find it easier to see the simple idiomatic loop structure after pulling the big <code>end</code> expression out of it.</p>\n<pre><code> int end = (int)(Math.sqrt(limit)) + 1;\n for (int i = 2; i &lt; end; i++) {\n ...\n }\n</code></pre>\n<hr />\n<p>Also, <code>2</code> is the only even prime, so you can just factor that out of the outer loop and do <code>i+=2;</code>. You do that in <code>LinearithmicPrimeFinder</code>, but not in <code>FasterPrimeFinder</code>, which leaves me wondering, &quot;faster than what&quot;? It isn't <em>totally</em> naive, for example calculating loop limits, and starting at <code>i*i</code>.</p>\n<p>Or better, <strong>don't even store even numbers in your bitset</strong>, so <code>bitset[i]</code> actually represents <code>i*2+3</code>, or odd integer <code>j</code> is represented by <code>bitset[ (j-3)&gt;&gt;1 ]</code>. Neither of your implementations do that.</p>\n<p>Even multiples of primes don't need to be marked off, you're already implicitly ignoring them. So you can still use <code>idx += i</code> to iterate through the odd multiples to mark them off, I think. (This does require some care to get the logic right, like the squaring for where to start needs to use the integer, not the bit-index.)</p>\n<p>This can even be generalized to a &quot;wheel&quot; of implicitly skipping multiples of 3 and 5 as well, but that's more complicated. Skipping even numbers is pretty much pure win. This is described in <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Overview\" rel=\"nofollow noreferrer\">https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Overview</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T23:28:21.977", "Id": "528309", "Score": "0", "body": "(*just factor [checking even numbers for primality] out of the outer loop and do `i+=2;`*: coderodde does in `LinearithmicPrimeFinder.findPrimesUpTo()`.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T23:31:21.760", "Id": "528310", "Score": "0", "body": "(Note that *next special bit* couldn't just be used in converting result set representation: It looks a valid alternative to using a wheel.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T00:28:41.663", "Id": "528313", "Score": "0", "body": "@greybeard: Good point, I did notice that, but forgot to specify that I was talking about the \"FasterPrimeFinder\" which doesn't. Re: a wheel: I think a big part of the reason for using a wheel is to save space, and memory / cache bandwidth when striding through marking off multiples. And also bit set/clear operations. Iterating over the bitmap at the end isn't the primary motivation for making it denser with a wheel. (But I forget exactly how the wheel algorithm works, and what extra costs it entails.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T00:28:50.450", "Id": "528314", "Score": "0", "body": "Of course, the cache footprint problem can be addressed by cache-blocking, which apparently is possible with a [segmented sieve](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes#Segmented_sieve), so you can get mostly L2 cache hits I guess." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T22:51:58.917", "Id": "267933", "ParentId": "267911", "Score": "2" } }, { "body": "<p>One can split hairs over naming until the cows come home. And at the end of the day, someone will always disagree anyway. As long as it's not horrid, you're good. Your code will work and do the thing.</p>\n<p>What's more important is the API that you present to your users.</p>\n<p>In this case you have chosen to create an extensible class hierarchy. This is OK, but your choice of interface methods leaks implementation details. In particular your base class assumed every prime finder will be of a sieve type and use a bit set to return it's results. These choices are limiting you to this class of solution. The API should allow you to implement a prime finder with trial division if you want, or to load a long list of primes from disk. Both of these become clonky to convert first to bit set and then back to a list.</p>\n<p>I would recommend changing the API so that it returns the list of integers directly and possibly offer a helper function to convert from bit list to list of integers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T11:03:07.620", "Id": "267955", "ParentId": "267911", "Score": "0" } }, { "body": "<p>I just wanted to give my two cents about a very small optimization that everybody oversees.</p>\n<p>You're developing a <code>FastErathostenes</code>, but you have the following code:</p>\n<pre><code> checkLimit(limit);\n \n if (limit &lt; 2) {\n return new BitSet(limit);\n }\n \n if (limit == 2) {\n BitSet bitSet = new BitSet(3);\n bitSet.set(2);\n return bitSet;\n }\n</code></pre>\n<p>If one wants to optimize, they'll think that limit will rarely be below 2. So we actually perform 3 times the same checks on the same value for most of the cases. So instead move the triple check to where it's the most likely to be less costly.</p>\n<p>I suggest instead the following code:</p>\n<pre><code> if (limit &lt;= 2) {\n if (limit &lt; 0) {\n throw new IllegalArgumentException(&quot;Negative limit: &quot; + limit);\n }\n BitSet primes = new BitSet();\n if (limit == 2) {\n primes.set(2);\n }\n return primes;\n }\n</code></pre>\n<p>When given no size or <code>nbits</code> between 0 and 63, <code>BitSet</code> will always create an array of at least one element. It doesn't say so on the Javadoc, but the implementation is rather clear about it. So there's no need to make a distinction between the constructors if you know that you'll never store any value above 63.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T12:16:14.510", "Id": "267959", "ParentId": "267911", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T09:14:20.150", "Id": "267911", "Score": "5", "Tags": [ "java", "algorithm", "comparative-review", "sieve-of-eratosthenes" ], "Title": "Comparing 2 distinct sieve of Eratosthenes algorithms in Java" }
267911
<p>I am working on a practice problem found here: <a href="https://www.hackinscience.org/exercises/sequence-mining" rel="nofollow noreferrer">https://www.hackinscience.org/exercises/sequence-mining</a></p> <blockquote> <p>Overview</p> <p>Sequence mining is useful for analyzing list of events when order matters. It's used for example for DNA and natural language analysis.</p> <p>Here, you'll implement an algorithm to extract common patterns among a set of sequences.</p> <p>Exercise</p> <p>You must provide a function seq_mining that takes as argument:</p> <p>A list of strings (representing the sequences), such as: ['CFEDS', 'SKDJFGKSJDFG', 'OITOER']</p> <p>The minimum proportion of the number of sequences that must have this pattern for being taken into account (float between 0 and 1): if 0.34, at least a third of the sequences must have a given pattern for the function to return it.</p> <p>The maximum pattern length that must be considered (int)</p> <p>If a given pattern occurs several time in a sequence, it must be counted only once.</p> <p>The function seq_mining must return a Counter containing:</p> <p>The found patterns as keys The number of sequences containing this pattern as values.</p> <p>In [&quot;ABC&quot;, &quot;BCD&quot;] there are three patterns common to both sequences:</p> <p>B C BC</p> <p>(A and AB occurs only in the first string, and D and CD only in the last one).</p> <p>So seq_mining([&quot;ABC&quot;, &quot;BCD&quot;], 0.66, 2) (searching patterns of length 2 maximum, must appear on at lest 66% of sequences) should return:</p> <p>Counter({'B': 2, 'C': 2, 'BC': 2})</p> <p>(because as we have only two sequences, 66% already means the two of them)</p> <p>while seq_mining([&quot;ABC&quot;, &quot;BCD&quot;], 0.33, 2) (searching patterns of length 2 maximum, must appear on at lest 33% of sequences) should return:</p> <p>Counter({'C': 2, 'B': 2, 'BC': 2, 'A': 1, 'D': 1, 'AB': 1, 'CD': 1})</p> <p>This tells us that BC is found in two sequences while AB is found in a single one. (because as we have only two sequences, 33% allows a pattern to be found in a single sequence).</p> </blockquote> <p>In this problem, I need to build a function which goes over a list of strings, finds patterns of up to a specific length that are present in at least a specific proportion of the given strings: The function takes 3 arguments: a list of strings, a float which will be the required proportion of strings that the pattern appears in to be counted, and the maximum length of the possible patterns. The function must return a <code>Counter()</code> object as well.</p> <p>I built a function which seems to work, although I know it's not pretty or efficient. When I initially submitted the solution, it says I failed because the run time is too long. I'm not too familiar with optimizing code yet because I'm still a beginner, but I did some reading and tried to implement some of the changes, such as removing a for loop in exchange for a while loop and using list comprehension where possible. I think this made the code much more unreadable and it seems to be running even slower. I think my function is poorly designed overall but before I start over I'd like to know if there are any obvious changes that could be made that I'm not seeing. I just think I'm heading in the wrong direction with the code and could use some expertise here.</p> <pre><code>import itertools, collections def seq_mining(data, prop, max_int): list_of_sequences=enumerate(data) pos_dict = collections.defaultdict(list) for seq_index, seq in list_of_sequences: for step in range(1, (max_int+1)): for sub_seq in range(0, len((seq))): if len(seq[sub_seq:sub_seq+step]) &gt;= step: pos_dict[seq_index].append(seq[sub_seq:sub_seq+step]) num_occurrence={k: sum(1 for l in pos_dict.values() if k in l) for k in set(sum(pos_dict.values(), []))} final_dict={} for l, t in num_occurrence.items(): if t/len(data) &gt;= float(prop): final_dict[l]=t c=collections.Counter(final_dict) return c </code></pre> <p>The above code was the initial one I submitted which failed. I did some reading and attempted to make it better, but I think I made it worse: My second attempt is below</p> <pre><code>def seq_mining(data, prop, max_int): list_of_sequences=enumerate(data) pos_dict = collections.defaultdict(list) for seq_index, seq in list_of_sequences: step = 1 while step &lt;=max_int: [pos_dict[seq_index].append(seq[sub_seq:sub_seq + step]) for sub_seq in range(0, len((seq))) if len(seq[sub_seq:sub_seq + step]) &gt;= step] step+=1 num_occurrence = {k: sum(1 for l in pos_dict.values() if k in l) for k in set(sum(pos_dict.values(), []))} final_dict = dict([(l, t) for l, t in num_occurrence.items() if t / len(data) &gt;= float(prop)]) c = collections.Counter(final_dict) return c </code></pre> <p>This is significantly more confusing to me. I read about a module called cProfile which can help locate areas that can be improved. The one below is what I got after running the second attempt.</p> <pre><code>958 function calls in 0.001 seconds 1 0.000 0.000 0.001 0.001 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 __init__.py:581(__init__) 1 0.000 0.000 0.000 0.000 __init__.py:649(update) 1 0.000 0.000 0.000 0.000 abc.py:96(__instancecheck__) 10 0.000 0.000 0.000 0.000 scratch_5.py:12(&lt;listcomp&gt;) 1 0.000 0.000 0.001 0.001 scratch_5.py:14(&lt;dictcomp&gt;) 254 0.000 0.000 0.000 0.000 scratch_5.py:14(&lt;genexpr&gt;) 1 0.000 0.000 0.000 0.000 scratch_5.py:15(&lt;listcomp&gt;) 1 0.000 0.000 0.001 0.001 scratch_5.py:6(pos_func) 1 0.000 0.000 0.000 0.000 {built-in method _abc._abc_instancecheck} 1 0.000 0.000 0.001 0.001 {built-in method builtins.exec} 1 0.000 0.000 0.000 0.000 {built-in method builtins.isinstance} 293 0.000 0.000 0.000 0.000 {built-in method builtins.len} 124 0.000 0.000 0.000 0.000 {built-in method builtins.sum} 1 0.000 0.000 0.000 0.000 {function Counter.update at 0x000001E9D0C0F430} 140 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects} 124 0.000 0.000 0.000 0.000 {method 'values' of 'dict' objects} </code></pre> <p>The cProfile below is for my first attempt at the function.</p> <pre><code>953 function calls (951 primitive calls) in 0.001 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.001 0.001 &lt;string&gt;:1(&lt;module&gt;) 1 0.000 0.000 0.000 0.000 __init__.py:581(__init__) 1 0.000 0.000 0.000 0.000 __init__.py:649(update) 2 0.000 0.000 0.000 0.000 _collections_abc.py:405(__subclasshook__) 2/1 0.000 0.000 0.000 0.000 abc.py:100(__subclasscheck__) 1 0.000 0.000 0.000 0.000 abc.py:96(__instancecheck__) 1 0.000 0.000 0.000 0.000 scratch_4.py:13(&lt;dictcomp&gt;) 254 0.000 0.000 0.000 0.000 scratch_4.py:13(&lt;genexpr&gt;) 1 0.000 0.000 0.001 0.001 scratch_4.py:5(pos_func) 1 0.000 0.000 0.000 0.000 {built-in method _abc._abc_instancecheck} 2/1 0.000 0.000 0.000 0.000 {built-in method _abc._abc_subclasscheck} 1 0.000 0.000 0.001 0.001 {built-in method builtins.exec} 1 0.000 0.000 0.000 0.000 {built-in method builtins.isinstance} 293 0.000 0.000 0.000 0.000 {built-in method builtins.len} 124 0.000 0.000 0.000 0.000 {built-in method builtins.sum} 1 0.000 0.000 0.000 0.000 {function Counter.update at 0x000001F12206D430} 140 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects} 124 0.000 0.000 0.000 0.000 {method 'values' of 'dict' objects} </code></pre> <p>Why does my function that returns a <code>Counter()</code> object have a very long run time? Looking at these results with an inexperienced eye, I would think the <code>len()</code> function is being run too many times and is slowing me down a lot. Is this correct?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:13:13.113", "Id": "528276", "Score": "0", "body": "Just a general remark: for me the code is just too dense to understand easily. My mind just starts to complain when trying to read stuff like `[pos_dict[seq_index].append(seq[sub_seq:sub_seq + step]) for sub_seq in range(0, len((seq))) if len(seq[sub_seq:sub_seq + step]) >= step]`. If I need to start puzzling to see what the code should be doing..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T16:51:26.497", "Id": "528285", "Score": "0", "body": "I honestly completely agree. That's why I was asking for help because my attempt to decrease the use of for loops left me with increasingly uglier code haha. I was able to figure out a way to get this to work without such an messy answer though. I think I just needed to step away from it for a while and recheck with fresh eyes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T17:27:14.960", "Id": "528289", "Score": "0", "body": "I pasted your code and `seq_mining( ['CFEDS', 'SKDJFGKSJDFG', 'OITOER'])` from the question. It doesn't run. Can you post the full code to run your example?" } ]
[ { "body": "<p>Any time you see nested <code>for</code> loops like this, you can visually clean them up (or at least separate them) with generators:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def create_substrings(data, max_int):\n # This function cleans up the seq mining function\n # by just creating your key, slice pairs\n for seq_index, seq in enumerate(data):\n for step in range(1, max_int+1):\n for sub_seq in range(len(seq)):\n slice_ = seq[sub_seq:sub_seq+step]\n\n if len(slice_) &lt; step:\n continue\n\n yield seq_index, slice_\n\n\ndef seq_mining(data, prop, max_int):\n positions = defaultdict(list)\n\n # Now this looks a lot less crowded\n for seq, slice_ in create_substrings(data, max_int):\n positions[seq].append(slice_)\n\n num_occurrence={k: sum(1 for l in positions.values() if k in l) for k in set(sum(positions.values(), []))}\n final_dict={}\n for l, t in num_occurrence.items():\n if t/len(data) &gt;= float(prop):\n final_dict[l]=t\n c=collections.Counter(final_dict)\n return c\n</code></pre>\n<p>It doesn't necessarily give you a performance benefit, but it makes the code look less dense, and is easier to read and digest later.</p>\n<p>There's a big red flag here. The <code>num_occurrence</code> dictionary comprehension is probably your biggest bottleneck. the <code>sum(1 for l in values if k in l)</code> is slow because the <code>k in l</code> test is of O(N) performance... nested inside a loop. Now, that's worst-case, but it's still slow. You're also iterating over values when using <code>set(sum(...))</code>. To break this up, let's consider the problem first:</p>\n<blockquote>\n<p>The minimum proportion of the number of sequences that must have this pattern for being taken into account (float between 0 and 1): if 0.34, at least a third of the sequences must have a given pattern for the function to return it.\nThe maximum pattern length that must be considered (int)\nIf a given pattern occurs several time in a sequence, it must be counted only once.</p>\n</blockquote>\n<p>With this in mind, your default dictionary is inside-out. You wind up trying to count the number of times the unique values in the dictionary occur instead of what you should be doing, which is counting how many sequences share a sub-sequence. Let's use a <code>defaultdict(set)</code> for that instead, where the sets contain the indices of the parent sequences:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def create_substrings(data, max_int):\n # This function cleans up the seq mining function\n # by just creating your key, slice pairs\n for seq_index, seq in enumerate(data):\n for step in range(1, max_int+1):\n # The (step - 1) will make it so that you don't have\n # to test the length of the slice anymore\n for sub_seq in range(len(seq) - (step - 1)):\n slice_ = seq[sub_seq:sub_seq+step]\n\n yield seq_index, slice_\n\n\n\ndef seq_mining(data, prop, max_int):\n positions = defaultdict(set)\n\n for i, seq in create_substrings(data, max_int):\n # each member now gets counted only once\n positions[seq].add(i)\n\n # data doesn't change size, so compute its length once\n data_len = len(data)\n\n # don't cast this, just make it a counter to begin with\n counter = Counter()\n\n for l, t in positions.items():\n t_len = len(t)\n\n if t_len/data_len &lt; prop:\n continue\n\n counter[l] = t\n\n return counter\n</code></pre>\n<p>A few things I've cleaned up:</p>\n<ol>\n<li><code>data_len</code>. Don't re-compute constants over and over. Look them up, define them as constants, and move on</li>\n<li><code>counter</code>: Avoid unnecessary re-casting. <code>Counter</code> is a pretty similar object to a dictionary, so use it like one</li>\n<li><code>positions</code>: Is now a <code>defaultdict(set)</code> which allows you to just see how many sequences share the dna pattern, regardless of how many times it actually shows up.</li>\n<li><code>if t_len...: continue</code>: The eye has to stay closer to the left side of the screen if we explicitly say what we want to ignore. It implies the <code>else</code> and leads to less deeply-nested loop structures</li>\n<li><code>for sub_seq in range(len(seq) - (step - 1)</code>: This eliminates the slice length testing</li>\n</ol>\n<p>Now, this certainly <em>looks</em> better, and even has a boost in performance, but it's still missing some pieces to be complete.</p>\n<h2>Checking proportion shared</h2>\n<p>Rather than comparing to a float that we calculate in every iteration, it would be <em>much</em> better to compare to a pre-defined integer. You know how many need to share a subsequence to be considered valid, it can be defined outside of your loop. Compute the proportion and use a ceiling function to make it an integer:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from math import ceil\n\n\ndef common_subsequences(sequences, sequence_len, proportion):\n positions = defaultdict(set)\n\n for i, seq in create_substrings(data, max_int):\n positions[seq].add(i)\n\n # this is the number of samples that need to share the subsequence\n num_required = ceil(len(sequences) * proportion)\n</code></pre>\n<p>Now, putting this into a loop to fill a <code>Counter</code> object:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def common_subsequences(sequences, sequence_len, proportion):\n positions = defaultdict(set)\n\n for i, seq in create_substrings(data, max_int):\n # each member now gets counted only once\n positions[seq].add(i)\n\n # this is the number of samples that need to share the subsequence\n num_required = ceil(len(sequences) * proportion)\n counter = Counter()\n\n for subsequence, members in positions.items():\n num_members = len(members)\n\n # now we're testing an integer, much simpler\n if num_members &lt; num_required:\n continue\n\n counter[subsequence] = num_members\n\n return counter\n\n</code></pre>\n<h1>Docstrings</h1>\n<p>Docstrings would help very much in terms of readability for any user. As it stands, it's tough to reason out what the code is actually doing. The names aren't clear, so a docstring giving a helpful description and some examples would go an exceptionally long way.</p>\n<h1>Type Hints</h1>\n<p>These are useful for communicating what types your variables are to the reader/user/maintainer</p>\n<pre class=\"lang-py prettyprint-override\"><code>from typing import List, Iterator, Tuple\n\n\ndef create_substrings(dna_sequences, sequence_len=1) -&gt; Iterator[Tuple[int, str]]:\n &quot;&quot;&quot;Creates slices of each member of `dna_sequences` up\n to `sequence_len` in size\n\n Yields tuples of the slices' sequence number and the slices themselves\n &quot;&quot;&quot;\n\n\ndef common_subsequences(sequences: List[str], sequence_len: int, proportion: float) -&gt; Counter:\n &quot;&quot;&quot;Finds common dna patterns shared between a list of strands.\n\n It returns a Counter of patterns up to `sequence_len` in length that are\n shared by at least `proportion` of the population\n &quot;&quot;&quot;\n</code></pre>\n<h1>Naming</h1>\n<p><code>l</code>, <code>t</code>, <code>prop</code>, and <code>max_int</code> are not clear variable names. They are certainly valid python, but are shorthand that is only useful to the one writing the code. But what happens when you go back a month or two from now to update it? It might be much more difficult to figure out what each of these names are. Pick descriptive (but not overly verbose) names, they communicate what values are.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T23:38:45.493", "Id": "267936", "ParentId": "267914", "Score": "0" } }, { "body": "<p>I submitted your first code there and got this failure message:</p>\n<blockquote>\n<p><code>seq_mining(['ABCD', 'ABABC', 'BCAABCD'], 0.34, 1000000)</code> is too slow (took 4.203785117715597s).</p>\n</blockquote>\n<p>Seeing that 1000000 is far larger than useful, I reduced it to the largest actual string length by adding this at the top of your function:</p>\n<pre><code>max_int = min(max_int, max(map(len, data)))\n</code></pre>\n<p>Submitting again gave this success message:</p>\n<blockquote>\n<p>Nice!! Your exercise is OK.</p>\n</blockquote>\n<p>Moral of the story: Don't ignore feedback.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T11:18:43.923", "Id": "528339", "Score": "0", "body": "Yep this is exactly what I realized and how I fixed it, just limited the length of the maximum string. Thank you!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T01:18:07.153", "Id": "267939", "ParentId": "267914", "Score": "1" } }, { "body": "<p>Some observations:</p>\n<pre><code>import itertools, collections\n</code></pre>\n<p>It don't see <code>itertools</code> used--don't import it</p>\n<pre><code>list_of_sequences=enumerate(data)\n</code></pre>\n<p><code>enumerate()</code> is a generator that yields a sequence of tuples. It doesn't return a list, so <code>list_of_sequences</code> is a misnomer.</p>\n<pre><code>for seq_index, seq in list_of_sequences:\n</code></pre>\n<p>To understand the <code>for</code> loop, you need to remember that <code>list_of_sequences</code> is an enumeration. It would be more readable to just put <code>enumerate(data)</code> in the <code>for</code> loop.</p>\n<p>Solving the problem does not require keeping track of which sequence had which subsequences. The index isn't needed, so the <code>enumerate</code> isn't needed either.</p>\n<pre><code>for step in range(1, (max_int+1)):\n</code></pre>\n<p><code>substring_length</code> or <code>width</code> might be a more descriptive name than <code>step</code>.</p>\n<p><code>sub_seq</code> is the starting index. If the loop ends at <code>len(seq) - step + 1</code>, the next <code>if</code> statement isn't needed.</p>\n<pre><code>pos_dict[seq_index].append(seq[sub_seq:sub_seq+step])\n</code></pre>\n<p>This line builds lists of all subsequences of a sequence.</p>\n<pre><code>num_occurrence={k: sum(1 for l in pos_dict.values() if k in l) for k in set(sum(pos_dict.values(), []))}\n</code></pre>\n<p>Then <code>set(sum(pos_dict.values(), []))</code> builds a set of subsequences so that <code>sum(1 for l in pos_dict.values() if k in l)</code> can count the number of sequence contain each subsequence. The line is too complicated and unnecessary.</p>\n<p>When you need to get a collection of items without duplicates, consider using a <code>set</code>. When you need to count things, consider using <code>Counter()</code>.</p>\n<pre><code>def seq_mining(data, ratio, maxlen):\n sub_seq_counts = Counter()\n\n for seq in data:\n patterns = set()\n\n # collect the set of subsequences\n for start in range(len(seq)):\n for width in range(1, min(len(seq) - start, maxlen) + 1):\n pattern = seq[start:start + width]\n patterns.add(pattern)\n \n print(patterns)\n\n # update the count of sequences that contain each\n # subsequence\n sub_seq_counts.update(patterns)\n\n # filter the subsequences that meet the minimum ratio of matches \n threshold = len(data) * ratio\n result = Counter({k:v for k,v in sub_seq_counts.items() if v &gt;= threshold})\n\n return result\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T07:19:42.163", "Id": "267951", "ParentId": "267914", "Score": "0" } } ]
{ "AcceptedAnswerId": "267936", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T12:02:18.503", "Id": "267914", "Score": "4", "Tags": [ "python", "programming-challenge", "time-limit-exceeded" ], "Title": "HackInScience exercise: Sequence Mining" }
267914
<p>This is my first time using StackExchange. I did not have any idea what this website for, but I guess is a place to review the code? So, I'm just going to give it a shot.</p> <pre><code>#include &lt;iostream&gt; std::string board[3][3]; void making_board(); void play_the_game(); void display_board(); void choose_position(int position, std::string* current_player); void find_row_column(int position, int* row, int* column); void player_turn(std::string* current_player); std::string computer_turn(std::string* current_player); std::string predict_future(std::string* current_player); std::string check_the_game(); int possible_move(int* row, int* column, std::string *current_player, std::string* position); int move_left(int row, int column, std::string* current_player); int predict_opponent(int* row, int* col, std::string opponent, std::string* ori_position); int possible_opponent(int* row, int* column, std::string opponent); int main() { play_the_game(); return 0; } std::string check_the_game(){ int area_filled = 0; for (int row = 0; row &lt; 3; row++){ if (board[row][0] == board[row][1] &amp;&amp; board[row][1] == board[row][2]){ return board[row][0]; } } for (int column = 0; column &lt; 3; column++){ if (board[0][column] == board[1][column] &amp;&amp; board[1][column] == board[2][column]){ return board[0][column]; } } if (board[0][0] == board[1][1] &amp;&amp; board[1][1] == board[2][2])return board[1][1]; else if (board[2][0] == board[1][1] &amp;&amp; board[1][1] == board [0][2]) return board[1][1]; for (int rows = 0; rows &lt; 3; rows++){ for (int columns = 0; columns &lt; 3; columns++){ if (board[rows][columns] == &quot;X&quot; || board[rows][columns] == &quot;O&quot;) area_filled++; if (area_filled == 9)return &quot;neither&quot;; } } return &quot;notyet&quot;; } int possible_opponent(int row, int column, std::string opponent){ std::string ori_position = board[row][column]; board[row][column] = opponent; if (check_the_game() == &quot;X&quot;){ board[row][column] = ori_position; return -10; }else { board[row][column] = ori_position; return 0; } } int predict_opponent(int* row, int* col, std::string opponent, std::string* ori_position){ int score; for (int r = 0; r &lt; 3; r++){ for (int c = 0; c &lt; 3; c++){ if (board[r][c] != &quot;X&quot; &amp;&amp; board[r][c] != &quot;O&quot;){ if (possible_opponent(r, c, opponent) == -10){ board[*row][*col] = *ori_position; *row = r; *col = c; return -10; } else continue; }else continue; } } return 0; } int possible_move(int* row, int* column, std::string *current_player, std::string* position){ std::string ori_position = board[*row][*column]; board[*row][*column] = *current_player; if (check_the_game() == &quot;O&quot;){ board[*row][*column] = ori_position; return 10; }else if (predict_opponent(row, column, &quot;X&quot;, &amp;ori_position) == -10){ *position = board[*row][*column]; board[*row][*column] = &quot;O&quot;; return -10; }else { board[*row][*column] = ori_position; return 0; } } std::string predict_future(std::string* current_player){ std::string position; int score; for (int row = 0; row &lt; 3; row++){ for (int column = 0; column &lt; 3; column++){ if (board[row][column] != &quot;X&quot; &amp;&amp; board[row][column] != &quot;O&quot;){ if (possible_move(&amp;row, &amp;column, current_player, &amp;position) == -10){ return position; } else if (possible_move(&amp;row, &amp;column, current_player, &amp;position) == 10){ position = board[row][column]; board[row][column] = *current_player; return position; }else if (move_left(row, column, current_player) == 1){ position = board[row][column]; board[row][column] = *current_player; return position; }else if(possible_move(&amp;row, &amp;column, current_player, &amp;position) == 0){ if (board[1][1] != &quot;X&quot; &amp;&amp; board[1][1] != &quot;O&quot; &amp;&amp; move_left(row, column, current_player) &lt; 9){ position = board[1][1]; board[1][1] = *current_player; return position; }else continue; } }else continue; } } } int move_left(int row, int column, std::string* current_player){ int move_left = 0; for (int r = row; r &lt; 3; r++){ for (int c = column; c &lt; 3; c++){ if (board[r][c] != &quot;X&quot; &amp;&amp; board[r][c] != &quot;O&quot;){ move_left++; } } } return move_left; } void play_the_game(){ bool still_playing = true; std::string current_player = &quot;X&quot;; std::string winner = &quot;&quot;; making_board(); while (still_playing){ display_board(); player_turn(&amp;current_player); winner = check_the_game(); if (winner == &quot;X&quot; || winner == &quot;O&quot; || winner == &quot;neither&quot;){display_board();break;} } std::cout &lt;&lt; &quot; Winner is &quot; &lt;&lt; winner &lt;&lt; std::endl; std::cout &lt;&lt; &quot; Play again (1 for yes and 0 for no)? &quot;; std::string answer; std::cin &gt;&gt; answer; if (answer == &quot;1&quot;){ system(&quot;CLS&quot;); play_the_game(); }else if(answer == &quot;0&quot;){ exit(0); }else { std::cout &lt;&lt; &quot; Invalid answer&quot;; std::cout &lt;&lt; &quot; Play again (1 for yes and 0 for no)? &quot;; } } void player_turn(std::string *current_player){ std::string sposition; int position; if (*current_player == &quot;O&quot;){ sposition = predict_future(current_player); std::cout &lt;&lt; &quot; &quot; &lt;&lt; *current_player &lt;&lt; &quot;'s turn, position chosen was: &quot; &lt;&lt; sposition &lt;&lt; std::endl; *current_player = &quot;X&quot;; }else { std::cout &lt;&lt; &quot; &quot; &lt;&lt; *current_player &lt;&lt; &quot;'s turn, choose position: &quot;; std::cin &gt;&gt; position; if (!std::cin &gt;&gt; position){ std::cin.clear(); std::cin.ignore(1000, '\n'); std::cout &lt;&lt; &quot; Position is not available&quot; &lt;&lt; std::endl; player_turn(current_player); } choose_position(position, current_player); } } void choose_position(int position, std::string *current_player){ int row, column; find_row_column(position, &amp;row, &amp;column); if (board[row][column] == &quot;X&quot; || board[row][column] == &quot;O&quot; || position &lt; 0 || position &gt; 9){ std::cout &lt;&lt; &quot; Position is not available&quot; &lt;&lt; std::endl; player_turn(current_player); } else { board[row][column] = *current_player; if (*current_player == &quot;X&quot;) *current_player = &quot;O&quot;; else *current_player =&quot;X&quot;; } } void find_row_column(int position, int* row, int* column){ *row = position/3; if (*row = 0) *column = 2; *column = position-*row-1; } void display_board(){ std::cout &lt;&lt; &quot;\n&quot;; for (int rows = 2; rows &gt;= 0; rows--){ for (int columns = 0; columns &lt; 3; columns++){ if (columns == 0){ std::cout &lt;&lt; &quot; &quot; &lt;&lt; board[rows][columns]; } else std::cout &lt;&lt; &quot; | &quot; &lt;&lt; board[rows][columns]; } if (rows &gt; 0)std::cout &lt;&lt; &quot;\n ---|---|---\n&quot;; else std::cout &lt;&lt; &quot;\n\n&quot;; } } void making_board(){ int i = 1; for (int rows = 0; rows &lt; 3; rows++){ for (int columns = 0; columns &lt; 3; columns++){ board[rows][columns] = std::to_string(i); i++; } } } </code></pre> <p>I tried to beat my AI. Somehow I still won.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T13:49:41.317", "Id": "528274", "Score": "0", "body": "Hi. Welcome to Code Review! Your post is rather chatty. We can already see that you are a first time user. It shows in your profile and your reputation score. We would prefer that you take the [tour](https://codereview.stackexchange.com/tour) before posting. Then you wouldn't need to tell us you have no idea what the site does. And finally, it would help if you told us, in words, what your code does. Yes, it's Tic-Tac-Toe. Does it take user input? For how many players? Does it provide an AI? For how many players?" } ]
[ { "body": "<p>No time for a full review, but here are some general remarks:</p>\n<ul>\n<li><code>making_board</code>: try and use verbs, as methods are things that perform actions, i.e. <code>make_board</code> or <code>setup_board</code> (you seem to do this right for the other methods, so maybe this is just the odd one out).</li>\n<li>C++ code often differs from C by using capital letters instead of underscores to separate method names. Style is subjective though - as long as you are aware of this.</li>\n<li>Use explicit <code>WIDTH</code> and <code>HEIGHT</code> instead of literals valued <code>2</code>, <code>3</code> and <code>9</code>.</li>\n<li><code>check_the_game</code> should have separate methods to check for rows, columns and diagonals. You could also explicitly define &quot;groups&quot;, which could be either, but this is a more advanced trick (I use it for my <code>SudokuSolver</code> code, where a Sudoku can have many forms).</li>\n<li>You could use an enum with <code>PLAYING</code>, <code>DRAW</code>, <code>WIN_O</code> and <code>WIN_X</code> constants, try and avoid <a href=\"https://blog.codinghorror.com/new-programming-jargon/#7\" rel=\"nofollow noreferrer\">&quot;stringly typed&quot;</a> code.</li>\n<li>Even if you don't split your code in separate classes, it makes sense to order them somewhat, e.g. first <code>main</code>, then <code>play_the_game</code> etc.. The declarations and definitions should probably have the same order as well, so people don't have to search when using a text editor (or GitHub raw code, yuck).</li>\n<li>Try and avoid readers to have to guess what e.g. <code>-10</code> means, a constant value could have been used.</li>\n<li><code>else continue</code> is completely unnecessary at the end of a code block within a loop - trust me, any loop will <code>continue</code> automatically; it's what they do.</li>\n<li>You could try and make a stream of positions instead of iterating over them all the time (this goes into lambda / functional territory though). This would also make sure that you don't get &quot;X-mas tree code blocks&quot; with many nested <code>for</code> and <code>if</code> statements.</li>\n<li>Closing parentheses should be followed by a space, e.g. <code>) {</code> instead of <code>){</code>, maybe put your code though <code>lint</code> or another formatter / static style analyzer.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:33:49.253", "Id": "528357", "Score": "0", "body": "_C++ code often differs from C by using capital letters instead of underscores to separate method names._ Some programmers like capital letters... if you read the C++ standard and its library, though, as well as the original (1980s) books, you'll see that it's orthodox to use lowercase and underscores. And, C++ doesn't have \"methods\". Those are not even member functions of a class, so calling them _methods_ is rather odd. (they are \"free functions\")" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:35:32.737", "Id": "528358", "Score": "0", "body": "Many reviewers will complain about using `ALL_CAPS` for symbol names, reserving their use for macros. I'm sure you were not advocating using `#define`, right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:54:24.337", "Id": "528359", "Score": "1", "body": "That's just my Java background leaking through :) I'll fix when I have the time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T06:45:25.810", "Id": "528408", "Score": "1", "body": "Good arguments in this review, but `C++ code often differs from C by using capital letters instead of underscores to separate ` is certainly not true. Lot's of programmers prefer snake case, have a look at the STL." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T13:42:16.803", "Id": "267921", "ParentId": "267916", "Score": "1" } }, { "body": "<pre><code>int possible_opponent(int row, int column, std::string opponent){\n</code></pre>\n<p>You're passing <code>opponent</code> by value, which duplicates the string. It's normal to pass strings by const reference, or better yet use a <code>string_view</code>.</p>\n<pre><code> std::string ori_position = board[row][column];\n board[row][column] = opponent;\n if (check_the_game() == &quot;X&quot;){\n board[row][column] = ori_position;\n return -10;\n }else {\n board[row][column] = ori_position;\n return 0;\n }\n}\n</code></pre>\n<p>So, you make a move, check the result, and then undo the move?<br />\nAt the very least, it's poor to duplicate the <code>board[row][column] = ori_position;</code> in both branches.</p>\n<p>If you make your board using byte-sized enumeration constants or characters rather than <code>string</code> objects for each cell, it becomes practical to copy the entire board state. In fact, a 9-byte board is smaller than a <code>string</code> instance! Making intermediate copies of the state is more normal for this kind of mini-maxi or speculative play algorithm.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:46:20.477", "Id": "267969", "ParentId": "267916", "Score": "0" } }, { "body": "<h2>Use another type for board representation</h2>\n<p>Maintaining an array of strings, constantly making comparisons and possibly copying it in a few places can get very expensive very fast, which makes representing the board internally using <code>std::string</code> inefficient.</p>\n<p>Using a plain <code>char</code> is more suitable, maybe even <a href=\"https://docs.microsoft.com/en-us/cpp/cpp/enumerations-cpp?view=msvc-160\" rel=\"nofollow noreferrer\">Enums</a> to map the characters to integral vales.</p>\n<h2>Use references</h2>\n<p>Prefer using <a href=\"https://en.cppreference.com/book/intro/reference\" rel=\"nofollow noreferrer\">references</a> over pointers when possible. Aside from looking cleaner syntactically, using a reference makes your intention clear. <a href=\"https://stackoverflow.com/questions/7058339/when-to-use-references-vs-pointers\">This</a> SO thread contains further discussion on this topic</p>\n<h2>More well-defined types</h2>\n<p>It seems to me that the code quality could largely benefit from defining proper types for a few things.</p>\n<p>A very simple example from your code is the way you define positions on the board.</p>\n<p>Even the ancient <code>struct Point {int x, y; }</code> with a few helper functions can make the code clearer, as you don't have to rely on passing around raw ints everywhere. The same applies to your board re-presentation. Have a look at object-oriented programming.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T07:15:08.087", "Id": "267986", "ParentId": "267916", "Score": "1" } }, { "body": "<p><strong>Code structure review</strong></p>\n<ol>\n<li><strong>It is C-style code</strong>. As you have added C++ tag, I assume you intend to write C++ code. Think from OOP point of view and abstractions will improve. Methods and signatures will improve and unnecessary passing of parameters will be avoided.</li>\n</ol>\n<pre><code>void choose_position(int position, std::string* current_player);\nvoid find_row_column(int position, int* row, int* column);\nvoid player_turn(std::string* current_player);\nstd::string computer_turn(std::string* current_player);\nstd::string predict_future(std::string* current_player);\nstd::string check_the_game();\nint possible_move(int* row, int* column, std::string* current_player, std::string* position);\nint move_left(int row, int column, std::string* current_player);\nint predict_opponent(int* row, int* col, std::string opponent, std::string* ori_position);\nint possible_opponent(int* row, int* column, std::string opponent);\n</code></pre>\n<ol start=\"2\">\n<li><p><strong>Board representation:</strong> Using 2D string array to represent board is not right choice. It is making code unnecessarily complex. Boolean array will be a better choice. For example function check_the_game is doing lots of string comparisons. With boolean array, it can be done using few AND operations. Return value of this function can be a int (or enum).</p>\n</li>\n<li><p><strong>Model and view should be separated.</strong> It will also allow you to bind any shape you want to use to represent icons for two player.</p>\n</li>\n<li><p><strong>Refs vs pointers</strong>: Code can be written with refs rather than pointers.</p>\n</li>\n<li><p><strong>Strings &quot;X&quot; and &quot;O&quot; is sprinkled throughout the code.</strong> It should be avoided.</p>\n</li>\n<li><p><strong>Random constants like -10, 10, 9, 1000 etc sprinkled throughout the code.</strong> It should be avoided.</p>\n</li>\n</ol>\n<p><strong>Summary:</strong> Rethink from OOP perspective. Separate model and view. Avoid random constants.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T21:08:40.953", "Id": "528503", "Score": "1", "body": "The board representation has at least three states: X played, O played, and free. So even without the free space numbering in the same data structure, an array of `bool` doesn't make sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T04:21:58.437", "Id": "528516", "Score": "0", "body": "@JDługosz: You are correct. Regular bool won't help as it can hold only two states. But we can use std optional<bool>. Or enum class will three values." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-16T04:04:26.000", "Id": "528560", "Score": "0", "body": "@nkvns Thank you for the review, this really is a good review. I appreciate it and will take the advice and suggestion. I just struggle on how to think in OOP way." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T16:00:04.253", "Id": "268003", "ParentId": "267916", "Score": "1" } } ]
{ "AcceptedAnswerId": "268003", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T12:16:01.643", "Id": "267916", "Score": "2", "Tags": [ "c++", "beginner", "tic-tac-toe" ], "Title": "My tic tac toe minimax implementation" }
267916
<p>I have been coding in Python for a number of years now. I've always felt that Matplotlib code takes up a lot more lines of code than it should. I could be wrong.</p> <p>I have the following function that plots a simple scatter plot graph with two additional solid lines. Is there any way for me to reduce the number of lines to achieve exactly the same outcome? I feel that my code is a little 'chunky'.</p> <p><code>dates</code> contains an array of DateTime values in the yyyy-mm-dd H-M-S format</p> <p><code>return_values</code> - array of floats</p> <p><code>main_label</code> - string</p> <pre><code>import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates %matplotlib inline plt.style.use('ggplot') def plot_returns(dates, return_values, ewma_values, main_label): plt.figure(figsize=(15, 10)) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m')) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=31)) plt.scatter(dates, return_values, linestyle = '-', color='blue', s = 3, label = &quot;Daily Returns&quot;) plt.plot(dates, ewma_values, linestyle = '-', color='green', label = &quot;EWMA&quot;) plt.gcf().autofmt_xdate() plt.xlabel('Day', fontsize = 14) plt.ylabel('Return', fontsize = 14) plt.title(main_label, fontsize=14) plt.legend(loc='upper right', facecolor='white', edgecolor='black', framealpha=1, ncol=1, fontsize=12) plt.xlim(left = min(dates)) plt.show() dates = pd.date_range(start = '1/1/2018', end = '10/10/2018') return_values = np.random.random(len(dates)) ewma_values = 0.5 + np.random.random(len(dates))*0.1 plot_returns(dates, return_values, ewma_values, &quot;Example&quot;) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T17:32:28.477", "Id": "528290", "Score": "1", "body": "It might be a good idea to include a little more code so people can run an analysis in their IDE. They should be able to reproduce what you're seeing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T19:32:53.843", "Id": "528381", "Score": "0", "body": "Thanks. I've added more code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T22:55:29.280", "Id": "528397", "Score": "0", "body": "Thanks, that runs. So, each of your statements does something specific to get the graph to draw. I don't find it too verbose compared to the example page https://matplotlib.org/2.0.2/users/screenshots.html given that you're drawing two graphs (scatter and line) on one plot. Is there something specific you want to highlight?" } ]
[ { "body": "<blockquote>\n<p>Is there any way for me to reduce the number of lines to achieve exactly the same outcome?</p>\n</blockquote>\n<p>should, in isolation, not be your overriding concern, and your code is about as minimally chunky as matplotlib will allow. Your current push - rather than to shed a line or two - should be to increase static testability, maintainability and structure. Said another way, this is not code golf, and not all short code is good code.</p>\n<p>To that end:</p>\n<ul>\n<li>Do not enforce a style in the global namespace - only call that from a routine in the application. What if someone else wants to import and reuse parts of your code?</li>\n<li>Add PEP484 type hints.</li>\n<li>Avoid calling <code>gca</code> and <code>gcf</code>. It's easy, and preferable, to have local references to your actual figure and axes upon creation, and to use methods bound to those specific objects instead of <code>plt</code>. Function calls via <code>plt</code> have more visual ambiguity, and need to infer the current figure and axes; being explicit is a better idea. On top of that, calls to <code>plt</code> are just wrappers to the bound instance methods anyway.</li>\n<li>Choose a consistent quote style. <code>black</code> prefers double quotes but I have a vendetta against <code>black</code> and personally prefer single quotes. It's up to you.</li>\n<li>Do not force a <code>show()</code> in the call to <code>plot_returns</code>, and return the generated <code>Figure</code> instead of <code>None</code>. This will improve reusability and testability.</li>\n<li>Do not use strings for internal date logic. Even if you had to use strings, prefer an unambiguous <code>YYYY-mm-dd</code> ISO format instead of yours.</li>\n<li><code>np.random.random</code> is <a href=\"https://numpy.org/doc/stable/reference/random/index.html\" rel=\"nofollow noreferrer\">deprecated</a>; use <code>default_rng()</code> instead.</li>\n</ul>\n<h2>Suggested</h2>\n<pre><code>from datetime import date\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nfrom matplotlib.figure import Figure\n\n\ndef plot_returns(\n dates: pd.DatetimeIndex,\n return_values: np.ndarray,\n ewma_values: np.ndarray,\n main_label: str,\n) -&gt; Figure:\n fig, ax = plt.subplots(figsize=(15, 10))\n\n ax.scatter(dates, return_values, linestyle='-', color='blue', s=3, label='Daily Returns')\n ax.plot(dates, ewma_values, linestyle='-', color='green', label='EWMA')\n\n fig.autofmt_xdate()\n \n ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))\n ax.xaxis.set_major_locator(mdates.DayLocator(interval=31))\n ax.set_xlabel('Day', fontsize=14)\n ax.set_ylabel('Return', fontsize=14)\n ax.set_title(main_label, fontsize=14)\n ax.legend(loc='upper right', facecolor='white', edgecolor='black', framealpha=1, ncol=1, fontsize=12)\n ax.set_xlim(left=min(dates))\n\n return fig\n\n\ndef main() -&gt; None:\n dates = pd.date_range(start=date(2018, 1, 1), end=date(2018, 10, 10))\n rand = np.random.default_rng()\n return_values = rand.random(len(dates))\n ewma_values = rand.uniform(low=0.5, high=0.6, size=len(dates))\n\n plt.style.use('ggplot')\n plot_returns(dates, return_values, ewma_values, 'Example')\n plt.show()\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n<p><a href=\"https://i.stack.imgur.com/0Hg8S.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/0Hg8S.png\" alt=\"screenshot of matplotlib\" /></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T16:20:48.307", "Id": "268005", "ParentId": "267917", "Score": "1" } } ]
{ "AcceptedAnswerId": "268005", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T12:41:42.690", "Id": "267917", "Score": "1", "Tags": [ "python", "matplotlib" ], "Title": "Plot a simple scatter plot graph with two additional solid lines" }
267917
<p>I've implemented a Game of Life in Clojure and would like to understand what I can do better, especially in terms of idiomatic Clojure (without losing readability/maintainability) of the current version.</p> <p>This is my first &quot;serious&quot; Clojure program (beyond hello world).</p> <p>Things that I'm specifically interested in:</p> <ul> <li>Anything that's not idiomatic and thus should be changed/improved.</li> <li>Whether P (Point) should be a record (<code>(defrecord Point [x y]) (defn P [x y] (Point. x y))</code>) instead.</li> </ul> <pre class="lang-clj prettyprint-override"><code>(ns com.nelkinda.game-of-life) (def rules { :survival #{2 3} :birth #{3} }) (defn P [x y] {:x x :y y}) (defn neighbors [cell] (def neighbors-of-origin #{(P -1 -1) (P -1 0) (P -1 1) (P 0 -1) (P 0 1) (P 1 -1) (P 1 0) (P 1 1)}) (defn plus [cell1 cell2] {:x (+ (:x cell1) (:x cell2)) :y (+ (:y cell1) (:y cell2))}) (map #(plus cell %) neighbors-of-origin)) (defn next-generation [life] (defn is-alive [cell] (contains? life cell)) (defn is-dead [cell] (not (is-alive cell))) (defn dead-neighbors [cell] (filter #(is-dead %) (neighbors cell))) (defn live-neighbors [cell] (filter #(is-alive %) (neighbors cell))) (defn count-live-neighbors [cell] (count (live-neighbors cell))) (defn born [cell rules] (contains? (:birth rules) (count-live-neighbors cell))) (defn survives [cell rules] (contains? (:survival rules) (count-live-neighbors cell))) (defn dead-neighbors-of-living-cells [] (mapcat #(dead-neighbors %) life)) (defn surviving-cells [] (filter #(survives % rules) life)) (defn born-cells [] (filter #(born % rules) (dead-neighbors-of-living-cells))) (into #{} (concat (surviving-cells) (born-cells)))) </code></pre> <p>Test Implementation:</p> <pre class="lang-clj prettyprint-override"><code>(use 'com.nelkinda.game-of-life) (use 'clojure.test) (def universe (atom #{})) (defn parse ([spec] (into #{} (parse (clojure.string/split spec #&quot;&quot;) 0 0 '()))) ([spec x y set] (case (first spec) &quot;.&quot; (parse (rest spec) (+ x 1) y set) &quot;*&quot; (parse (rest spec) (+ x 1) y (cons (P x y) set)) &quot;\n&quot; (parse (rest spec) 0 (+ y 1) set) (nil &quot;&quot;) set (throw (AssertionError. (str &quot;Wrong input: '&quot; (first spec) &quot;'&quot;)))))) (Given #&quot;the following universe:&quot; [spec] (reset! universe (parse spec))) (Then #&quot;the next generation MUST be:&quot; [spec] (assert (= (reset! universe (next-generation @universe)) (parse spec)))) </code></pre> <p>Test Specification:</p> <pre><code>Feature: Conway's Game of Life Rules of Conway's Game of Life &gt; The universe of the _Game of Life_ is an infinite, two-dimensional orthogonal grid of square cells. &gt; Each cell is in one of two possible states: &gt; * Alive aka populated &gt; * Dead aka unpopulated &gt; &gt; Every cell interacts with its eight neighbors. &gt; The neighbors are the cells that are horizontally, vertically, or diagonally adjacent. &gt; At each step in time, the following transitions occur: &gt; 1. Underpopulation: Any live cell with fewer than 2 live neighbors dies. &gt; 1. Survival: Any live cell with 2 or 3 live neighbors survives on to the next generation. &gt; 1. Overpopulation Any live cell with more than 3 live neighbors dies. &gt; 1. Reproduction (birth): Any dead cell with exactly 3 live neighbors becomes a live cell. Scenario: Empty universe Given the following universe: &quot;&quot;&quot; &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; &quot;&quot;&quot; Scenario: Single cell universe Given the following universe: &quot;&quot;&quot; * &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; &quot;&quot;&quot; Scenario: Block Given the following universe: &quot;&quot;&quot; ** ** &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; ** ** &quot;&quot;&quot; Scenario: Blinker Given the following universe: &quot;&quot;&quot; .* .* .* &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; *** &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; .* .* .* &quot;&quot;&quot; Scenario: Glider Given the following universe: &quot;&quot;&quot; .* ..* *** &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; *.* .** .* &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; ..* *.* .** &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; .* ..** .** &quot;&quot;&quot; Then the next generation MUST be: &quot;&quot;&quot; ..* ...* .*** &quot;&quot;&quot; </code></pre> <p>Repository URL in case you want to clone it yourself: <a href="https://github.com/nelkinda/gameoflife-clojure" rel="nofollow noreferrer">https://github.com/nelkinda/gameoflife-clojure</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T13:52:17.863", "Id": "267922", "Score": "3", "Tags": [ "clojure", "game-of-life" ], "Title": "Game of Life in Clojure" }
267922
<p>I'm new to writing benchmarks and would like some advice whether I am doing this correctly.</p> <p>I currently have two classes: <code>Person.java</code> and <code>PersonFinaliser.java</code> which each have a single field <code>age</code>. The only difference is that <code>PersonFinaliser.java</code> has a <code>finalizer()</code> method.</p> <p>I am trying to measure the perfomance difference between creating objects from classes with and without <code>finalize()</code> overidden. I know it has been deprecated since Java 9, but I am testing a number of optimisation techniques as part of my dissertation.</p> <pre class="lang-java prettyprint-override"><code>public class Person { private int age; public Person(int age) { this.age = age; } } </code></pre> <pre class="lang-java prettyprint-override"><code>public class PersonFinaliser { private int age; public PersonFinaliser(int age) { this.age = age; } @Override protected void finalize() throws Throwable { age++; } } </code></pre> <pre class="lang-java prettyprint-override"><code>@Fork(warmups = 5, value = 5) @BenchmarkMode(Mode.SingleShotTime) @Warmup(iterations = 10, batchSize = 5000) @Measurement(iterations = 10, batchSize = 5000) @OutputTimeUnit(TimeUnit.MILLISECONDS) public class FinaliserBenchmark { @State(Scope.Benchmark) public static class BenchmarkState { int age = 18; } @Benchmark public Person personBenchmark(BenchmarkState state) { return new Person(state.age); } @Benchmark public PersonFinaliser personFinaliserBenchmark(BenchmarkState state) { return new PersonFinaliser(state.age); } } </code></pre> <p>The output I'm getting seems to be what I expect, with low error margins.</p> <pre><code>Benchmark Mode Cnt Score Error Units FinaliserBenchmark.personBenchmark ss 50 0.210 ± 0.060 ms/op FinaliserBenchmark.personFinaliserBenchmark ss 50 0.852 ± 0.074 ms/op </code></pre> <p>Have I done this correctly or is there a better way to perform this benchmark? Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T19:04:12.713", "Id": "528547", "Score": "0", "body": "According to https://github.com/openjdk/jmh/blob/99e9c19c80a0133c28f6532ef2b5776d5b8bd023/jmh-core/src/main/java/org/openjdk/jmh/annotations/Mode.java#L65 `Mode.SingleShotTime` estimates the \"cold\" performance. For you to decide if this is something you want to account for." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:22:54.460", "Id": "267924", "Score": "2", "Tags": [ "java", "performance", "benchmarking" ], "Title": "Measuring Performance of Class Instantiation with JMH" }
267924
<p>I just have the free account at leetcode. I've been practicing some coding there in preparation for interviews. But I can't see the solution logic behind the <code>IntegerToRoman</code> conversion function. I solved both the leetcode Roman Numbers problems (Arabic -&gt; roman, and roman -&gt; Arabic). I made a solution of my own but its slower than most accepted leetcode solutions.</p> <p>I would appreciate any feedback code review-wise on the solutions but the main goal is to make them faster somehow. Especially the <code>IntToRoman</code> seemed trickier when I got to coding it. The <code>RomanToInt</code> was tricky as well, but when I realized the reversal it seemed OK. I started to code it with a stack originally instead of the oldval, but variable is enough and stack isn't needed as such.</p> <p>The main code:</p> <pre><code>int fasterRomanToInt(std::string s) { int romanSum{ 0 }; if (s.size() == 1) { return oneSizeRomans(s[0]); } else { int oldval = 0; int i = s.length() - 1; while (i &gt;= 0) { char current = s[i]; int curval = oneSizeRomans(current); if (curval &gt;= oldval) { romanSum += curval; } else { romanSum -= curval; } oldval = curval; --i; } return romanSum; } } std::string intToRoman(int num) { std::map&lt;int, std::string&gt; ArabicvalueToRomans { {1000, &quot;M&quot;}, {900, &quot;CM&quot;}, {500, &quot;D&quot;}, {400, &quot;CD&quot;}, {100, &quot;C&quot;}, {90, &quot;XC&quot;}, {50, &quot;L&quot;}, {40, &quot;XL&quot;}, {10, &quot;X&quot;}, {9, &quot;IX&quot;}, {8, &quot;VIII&quot;}, {7, &quot;VII&quot;}, {6, &quot;VI&quot;}, {5, &quot;V&quot;}, {4, &quot;IV&quot;}, {3, &quot;III&quot;}, {2, &quot;II&quot;}, {1, &quot;I&quot;} }; std::vector&lt;int&gt; romanSpecials{ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 8,7,6,5,4,3,2,1 }; int arabic = num; std::string result = &quot;&quot;; while (arabic &gt; 0) { int d = seekLargestPossible(romanSpecials, arabic); int r = arabic % d; std::string characters = processToRoman(d, ArabicvalueToRomans); arabic -= d; result += characters; } return result; } </code></pre> <p>Here's a couple helper functions for <code>intToRoman</code>:</p> <pre><code>int seekLargestPossible(std::vector&lt;int&gt;&amp; vecRef, int a) { // input bigger than biggest divisor so use 1000 if (a &gt;= 1000) { return 1000; } // seek the biggest divisor that is smallerorequal than the A inputvalue for (auto iter = vecRef.begin(); iter != vecRef.end(); iter++) { auto key = *(iter); if (key &lt;= a) { return key; } } throw &quot;something went bad in seekLargestPossible&quot;; } std::string processToRoman(int value, std::map&lt;int, std::string&gt;&amp; mapRef) { // if cannot access romanstr in map with key, throws which is good // shuldnt be happening tho std::string s = mapRef.at(value); return s; } </code></pre> <p>And here's a helper function for <code>RomanToInt</code>:</p> <pre><code>int oneSizeRomans(char c) { /* I 1 V 5 X 10 L 50 C 100 D 500 M 1000*/ switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C':return 100; case 'D':return 500; case 'M':return 1000; default: throw &quot;bad things one size romans func&quot;; break; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T13:58:05.187", "Id": "528353", "Score": "0", "body": "`std::map` is slow unless your benchmark shows it to be faster than say `std::vector`. Only ever use it where it performs better, or when it makes code simpler but the performance hit doesn't matter much. For small maps that would fit into a couple of cache lines if they were a vector, the vector always wins: less page misses, less data cache misses, less code cache misses since the code is smaller, less branch mispredictions." } ]
[ { "body": "<pre><code>if (s.size() == 1)\n{\n return oneSizeRomans(s[0]);\n}\n</code></pre>\n<p>There is nothing special with a size of 1. Yes, you can return early of course, but <em>all the other values</em> will have to go through this spurious <code>if</code> statement as well.</p>\n<p>If well programmed you could even get away with a length of <em>zero</em> (hint)!</p>\n<hr />\n<pre><code>int i = s.length() - 1;\nwhile (i &gt;= 0)\n</code></pre>\n<p>What's wrong with a <code>for</code> loop? I'm not sure if this makes any difference when a smart compiler handles things, but I am pretty sure that the <code>for</code> won't be <em>slower</em>.</p>\n<hr />\n<pre><code>int curval = oneSizeRomans(current);\n</code></pre>\n<p>Note that calling methods always has a performance penalty. You could use a macro or inline call instead. Or you could actually inline the code.</p>\n<hr />\n<pre><code>return romanSum;\n</code></pre>\n<p>Well, for a performance race this is fine, but this will definitely allow invalid roman numerals. If I would see this code in a library I would certainly reprimand the person who wrote the function. Even in a race, I would definitely like invalid Roman values such as <code>&quot;IC&quot;</code> to be rejected; otherwise testing for those would take any performance advantage.</p>\n<p>One ugly trick is to re-encode the resulting integer and then compare. In that case you will always have a valid input string. Yes, this does imply a performance penalty, but one that is necessary.</p>\n<hr />\n<pre><code>std::string intToRoman(int num)\n</code></pre>\n<p>You are recreating a <code>Map</code> <em>and</em> a <code>Vector</code> within a function. I definitely hope your compiler saves you from this, but I honestly don't think so. <em>Do you notice that these will never change between function calls?</em></p>\n<p>Personally I would be vary wary of using <em>any</em> kind of collections. I can easily program this <em>by using a single character array</em>, no higher level collections whatsoever. Even just calculating the hash value for the map is going to <em>kill</em> performance. It may well take more time than the whole conversion in the first place!</p>\n<p>Note that performing calculations on current CPU's is blistering fast. De-referencing data structures generally is <em>not</em> that fast.</p>\n<hr />\n<pre><code>std::string s = mapRef.at(value);\n</code></pre>\n<p>Definitely can do without a method surrounding it.</p>\n<hr />\n<pre><code> int oneSizeRomans(char c)\n</code></pre>\n<p>Alright, but that comment is really not necessary. You need comments in case it is not clear <em>what</em> the code is doing or <em>how it is doing that</em>. Neither do apply here.</p>\n<h2>Hints</h2>\n<p>All in all, try to code this using <strong>just one array containing the roman literals</strong>. You will be surprised how fast you can search through a tiny array of just 7 elements using a simple <code>for</code> loop.</p>\n<hr />\n<p>In Java, which is particularly C-like, I could do:</p>\n<pre class=\"lang-java prettyprint-override\"><code>int toValue(char numeral) {\n int value = 1;\n for (int i = 0; i &lt; NUMERALS.length; i++) {\n if (NUMERALS[i] == numeral) {\n return value;\n }\n value = value * (i % 2 == 0 ? 5 : 2);\n }\n return 0;\n}\n</code></pre>\n<p>You can of course optimize away the <code>?</code>, this is a useful exercise in itself. Processors are even less fond of branching than of de-referencing.</p>\n<hr />\n<p>You may use the values <code>0</code> to <code>9</code> in a switch / case statement for fast encoding to Roman literals.</p>\n<hr />\n<p>Pre-calculate <em>anything</em> you can before going into the functions</p>\n<hr />\n<p>Please make sure your code rejects incorrect values: correctness should always trump performance!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T18:43:21.953", "Id": "528293", "Score": "1", "body": "Yes I forgot to tell but it actually said in the leetcode problem originally that input validation as such wasnt required for roman number converting (it was assumed to be correctly formed inputs). For RomanStr-> int input was said to be (s is a valid roman numeral in the range [1, 3999].). but Definitely the correctness in terms of validation could be improved. For the case of IntToRoman, the input was said to be 1 <= num <= 3999" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T18:45:07.897", "Id": "528294", "Score": "0", "body": "Alright. Please check if you have any questions about my answer, I won't have much time tomorrow. Main issue is of course `intToRoman`, I expect that this has the most problems w.r.t. speed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T18:47:29.457", "Id": "528296", "Score": "0", "body": "Writing library quality code would of course be very commendable in leetcode I have to admit. Sometimes well voted solutions on codewars look like that could be it. But rarely is there much input validation in these kind of small problems" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T18:51:33.027", "Id": "528297", "Score": "0", "body": "Well, I can remember that I got exactly this assignment in my first year at uni, a long time ago. I'm pretty sure that they only looked at these kind of things, not performance. Took some time to get used to everything back then. Now I can program this just in half an hour. I surprised the teaching assistant with my check that simply computed the roman numerals again, but it was accepted." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T19:27:26.413", "Id": "528299", "Score": "0", "body": "yea that romanSpecials I made it to constexpr int array inside seekLargestPossible. And removed the map thing and vector thing. processToRoman could be converted easily to switch case which probably would make it faster. Process to roman could be refactored a bit so it doesnt return a new string by value... I gota admit its been a while since I did the whole char arrays thing back in C. It would take careful attention to make everything use char arrays again rather than c++ string (I suspect that c++ string usage it the main problem now)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T17:06:45.303", "Id": "267928", "ParentId": "267925", "Score": "2" } }, { "body": "<p>Adding to Maarten Bodewes' answer:</p>\n<h1>Prefer range-<code>for</code> where possible</h1>\n<p>In <code>seekLargestPossible()</code>, you can replace the <code>for</code>-loop with this one:</p>\n<pre><code>for (auto&amp; key: vecRef)\n{\n if (key &lt;= a)\n return key;\n}\n</code></pre>\n<h1>Naming things</h1>\n<p>Avoid naming things after their type, instead always try to give them a name that describes what they represent. For example, <code>vecRef</code> and <code>mapRef</code> are bad names; that just repeats their type, but doesn't tell you anything about what's in the vector or map their are referencing. For <code>vecRef</code> for example, you could use <code>romanSpecials</code> as the name as that's what you are seeking in, or if you want to keep it more generic, then I suggest <code>values</code>, as <code>vecRef</code> just references a collection of values.</p>\n<h1>Make use of STL algorithms</h1>\n<p>The standard library comes with lots of <a href=\"https://en.cppreference.com/w/cpp/algorithm\" rel=\"nofollow noreferrer\">algorithms</a> that you can use instead of writing your own. For example, <code>seekLargestPossible()</code> could be replaced with a call to <a href=\"https://en.cppreference.com/w/cpp/algorithm/lower_bound\" rel=\"nofollow noreferrer\"><code>std::lower_bound()</code></a>:</p>\n<pre><code>int d = arabic &gt;= 1000 ? 1000 : *std::lower_bound(romanSpecials.begin(), romanSpecials.end(), arabic, std::greater&lt;int&gt;());\n</code></pre>\n<p>Although it is perhaps overkill here.</p>\n<h1>Avoid writing unnecessary code</h1>\n<p>The function <code>processToRoman</code> is not very useful. You can write the following directly inside <code>intToRoman()</code>:</p>\n<pre><code>std::string characters = ArabicValueToRomans.at(d);\n</code></pre>\n<h1>Be consistent</h1>\n<p>Why do you have a <code>std::map</code> to go from values to roman numerals, but have a function with a <code>switch</code>-statement to go from roman numerals to values? You can use the same technique for both directions.</p>\n<h1>Don't <code>throw</code> raw strings</h1>\n<p>Instead of just <code>throw</code>ing a string when something goes wrong, I strongly recommend that you throw one of the <a href=\"https://en.cppreference.com/w/cpp/header/stdexcept\" rel=\"nofollow noreferrer\">standard exception types</a> instead, or possibly create your own exception class that derives from one of the standard types. It's quite simple to use them:</p>\n<pre><code>#include &lt;stdexcept&gt;\n...\nint seekLargestPossible(...)\n{\n ...\n throw std::logic_error(&quot;Could not find largest possible roman numeral&quot;);\n}\n</code></pre>\n<p>The type adds more information about the kind of error, and this allows the caller to distinguish between different errors by using different <a href=\"https://en.cppreference.com/w/cpp/language/try_catch\" rel=\"nofollow noreferrer\"><code>catch</code></a> statements.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T21:09:15.917", "Id": "528302", "Score": "0", "body": "yea I think sometimes you get unlucky on the execution speed at leetcode(???). Like I managed to find the C++ solution for one guy from the discussions page and it didnt really run as fast as he claimed, consistently. It would be intersting to see solution without any cpp strings except the return value when it gets returned as std::string the romanStr. They way I coded the solution was that first I scribbled a bit on paper and then started coding it. I didnt prove how to solve it like mathematical proof or anything like that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T21:11:24.400", "Id": "528303", "Score": "1", "body": "I suspect that char array use and consexpr arrays (esp the romanSpecials style) if necessary would be useful." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T20:48:54.367", "Id": "267931", "ParentId": "267925", "Score": "1" } }, { "body": "<h2>Performance</h2>\n<p>Performance code is not always good code.</p>\n<p>Improving performance can also make the code more complex and thus harder to maintain. One must balance ones experience against the need for performance.</p>\n<h2>Roman To Int</h2>\n<p>In this example we can combine the data (Roman numerals) with the code creating a function that reads the characters one by one and contains all the roman characters as part of the code. This lets use conditional search roman numerals depending on the one we have just encountered.</p>\n<p>We also know that only <code>M</code> <code>C</code> and <code>X</code> will be repeated so we check for repeats only after finding one of them.</p>\n<p>Tracking the string read position can also be ignored when the remaining value is &lt;= 9 (&lt;= IX). That means we do lose track of just how many digits are read, but I don't see that is a requirement in this case.</p>\n<h2>Example 2</h2>\n<p>The result is not pretty</p>\n<p>Be careful with the pointer to i</p>\n<pre><code>unsigned romanValueAt(unsigned *i, std::string s) {\n unsigned val;\n switch (s[(*i)++]) {\n case 'D': return 500;\n case 'L': return 50;\n case 'I':\n switch (s[(*i)++]) {\n case 'X': return 9;\n case 'V': return 4;\n case 'I': \n if (s[(*i)++] == 'I') { return 3; }\n else { return 2; }\n default: { return 1; } \n }\n case 'V': {\n if (s[(*i)++] == 'I') {\n if (s[(*i)++] == 'I') {\n if (s[(*i)++] != 'I') { return 7; } /* Warning i could be past\n return 8; end of string */\n } \n return 6;\n } \n return 5;\n }\n case 'M': {\n val = 1000;\n while (s[(*i)++] == 'M') { val += 1000; }\n (*i)--;\n return val;\n }\n case 'C':\n switch (s[*i]) {\n case 'M': { (*i)++; return 900; }\n case 'D': { (*i)++; return 400; }\n default: {\n val = 100;\n while (s[(*i)++] == 'C') { val += 100; }\n (*i)--;\n return val;\n }\n }\n case 'X':\n switch (s[*i]) {\n case 'C': { (*i)++; return 90; }\n case 'L': { (*i)++; return 40; }\n default: {\n val = 10;\n while (s[(*i)++] == 'X') { val += 10; }\n (*i)--;\n return val;\n } \n }\n }\n return 0;\n}\nunsigned romanToUint(std::string roman) {\n unsigned value = 0, i = 0, len = roman.length();\n while (i &lt; len) { value += romanValueAt(&amp;i, roman); }\n return value;\n}\n</code></pre>\n<h2>Int to Roman</h2>\n<p>Converting from number to roman also has some room for optimizations.</p>\n<h3><code>log10</code> to count digits</h3>\n<p>We can use the 'log10' of a number to quickly know how many digits it contains, That means we don't need to wast time checking the value against higher values than needed.</p>\n<h3>Divide for sequences</h3>\n<p>For the sequences eg <code>XXX</code> or <code>MMXXX</code> we can also do them in one step if we divide by the roman value we get the number of repeats. EG 3992 / 1000 = 3 (as int) which is the number of <code>M</code> it contains <code>MMMCMXCII</code></p>\n<h3>Use hash map for large data sets</h3>\n<p>Avoid using <code>map</code> as each time you lookup an item it needs to run a hash function and for small maps the overhead outweighs any time complexity gain.</p>\n<h3>Example 2</h3>\n<p>In this case you only need to iterate at max 9 values, everything else is just direct array indexing. Values under 10 are looked up directly.</p>\n<pre><code>#include &lt;math.h&gt; \nstd::string UintToRoman(unsigned value) {\n const std::string digits[9] = {&quot;I&quot;, &quot;II&quot;, &quot;III&quot;, &quot;IV&quot;, &quot;V&quot;, &quot;VI&quot;, &quot;VII&quot;, &quot;VIII&quot;, &quot;IX&quot;};\n const std::string copies[9][2] = {{&quot;MM&quot;, &quot;MMM&quot;},{},{},{},{&quot;CC&quot;,&quot;CCC&quot;},{},{},{},{&quot;XX&quot;,&quot;XXX&quot;}};\n const std::string romB[9] = {&quot;M&quot;, &quot;CM&quot;, &quot;D&quot;, &quot;CD&quot;, &quot;C&quot;, &quot;XC&quot;, &quot;L&quot;, &quot;XL&quot;, &quot;X&quot;};\n const unsigned rom[9] = {1000, 900, 500, 400, 100, 90, 50, 40, 10};\n const unsigned starts[4] = {9, 5, 1, 0}; \n \n std::string res = &quot;&quot;;\n unsigned i = starts[(unsigned) log10((double) value)];\n while (i &lt; 9 &amp;&amp; value &gt;= 10) {\n const unsigned v = rom[i];\n if (value &gt;= v) {\n const int c = value / v;\n value -= c * v;\n res += c == 1 ? romB[i] : copies[i][c - 2];\n }\n i++;\n }\n return value &gt; 0 ? res + digits[value - 1] : res;\n}\n</code></pre>\n<h2>Improvements</h2>\n<p>Do the above example provide an performance benefit. I am unsure as I am not a member of leetcode so have no environment to compare against.</p>\n<p>There are also many more ways to improve the examples.</p>\n<h2>Constraints</h2>\n<p>Roman numerals have a very limited range 1 to 3999. The examples give in the answer are only valid to this range.</p>\n<p>It is assumed inputs are correctly formatted and within range.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T07:18:30.967", "Id": "267950", "ParentId": "267925", "Score": "-1" } }, { "body": "<p>A couple of minor things that haven't been pointed out explicitly elsewhere:</p>\n<h2>copying strings is slow</h2>\n<p><code>int fasterRomanToInt(std::string s)</code> This copies a string.</p>\n<p>It's possible that the string is short enough that this copy doesn't involve memory allocation. It's also possible that we're moving from the input string, so that it becomes just a copy of a pointer and size. But we can't count on either of those things.</p>\n<p>So we should pass the <code>std::string</code> by reference, or instead pass a <code>std::string_view</code> (effectively just a pointer and a size) by value:</p>\n<pre><code>int fasterRomanToInt(std::string const&amp; s)\nint fasterRomanToInt(std::string_view sv)\n</code></pre>\n<p>Note that you can change the function signature in LeetCode's <code>class Solution</code> too!</p>\n<hr />\n<h2>use (reverse) iterators for iteration:</h2>\n<p>The overall algorithm for <code>romanToInt</code> looks decent, but it could be presented more neatly.</p>\n<p>For example, we can iterate backwards through a <code>std::string</code> (or <code>std::string_view</code>) using reverse iterators:</p>\n<pre><code>constexpr int roman_to_int(std::string_view sv)\n{\n auto total = 0;\n auto prev = 0;\n \n for (auto c = sv.rbegin(); c != sv.rend(); ++c)\n {\n auto value = get_roman_value(*c); // switch statement...\n total += (value &gt;= prev) ? value : -value;\n prev = value;\n }\n \n return total;\n}\n</code></pre>\n<hr />\n<h2>avoid extra work:</h2>\n<pre><code>while (arabic &gt; 0)\n{\n int d = seekLargestPossible(romanSpecials, arabic);\n int r = arabic % d;\n std::string characters = processToRoman(d, ArabicvalueToRomans);\n arabic -= d;\n result += characters;\n}\n</code></pre>\n<p><code>seekLargestPossible</code> searches the entire map every loop. Note that once we've dealt with the largest value, the next one must be equal or smaller, so we can search a smaller subset.</p>\n<p><code>r</code> appears to be unused! (I'm guessing you were going to create a repeating string where necessary - note however, that only 1 values are repeated, and only up to 3 times, so perhaps there's not much point in doing an extra division, compared to simply continuing with the loop).</p>\n<h2>write the simplest possible code first:</h2>\n<p>Given the very restricted set of inputs, and the fact that the next number we deal with is always smaller, we could write everything out long-hand:</p>\n<pre><code>std::string int_to_roman(int num)\n{\n assert(num &gt; 0);\n assert(num &lt;= 3999);\n \n auto out = std::string();\n \n for (; num &gt;= 1000; num -= 1000) { out += 'M'; }\n \n if (num &gt;= 900) { num -= 900; out += &quot;CM&quot;; }\n if (num &gt;= 500) { num -= 500; out += 'D'; }\n if (num &gt;= 400) { num -= 400; out += &quot;CD&quot;; }\n for (; num &gt;= 100; num -= 100) { out += 'C'; }\n \n if (num &gt;= 90) { num -= 90; out += &quot;XC&quot;; }\n if (num &gt;= 50) { num -= 50; out += 'L'; }\n if (num &gt;= 40) { num -= 40; out += &quot;XL&quot;; }\n for (; num &gt;= 10; num -= 10) { out += 'X'; }\n \n if (num &gt;= 9) { num -= 9; out += &quot;IX&quot;; }\n if (num &gt;= 5) { num -= 5; out += 'V'; }\n if (num &gt;= 4) { num -= 4; out += &quot;IV&quot;; }\n for (; num &gt;= 1; num -= 1) { out += 'I'; }\n \n return out;\n}\n</code></pre>\n<p>And... this is probably fast enough (&quot;0ms&quot; according to leetcode)! We could of course factor out the obvious grouping pattern of N * (9, 5, 4, 1), but there's not really any need (and we actually have to be careful to avoid making it slower).</p>\n<p>Another (perhaps even simpler) approach is to notice that we're still dealing with a decimal system, and we don't have to care at all about the logic of how the characters are calculated! We can get them directly from a size-10 lookup table:</p>\n<pre><code>using chars_t = std::array&lt;std::string_view, 10&gt;;\nauto static constexpr thousands = chars_t{ &quot;M&quot;, &quot;MM&quot;, &quot;MMM&quot;, &quot;_&quot;, &quot;_&quot;, &quot;_&quot;, &quot;_&quot;, &quot;_&quot;, &quot;_&quot; };\nauto static constexpr hundreds = chars_t{ &quot;C&quot;, &quot;CC&quot;, &quot;CCC&quot;, &quot;CD&quot;, &quot;D&quot;, &quot;DC&quot;, &quot;DCC&quot;, &quot;DCCC&quot;, &quot;CM&quot; };\nauto static constexpr tens = chars_t{ &quot;X&quot;, &quot;XX&quot;, &quot;XXX&quot;, &quot;XL&quot;, &quot;L&quot;, &quot;LX&quot;, &quot;LXX&quot;, &quot;LXXX&quot;, &quot;XC&quot; };\nauto static constexpr ones = chars_t{ &quot;I&quot;, &quot;II&quot;, &quot;III&quot;, &quot;IV&quot;, &quot;V&quot;, &quot;VI&quot;, &quot;VII&quot;, &quot;VIII&quot;, &quot;IX&quot; };\n\nstd::string int_to_roman(int num)\n{\n assert(num &gt;= 1);\n assert(num &lt;= 3999);\n \n auto out = std::string();\n \n if (num &gt;= 1000) { auto const index = num / 1000; num -= index * 1000; out += thousands[index-1]; }\n if (num &gt;= 100) { auto const index = num / 100; num -= index * 100; out += hundreds[index-1]; }\n if (num &gt;= 10) { auto const index = num / 10; num -= index * 10; out += tens[index-1]; }\n if (num &gt;= 1) { auto const index = num / 1; num -= index * 1; out += ones[index-1]; }\n \n return out;\n}\n</code></pre>\n<p>Again, this is super fast (I suspect faster).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T12:42:54.167", "Id": "267960", "ParentId": "267925", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T15:28:01.290", "Id": "267925", "Score": "2", "Tags": [ "c++", "performance", "roman-numerals" ], "Title": "Improving speed and simplify code of \"leetcode\" Roman Numbers converter" }
267925
<p>Originally written in C (which was abysmal, you may check <a href="https://pastebin.com/QP8D3rFt" rel="nofollow noreferrer">here</a> if you want), I rewrote my simple credit card validation program using Python</p> <pre><code>def main(): # Prompts user for card number nums = int(input(&quot;Number: &quot;)) if len(str(nums)) &gt; 16 or len(str(nums)) &lt; 12: print(&quot;INVALID&quot;) else: card_classify(card_luhn(nums), nums) # Luhn's Algorithm def card_luhn(nums): tmp = str(nums) digit_sum = 0 # Loops through the digits that needs to be multiplied by 2 for i in range(2, len(tmp) + 1, 2): digits = 2 * int(tmp[-i]) # Condition if resulting product has 2 digits if_sum = 0 if len(str(digits)) == 2: for digit in str(digits): if_sum += int(digit) digits = 0 if_sum += digits digit_sum += if_sum # Loops through the digits that does not need to be multiplied by 2 for i in range(1, len(tmp) + 1, 2): digits = int(tmp[-i]) digit_sum += digits if digit_sum % 10 == 0: return 0 else: return 1 # Classifies the card whether AMEX, VISA, or MASTERCARD def card_classify(check, nums): num = int(str(nums)[:2]) if check != 0: print(&quot;INVALID&quot;) # AMEX condition (first two digits from left are either 37 or 34) elif num == 37 or num == 34: print(&quot;AMEX&quot;) # VISA condition (first digit from left is 4) elif str(num)[:1] == &quot;4&quot;: print(&quot;VISA&quot;) # MASTERCARD condition (first two digits from left are between 50 and 56) elif num &gt; 50 and num &lt; 56: print(&quot;MASTERCARD&quot;) else: print(&quot;INVALID&quot;) if __name__ == &quot;__main__&quot;: main() </code></pre> <p>Could someone please review my code if it follows good practice and style? I want to be more Pythonic as I continue to learn.</p> <p>I also think that my implementation of Luhn's Algorithm could be improved, considering I looped over the card number twice.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T14:58:02.097", "Id": "528446", "Score": "0", "body": "Suggested reading: https://codereview.stackexchange.com/questions/256078/how-can-i-shorten-this-program-using-luhns-algorithm-to-check-credit-card-numbe" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T19:55:53.313", "Id": "528493", "Score": "0", "body": "@Reinderien I see that you have no `main()` function in your implementation. Coming from C, I still find it hard not to put one. What, in your opinion, is more Pythonic? Or does that not matter at all (i.e. does not affect performance and readability)?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T20:08:28.610", "Id": "528497", "Score": "0", "body": "It's a better idea to have a `main`, to promote code reusability and keep the global namespace clean. So that answer from February was a little hasty and should ideally have one." } ]
[ { "body": "<h1>Getting the First 2 Digits of a Number</h1>\n<p>A solution for this in constant space and time is already documented in <a href=\"https://stackoverflow.com/a/48716024/7867968\">this answer</a>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from math import log10\n\n# go from this\nnum = int(str(nums)[:2])\n\n# to this\ndef leading_digits(num):\n return num // 10 ** (int(math.log10(num)) - 1)\n</code></pre>\n<p>And checking for a type of card lends itself to using a dictionary</p>\n<h1>Credit Card Types</h1>\n<p>Replace your <code>if</code>/<code>elif</code> statements with a dictionary:</p>\n<pre class=\"lang-py prettyprint-override\"><code>card_types = {\n 37: 'AMEX',\n 34: 'AMEX',\n}\n\ncard_types.update({i: 'MASTERCARD' for i in range(51, 56)})\n# these all start with 4\ncard_types.update({i: 'VISA' for i in range(40, 50)})\n\ntry:\n card_type = card_types[leading_digits(num)]\nexcept KeyError:\n print(&quot;Invalid card type!&quot;)\n</code></pre>\n<h1><code>card_luhn</code></h1>\n<p>I don't think this is a good name for this function. I think it's better as\n<code>is_valid_card</code>, which implies returning a boolean, which is technically being\ndone here. I'd change the <code>return</code> to more explicitly be either <code>True</code> or <code>False</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code># instead of this\nif digit_sum % 10 == 0:\n return 0\nelse:\n return 1\n\n\n# do this\nreturn bool(digit_sum % 10)\n</code></pre>\n<h1>Checking for Two-Digit Numbers</h1>\n<p>You already know what the 2-digit numbers are, they are all in the range 10 &lt;= x &lt;= 99. So a comparison test here is the answer:</p>\n<pre class=\"lang-py prettyprint-override\"><code># go from this\nif len(str(digits)) == 2:\n\n# to this\nif 9 &lt; digits &lt; 100:\n</code></pre>\n<h1>Determining the Number of Digits in an Integer</h1>\n<p><a href=\"https://stackoverflow.com/a/2189827/7867968\">Here</a> is a good answer for that. It avoids casting to string unnecessarily</p>\n<h1>Getting each digit in a number</h1>\n<p>Using the previous point, we can construct a function that will give us each digit in the number provided:</p>\n<pre class=\"lang-py prettyprint-override\"><code>from math import log10, ceil\n\n\ndef get_digits(number):\n if not number:\n yield 0\n return\n elif number &lt; 0:\n # for a solution that processes negative numbers\n # however, for your case, it might be better to\n # raise a ValueError here\n number *= -1\n\n num_digits = ceil(log10(number))\n\n for _ in range(num_digits):\n digit = (number % 10)\n\n yield digit\n\n number //= 10\n\n</code></pre>\n<p>This has a few benefits:</p>\n<ol>\n<li>You aren't casting to string, avoiding unnecessary overhead</li>\n<li>This gives you the digits in the order you want (right to left)</li>\n<li>No more index lookups</li>\n</ol>\n<p>We can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>itertools.islice</code></a> to get an iterator from digit 2 onward in steps of 2:</p>\n<pre class=\"lang-py prettyprint-override\"><code># go from this:\nfor i in range(2, len(tmp) + 1, 2):\n\n# to this\n# islice takes arguments:\n# iterator, start, stop, step\nfor digit in islice(get_digits(nums), 2, None, 2):\n\n</code></pre>\n<p>Unfortunately, <code>islice</code> doesn't take keyword arguments, so a comment might be useful to remind yourself what the arguments are\nThis same snippet can be used on the odd digits as well.</p>\n<h1>Looping once</h1>\n<p>As you mentioned, you only need to iterate once over the digits, and you can use <code>enumerate</code> to track if you're on an even or odd index:</p>\n<pre class=\"lang-py prettyprint-override\"><code>digits_iter = islice(get_digits(card_number), 1, None)\n\nfor i, digit in enumerate(digits_iter, start=1):\n if i % 2:\n # odd\n else:\n # even\n</code></pre>\n<h1>Refactoring <code>card_luhn</code></h1>\n<pre class=\"lang-py prettyprint-override\"><code>from math import log10, ceil\nfrom itertools import islice\nfrom typing import Iterator\n\n\ndef get_digits(number: int) -&gt; Iterator[int]:\n &quot;&quot;&quot;Yields the digits of an integer from right to left&quot;&quot;&quot;\n if not number:\n yield 0\n # stops the generator\n return\n elif number &lt; 0:\n # for a solution that processes negative numbers\n # however, for your case, it might be better to\n # raise a ValueError here\n number *= -1\n\n num_digits = ceil(log10(number))\n\n for _ in range(num_digits):\n digit = (number % 10)\n\n yield digit\n\n number //= 10\n\n\ndef is_valid_card(card_number: int) -&gt; bool:\n &quot;&quot;&quot;Uses Luhn's algorithm to determine if a credit card number is valid&quot;&quot;&quot;\n digit_sum = 0\n\n digits_iter = islice(get_digits(card_number), 1, None)\n for i, digit in enumerate(digits_iter, start=1):\n # process odd digits\n if i % 2:\n digit_sum += digit\n continue\n\n doubled = 2 * digit\n\n # Condition if resulting product has 2 digits\n if 10 &lt;= doubled &lt;= 99:\n digit_sum += sum(get_digits(doubled))\n else:\n digit_sum += doubled\n\n\n return bool(digit_sum % 10)\n</code></pre>\n<p>Quite a few changes here. First, note I'm checking if the index is odd or even with the <code>i % 2</code> operation. The <code>continue</code> keyword allows me to skip the rest of the loop body and go on to the next iteration. Next, I renamed <code>digits</code> to <code>doubled</code>, since <code>digits</code> isn't really what it is, it's twice the value of a digit. I'm using the int comparison operation to test if <code>doubled</code> is in a given range, which is fast and very readable. I've gotten rid of the <code>if_sum</code> temporary variable, simply sum the digits returned by the iterator and add that sum to <code>digit_sum</code>. Last, I'm returning a <code>bool</code>, so you get an explicit <code>True</code> or <code>False</code> from the function. I've also added type hints and some short docstrings to help with readability.</p>\n<h1><code>card_classify</code></h1>\n<p>Let's reorder these to <code>classify_card</code>. I don't think <code>check</code> needs to be a variable here. Call the <code>is_valid_card</code> function inside that function. It's easier to see what's happening that way:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def classify_card(card_number: int) -&gt; None:\n &quot;&quot;&quot;Classifies a card as AMEX, VISA, MASTERCARD or INVALID&quot;&quot;&quot;\n # test if the card number is valid\n if not is_valid_card(card_number):\n print(&quot;INVALID&quot;)\n return\n\n card_types = {\n 37: 'AMEX',\n 34: 'AMEX',\n }\n\n card_types.update({i: 'MASTERCARD' for i in range(51, 56)})\n # these all start with 4\n card_types.update({i: 'VISA' for i in range(40, 50)})\n\n try:\n card_type = card_types[leading_digits(num)]\n except KeyError:\n print(&quot;INVALID&quot;)\n else:\n print(card_type)\n</code></pre>\n<h1><code>main</code></h1>\n<p>I'd postpone your integer conversion of the <code>input</code> string, since it's really easy to test the length while it's still a <code>str</code>:</p>\n<pre class=\"lang-py prettyprint-override\"><code>def main():\n card_num = input(&quot;Number: &quot;)\n\n if len(card_num) not in range(12, 17):\n print('INVALID')\n else:\n classify_card(int(card_num))\n</code></pre>\n<p>And I would move <code>main</code> towards the bottom of the script.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T04:33:19.933", "Id": "528325", "Score": "2", "body": "Awesome! I find this comprehensive review really well-explained. Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T14:55:10.000", "Id": "528445", "Score": "2", "body": "Hmmmm. You seem to want to micro-optimize beyond what's useful or probably even measurable (have you profiled the difference between string conversion and logarithms?), and some of your suggestions will harm performance rather than hurt it. For instance, rather than pushing for `islice`, you should simply have a tuple of integers and use regular `[2:]` slicing on it, which is both more legible and performant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T19:27:13.420", "Id": "528654", "Score": "1", "body": "Have you checked that your algorithm is actually correct? It does not seem to pass the testcases here https://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T19:39:07.887", "Id": "528657", "Score": "0", "body": "@Reinderien Looking back, I think you might be right. I'll have to edit this to be a better answer, can't delete it since it's accepted" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T19:39:47.907", "Id": "528658", "Score": "0", "body": "@N3buchadnezzar hm, good catch, I was going to take this down anyways, but I'll rerun test cases when I update this to be a more satisfactory review" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T02:06:10.610", "Id": "267940", "ParentId": "267932", "Score": "4" } }, { "body": "<p>So C. Nivs gave a great review of your code, despite some minor flaws in the improvements. Take his advice at heart and you will be a great coder in no time. This review focuses more on how to properly implement Luhn's algorithm.</p>\n<h1>Reeinventing the wheel</h1>\n<p>While reinventing the wheel can be good sometimes, it is also important to look for existing resources before starting. If we look at <a href=\"https://rosettacode.org/wiki/Luhn_test_of_credit_card_numbers#Python\" rel=\"nofollow noreferrer\">Rosetta Code's webpage</a> we find the following piece of code</p>\n<pre><code>&gt;&gt;&gt; def luhn(n):\n r = [int(ch) for ch in str(n)][::-1]\n return (sum(r[0::2]) + sum(sum(divmod(d*2,10)) for d in r[1::2])) % 10 == 0\n \n&gt;&gt;&gt; for n in (49927398716, 49927398717, 1234567812345678, 1234567812345670):\n print(n, luhn(n))\n</code></pre>\n<p>Only two lines! <a href=\"https://en.wikipedia.org/wiki/Luhn_algorithm\" rel=\"nofollow noreferrer\">The wikipedia page for Luhn's algorithm</a> gives a similiar albiet longer code snippet</p>\n<pre><code>function checkLuhn(string purportedCC) {\n int nDigits := length(purportedCC)\n int sum := integer(purportedCC[nDigits-1])\n int parity := (nDigits-1) modulus 2\n for i from 0 to nDigits - 2 {\n int digit := integer(purportedCC[i])\n if i modulus 2 = parity\n digit := digit × 2\n if digit &gt; 9\n digit := digit - 9 \n sum := sum + digit\n }\n return (sum modulus 10) = 0\n}\n</code></pre>\n<p>Be careful though. <a href=\"https://softwareengineering.stackexchange.com/questions/203684/is-fewer-lines-of-code-always-better\">Short code != readable code</a>.</p>\n<blockquote>\n<p>Any fool can write code that a computer can understand. Good\nprogrammers write code that humans can understand. (M. Fowler)</p>\n</blockquote>\n<p>Make sure to always strife for code that is readable. Your code is on the verbose side, while the Rosetta code is very terse.</p>\n<h1>Test, test, test</h1>\n<p>Hmm, the code from Rosetta looks a bit cryptic (terse). Let us compare it with my first draft</p>\n<pre><code>from typing import Annotated\n\nCreditCard = Annotated[int, &quot;An integer representing a credit card number&quot;]\n\n\ndef is_card_valid_1(number: CreditCard) -&gt; bool:\n &quot;&quot;&quot;Uses Luhn's algorithm to determine if a credit card number is valid\n\n 1. Reverse the order of the digits in the number.\n 2. Take the first, third, ... and every other odd digit in the reversed\n digits and sum them to form the partial sum s1\n 3. Taking the second, fourth ... and every other even digit in the reversed digits:\n\n 1. Multiply each digit by two and sum the digits if the answer is greater\n than nine to form partial sums for the even digits\n 2. Sum the partial sums of the even digits to form s2\n\n If s1 + s2 ends in zero then the original number is in the form of a valid\n credit card number as verified by the Luhn test.\n\n For example, if the trial number is 49927398716:\n\n Reverse the digits:\n 61789372994\n Sum the odd digits:\n 6 + 7 + 9 + 7 + 9 + 4 = 42 = s1\n The even digits:\n 1, 8, 3, 2, 9\n Two times each even digit:\n 2, 16, 6, 4, 18\n Sum the digits of each multiplication:\n 2, 7, 6, 4, 9\n Sum the last:\n 2 + 7 + 6 + 4 + 9 = 28 = s2\n\n s1 + s2 = 70 which ends in zero which means that 49927398716 passes the Luhn test\n\n Example:\n &gt;&gt;&gt; is_card_valid_1(0)\n True\n &gt;&gt;&gt; any(map(is_card_valid_1, range(1,10)))\n False\n &gt;&gt;&gt; [is_card_valid_1(i) for i in [59, 60]]\n [True, False]\n &gt;&gt;&gt; [is_card_valid_1(i) for i in [49927398716, 49927398717]]\n [True, False]\n &gt;&gt;&gt; [is_card_valid_1(i) for i in [1234567812345678, 1234567812345670]]\n [False, True]\n &quot;&quot;&quot;\n digits = map(int, reversed(str(number)))\n check_sum = 0\n for i, digit in enumerate(digits):\n if i % 2:\n # The sum of the digits of a 2 digit number is number - 9\n # (15 = 1+5 and 15 - 9 = 6)\n digit = double if (double := 2 * digit) &lt; 9 else double - 9\n check_sum += digit\n return check_sum % 10 == 0\n\n\nif __name__ == &quot;__main__&quot;:\n cards0 = [0, 1, 59, 60, 596, 567]\n cards1 = [79927398713]\n cards2 = [49927398716, 49927398717, 1234567812345678, 1234567812345670]\n\n print([is_card_valid_1(card) for card in cards0])\n</code></pre>\n<ul>\n<li>Count how many lines of my code is comments versus actual code.</li>\n<li>Everything after <code>Example:</code> are <a href=\"https://docs.python.org/3/library/doctest.html\" rel=\"nofollow noreferrer\">doctests</a>. This means I automatically add test cases, and check whether my implementation is correct.</li>\n<li>I have some more test cases in my <code>__main__</code> guard, just for testing the implementation.</li>\n</ul>\n<p>See for yourself if you can figure out how my implementation works without me telling you. <em>If</em> my code is well written it will take you a short while. If it takes a while, it is a good sign that it could be improved.</p>\n<h1>Improvements on the first draft</h1>\n<p>I have yet to reach a consensus on this, but the following part sticks out to me</p>\n<pre><code>for i, digit in enumerate(digits):\n if i % 2:\n # The sum of the digits of a 2 digit number is number - 9\n # (15 = 1+5 and 15 - 9 = 6)\n digit = double if (double := 2 * digit) &lt; 9 else double - 9\n</code></pre>\n<ol>\n<li>It requires a comment that streches over two lines, and even then it is unclear at best.</li>\n<li>We <em>know</em> every other digit is even. even so we still check every iteration if <code>i % 2</code>. This is again a minor gripe.</li>\n</ol>\n<p>We could &quot;solve&quot; the first problem by rewriting it using <a href=\"https://docs.python.org/3/library/functions.html#divmod\" rel=\"nofollow noreferrer\"><code>divmod(x,y) = x // y, x % y</code></a></p>\n<pre><code>for i, digit in enumerate(digits):\n check_sum += sum(divmod(2 * digit, 10)) if i % 2 else digit\n</code></pre>\n<p>Which still needs a comment explaining what it does. If speed is an concern (it really should not be, you are using Python and this is a miniscule micro-optimization) we could do</p>\n<pre><code># Calculates the digit sum of 2*i for the i'th digit [2*9 = 18 and 1+8=9 so 9 maps to 9]\ndouble_check_sum = {0: 0, 1: 2, 2: 4, 3: 6, 4: 8, 5: 1, 6: 3, 7: 5, 8: 7, 9: 9}\nfor i, digit in enumerate(digits):\n check_sum += double_check_sum[digit] if i % 2 else digit\n</code></pre>\n<p>The second problem could be solved by exploiting <a href=\"https://stackoverflow.com/questions/509211/understanding-slice-notation\">Pythons slice notation</a>.</p>\n<pre><code># Calculates the digit sum of 2*i for the i'th digit [2*9 = 18 and 1+8=9 so 9 maps to 9]\ndouble_check_sum = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]\neven, odd = sum(digits[::2]), sum(double_check_sum[odd] for odd in digits[1::2])\n</code></pre>\n<p>Where we converted our <code>double_check_sum</code> to a list, and now iterates separately over respectively the even and odd digits. To summerize our final function <em>could</em> look something like this</p>\n<pre><code>def is_card_valid_4(number: CreditCard) -&gt; bool:\n digits = [int(i) for i in reversed(str(number))]\n # Calculates the digit sum of 2*i for the i'th digit \n # [2*9 = 18 and 1+8=9 so 9 maps to 9]\n double_check_sum = [0, 2, 4, 6, 8, 1, 3, 5, 7, 9]\n even, odd = sum(digits[::2]), sum(double_check_sum[odd] for odd in digits[1::2])\n return (even + odd) % 10 == 0\n</code></pre>\n<p>Without the docstrings, which is not too shaby. If we wanted to be really pedantic, we could improve it further by extracting the constant and defining a sub function</p>\n<pre><code># Calculates the digit sum of 2*i for the i'th digit\n# [2*9 = 18 and 1+8=9 so 9 maps to 9]\nDOUBLE_DIGIT_SUM = [sum(int(i) for i in str(2 * i)) for i in range(10)]\n\n\ndef is_card_valid_4(number: CreditCard) -&gt; bool:\n digits = [int(i) for i in reversed(str(number))]\n even, odd = sum(digits[::2]), sum(DOUBLE_DIGIT_SUM[i] for i in digits[1::2])\n return (even + odd) % 10 == 0\n</code></pre>\n<p>Note that <code>DOUBLE_DIGIT</code> was calculated explicitly to increase the readability and remove the &quot;magic list&quot;. Since <code>DOUBLE_DIGIT</code> is only calculated once we can afford to be slow.</p>\n<h1>Pythonic</h1>\n<p>Another approach is also grounded in the <code>divmod</code> approach</p>\n<pre><code>def is_card_valid_5(number: CreditCard) -&gt; bool:\n check_sum = 0\n while number:\n number, even_digit = divmod(number, 10)\n number, odd_digit = divmod(number, 10)\n # sum(divmod(2*7, 10)) = sum((1, 4)) = 5 [calculates the digit sum of twice the number]\n check_sum += even_digit + sum(divmod(2 * odd_digit, 10))\n return check_sum % 10 == 0\n</code></pre>\n<p>I'll let you figure out the details here. When does the iteration stop? What does the <code>sum(divmod(2 * odd_digit, 10))</code> do? Does it work for single and double digits? Does it iterate from the last digit as required in the algorithm?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T23:06:17.990", "Id": "268103", "ParentId": "267932", "Score": "2" } } ]
{ "AcceptedAnswerId": "267940", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T20:57:41.153", "Id": "267932", "Score": "2", "Tags": [ "python", "algorithm", "validation", "finance", "checksum" ], "Title": "Simple credit card validation with Luhn's Algorithm" }
267932
<p>I wrote this code in c#. It is a question from LeetCode, number 49. Given an array of strings, group the anagrams.</p> <p>The examples it gives are:</p> <blockquote> <p>[&quot;eat&quot;,&quot;tea&quot;,&quot;tan&quot;,&quot;ate&quot;,&quot;nat&quot;,&quot;bat&quot;]</p> </blockquote> <p>then return:</p> <blockquote> <p>[[&quot;bat&quot;],[&quot;nat&quot;,&quot;tan&quot;],[&quot;ate&quot;,&quot;eat&quot;,&quot;tea&quot;]]</p> </blockquote> <p>I am wondering what exactly my time complexity is? I believe it is O(2n) which becomes O(n) after dropping the constant. But I am also thinking it might actually be O(2n^2) or O(n^2) because in my first for loop I have <code>Array.Sort(new string(temp))</code> which may increase the time complexity. Please let me know.</p> <p>Overall, how can I improve and speed up my code? Maybe I could get rid of the dictionary? Get rid of <code>Array.Sort(new string(temp))</code>? Create one instance of <code>new string(temp)</code> and use the variable instead? I am also thinking I should move everything into one for loop. How could this best be accomplished?</p> <pre><code>public IList&lt;IList&lt;string&gt;&gt; GroupAnagrams(string[] strs) { IList&lt;IList&lt;string&gt;&gt; ans = new List&lt;IList&lt;string&gt;&gt;(); Dictionary&lt;string, List&lt;string&gt;&gt; values = new Dictionary&lt;string, List&lt;string&gt;&gt;(); for (int i = 0; i &lt; strs.Length; i++){ char[] temp = strs[i].ToCharArray(); Array.Sort(new string(temp)); if (!values.ContainsKey(new string(temp))) values.Add(new string(temp), new List&lt;string&gt; { strs[i] }); else values[new string(temp)].Add(strs[i]); } for (int i = 0; i &lt; values.Count; i++){ ans.Add(values.ElementAt(i).Value); return ans; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:20:49.280", "Id": "528330", "Score": "0", "body": "Array.Sort(new string(temp)); -> Impossible to convert from \"string\" to \"System.Array\"." } ]
[ { "body": "<p>Here is my 4 lines long alternative:</p>\n<pre><code>var anagrams = from word in words\n let pair = new { Original = word, AlphabeticallyOrdered = string.Concat(word.OrderBy(@char =&gt; @char)) }\n group pair by pair.AlphabeticallyOrdered into anagram\n select anagram.Select(@group =&gt; @group.Original);\n</code></pre>\n<p>Here are my line by line explanations:</p>\n<ol>\n<li>Iterate through the received <code>words</code></li>\n<li>Create a new string pair where we store the <em>original word</em> and the <em>alphabetically ordered version</em></li>\n<li>Group them based on the <em>alphabetically ordered version</em></li>\n<li>Retrieve them based on the <em>original version</em></li>\n</ol>\n<hr />\n<p>If I iterate the result like this:</p>\n<pre><code>foreach(var anagram in anagrams)\n{\n Console.WriteLine(string.Join(&quot;,&quot;, anagram));\n}\n</code></pre>\n<p>the output will look like that:</p>\n<pre><code>eat,tea,ate\ntan,nat\nbat\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T07:30:49.597", "Id": "267952", "ParentId": "267935", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T23:36:01.223", "Id": "267935", "Score": "2", "Tags": [ "c#", "strings", "array" ], "Title": "Grouping anagrams together from a string array" }
267935
<p>I have just recently picked up coding and am trying to improve my coding. I've written this bit of code to create a little adventure world. I haven't completed the code, everything runs how I want it too but I'm aware this code isn't efficient. I would like some advice and some help on how I would make my code better, particularly more efficient. Also, I have not coded further from guessing the number from the box, so it just exits the code after.</p> <p>Anything would be appreciated, as I know I have a lot to learn!</p> <pre><code>import random attack = 0 health = 0 element = 0 def character(): number = int(input(&quot;&quot;&quot;Please choose your character. \n1. You control the element of fire, and bend it to your will freely. \n2. You control the element of water, you feel the flow and control it elegantly. \n3. You control the element of ice, you're power is the to call on ice and use it lethally. &gt; &quot;&quot;&quot;)) if number == 1: choice = 1 fire_character() elif number == 2: choice = 2 water_character() elif number == 3: choice = 3 ice_character() else: print(&quot;Sorry you can only choose a number between 1 and 3.&quot;) def fire_character(): global attack global health global element attack += 100 health += 50 element = 'fire' print(f&quot;\nSince you have chosen fire: Attack = {attack}, Health = {health}&quot;) def water_character(): global attack global health global element attack = 75 health = 75 element = 'water' print(f&quot;\nSince you have chosen water: Attack = {attack}, Health = {health}&quot;) def ice_character(): global attack global health global element attack = 50 health = 100 element = 'ice' print(f&quot;\nSince you have chosen ice: Attack = {attack}, Health = {health}&quot;) def welcome(attack, health, element): print(f&quot;&quot;&quot; Welcome to the game! You have chosen the {element} element! Lets see how far you can get! Best of luck, I hope the game ends up well! &quot;&quot;&quot;) def which_way(): print(f&quot;With your newly discovered {element} powers, you mysteriously wake up in a whole new world.&quot;) print(&quot;You're in a crowded forest and there's noises coming from every direction.&quot;) print(&quot;A small furry animal approaches you and startles you!&quot;) print(&quot;&quot;&quot; 'DO NOT WORRY SIR, I NO HARM YOU! I HEAR TO GUIDE YOU THROUGH NEW PLACE', the little creature says. &quot;&quot;&quot;) print(&quot;The creature then tells you he seems to have forgotten the safe way through... He says he has a foggy idea.&quot;) print(&quot;He will reccomend which way to go he says.. but he says not to trust his memory...&quot;) print(&quot;\n The furry guy reccomends going left.&quot;) loop = False while loop == False: choice = input(&quot;Are you going to go left or right? &gt; &quot;).lower() if choice == 'right': enemy1() loop = True elif choice == 'left': print(&quot;\nYou decide to listen to the lil fella and go left. You walk through a relaxing walkway in the forest.&quot;) print(&quot;You look around and see a gorgeous lake and beautiful animals sitting around it.&quot;) print(&quot;You peacfully walk around for a while, admiring all of the natures beauty and then eventually carry on.&quot;) choice_two() loop = True else: print(&quot;Thats not an option sorry &quot;) def enemy1(): global attack global health global element en_attack = 20 en_health = 100 en_element = 'ice' print(&quot;\nYou go against your little companions advice and turn right.&quot;) print(&quot;As you walk through the forest you hear sounds coming out of the bushes.&quot;) print(&quot;An enemy with frost emitting from around his body slowly walks out...&quot;) print(&quot;You're little body comes upto you and tells you about the character.&quot;) print(&quot;THIS ICE GUY WEAK HAHA, HE STATS ARE:&quot;) print(f&quot;Attack: {en_attack}, Health: {en_health}, Element: {en_element}&quot;) loop = False while loop == False: choice = input(&quot;\nWhat do you want to do? Attack, run or try talk it out? (attack, run or talk): &quot;).lower() if choice == 'attack': print(f&quot;You throw a {element} ball at him!&quot;) if element == 'fire': print(&quot;Your fire ball does extra damage!&quot;) print(f&quot;\nEnemy Health: {en_health} - Your attack: {attack}&quot;) en_health = en_health - attack print(f&quot;The enemy took an extra 10 damage beacuse of the element difference!&quot;) en_health = en_health - 10 print(f&quot;The enemys health is at {en_health}! He melts into a puddle as you carry on.&quot;) loop = True if en_health &lt;= 0: print(&quot;Enemy falls on the ground and dies.&quot;) choice_two() if element == 'water': print(&quot;Your water ball does terribe damage!&quot;) print(f&quot;\nEnemy Health: {en_health} - Your attack: {attack}&quot;) en_health = en_health - attack print(f&quot;The enemy uses your water and hardens his armor back up a bit... Enemy adds 10 health back&quot;) en_health = en_health + 10 print(f&quot;The enemys health is at {en_health}!&quot;) if en_health &lt;= 0: print(&quot;Enemy falls on the ground and dies.&quot;) choice_two() print(f&quot;\nThe enemy wasn't happy that you just attacked him out of nowhere and attacks you!&quot;) health = health - en_attack - 10 print(f&quot;The enemy hardens the water around it and turns them into icyicles launching them at you doing {en_attack} damage!&quot;) print(f&quot;The ice enemies attack does an extra 10 damage..&quot;) print(f&quot;Your health is {health}&quot;) if element == 'ice': print(&quot;Your ice ball does neutral damage!&quot;) print(f&quot;\nEnemy Health: {en_health} - Your attack: {attack}&quot;) en_health = en_health - attack print(f&quot;The enemys health is at {en_health}!&quot;) if en_health &lt;= 0: print(&quot;Enemy falls on the ground and dies.&quot;) choice_two() print(f&quot;\nThe enemy wasn't happy that you just attacked him out of nowhere and attacks you!&quot;) health = health - en_attack print(f&quot;The enemy hardens the water around it and turns them into icyicles launching them at you doing {en_attack} damage!&quot;) print(f&quot;Your health is {health}&quot;) loop = False elif choice == 'run': print(&quot;\nYou runaway with your tail between your legs!&quot;) die(&quot;While running away you trip into a hole of acid. Shame.&quot;) loop = True elif choice == 'talk': print(&quot;\nWhen the beast gets close to you, you calmly ask for his name.&quot;) print(&quot;The beast tells you his name and then you guys chat for a while.&quot;) print(&quot;When you guys finishing talking about past lives he kindly lets you stroll on past.&quot;) choice_two() loop = True else: print(&quot;Sorry that's not an option.&quot;) loop = False def choice_two(): global health print(f&quot;\n You're health is {health}&quot;) print(&quot;\n While you are strolling a mysterious blue box appears. You approach the box and start inspecting it.&quot;) print(&quot;Your little guide starts going on a bit how you have to guess a number to open it. But there's a catch... &quot;) print(&quot;If you don't guess the number right you get inflicted with an uncurable poison. You get 3 guesses.&quot;) print(&quot;The little guy says guess between 1 and 8...&quot;) if element == 'water': print(f&quot;\nAs you aproach the box it starts lighting up a bit.. It seems to connect with your element {element}.&quot;) print(&quot;Guess between 1 and 5.&quot;) box_number_notwater = random.randint(1, 8) box_number_water = random.randint(1, 5) guess_count = 0 while guess_count &lt;= 2: if element == 'fire' or 'ice': guess = int(input(&quot;Guess a number: &quot;)) if guess == box_number_notwater: print(&quot;You got it right!&quot;) exit() elif guess &lt; box_number_notwater: print(&quot;Sorry! Try guessing higher!&quot;) guess_count += 1 elif guess &gt; box_number_notwater: print(&quot;Sorry! Try guessing lower!&quot;) guess_count += 1 elif element == 'water': guess = int(input(&quot;Guess a number: &quot;)) if guess == box_number_water: print(&quot;You got it right!&quot;) exit() elif guess &lt; box_number_water: print(&quot;Sorry! Try guessing higher!&quot;) guess_count += 1 elif guess &gt; box_number_water: print(&quot;Sorry! Try guessing lower!&quot;) guess_count += 1 if guess_count == 3: die('A squirrel comes from the box and bites your finger. You start slowly dosing off and die.') def die(reason): print(&quot;&quot;) print(f&quot;{reason} Good Job!!&quot;) exit() player = input(&quot;Would you like to play the game? &quot;).lower() if player == 'yes': character() else: print(&quot;Goodbye!&quot;) exit() welcome(attack, health, element) which_way() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T13:32:14.020", "Id": "528350", "Score": "1", "body": "I receive errors when testing your code. It appears that the paste is missing the import statements? Can you fix? Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T23:54:30.170", "Id": "528398", "Score": "0", "body": "@C.Harley Just edited it, sorry I had forgot to paste in the import of random." } ]
[ { "body": "<p>This is a fun start to a game.</p>\n<p>Decrease your reliance on globals, passing around variables in function parameters instead. Encapsulating the character stats in a class will make things easier.</p>\n<p>You need to work on your spelling and grammar - for example, <code>you're power is the to call</code> -&gt; <code>your power is the ability to call</code>.</p>\n<p>Consider representing the element choice as an enumeration - among other advantages, to make iteration over its options easier.</p>\n<p>You have some input validation - in <code>character</code>, consider expanding it by adding a loop that doesn't exit until the user enters valid input.</p>\n<p>As a growing developer you need to develop a deep, burning hatred for copy-and-pasted code repetition such as that seen in <code>print('Since you have chosen ...</code>. There are many ways to reduce this repetition, the easiest being to factor out the repeated code into functions.</p>\n<p>Try to flatten out your call structure - instead of <code>which_way</code> calling into the enemy function, just return the choice and have the outer level call the next function.</p>\n<p>You don't need to use separate variables for <code>box_number_notwater</code> and <code>box_number_water</code> - you can use one variable, initializing it conditionally based on player element.</p>\n<p>I find it odd that you're asking the player whether they want to play the game? Presumably if they started the program, they already want to play the game, and if they somehow accidentally clicked on its icon, they could just close it without that prompt. I would delete it.</p>\n<h2>Suggested</h2>\n<p>This doesn't go far enough to eliminate e.g. your repeated code in the fight sequence, but it's a start and food for thought.</p>\n<pre class=\"lang-py prettyprint-override\"><code>import enum\nimport random\nfrom enum import Enum\nfrom typing import ClassVar\n\n\n@enum.unique\nclass Element(Enum):\n FIRE = 1\n WATER = 2\n ICE = 3\n\n\nclass Character:\n DESCRIPTION: ClassVar[str]\n ATTACK: ClassVar[int]\n START_HEALTH: ClassVar[int]\n ELEMENT: ClassVar[Element]\n\n def __init__(self):\n self.health = self.START_HEALTH\n\n @property\n def element_name(self) -&gt; str:\n return self.ELEMENT.name.lower()\n\n\ndef choose_character() -&gt; 'Character':\n prompt = (\n 'Please choose your character.\\n' +\n '\\n'.join(\n f'{element.value}. {CHARACTERS[element].DESCRIPTION}'\n for element in Element\n )\n )\n while True:\n try:\n number = int(input(prompt))\n if 1 &lt;= number &lt;= len(Element):\n break\n print(f&quot;Sorry, you can only choose a number between 1 and {len(Element)}.&quot;)\n except ValueError:\n print('Please enter a number.')\n\n player = CHARACTERS[Element(number)]()\n print(\n f&quot;Since you have chosen {player.element_name}: &quot;\n f&quot;Attack = {player.ATTACK}, Health = {player.health}&quot;\n )\n return player\n\n\nclass FireCharacter(Character):\n ELEMENT = Element.FIRE\n DESCRIPTION = 'You control the element of fire, and bend it to your will freely.'\n ATTACK = 100\n START_HEALTH = 50\n\n\nclass WaterCharacter(Character):\n ELEMENT = Element.WATER\n DESCRIPTION = 'You control the element of water; you feel the flow and control it elegantly.'\n ATTACK = 75\n START_HEALTH = 75\n\n\nclass IceCharacter(Character):\n ELEMENT = Element.ICE\n DESCRIPTION = 'You control the element of ice; your power is the ability to call on ice and use it lethally.'\n ATTACK = 50\n START_HEALTH = 100\n\n\nCHARACTERS = {\n cls.ELEMENT: cls\n for cls in (FireCharacter, WaterCharacter, IceCharacter)\n}\n\n\ndef welcome(player: Character) -&gt; None:\n print(f&quot;&quot;&quot;\nWelcome to the game! You have chosen the {player.element_name} element! Let's see how far you can get!\nBest of luck, I hope the game ends up well!\n &quot;&quot;&quot;)\n\n\ndef which_way(player: Character) -&gt; str:\n print(\nf&quot;&quot;&quot;With your newly discovered {player.element_name} powers, you mysteriously wake up in a whole new world.\nYou're in a crowded forest and there's noises coming from every direction.\nA small furry animal approaches you and startles you!\n'DO NOT WORRY SIR, I NO HARM YOU! I HEAR TO GUIDE YOU THROUGH NEW PLACE', the little creature says.\nThe creature then tells you he seems to have forgotten the safe way through... He says he has a foggy idea.\nHe will recommend which way to go he says.. but he says not to trust his memory...\nThe furry guy recommends going left.\n&quot;&quot;&quot;\n )\n\n while True:\n choice = input(&quot;Are you going to go left or right? &gt; &quot;).lower()\n if choice in {'left', 'right'}:\n return choice\n print(&quot;That's not an option, sorry&quot;)\n\n\ndef forest() -&gt; None:\n print(\n&quot;&quot;&quot;\\nYou decide to listen to the lil fella and go left. You walk through a relaxing walkway in the forest.\nYou look around and see a gorgeous lake and beautiful animals sitting around it.\nYou peacefully walk around for a while, admiring all of the natures beauty and then eventually carry on.\n&quot;&quot;&quot;)\n\n\ndef enemy1(player: Character) -&gt; None:\n en_attack = 20\n en_health = 100\n en_element = Element.ICE\n\n print(\nf&quot;&quot;&quot;\\nYou go against your little companions advice and turn right.\nAs you walk through the forest you hear sounds coming out of the bushes.\nAn enemy with frost emitting from around his body slowly walks out...\nYou're little body comes upto you and tells you about the character.\nTHIS ICE GUY WEAK HAHA, HE STATS ARE:\nAttack: {en_attack}, Health: {en_health}, Element: {en_element.name.lower()}\n&quot;&quot;&quot;)\n\n while True:\n choice = input(&quot;\\nWhat do you want to do? Attack, run or try talk it out? (attack, run or talk): &quot;).lower()\n if choice == 'run':\n print(&quot;\\nYou run away with your tail between your legs!&quot;)\n die(&quot;While running away you trip into a hole of acid. Shame.&quot;)\n if choice == 'talk':\n print(\n &quot;\\nWhen the beast gets close to you, you calmly ask for his name.&quot;\n &quot;\\nThe beast tells you his name and then you guys chat for a while.&quot;\n &quot;\\nWhen you guys finishing talking about past lives he kindly lets you stroll on past.&quot;\n )\n return\n if choice != 'attack':\n print(&quot;Sorry that's not an option.&quot;)\n continue\n\n print(f&quot;You throw a {player.element_name} ball at him!&quot;)\n if player.ELEMENT == Element.FIRE:\n print(&quot;Your fire ball does extra damage!&quot;)\n print(f&quot;\\nEnemy Health: {en_health} - Your attack: {player.ATTACK}&quot;)\n en_health -= player.ATTACK\n print(f&quot;The enemy took an extra 10 damage because of the element difference!&quot;)\n en_health -= 10\n print(f&quot;The enemy's health is at {en_health}! He melts into a puddle as you carry on.&quot;)\n if en_health &lt;= 0:\n print(&quot;Enemy falls on the ground and dies.&quot;)\n return\n\n elif player.ELEMENT == Element.WATER:\n print(&quot;Your water ball does terrible damage!&quot;)\n print(f&quot;\\nEnemy Health: {en_health} - Your attack: {player.ATTACK}&quot;)\n en_health = en_health - player.ATTACK\n print(f&quot;The enemy uses your water and hardens his armor back up a bit... Enemy adds 10 health back&quot;)\n en_health = en_health + 10\n print(f&quot;The enemys health is at {en_health}!&quot;)\n if en_health &lt;= 0:\n print(&quot;Enemy falls on the ground and dies.&quot;)\n return\n print(f&quot;\\nThe enemy wasn't happy that you just attacked him out of nowhere and attacks you!&quot;)\n player.health -= en_attack - 10\n print(f&quot;The enemy hardens the water around it and turns them into icyicles launching them at you doing {en_attack} damage!&quot;)\n print(f&quot;The ice enemies attack does an extra 10 damage..&quot;)\n print(f&quot;Your health is {player.health}&quot;)\n\n if player.ELEMENT == Element.ICE:\n print(&quot;Your ice ball does neutral damage!&quot;)\n print(f&quot;\\nEnemy Health: {en_health} - Your attack: {player.ATTACK}&quot;)\n en_health = en_health - player.ATTACK\n print(f&quot;The enemys health is at {en_health}!&quot;)\n if en_health &lt;= 0:\n print(&quot;Enemy falls on the ground and dies.&quot;)\n return\n print(f&quot;\\nThe enemy wasn't happy that you just attacked him out of nowhere and attacks you!&quot;)\n player.health -= en_attack\n print(f&quot;The enemy hardens the water around it and turns them into icyicles launching them at you doing {en_attack} damage!&quot;)\n print(f&quot;Your health is {player.health}&quot;)\n\n\ndef guess_box(player: Character) -&gt; None:\n n = 8\n\n print(\nf&quot;&quot;&quot;\\n Your health is {player.health}\nWhile you are strolling a mysterious blue box appears. You approach the box and start inspecting it.\nYour little guide starts going on a bit how you have to guess a number to open it. But there's a catch...\nIf you don't guess the number right you get inflicted with an uncurable poison. You get 3 guesses.\nThe little guy says guess between 1 and {n}...\n&quot;&quot;&quot;)\n\n if player.ELEMENT == 'water':\n print(f&quot;\\nAs you aproach the box it starts lighting up a bit.. It seems to connect with your element {player.element_name}.&quot;)\n n = 5\n print(f&quot;Guess between 1 and {n}.&quot;)\n\n box_number = random.randint(1, n)\n\n for guess_count in range(3):\n guess = int(input(&quot;Guess a number: &quot;))\n if guess &lt; box_number:\n print(&quot;Sorry! Try guessing higher!&quot;)\n elif guess &gt; box_number:\n print(&quot;Sorry! Try guessing lower!&quot;)\n else:\n print(&quot;You got it right!&quot;)\n return\n\n die('A squirrel comes from the box and bites your finger. You start slowly dosing off and die.')\n\n\ndef die(reason: str) -&gt; None:\n print(f&quot;\\n{reason} Good Job!!&quot;)\n exit()\n\n\ndef main():\n should_play = input(&quot;Would you like to play the game? &quot;).lower()\n if not should_play.startswith('y'):\n print(&quot;Goodbye!&quot;)\n exit()\n\n player = choose_character()\n welcome(player)\n if which_way(player) == 'right':\n enemy1(player)\n else:\n forest()\n\n guess_box(player)\n\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T00:06:46.850", "Id": "528508", "Score": "1", "body": "Thank you for the time you put into this! I will make sure to have a good read and deep dive into all the new concepts you've presented me. Your review will help me in growing my coding skill. Thank you so much again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T02:53:06.810", "Id": "267983", "ParentId": "267937", "Score": "4" } }, { "body": "<p>Welcome to CodeReview! Your code is very much &quot;beginner&quot; code, and I don't propose to change that too much. Instead, I'm going to point you at some things that you can do better in the same framework.</p>\n<h3>Global variables</h3>\n<p>You are using globals, which everyone is going to tell you is bad, bad, bad. It's horrible to use globals. Dogs and cats lying down together. Fire and brimstone falling from the skies. Whenever you use a global variable, an orphan dies of starvation. What kind of orphan-killing, brimstone-dropping, pet breeding monster are you?</p>\n<p>Anyway.</p>\n<p>Your use of globals is inconsistent. There are a few things you need to know:</p>\n<ol>\n<li><p>You only need to use the <code>global</code> keyword when you are changing the value of a global variable. In particular, <strong>not</strong> when you are changing an element or attribute of a global variable. Thus, you have to say <code>global element</code> if <code>element</code> is an integer or a string, but not if it's an object or a list or a dict (hint, hint!).</p>\n</li>\n<li><p>You should be consistent in how you make changes to your globals. You can use <code>+=</code> or <code>=</code>, but you shouldn't use both operators to accomplish the same task (in different places). You have</p>\n<pre><code> def fire_character():\n global attack\n ...\n attack += 100\n\n def water_character():\n global attack\n ...\n attack = 75\n</code></pre>\n</li>\n<li><p>Use a naming convention to help distinguish globals. I'd suggest either using <code>ALL_CAPS</code> or <code>Cap_snake</code> for globals.</p>\n</li>\n<li><p>Use helper functions for accessing globals. This will make it easier to change when you convert to an aggregate object like a dict or class. Write something like</p>\n<pre><code> def set_attack(new_value: int): \n global Attack\n Attack = new_value\n</code></pre>\n</li>\n</ol>\n<p>This way you never have to write <code>global attack</code> again -- you can just call <code>set_attack(75)</code> and be done with it.</p>\n<h3>Function names</h3>\n<p>For &quot;modular&quot; code like this, try to put a verb into each function name, unless it's a pure function (like &quot;sine&quot; or &quot;average&quot;) that only computes a result. For code with side effects, or &quot;procedures&quot;, you definitely want a verb in there!</p>\n<p>You have a function called <code>character()</code>. What does that do? Why not call it <code>pick_character_type()</code> instead?</p>\n<h3>Loop on input</h3>\n<p>Pretty much all user input needs to be validated. So any input code should be inside a loop. Look at your <code>character()</code> function - it prints an error if something goes wrong, but then it doesn't loop!</p>\n<p>Fix that code! Add a loop to repeat the prompt until the user surrenders (or presses Ctrl+C).</p>\n<h3>Avoid redundancy</h3>\n<p>You've got a <code>choice</code> variable and an <code>element</code> variable that both tell what kind of character the user has chosen. One of those is redundant!</p>\n<p>I'd suggest keeping the <code>element</code> variable and just comparing <code>Element == 'water'</code> instead of <code>choice == 1</code> or whatever.</p>\n<p>Even if you decide to keep both variables, the <code>choice</code> variable should be set in the element function, not in the character function -- just like all the other variables are set there.</p>\n<h3>Start looking for patterns</h3>\n<p>You've got two &quot;location&quot; functions written, and you can start to see patterns already.</p>\n<p>You have repeatedly written code that prompts the user for input, checks the input is valid, and loops until it is valid.</p>\n<p>You have location functions that print messages, ask for input, and do stuff.</p>\n<p>Those are the kinds of patterns that you can turn into functions. If you find a pattern of action/behavior, then by all means make it more general! Code it into a function and pass the variable parts in as data or as parameters.</p>\n<h3>Learn about dictionaries</h3>\n<p>Python has dictionaries, which other languages call hashes or associative arrays. They are a fundamental data type, built in to the language and supported with special syntax, special opcodes in the VM, etc.</p>\n<p>For what you're doing right now, you want to be able to group things by a key (the location). You could do that with lists, but it's more clear to do it with dictionaries:</p>\n<pre><code>places = {'icy cavern': ..., 'fiery desert': ...}\n</code></pre>\n<p>Once you start on this road, you'll immediately start nesting dictionaries inside other dictionaries, and look out, Zork!</p>\n<pre><code>places = {\n 'icy cavern': {\n 'enemy name': 'Dave the Dragon',\n 'element': 'ice',\n 'attack': 20,\n 'health': 30,\n },\n 'fiery desert': {\n 'enemy name': 'Nick the Newt',\n 'element': 'fire',\n 'attack': 50,\n 'health': 10,\n },\n }\n</code></pre>\n<p>That seems like enough to keep you going. Feel free to post a follow-up question (with a link back to this question) after you've got another 10 or 20 rooms done. Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T03:38:59.107", "Id": "528405", "Score": "0", "body": "Other languages call dictionaries hash maps, not hashes" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T17:06:31.293", "Id": "528459", "Score": "0", "body": "*cough* [Perl](https://perlmaven.com/perl-hashes) *cough*" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T17:10:15.330", "Id": "528460", "Score": "0", "body": "TMYK. I'll instead say \"most modern\" languages call them hash maps, and calling it a \"hash\" is not a great idea as it conflates the name of the data structure with its key mechanism and they're not the same thing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T00:10:39.140", "Id": "528509", "Score": "0", "body": "Thank you! I knew the global variables felt really off.. Reading your description of them made me laugh, I will make sure to never been an orphan killing coder again. Thank you for the clarity in your review. I will start trying to cut down my code by using some of these methods. The time you took to write this is very appreciated!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T03:15:14.117", "Id": "267984", "ParentId": "267937", "Score": "2" } }, { "body": "<p>Thanks NewWalker for your post. I can see you have big ideas for your game, and that means you'll need to learn some new ideas for getting the game to completion.</p>\n<p>The first thing that jumps out at me is it's one huge blob of code. Coding is about re-using code snippets, so we try to make functions where you give it a value (or not), it does some processing, and gives you back a result. Something like:</p>\n<pre><code>def title_message():\n return &quot;Adventure World Quest!&quot;\n</code></pre>\n<p>So we can run it to get the message on the screen: <code>print(title_message())</code>. Admittedly it's <strong>too</strong> simple a function, so instead you would just write <code>print(&quot;Adventure World Quest!&quot;)</code>. However, if you start using it in many places around your code, then it makes sense to put the statement into function, because D.R.Y. (Don't Repeat Yourself).</p>\n<p>We use this process to keep our functions small, typically around 5 lines. Why 5 lines? Well, usually a function does only a single thing, we call this the Single Responsibility Principle. It's part of S.O.L.I.D - have a look at that concept and try to apply it to your code.<br>So, you can pretty much achieve anything in around 5 lines of code. If it's getting bigger than that, there's a good chance we can do some refactoring (rewriting code to simplify it or extract certain parts away into their own function).</p>\n<p>Your blob of code looks like it would enjoy lots of refactoring :)</p>\n<p>So, functions, D.R.Y., S.O.L.I.D, and refactoring. These are some ideas which evolved in the programming field over time. Let's look at how your character functions could be refactored:</p>\n<pre><code>def fire_character():\n global attack\n global health\n global element\n attack += 100\n health += 50\n element = 'fire'\n print(f&quot;\\nSince you have chosen fire: Attack = {attack}, Health = {health}&quot;)\n \ndef water_character():\n global attack\n global health\n global element\n attack = 75\n health = 75\n element = 'water'\n print(f&quot;\\nSince you have chosen water: Attack = {attack}, Health = {health}&quot;)\n</code></pre>\n<p>These two look pretty much the same, so let's use a programmatic approach (with different variables giving us different outcomes) to make their construction easier:</p>\n<pre><code>from enum import Enum\n\nclass Skill(Enum):\n Fire = 0\n Water = 1\n Ice = 2\n\nclass Character:\n def __init__(self, name, health, element):\n self.name = name\n self.health = health\n self.element = element\n \n\nfire_char = Character(&quot;Fireball&quot;, 50, Skill.Fire)\nwater_char = Character(&quot;Waterboy&quot;, 75, Skill.Water)\nice_char = Character(&quot;Icy&quot;, 100, Skill.Ice)\n</code></pre>\n<p>What we've achieved here is instead of hard-coding the elements of a character, we make their creation in a programmatic fashion. Now, when we add a function <code>attack(enemy)</code> to the class of <code>Character</code>, any characters we create after that will automatically get the ability to attack. Something like:</p>\n<pre><code> def attack(self, enemy):\n print(f&quot;{self.name} attacks {enemy.name}&quot;)\n \n</code></pre>\n<p>Starting the battle <code>fire_char.attack(water_char)</code> would show the message <code>Fireball attacks Waterboy</code>. If we go for a more in-depth attack function, we could come up with something like:</p>\n<pre><code>class Dice(Enum):\n @staticmethod\n def d6():\n return randint(1, 6)\n \n</code></pre>\n<p>(adding to class Character)</p>\n<pre><code>def attack(self, enemy):\n dice = Dice.d6()\n\n print(f&quot;{self.name} attacked {enemy.name} with {self.skill.name}&quot;)\n\n if self.skill == enemy.weakness and enemy.weakness != Skill.NoSkill:\n dice += 2\n print(f&quot;-=&lt; {self.name}'s power overwhelms {enemy.name} &gt;=-&quot;)\n if self.skill == enemy.skill and enemy.weakness != Skill.NoSkill:\n dice -= 2\n print(f&quot;___ {enemy.name} knows your skills ___&quot;)\n\n final_damage = dice - enemy.armor_class\n msg = f&quot;{self.name} {Hit(final_damage).name} {enemy.name}&quot;\n\n if final_damage &gt; 0:\n msg += f&quot; for {final_damage} hit point&quot;\n if final_damage &gt; 1:\n msg += &quot;s&quot;\n print(msg)\n return 0 if final_damage &lt; 0 else final_damage\n \n</code></pre>\n<p>When attacking, if the player's skill is the enemy's weakness, we add 2 points of damage. If the player's skill is the same as the enemy, we subtract 2 points due to resistance. The &quot;NoSkill&quot; functionality is for players whom might have a skill that has no weakness. In fact, we should add &quot;NoWeakness&quot; to clarify that (and fix the if statement), but keep &quot;NoSkill&quot; as an option for potential characters who don't wish to use an element skill.</p>\n<p>Looking at line <code>msg = f&quot;{self.name} {Hit(final_damage).name} {enemy.name}&quot;</code> what we're doing is giving a verb response based on the amount of damage inflicted. Here is the function:</p>\n<pre><code>class Hit(Enum):\n missed = 0\n grazed = 1\n knicked = 2\n hit = 3\n sliced = 4\n wounded = 5\n chopped = 6\n</code></pre>\n<p>Rather than hard-coding the various messages and attacks, such as:</p>\n<pre><code> if element == 'fire': ... \n if element == 'water': ...\n if element == 'ice': ...\n\n print(&quot;Your fire ball does extra damage!&quot;)\n print(f&quot;\\nEnemy Health: {en_health} - Your attack: {attack}&quot;)\n en_health = en_health - attack\n print(f&quot;The enemy took an extra 10 damage beacuse of the element difference!&quot;)\n en_health = en_health - 10\n print(f&quot;The enemys health is at {en_health}! He melts into a puddle as you carry on.&quot;)\n \n</code></pre>\n<p>We're using functions to do all those individual statements, and when we want to add another dice - such as a d8 - for a leveled-up character, we need to add more messages, say:</p>\n<pre><code> smashed = 7\n pulverised = 8\n \n</code></pre>\n<p>to the Hit enum class. We can now add the dice to the <code>Dice</code> class use these messages:</p>\n<pre><code> @staticmethod\n def d8():\n return randint(1, 8)\n</code></pre>\n<p>Now we can start to have Fighters, Clerics and Necromancers, oh my. So, if we take your code and write it how you will write it in a few years, we probably come up with something like the below. There is a lot to unpack from the code below - don't be daunted. It's probably easier to understand how it's put together by stepping through the code line by line in your debugger.</p>\n<pre><code>from random import randint\nfrom enum import Enum\nfrom itertools import cycle, permutations\n\n\nclass Dice(Enum):\n @staticmethod\n def d6():\n return randint(1, 6)\n\n @staticmethod\n def d8():\n return randint(1, 8)\n\n\nclass Skill(Enum):\n Fire = 0\n Water = 1\n Ice = 2\n Poison = 3\n Lightning = 4\n Wood = 5\n Necromancy = 6\n Healing = 7\n NoSkill = 8\n NoWeakness = 99\n\n def weakness(self):\n _weakness = {self.Fire: self.Water,\n self.Water: self.Lightning,\n self.Ice: self.Fire,\n self.Poison: self.Healing,\n self.Lightning: self.Wood,\n self.Wood: self.Fire,\n self.Healing: self.Necromancy,\n self.Necromancy: self.Healing,\n self.NoSkill: self.NoWeakness}\n\n return _weakness[self]\n\n\nclass Hit(Enum):\n missed = 0\n grazed = 1\n knicked = 2\n hit = 3\n sliced = 4\n wounded = 5\n chopped = 6\n smashed = 7\n pulverised = 8\n\n\nclass Character:\n def __init__(self, name: str, hit_points: int, skill: Skill, is_player=None):\n self.name = name\n if not isinstance(skill, Skill):\n print(&quot;Character creation invalid. Skill must be of type Skill.Fire, Skill.Water, etc.&quot;)\n return\n self.skill = skill\n self.weakness = skill.weakness()\n self._hit_points = hit_points\n self._is_player = is_player\n self._active_effects = []\n self._is_alive = True\n self._armor_class = 1\n char_type = &quot;is a player&quot; if is_player else &quot;is not a player&quot;\n # print(f&quot;Character {self.name} is now alive. They have {hit_points} hit points and {char_type}&quot;)\n\n def attack(self, enemy):\n dice = Dice.d6()\n\n print(f&quot;{self.name} attacked {enemy.name} with {self.skill.name}&quot;)\n\n if self.skill == enemy.weakness and enemy.weakness != Skill.NoSkill:\n dice += 2\n print(f&quot;-=&lt; {self.name}'s power overwhelms {enemy.name} &gt;=-&quot;)\n if self.skill == enemy.skill and enemy.weakness != Skill.NoSkill:\n dice -= 2\n print(f&quot;___ {enemy.name} knows your skills ___&quot;)\n\n final_damage = dice - enemy.armor_class\n final_damage = 0 if final_damage &lt; 0 else final_damage\n\n msg = f&quot;{self.name} {Hit(final_damage).name} {enemy.name}&quot;\n\n if final_damage &gt; 0:\n msg += f&quot; for {final_damage} hit point&quot;\n if final_damage &gt; 1:\n msg += &quot;s&quot;\n print(msg)\n return final_damage\n\n @property\n def hit_points(self):\n return self._hit_points\n\n def takes_damage(self, value):\n self._hit_points -= value\n if self._hit_points &lt;= 0:\n print(f&quot;{self.name} died&quot;)\n self._is_alive = False\n\n @property\n def armor_class(self):\n return self._armor_class\n\n @armor_class.setter\n def armor_class(self, value):\n print(f&quot;{self.name} puts on new armor.&quot;)\n self._armor_class = value + 1 # skin\n\n @property\n def is_dead(self):\n return self._is_alive == False\n\n\ndef get_user_choice(params, display_params=&quot;&quot;):\n is_a_valid_choice = False\n if display_params == &quot;&quot;:\n display_params = params\n while not is_a_valid_choice:\n choice = input(f&quot;\\nPlease select a choice ({display_params}): &quot;)\n if choice.isalpha():\n choice = choice.lower()\n if choice.isnumeric():\n choice = int(choice)\n if choice in params:\n return choice\n\n print(f&quot;That's unfortunately not a selection you can make. Please select one of these: {display_params}&quot;)\n\n\ndef begin_battle(combatants: list):\n &quot;&quot;&quot;Given a list of combatants, begin the battle. List order determines the sequence of the actions&quot;&quot;&quot;\n\n phases = permutations(combatants)\n fighters = cycle(phases)\n combatants_alive = True\n while combatants_alive:\n act = next(fighters)\n attacker = act[0]\n defender = act[1]\n damage = attacker.attack(defender)\n defender.takes_damage(damage)\n if defender.is_dead:\n combatants_alive = False\n\n return combatants\n\n\ndef title_message():\n return &quot;Adventure World Quest!&quot;\n\n\ndef welcome_message():\n msg = &quot;Welcome to the greatest experience since sliced bread was held over a fire!\\n\\n&quot;\n msg += &quot;You are about to embark on a perilous quest to save a dragon from a princess.\\n\\n&quot;\n msg += &quot;Are you ready?&quot;\n return msg\n\n\ndef okay_bye():\n msgs = [&quot;Thanks for trying!&quot;,\n &quot;Well, *huff* I put all this together and you don't want to keep playing?&quot;,\n &quot;Digital Characters were harmed in the making of this quest.&quot;]\n return msgs[randint(0, 2)]\n\n\ndef do_auto_character():\n return &quot;Do you want to create your own character or just have a random character generated?&quot;\n\n\ndef create_character():\n print(&quot;Welcome to the Unique Character Creation Process&quot;)\n print(&quot;Sorry, it's not ready, so here's a randomly generated character!&quot;)\n character = Character(&quot;Player&quot;, 10, Skill(randint(0, 6)), is_player=True)\n return character\n\n\nif __name__ == &quot;__main__&quot;:\n print(title_message())\n print(welcome_message())\n choices = get_user_choice([&quot;y&quot;, &quot;n&quot;, &quot;yes&quot;, &quot;no&quot;], &quot;y or n&quot;)\n player = Character(&quot;Player&quot;, 10, Skill.Fire, is_player=True)\n\n if choices[0].lower() == &quot;n&quot;:\n print(okay_bye())\n else:\n\n print(do_auto_character())\n choices = get_user_choice([&quot;y&quot;, &quot;n&quot;, &quot;yes&quot;, &quot;no&quot;, &quot;random&quot;], &quot;y or n/random&quot;)\n if choices[0].lower() == &quot;y&quot;:\n player = create_character()\n\n enemy = Character(&quot;Ice Wizard&quot;, 7, Skill.Ice)\n\n player, enemy = begin_battle([player, enemy])\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T03:14:53.280", "Id": "268019", "ParentId": "267937", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-12T23:51:45.247", "Id": "267937", "Score": "4", "Tags": [ "python", "performance", "beginner", "game", "role-playing-game" ], "Title": "Create a little adventure world" }
267937
<blockquote> <p>Given a file or directory, create an iterator that returns the non-empty words from the file or from all files <em>recursively</em> in the directory. Only process &quot;.txt&quot; files. Words are sequence of characters separated by whitespace.</p> </blockquote> <pre><code>class WordIterable: def __init__(self, path: str): root = Path(path) self._walker: Optional[Iterator[Path]] = None if root.is_dir(): self._walker = root.rglob(&quot;*.txt&quot;) elif root.suffix == &quot;.txt&quot;: self._walker = (p for p in [root]) self._open_next_file() self._read_next_line() def __iter__(self) -&gt; Iterator[str]: return self def __next__(self) -&gt; str: next_word = self._next_word() if not next_word: self._read_next_line() next_word = self._next_word() if not next_word: self._close_file() self._open_next_file() self._read_next_line() next_word = self._next_word() return next_word if WordIterable._is_not_blank(next_word) else next(self) def _next_word(self) -&gt; Optional[str]: return self._line.pop() if self._line else None def _read_next_line(self) -&gt; None: self._line = self._fp.readline().split()[::-1] def _open_next_file(self) -&gt; None: if self._walker: self._file: Path = next(self._walker, None) if self._file: self._fp = self._file.open(encoding=&quot;utf8&quot;) return raise StopIteration def _close_file(self) -&gt; None: self._fp.close() @staticmethod def _is_not_blank(s: str) -&gt; bool: return s and s != &quot;\n&quot; </code></pre> <p>This works but seems like a lot of code. Can we do better?</p> <p><strong>Edit:</strong></p> <blockquote> <p>What is a &quot;word&quot; and a &quot;non-empty word&quot;?</p> </blockquote> <p>Words are sequence of characters separated by whitespace.</p> <blockquote> <p>The question doesn't say to recursively processes a directory and it's sub-directories, but that's what the code appears to do.</p> </blockquote> <p>It does now.</p> <blockquote> <p>The code only does &quot;.txt&quot; files.</p> </blockquote> <p>Yes.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:38:24.923", "Id": "528328", "Score": "0", "body": "The question is vague and the code makes some assumptions that aren't in the question. For example, what is a \"word\" and a \"non-empty word\"? Just letters? What about numbers or punctuation? Also, the question doesn't say to recursively processes a directory and it's sub-directories, but that's what the code appears to do. Lastly, the question says to process all files in a directory, but the code only does \".txt\" files." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:02:39.873", "Id": "528329", "Score": "0", "body": "@RootTwo This question was asked in an interview, and interview questions are sadly, but deliberately vague. I've added an edit for your follow up questions." } ]
[ { "body": "<p>The code seems overly complicated and complex for a relatively simple task.</p>\n<pre><code>from pathlib import Path\n\ndef words(file_or_path):\n path = Path(file_or_path)\n \n if path.is_dir():\n paths = path.rglob('*.txt')\n else:\n paths = (path, )\n \n for filepath in paths:\n yield from filepath.read_text().split()\n</code></pre>\n<p>The function can take a a directory name or a file name. For both cases, create an iterable, <code>paths</code>, of the files to be processed. This way, both cases can be handled by the same code.</p>\n<p>For each filepath in <code>paths</code> use <code>Path.read_text()</code> to open the file, read it in, close the file, and return the text that was read. <code>str.split()</code> drops leading and trailing whitespace and then splits the string on whitespace. <code>yield from ...</code> yields each word in turn.</p>\n<p>If you don't want to read an entire file in at once, replace the <code>yield from ...</code> with something like:</p>\n<pre><code> with filepath.open() as f:\n for line in f:\n yield from line.split()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T09:58:03.227", "Id": "528336", "Score": "0", "body": "This is great, but I’d like to take it one step further by reading one word at a time instead of the whole line. However, I’m wondering if that can somehow backfire, since reading one character at a time until a white space is encountered isn’t exactly efficient. I wish there was a `readword` function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T15:04:21.520", "Id": "528360", "Score": "0", "body": "The most commonly used python implementations will be based on C, its stdlib, and UNIX philosophy.\nThe IO there is build around lines and line-by-line processing. A `readword` function in python can be implemented very easily, but under the hood the implementation would read the line and discard everything except the word. You would not gain much" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T17:27:31.420", "Id": "528374", "Score": "0", "body": "It would be totally possible, although definitely harder and less clean, to read the file in fixed-sized chunks instead of by line. And you would gain the ability to not crash if you come across a file with very long lines, e.g. a 32-gigabyte file without the `\\n` character. Although I suppose such a file would likely [exceed `{LINE_MAX}`](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/limits.h.html) (implementation-defined and only required to be >= 2048) and thus [wouldn't count as a \"text file\" according to the POSIX standard](https://unix.stackexchange.com/q/446237)..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T19:40:30.650", "Id": "528383", "Score": "0", "body": "There's one issue with the `yield from` used here, it doesn't check for empty words, which is a requirement in the question. I changed it to `yield from filter(_is_not_blank, line.split())`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T19:59:32.170", "Id": "528385", "Score": "1", "body": "@AbhijitSarkar, `.split()` should already filter out the blanks. Do you have an example input that causes it to return an empty word?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T21:11:49.237", "Id": "528395", "Score": "0", "body": "@RootTwo You're right, I tested with a file containing a line with `\\n` only, a line with spaces and `\\n`, and `split` handled those cases just fine." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:30:43.830", "Id": "267946", "ParentId": "267941", "Score": "6" } } ]
{ "AcceptedAnswerId": "267946", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T03:35:41.043", "Id": "267941", "Score": "4", "Tags": [ "python", "io", "iterator" ], "Title": "Iterate through non-empty words from text files" }
267941
<p>So I did my own take (I wrote my own algorithm) for generating prime numbers from <code>1 to 1000</code>.</p> <pre><code>lst = [y for y in range(1000)] for i in range(0,len(lst)): #i = 1 and i is traversal print(&quot;iterate - &quot; + str(i)) for j in range(i,0,-1): #divisor range print(j) if j != 1 and j &lt; lst[i] and lst[i] % j == 0: if j in lst: lst[i] = 0 break for k in range(len(lst)): if 0 in lst: lst.remove(0) if 1 in lst: lst.remove(1) print(lst) </code></pre> <p>My concerns are</p> <ul> <li>Is this code easy to read?</li> <li>Is this optimal (I don't think so)?</li> <li>What should I do for improving my code?</li> </ul> <p>OUTPUT</p> <blockquote> <p>2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67,<br /> 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149,<br /> 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229,<br /> 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313,<br /> 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409,<br /> 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499,<br /> 503, 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601,<br /> 607, 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691,<br /> 701, 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809,<br /> 811, 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907,<br /> 911, 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997</p> </blockquote>
[]
[ { "body": "<h1>Remove print statements</h1>\n<p>Printing to the console takes a significant amount of time, and you are printing for every iteration and every element in the list. Run it once with the statements, and once without. It's a substantial time save.</p>\n<h1>Removing elements</h1>\n<p>For every iteration in the second loop, you check if <code>1</code> is there. When in reality, you just need to remove the first element of the loop. Second, you can use list comprehension to shorten the amount of code you have to write.</p>\n<pre><code>lst = [x for x in lst if x != 0][1:]\n</code></pre>\n<p>The first set of brackets is the list comprehension, while the <code>[1:]</code> is using pythons list slicing. What this does is takes the result of the list comprehension, and slices off the first element while keeping everything else. <a href=\"https://stackoverflow.com/a/509295\">Here is a Stack Overflow</a> answer that describes this perfectly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:46:43.717", "Id": "267947", "ParentId": "267944", "Score": "1" } }, { "body": "<p>I am not a professional Python developer, so I will address only the performance issue: judging from you <code>for</code> loops structure, it seems that the running time of your implementation is <span class=\"math-container\">\\$\\Theta(n^2)\\$</span>, where <span class=\"math-container\">\\$n\\$</span> is the prime limit. However, you can do the same in <span class=\"math-container\">\\$O(n \\log n)\\$</span>, or even, <span class=\"math-container\">\\$O(n \\log \\log n)\\$</span> time. (See below.)</p>\n<pre><code>import math\nimport time\n\n\ndef op_sieve(limit):\n lst = [y for y in range(limit + 1)]\n for i in range(0, len(lst)): # i = 1 and i is traversal\n for j in range(i, 0, -1): # divisor range\n if j != 1 and j &lt; lst[i] and lst[i] % j == 0:\n if j in lst:\n lst[i] = 0\n break\n\n for k in range(len(lst)):\n if 0 in lst:\n lst.remove(0)\n if 1 in lst:\n lst.remove(1)\n return lst\n\n\ndef sieve(limit):\n s = [True for i in range(limit + 1)]\n s[0] = s[1] = False\n\n for i in range(4, limit + 1, 2):\n s[i] = False\n\n for i in range(3, math.floor(math.sqrt(limit)) + 1, 2):\n if s[i]:\n for m in range(2 * i, limit + 1, i):\n s[m] = False\n\n primes = []\n prime_candidate = 0\n for i in s:\n if i:\n primes.append(prime_candidate)\n prime_candidate += 1\n\n return primes\n\n\ndef sieve2(limit):\n s = [True for i in range(limit + 1)]\n s[0] = s[1] = False\n\n for i in range(2, math.floor(math.sqrt(limit)) + 1):\n if s[i]:\n for j in range(i * i, limit + 1, i):\n s[j] = False\n\n primes = []\n prime_candidate = 0\n for i in s:\n if i:\n primes.append(prime_candidate)\n prime_candidate += 1\n\n return primes\n\n\ndef millis():\n return round(time.time() * 1000)\n\n\nlimit = 5000\n\nstart = millis()\noriginal_sieve = op_sieve(limit)\nend = millis()\n\nprint(end - start)\n\nstart = millis()\nmy_sieve = sieve(limit)\nend = millis()\n\nprint(end - start)\n\nstart = millis()\nmy_sieve2 = sieve2(limit)\nend = millis()\n\nprint(end - start)\n\n#print(original_sieve)\n#print(my_sieve)\n#print(my_sieve2)\nprint(&quot;Agreed: &quot;, original_sieve == my_sieve and my_sieve == my_sieve2)\n</code></pre>\n<p>The output might be as follows:</p>\n<pre><code>7199\n2\n2\nAgreed: True\n</code></pre>\n<p>Hope that helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T11:55:49.123", "Id": "267995", "ParentId": "267944", "Score": "2" } }, { "body": "<h1>PEP 8</h1>\n<blockquote>\n<p>Is the code easy to read?</p>\n</blockquote>\n<p>No, it violates <a href=\"https://pep8.org/\" rel=\"nofollow noreferrer\">the Style Guide for Python Code</a> in a few areas.</p>\n<p>Commas should be followed by a space. Eg, <code>range(0,len(lst))</code> should be <code>range(0, len(lst))</code>, and <code>range(i,0,-1)</code> should be <code>range(i, 0, -1)</code>.</p>\n<p>For throw-away varables, you should use <code>_</code>. Since <code>k</code> is not used in the loop <code>for k in range(len(lst)):</code>, you should write <code>for _ in range(len(lst)):</code> instead.</p>\n<p><code>lst</code> is not the best variable name. It is a list, fine, but a list of what? <code>candidates</code> might be a better name.</p>\n<p>Using <code>for index_variable in range(0, len(some_list)):</code> is an anti-pattern in Python. It is better to enumerate directly over the container. If the index into the container is required, then you should iterate over <code>enumerate(some_list)</code> instead.</p>\n<pre class=\"lang-py prettyprint-override\"><code>candidates = [candidate for candidate in range(1000)]\nfor index, candidate in enumerate(candidates):\n for divisor in range(candidate, 0, -1):\n if divisor != 1 and divisor &lt; candidate and candidate % divisor == 0:\n if divisor in candidates:\n candidates[index] = 0\n break\n\nfor _ in range(len(candidates)):\n if 0 in candidates:\n candidates.remove(0)\n if 1 in candidates:\n candidates.remove(1)\n\nprint(candidates)\n</code></pre>\n<h1>Optimization</h1>\n<blockquote>\n<p>Is this optimal (I don't think so)?</p>\n</blockquote>\n<p>No, it is not optimal.</p>\n<p>You have a list of candidates (<code>lst</code>), an index into the list <code>i</code>, and the candidate value itself <code>lst[i]</code>. It should be clear that your candidate values and indices are actually equal (<code>i == lst[i]</code>), at least before you zero out non-prime values. So we could simplify the first loop, eliminating the extra index.:</p>\n<pre class=\"lang-py prettyprint-override\"><code>candidates = [candidate for candidate in range(1000)]\nfor candidate in candidates:\n for divisor in range(candidate, 0, -1):\n if divisor != 1 and divisor &lt; candidate and candidate % divisor == 0:\n if divisor in candidates:\n candidates[candidate] = 0\n break\n</code></pre>\n<p>Next, consider you divisor range. You test <code>divisor != 1 and divisor &lt; candidate</code>. Why? Because you loop over <code>range(candidate, 0, -1)</code> which includes both <code>1</code> and <code>candidate</code>. A simple modification to the limits eliminates the need to check for those:</p>\n<pre class=\"lang-py prettyprint-override\"><code>candidates = [candidate for candidate in range(1000)]\nfor candidate in candidates:\n for divisor in range(candidate - 1, 1, -1):\n if candidate % divisor == 0:\n if divisor in candidates:\n candidates[candidate] = 0\n break\n</code></pre>\n<p>I'm not sure what the point of the <code>divisor in candidates</code> test is for, but it is not optimal. If <code>divisor in candidates</code> is <code>True</code>, which necessitates an <span class=\"math-container\">\\$O(n)\\$</span> search through the list, then <code>candidates[divisor] != 0</code> will be <code>True</code>, which is a <span class=\"math-container\">\\$O(1)\\$</span> lookup.</p>\n<p>But wait! If we test <code>4</code>, we discover it is divisible by <code>2</code>, and zero it out. Later, when we test <code>8</code>, we discover it is divisible by <code>4</code> ... but <code>4 in candidates</code> is <code>False</code>, so the search goes on until we discover that <code>8</code> is divisible by <code>2</code> which is in the <code>candidates</code> list. Does it matter that <code>4</code> was not prime? No.</p>\n<pre class=\"lang-py prettyprint-override\"><code>candidates = [candidate for candidate in range(1000)]\nfor candidate in candidates:\n for divisor in range(candidate - 1, 1, -1):\n if candidate % divisor == 0:\n candidates[candidate] = 0\n break\n</code></pre>\n<p>Also, you'd actually eliminate composite numbers faster by searching divisors in ascending order.</p>\n<pre class=\"lang-py prettyprint-override\"><code>candidates = [candidate for candidate in range(1000)]\nfor candidate in candidates:\n for divisor in range(1, candidate):\n if candidate % divisor == 0:\n candidates[candidate] = 0\n break\n</code></pre>\n<p>Finally, if you want to do something if some condition is <code>True</code> for <code>any</code> value in a list/range, you can use <code>any()</code>.</p>\n<pre class=\"lang-py prettyprint-override\"><code>candidates = [candidate for candidate in range(1000)]\nfor candidate in candidates:\n if any(candidate % divisor == 0 for divisor in range(1, candidate)):\n candidates[candidate] = 0\n</code></pre>\n<p>The <code>any()</code> loop short-circuits and stops at the first <code>True</code> condition, which means you don't have to <code>break</code> out of the inner loop yourself.</p>\n<p>See other answers about filtering the <code>0</code> and <code>1</code> values out of the <code>candidates</code> list.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T23:22:07.180", "Id": "268017", "ParentId": "267944", "Score": "2" } }, { "body": "<h1>Style</h1>\n<ul>\n<li>Wrap your code in one or more clearly named functions. For example, <code>print(primes_up_to(1000))</code>, or <code>is_prime(38)</code></li>\n<li>Remove the print statements</li>\n<li>Don't call your variables <code>i</code>, <code>j</code>, and <code>k</code>. Use descriptive names like <code>possible_prime</code> and <code>test_divisor</code></li>\n<li>Start your divisor test list at 2, instead of checking whether the divisor is 1 each loop.</li>\n<li>Similarly, start your test prime list at 2, instead of removing 0 and 1 afterwards. You should generally try to avoid doing things and then undoing them. Just don't do them to begin with, it's much clearer.</li>\n</ul>\n<h1>Efficiency</h1>\n<p>Remove the print statements (they will slow things down quite a bit)</p>\n<p>Yes, this is not as efficient as possible. If you want to make things faster, you can speed things up more or less as much as you want, putting in more and more effort--this is a fairly famous problem, so there's plenty to read about it elsewhere. Here are some common optimizations people might do.</p>\n<ul>\n<li>Rather than having a list of 1000 numbers, marking some of them 0, and then removing them, build up your list gradually with only things you won't remove. Also, removing an item from the middle of a list in Python is somewhat slow.</li>\n<li>Iterate through divisors in positive order, not reverse order. Something is more likely to be divisible by 2 than divisible by 429, so you should check that first.</li>\n<li>If you are testing whether 100 is prime, you only need to check divisors up to 10 (the square root). If it's divisible by say, 50, 100/50 = 2, so it will be divisible by a smaller number (2) as well. The cutoff is 100/10 = 10, where the numbers exactly match.</li>\n<li>If you want, you can only check prime numbers for divisibility. You don't need to check divisibility by 4 if you've already checked 2. Just keep a list of prime numbers so far, and check all the primes up to 10, instead of all the numbers up to 10.</li>\n<li>This gets you 'trial division', a reasonably fast way to check if ONE number is prime. But since you're checking all 1000 numbers, there are some more tricks you can do.</li>\n<li>For example, you can check only odd numbers to start with, or only numbers ending in 1, 3, 7, and 9, etc etc</li>\n<li>You could go read about the Sieve of Eratosthenes, discussed I believe in one of the other answers, which is an even faster option. I'm not sure where exactly this sieve starts being faster than trial division, but it's probably around 100-1000. It will be faster for all primes up to 1,000,000 for sure.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T22:22:02.730", "Id": "528664", "Score": "0", "body": "OK I did some testing and it looks like the sieve is basically just always faster, even for small lists." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-17T22:04:29.163", "Id": "268099", "ParentId": "267944", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T05:04:20.983", "Id": "267944", "Score": "4", "Tags": [ "python", "algorithm", "primes" ], "Title": "My prime number generation program in Python" }
267944
<p>I'm using Python's <code>Enum</code> to define the physical units in which a value is expressed.</p> <p>Eventually, I want to add them as an attribute to my <code>pandas.Series</code> and <code>pandas.DataFrame</code> instances, so that this information does not need to be stored in the variable name or in comments in the code. Also, it allows for automatic calculation of the unit of a calculation, e.g., that the result of 40 megawatts during 5 hours is a value in MWh.</p> <p>Here's my code; my questions are below.</p> <pre class="lang-py prettyprint-override"><code>class Unit(Enum): H = (&quot;h&quot;, &quot;duration&quot;) MW = (&quot;MW&quot;, &quot;power&quot;) MWH = (&quot;MWh&quot;, &quot;energy&quot;) EUR = (&quot;Eur&quot;, &quot;revenue&quot;) EURMWH = (&quot;Eur/MWh&quot;, &quot;price&quot;) DEGC = (&quot;degC&quot;, &quot;temperature&quot;) def __init__(self, txt: str = &quot;&quot;, col: str = &quot;&quot;): self._txt = txt self._col = col def __mul__(self, other): if isinstance(other, Unit): relations = ((Unit.MWH, Unit.MW, Unit.H), (Unit.EUR, Unit.MWH, Unit.EURMWH)) for (prod, mul1, mul2) in relations: if (mul1, mul2) == (self, other) or (mul1, mul2) == (other, self): return prod raise NotImplementedError(&quot;This multiplication is not defined.&quot;) def __truediv__(self, other): if isinstance(other, Unit): relations = ((Unit.MWH, Unit.MW, Unit.H), (Unit.EUR, Unit.MWH, Unit.EURMWH)) for (prod, mul1, mul2) in relations: if prod is self and mul1 is other: return mul2 if prod is self and mul2 is other: return mul1 raise NotImplementedError(&quot;This division is not defined.&quot;) def __str__(self): return self._txt u1 = Unit.EUR u2 = Unit.MWH u3 = u1 / u2 # Unit.EURMWH </code></pre> <p>Two questions:</p> <ol> <li>The variable <code>relations</code> is repeated. Is there a better way to do this? I'd prefer to keep in inside the class, but I can't put it at the class's root as it'd be interpreted as an enum value. Put it in a <code>@staticmethod</code> and replace references to it by <code>self.relations()</code>?</li> <li>More generally, is this a valid use case of <code>Enum</code>s? It seems sensible to me, but it's going far beyond just being a list of integers as used in other languages.</li> </ol>
[]
[ { "body": "<p>A small suggestion is to move the <code>relations</code> variable from the function calls to the class and make it static as well. As it will be creating the same variable every time you try to call the <code>__mult__</code> or <code>__truediv__</code> this might be overhead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T07:11:33.117", "Id": "528332", "Score": "0", "body": "Thanks for your comment @rishabh-deep-singh. Could you elaborate? My first question proposes using a `@staticmethod def relations(): return ((. ,. ,. ),(., ., .))`, but that too recreates the variable every time it's called. I suppose I could add `@functools.lru_cache`, but that's not what you mean, correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T16:01:57.537", "Id": "528365", "Score": "1", "body": "I think @Alex Waygood did a great job in this." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:59:01.433", "Id": "267949", "ParentId": "267948", "Score": "0" } }, { "body": "<blockquote>\n<p>Is this a valid use case of <code>Enum</code>s?</p>\n</blockquote>\n<p>In my opinion, using Python's <code>enum</code> module for this kind of task is highly idiomatic — I think you've chosen the best way to express your code's intent here. However, I think there are nonetheless several aspects I might do differently.</p>\n<hr />\n<ol>\n<li><p><strong>Use more descriptive names for your attributes.</strong></p>\n<p>The structure of your data is clear: all members of the <code>Unit</code> enumeration have values that are 2-item tuples, the first item of which is the unit's symbol, and the second item of which is the unit's domain. The names for <code>Unit</code>'s attributes should reflect this, rather than <code>txt</code> and <code>col</code>, both of which are opaque to anyone else reading your code.</p>\n<br>\n<p>(<code>col</code> looks suspiciously like you've named this attribute according to how you intend to use your <code>Unit</code> enumeration in your <code>pandas</code> dataframe. Don't do that. Your <code>Unit</code> class should, ideally, make sense as an abstraction in its own terms, without reference to any external functions or classes. It should know nothing about how you intend to use it in your wider code base.)</p>\n<br>\n<p>Moreover, it's unclear why you have default values in your <code>__init__</code> signature, given that each <code>Unit</code> member <em>must</em> (and does) have a two-item tuple as its value.</p>\n<br>\n<p>You should refactor your <code>__init__</code> and <code>__str__</code> methods to the following:</p>\n<pre><code>from enum import Enum\n\n\nclass Unit(Enum):\n # &lt;-- snip --&gt;\n\n def __init__(self, symbol: str, domain: str) -&gt; None:\n self._symbol = symbol\n self._domain = domain\n\n # &lt;-- snip --&gt;\n\n def __str__(self) -&gt; str:\n return self._symbol\n</code></pre>\n<br>\n</li>\n<li><p><strong>Give your enum members more descriptive names!</strong></p>\n<p>Currently, you have duplication of data in your enumeration: each member's name is the same as the first item of its value, the only difference being that the members all have all-uppercase names, while not all members have all-uppercase <code>symbol</code>s.</p>\n<br>\n<p>You can make your code less repetitive and more readable by giving your enum members more descriptive names:</p>\n<pre><code>from enum import Enum\n\n\nclass Unit(Enum):\n HOUR = &quot;h&quot;, &quot;duration&quot;\n MEGAWATT = &quot;MW&quot;, &quot;power&quot;\n MEGAWATT_HOUR = &quot;MWh&quot;, &quot;energy&quot;\n EURO = &quot;Eur&quot;, &quot;revenue&quot;\n EURO_PER_MEGAWATT_HOUR = &quot;Eur/MWh&quot;, &quot;price&quot;\n DEGREES_CENTIGRADE = &quot;degC&quot;, &quot;temperature&quot;\n\n # &lt;-- snip --&gt;\n</code></pre>\n<br>\n</li>\n<li><p><strong>... You probably shouldn't have an <code>__init__</code> method at all.</strong></p>\n<p>The pattern you're implementing in your code is essentially a <code>NamedTuple</code>/<code>Enum</code> hybrid. You have structured data, much like you would with a series of <code>NamedTuple</code>s all of the same type (each member's value is a 2-item tuple; the first item of each member's value is always the unit's symbol, while the second item is always the unit's domain). Meanwhile, you have a predefined set of <code>Unit</code>s that is known at compilation time and cannot be extended at runtime, much like the traditional conception of an <code>Enum</code>.</p>\n<br>\n<p>By using an <code>__init__</code> method to name the fields in your <code>Enum</code> members' values, however, you in fact add mutable attributes to your enumeration's members. Say we have the following definitions:</p>\n<pre><code>from typing import NamedTuple\nfrom enum import Enum\n\n\nclass UnitNT(NamedTuple):\n symbol: str\n domain: str\n\n\nclass UnitEnum(Enum):\n def __init__(self, symbol: str, domain: str) -&gt; None:\n self._symbol = symbol\n self._domain = domain\n\n HOUR = 'h', 'duration'\n</code></pre>\n<br>\n<p>Let's observe how these behave in the interactive REPL. Here's the <code>NamedTuple</code> version:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; hour_nt = UnitNT(symbol='h', domain='duration')\n&gt;&gt;&gt; hour_nt\nUnitNT(symbol='h', domain='duration')\n&gt;&gt;&gt; hour_nt.symbol\n'h'\n&gt;&gt;&gt; hour_nt.symbol = 'foo'\nTraceback (most recent call last):\n File &quot;&lt;string&gt;&quot;, line 1, in &lt;module&gt;\nAttributeError: can't set attribute\n&gt;&gt;&gt; hour_nt.symbol\n'h'\n&gt;&gt;&gt; hour_nt\nUnitNT(symbol='h', domain='duration')\n</code></pre>\n<br>\n<p>And here's the <code>Enum</code> version:</p>\n<pre class=\"lang-none prettyprint-override\"><code>&gt;&gt;&gt; hour_enum = UnitEnum.HOUR\n&gt;&gt;&gt; hour_enum\n&lt;UnitEnum.HOUR: ('h', 'duration')&gt;\n&gt;&gt;&gt; hour_enum._symbol\n'h'\n&gt;&gt;&gt; hour_enum.value\n('h', 'duration')\n&gt;&gt;&gt; hour_enum._symbol = 'foo'\n&gt;&gt;&gt; hour_enum._symbol\n'foo'\n&gt;&gt;&gt; hour_enum\n&lt;UnitEnum.HOUR: ('h', 'duration')&gt;\n&gt;&gt;&gt; hour_enum.value\n('h', 'duration')\n</code></pre>\n<br>\n<p>As we can see, the <code>NamedTuple</code> version here is truly immutable, and raises an exception if we try to alter the <code>.symbol</code> attribute of the data, leaving the original data unchanged. However, the behaviour of the <code>Enum</code> is... surprising. If we try to change the <code>._symbol</code> attribute... no error is raised! The <code>._symbol</code> attribute is a mutable attribute, just like you'd get in a normal python class. But when we examine the enum member again, we find that, although the <code>._symbol</code> attribute has been altered, the member's <em>value</em> is unchanged. All that we've done is created a situation in which the <code>._symbol</code> attribute no longer corresponds to the first item of the member's value.</p>\n<br>\n<p>I don't consider this a bug in the design of python <code>enum</code>s, as there are some situations in which you might want to attach a mutable attribute to an otherwise-immutable constant.</p>\n<br>\n<p><em>(For example: consider a pack of cards in a <code>pygame</code> game. There will only ever be 52 cards, so an <code>Enum</code> might make sense as a good way of representing the pack. Nonetheless, it may be desirable for each member of the pack to have mutable attributes describing the location of the card on the screen, etc., as well as immutable attributes that will never change — the card's suit, the card's rank, etc.)</em></p>\n<br>\n<p>However, it's undesirable behaviour in this situation. You should get rid of your <code>__init__</code> method and replace it with read-only properties. While we're at it, we can also improve our <code>__repr__</code> method to make it more <code>NamedTuple</code>-ish.</p>\n<pre><code>class Unit(Enum):\n HOUR = &quot;h&quot;, &quot;duration&quot;\n MEGAWATT = &quot;MW&quot;, &quot;power&quot;\n MEGAWATT_HOUR = &quot;MWh&quot;, &quot;energy&quot;\n EURO = &quot;Eur&quot;, &quot;revenue&quot;\n EURO_PER_MEGAWATT_HOUR = &quot;Eur/MWh&quot;, &quot;price&quot;\n DEGREES_CENTIGRADE = &quot;degC&quot;, &quot;temperature&quot;\n\n @property\n def symbol(self) -&gt; str:\n &quot;&quot;&quot;Get the symbol which is most commonly used for this unit.&quot;&quot;&quot;\n return self.value[0]\n\n @property\n def domain(self) -&gt; str:\n &quot;&quot;&quot;Get the domain for which this unit is relevant.&quot;&quot;&quot;\n return self.value[1]\n\n # __mul__ and __truediv__ skipped (for now)\n\n def __str__(self) -&gt; str:\n return self.symbol\n\n def __repr__(self) -&gt; str:\n return f'&lt;Unit.{self.name}(symbol={self.symbol!r}, domain={self.domain!r})&gt;'\n</code></pre>\n<br>\n<p>Now we have the best parts of <code>NamedTuple</code> and <code>Enum</code> combined in our class.</p>\n<br>\n</li>\n<li><p><strong>Your <code>__mul__</code> and <code>__truediv__</code> methods are not extensible or self-documenting.</strong></p>\n<p>In these two methods, you define certain groups of units for which multiplication/division is defined. However, as you note, this logic is repeated between the two methods. Moreover, it's not great having this data hardcoded into the middle of this method at all. This information is fundamental to the definition of the enum, so should be in the class namespace rather than buried in a method.</p>\n<br>\n<p>I'd refactor your code like so:</p>\n<pre><code>from __future__ import annotations\n\nfrom enum import Enum \nfrom typing import NamedTuple\nfrom functools import cache\n\n\nclass MultipliableUnitGroup(NamedTuple):\n &quot;&quot;&quot;\n A class defining a relationship between two `Unit` enum members\n such that they can be multiplied together to create a third unit.\n &quot;&quot;&quot;\n\n multipliers: frozenset[Unit]\n result_unit: Unit\n\n\nclass Unit(Enum):\n HOUR = &quot;h&quot;, &quot;duration&quot;\n MEGAWATT = &quot;MW&quot;, &quot;power&quot;\n MEGAWATT_HOUR = &quot;MWh&quot;, &quot;energy&quot;\n EURO = &quot;Eur&quot;, &quot;revenue&quot;\n EURO_PER_MEGAWATT_HOUR = &quot;Eur/MWh&quot;, &quot;price&quot;\n DEGREES_CENTIGRADE = &quot;degC&quot;, &quot;temperature&quot;\n\n @property\n def symbol(self) -&gt; str:\n &quot;&quot;&quot;Get the symbol which is most commonly used for this unit.&quot;&quot;&quot;\n return self.value[0]\n\n @property\n def domain(self) -&gt; str:\n &quot;&quot;&quot;Get the domain for which this unit is relevant.&quot;&quot;&quot;\n return self.value[1]\n\n @classmethod\n @property\n @cache\n def multipliable_unit_groups(cls) -&gt; frozenset[MultipliableUnitGroup]:\n &quot;&quot;&quot;Get the subgroups of members for which multiplication and division are defined.&quot;&quot;&quot;\n\n return frozenset({\n MultipliableUnitGroup(\n multipliers=frozenset({cls.MEGAWATT, cls.HOUR}),\n result_unit=cls.MEGAWATT_HOUR\n ),\n MultipliableUnitGroup(\n multipliers=frozenset({cls.EURO_PER_MEGAWATT_HOUR, cls.MEGAWATT_HOUR}),\n result_unit=cls.EURO\n )\n })\n\n def __mul__(self, other: Unit) -&gt; Unit:\n if type(other) is Unit:\n as_set = {self, other}\n for multipliers, result_unit in self.multipliable_unit_groups:\n if multipliers == as_set:\n return result_unit\n return NotImplemented\n\n __rmul__ = __mul__\n\n def __truediv__(self, other: Unit) -&gt; Unit:\n if type(other) is Unit:\n for multipliers, result_unit in self.multipliable_unit_groups:\n if result_unit is self and other in multipliers:\n return next(filter(other.__ne__, multipliers)) \n return NotImplemented\n\n def __rtruediv__(self, other: Unit) -&gt; Unit:\n return (other / self) if type(other) is Unit else NotImplemented\n\n def __str__(self) -&gt; str:\n return self.symbol\n\n def __repr__(self) -&gt; str:\n return f'&lt;Unit.{self.name}(symbol={self.symbol!r}, domain={self.domain!r})&gt;'\n</code></pre>\n<br>\n<p>Since python 3.9, we've been able to stack <code>@classmethod</code> on top of <code>@property</code>, which is extremely helpful if we want to add read-only class attributes to an <code>Enum</code> that we <em>don't</em> want to be converted into members. By throwing <code>functools.cache</code> into the mix as well, we ensure that the class attribute is only computed once.</p>\n<br>\n<p>Note also that I changed your <code>isinstance</code> check to an <code>if type(other) is Unit</code> check — since enums that have members are not subclassable, this makes more sense.</p>\n<br>\n<p>Lastly, it's <a href=\"https://docs.python.org/3/library/exceptions.html#NotImplementedError\" rel=\"nofollow noreferrer\">good</a> <a href=\"https://docs.python.org/3/library/constants.html#NotImplemented\" rel=\"nofollow noreferrer\">practice</a> to return <code>NotImplemented</code> for undefined operations in methods where you're overloading an operator, rather than raising <code>NotImplementedError</code>. This is because the object on the right-hand side of the operator might know how to multiply the two objects together, even if the object on the left side doesn't. In the code <code>x * y</code>, python will first try multiplying the two items together by using <code>x.__mul__</code>, but if that returns <code>NotImplemented</code>, it will try again using <code>y.__rmul__</code>, and only if <em>that also</em> returns <code>NotImplemented</code> will it then raise a <code>TypeError</code> telling you that that operation is undefined between <code>x</code> and <code>y</code> due to incompatible types. If <code>x.__mul__</code> raises <code>NotImplementedError</code> instead of returning <code>NotImplemented</code>, however, python has no opportunity to try using <code>y.__rmul__</code>; the raised exception means the programme has already ended. For the same reason, you <a href=\"https://stackoverflow.com/a/5182501/13990016\">should always define</a> <code>__rmul__</code> and <code>__rtruediv__</code> whenever you define <code>__mul__</code> and <code>__truediv__</code> in a class, as I've done above.</p>\n</li>\n</ol>\n<br>\n<hr />\n<br>\n<p><em>Addendum</em></p>\n<p>In my final code snippet above, I used two Python 3.9 features: <code>functools.cache</code> and the ability to stack <code>@classmethod</code> on top of <code>@property</code>. However, note that if you're on Python &lt;= 3.8, you can use the following code instead, which is more backwards-compatible. It utilises the fact that methods and properties declared in a metaclass definition <a href=\"https://stackoverflow.com/questions/59341761/what-are-the-differences-between-a-classmethod-and-a-metaclass-method\">have similar behaviour</a> to classmethods and classmethod-properties declared in a class definition:</p>\n<pre><code>from __future__ import annotations\n\nfrom enum import Enum, EnumMeta\nfrom typing import NamedTuple\nfrom functools import lru_cache\n\n\nclass MultipliableUnitGroup(NamedTuple):\n &quot;&quot;&quot;\n A class defining a relationship between two `Unit` enum members\n such that they can be multiplied together to create a third unit.\n &quot;&quot;&quot;\n\n multipliers: frozenset[Unit]\n result_unit: Unit\n\n\nclass UnitEnumMeta(EnumMeta):\n &quot;&quot;&quot;Metaclass for `Unit`&quot;&quot;&quot;\n\n @property\n @lru_cache\n def multipliable_unit_groups(cls) -&gt; frozenset[MultipliableUnitGroup]:\n &quot;&quot;&quot;Get the subgroups of members for which multiplication and division are defined.&quot;&quot;&quot;\n\n return frozenset({\n MultipliableUnitGroup(\n multipliers=frozenset({cls.MEGAWATT, cls.HOUR}),\n result_unit=cls.MEGAWATT_HOUR\n ),\n MultipliableUnitGroup(\n multipliers=frozenset({cls.EURO_PER_MEGAWATT_HOUR, cls.MEGAWATT_HOUR}),\n result_unit=cls.EURO\n )\n })\n\n\nclass Unit(Enum, metaclass=UnitEnumMeta):\n HOUR = &quot;h&quot;, &quot;duration&quot;\n MEGAWATT = &quot;MW&quot;, &quot;power&quot;\n MEGAWATT_HOUR = &quot;MWh&quot;, &quot;energy&quot;\n EURO = &quot;Eur&quot;, &quot;revenue&quot;\n EURO_PER_MEGAWATT_HOUR = &quot;Eur/MWh&quot;, &quot;price&quot;\n DEGREES_CENTIGRADE = &quot;degC&quot;, &quot;temperature&quot;\n\n @property\n def symbol(self) -&gt; str:\n &quot;&quot;&quot;Get the symbol which is most commonly used for this unit.&quot;&quot;&quot;\n return self.value[0]\n\n @property\n def domain(self) -&gt; str:\n &quot;&quot;&quot;Get the domain for which this unit is relevant.&quot;&quot;&quot;\n return self.value[1] \n\n def __mul__(self, other: Unit) -&gt; Unit:\n if type(other) is Unit:\n as_set = {self, other}\n for multipliers, result_unit in type(self).multipliable_unit_groups:\n if multipliers == as_set:\n return result_unit\n return NotImplemented\n\n __rmul__ = __mul__\n\n def __truediv__(self, other: Unit) -&gt; Unit:\n if type(other) is Unit:\n for multipliers, result_unit in type(self).multipliable_unit_groups:\n if result_unit is self and other in multipliers:\n return next(filter(other.__ne__, multipliers)) \n return NotImplemented\n\n def __rtruediv__(self, other: Unit) -&gt; Unit:\n return (other / self) if type(other) is Unit else NotImplemented\n\n def __str__(self) -&gt; str:\n return self.symbol\n\n def __repr__(self) -&gt; str:\n return f'&lt;Unit.{self.name}(symbol={self.symbol!r}, domain={self.domain!r})&gt;'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T11:28:17.583", "Id": "528340", "Score": "1", "body": "Great answer @Alex and many good points. Many thanks for taking the time! I was aware of the mutability and had already added property accessors to get the `._txt` and `._col` values, but forgoing `__init__` altogether is a good idea I wasn't aware of." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T11:40:57.270", "Id": "528341", "Score": "0", "body": "@ElRudi No problem - glad I was helpful! Good catch with the suggested edit -- I was editing my answer simultaneously so it got lost, but I've made your suggested change." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T12:39:02.963", "Id": "528345", "Score": "1", "body": "Thanks also for suggesting `return NotImplemented` instead of `raise NotImplementedError`; I wasn't aware of this distinction. About implementing `__rmul__`: in this particular case, the only implemented case is when 2 units are multiplied, so if `__mul__` returns `NotImplemented`, so does `__rmul__`. Same for division. Is it still necessary/good practice to define both in that case? (`__rmul__ = __mul__` is easy enough, but `__rtruediv__` must be implemented seperately.)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T12:42:27.700", "Id": "528346", "Score": "0", "body": "@ELRudi, yes -- it's arguable whether it's *strictly* necessary to define `__rmul__` and `__rtruediv__` in this particular case. But I'd say it's a good habit to get into nonetheless. Also, my initial implementation of `__rtruediv__` was far more convoluted than it needed to be. You can just delegate to `__truediv__` in this situation, making it a one-liner (see my edited version!)." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T10:33:43.493", "Id": "267954", "ParentId": "267948", "Score": "18" } }, { "body": "<p>It's an excellent exercise to try to write your own library.</p>\n<p>Since you mentioned pandas and currency units, you might want to try <a href=\"https://pint.readthedocs.io/en/stable/\" rel=\"noreferrer\">pint</a>.</p>\n<blockquote>\n<p>Pint is a Python package to define, operate and manipulate physical\nquantities: the product of a numerical value and a unit of\nmeasurement. It allows arithmetic operations between them and\nconversions from and to different units.</p>\n</blockquote>\n<p>You can <a href=\"https://pint.readthedocs.io/en/stable/defining.html\" rel=\"noreferrer\">define your own units and dimensions</a>:</p>\n<pre><code>from pint import UnitRegistry\n\nunit = UnitRegistry()\n\nunit.define('dollar = [currency] = USD')\nunit.define('euro = 1.18 dollar = EUR')\nunit.define('bitcoin = 44733 USD = BTC')\n\nprice = 10 * unit.EUR\nprint(price)\n# 10 euro\nprint(price.to('dollars'))\n# 11.799999999999999 dollar\nprint(price.to('BTC'))\n# 0.0002637873605615541 bitcoin\nprint(10 * unit.EUR + 2 * unit.USD)\n# 11.694915254237289 euro\n</code></pre>\n<p>You can now combine monetary units with energy units:</p>\n<pre><code>print((123 * unit.EUR / unit.MWh * 5 * unit.kW * 1 * unit.year).to('USD'))\n# 6361.486199999999 dollar\n</code></pre>\n<p>Pint seems to support numpy arrays out of the box, so it should work fine with series and dataframes in pandas too:</p>\n<pre><code>energy_per_year = [1, 2, 3] * unit.MWh / unit.year\nprint(energy_per_year)\n# [1.0 2.0 3.0] megawatt_hour / year\nprint(energy_per_year.to(unit.kW))\n# [0.11407711613050422 0.22815423226100845 0.3422313483915127] kilowatt\n</code></pre>\n<p>Pint also delivers meaningful error messages for forbidden operations:</p>\n<pre><code>print(1 * unit.EUR + 3 * unit.kW)\n# pint.errors.DimensionalityError: Cannot convert from 'euro' ([currency]) to 'kilowatt' ([length] ** 2 * [mass] / [time] ** 3)\n</code></pre>\n<p>Since it's open-source, you can take a look at the <a href=\"https://github.com/hgrecco/pint/blob/master/pint/unit.py\" rel=\"noreferrer\">code</a> and compare it to yours.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T19:20:15.073", "Id": "528481", "Score": "0", "body": "I wanted to easily convert time from seconds to months and honestly found pint to be really _really_ easy. +1 One note tho; I found something like `unit(\"20 m / 5 s\")` to output nonsense. But `unit(\"20 / 5 m / s\")` seemed to fix the problem." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T19:38:17.993", "Id": "528486", "Score": "0", "body": "@Peilonrayz: It's a great library indeed, and the seamless integration with numpy is a nice touch. When writing fractions on a piece of paper, it's really easy to show the difference between \\$\\frac{ab}{cd}\\$ and \\$a * \\frac{b}{c} * d\\$. But when writing code, on one line, and without parens, `20 m / 5 s` is `20 * (m / 5) * s`, even though humans might interpret it as `(20 m) / (5 s)`. I used to write `kWh / m² . y` for annual solar energy, even though it should be `kWh / (m² . y)`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T19:47:49.900", "Id": "528488", "Score": "0", "body": "Oh gosh darn it, you're so right. Now I feel a little silly :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T19:55:45.580", "Id": "528492", "Score": "2", "body": "@Peilonrayz: No problem. It feels natural to read it as `(20 m) / (5 s)`, especially when it's written `20m / 5s`. It feels weird to separate `5` and `s` since they're apparently stuck together. There are trick questions on social media based on this ambiguity, e.g. `6 ÷ 2(1+2)`. The only correct answer is : \"use parentheses!\"." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T20:04:34.217", "Id": "267979", "ParentId": "267948", "Score": "8" } }, { "body": "<p>One comment about the design: your current list of units</p>\n<pre><code>H = (&quot;h&quot;, &quot;duration&quot;)\nMW = (&quot;MW&quot;, &quot;power&quot;)\nMWH = (&quot;MWh&quot;, &quot;energy&quot;)\nEUR = (&quot;Eur&quot;, &quot;revenue&quot;)\nEURMWH = (&quot;Eur/MWh&quot;, &quot;price&quot;)\nDEGC = (&quot;degC&quot;, &quot;temperature&quot;)\n</code></pre>\n<p>does not separate unit from scale. Energy and power have &quot;mega&quot; baked in, for instance. A more general approach would offer</p>\n<ul>\n<li>time in units of years, months, weeks, days, hours, minutes, seconds, and SI fractions of seconds;</li>\n<li>SI multiples for power, energy and temperature; and perhaps</li>\n<li>Euros or cents (the accepted sub-unit for euros).</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T07:33:01.777", "Id": "528522", "Score": "1", "body": "That's a valid point! In this use-case, for energy trade, the units are always the ones mentioned here, and e.g. a GWh is thought of as 1000 MWh, not 1e9 Wh or 3.6e12 J. A more general application would take various prefixes into consideration. BTW: allowing time to be expressed in year, months, quarters or days is extremely tricky, as these do not have a fixed duration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T13:28:18.283", "Id": "528536", "Score": "0", "body": "Of course time will be tricky, but will sometimes be necessary. You're working in the energy sector: what if you're asked how much energy was consumed over a billing period of one month?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-15T22:06:38.823", "Id": "528551", "Score": "0", "body": "My point was that, e.g. MWh/month is not a useful unit in and of itself. 720 MWh/month is an average rate of less than, more than, or exactly 1 MW, depending on the month, and therefore only makes sense if the actual month is added to the number. (For this exact use case I've created and added a `.duration` property to pandas `DateatimeIndex` and `Timestamp` objects, which uses the timestamp and its `freq` argument to find the timedelta in hours. Ah and don't tell me about periodindices. They don't work with DST )" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-14T14:38:06.757", "Id": "268002", "ParentId": "267948", "Score": "3" } } ]
{ "AcceptedAnswerId": "267954", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T06:53:54.230", "Id": "267948", "Score": "12", "Tags": [ "python", "reinventing-the-wheel", "enum" ], "Title": "Using Python enums to define physical units" }
267948
<p>I'm doing the following exercise from PPP - Bjarne Stroustrup, Chapter 19, ex.10.</p> <blockquote> <p>Implement a simple <code>unique_ptr</code> supporting only a constructor, destructor,<code>-&gt;</code>, <code>*</code> and <code>release()</code>. In particular, don't try to implement an assignment or a copy constructor</p> </blockquote> <p>Here's what I've done so far, for which I'd like to have a check. I did this without looking at available resources on this site or on the web, so I'd like to have a check and, of course, any suggestion in highly appreciated! I tried to copy the declarations from the std::unique_ptr reference on the web.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; template &lt;typename T&gt; class Unique_Ptr { private: T *ptr; public: explicit Unique_Ptr(T *p) noexcept : ptr{p} {} ~Unique_Ptr() { delete ptr; }; T *operator-&gt;() const noexcept { return ptr; } inline T operator*() const { return *ptr; } inline T *get() const noexcept { return ptr; } T *release() noexcept { auto tmp = ptr; ptr = nullptr; return tmp; } }; int main() { //Constructor test Unique_Ptr p{new int{2}}; std::cout &lt;&lt; *p &lt;&lt; &quot;\n&quot;; //Test with pointer to a vector Unique_Ptr pp{new std::vector&lt;int&gt;{1, 2, 3}}; std::cout &lt;&lt; pp-&gt;size() &lt;&lt; &quot;\n&quot;; //release() test auto test_release = pp.release(); std::cout &lt;&lt; (pp.get() == nullptr) &lt;&lt; &quot;\n&quot;; //expect 1 std::cout &lt;&lt; test_release-&gt;size() &lt;&lt; &quot;\n&quot;; return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T13:08:50.397", "Id": "528348", "Score": "0", "body": "You need to deal with copy / move constructors and assignments - their implementation and declarations are missing. Also default one ought to set `ptr` to `nullptr`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T17:25:56.993", "Id": "528372", "Score": "0", "body": "I have rolled back Rev 3 → 1. Please see [_What to do when someone answers_](https://codereview.stackexchange.com/help/someone-answers)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T17:26:31.197", "Id": "528373", "Score": "1", "body": "Ok, I'm going to ask a new question! Thanks." } ]
[ { "body": "<p>First of all, you don't need to write <code>inline</code> when a function is defined inside the class. You might notice that you've used it in some but not all of them; it doesn't add anything to the meaning.</p>\n<blockquote>\n<p>In particular, don't try to implement an assignment [operator] or a copy constructor</p>\n</blockquote>\n<p>(N.B. did you leave out the word <em>operator</em> when you typed the quotation?)</p>\n<p>Rather than leaving them off, which will cause an incorrect default implementation to be generated, mark them as <code>=delete</code>. That way you'll get an error if your test code would try to make use of them, rather than just some bizarre malfunction. Use the &quot;rule of 5&quot;.</p>\n<p><code> T *operator-&gt;()</code><br />\nThat looks odd...<br />\nThe style in C++ is to put the <code>*</code> or <code>&amp;</code> with the <em>type</em>, not the identifier. This is called out specifically near the beginning of Stroustrup’s first book, and is an intentional difference from C style.</p>\n<p>The problem did specify <em>a constructor</em> implying the singular. And you've given one, which prevents a default constructor from being automatically generated. But you could add a default constructor or add a default argument to your one-argument constructor, without getting into territory that's too advanced for you.</p>\n<p><code>std::cout &lt;&lt; test_release-&gt;size() &lt;&lt; &quot;\\n&quot;;</code><br />\nThis should cause a run-time error when it dereferences the nullptr. That's not a good way to implement a test program, especially without commenting that.</p>\n<p>BTW, using <code>'\\n'</code> instead of <code>&quot;\\n&quot;</code> is more efficient.</p>\n<h2>All in all, it looks good.</h2>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T17:19:13.313", "Id": "528368", "Score": "0", "body": "Thanks for your answer. I updated my question with the fixed code. I need, however, a check on my move semantics. I wrote in the edit what's my issue" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T17:31:25.200", "Id": "528375", "Score": "0", "body": "I've posted a new question here with the improved version you suggested: https://codereview.stackexchange.com/questions/267976/improving-my-implementation-of-a-unique-ptr-ppp-stroustrup-book" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T20:41:58.823", "Id": "528392", "Score": "1", "body": "`operator->()` should also return a `T&`, not a `T*`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:03:23.410", "Id": "267963", "ParentId": "267957", "Score": "1" } }, { "body": "<ol>\n<li><p>The default constructor is missing.</p>\n</li>\n<li><p>The move constructor and move assignment operator are missing (they are <em>not</em> copying!).</p>\n</li>\n</ol>\n<p>Otherwise, it looks good.</p>\n<p>Although a matter of style, I find that it helps to indicate pointer types even when using <code>auto</code>, i.e.</p>\n<pre><code>auto* test_release = pp.release();\n</code></pre>\n<p>When writing &quot;ad hoc&quot; tests, prefer to use <code>assert</code> instead of writing to the console. You don't need human eyes to verify that the results are correct:</p>\n<pre><code>constexpr auto N = std::vector&lt;int&gt;::size_type(3);\n\nauto *const vector = new std::vector&lt;int&gt;(N);\nstd::iota(vector-&gt;begin(), vector-&gt;end(), 0);\nassert(vector-&gt;size() == N);\n\nUnique_Ptr pp{vector};\nassert(pp-&gt;get() == vector);\nassert(pp-&gt;size() == N);\n\nauto *test_release = pp.release();\nassert(!pp-&gt;get());\nassert(test_release == vector);\nassert(test_release-&gt;size() == N);\n</code></pre>\n<p>Such tests are then very easy to convert to use an actual testing framework. E.g. for the <a href=\"https://github.com/catchorg/Catch2/blob/devel/docs/assertions.md\" rel=\"nofollow noreferrer\">Catch2</a> framework, just replace <code>assert</code> with <code>REQUIRE</code> or <code>CHECK</code> (those two are equivalent, the latter continues testing even if the statement wasn't true).</p>\n<p>Output to console may be useful when debugging, but even then examining the state in the debugger may save time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T17:21:25.990", "Id": "528370", "Score": "0", "body": "Thanks for your useful answer. I've updated my code using your suggestions about `assert`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:06:49.597", "Id": "267965", "ParentId": "267957", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T11:56:33.757", "Id": "267957", "Score": "0", "Tags": [ "c++", "reinventing-the-wheel", "c++14", "pointers" ], "Title": "Implementing a unique_ptr - PPP Stroustrup exercise" }
267957
<p>Dumbserver, or the simplest workable HTTP server. It is supposed to operate in the 'traditional' way, that is, mapping paths in requests to the directory structure.</p> <p>Why did I write it: I needed a simple development server for a website I'm trying to make. Instead of using Express or something like that for this purpose, I thought I'd make my own simplistic server as an exercise.</p> <p>I don't know Javascript very well and I suppose that especially here they may be multiple subtleties I don't know about and/or failed to handle. Pointing these out would be much appreciated.</p> <p>Also I suppose that reading the whole file into memory and then writing it to the socket is a poor thing to do, I should instead pipe the file stream into the socket? But I'm not sure how to do this. <code>createReadStream</code> will only give me errors <em>after</em> I start reading it, but then it is too late: I need to set an erroneous HTTP code <em>before</em> I start writing to the response object ;/</p> <pre class="lang-js prettyprint-override"><code>const {createServer} = require('http'); const {join} = require('path') const {readFile} = require('fs').promises const {getType} = require('mime/lite') const argv = require('minimist')(process.argv.slice(2)) const dir = argv.www const host = argv.host const port = argv.port if(dir === undefined || host == undefined || port == undefined) { console.error(`Usage: ${process.argv[1]} --www=C:\\directory\\of\\your\\webpage --host=example.com --port=80`) process.exit(1) } function decodePathname(pathname, err) { try { return decodeURIComponent(pathname) } catch(e) { if(e instanceof(URIError)) { err.code = 400 return } else { throw e } } } function splitPathname(pathname, err) { const decodedPathname = decodePathname(pathname, err) if(decodedPathname) { return pathname.split('/') } } function constructOsPath(pathname, err) { const parts = splitPathname(pathname, err) if(parts) { let res = dir for(const part of parts) { res = join(res, part) // Defense against escaping from dir by stacking ..'s in request URL // Checking this on each step to prevent guessing directory structure by requests such as http://example.com/../../var/www/index.html if(!res.startsWith(dir)) { err.code = 403 return } } return {path: res, mime: getType(res)} } } async function getResponse(pathname, err) { const pathMime = constructOsPath(pathname, err) if(pathMime) { try { return {content: await readFile(pathMime.path), mime: pathMime.mime} } catch(e) { if(e instanceof(Error)) { if(e.code == 'ENOENT') { err.code = 404 return } else if(e.code == 'EACCESS') { err.code = 403 return } else if(e.code == 'EISDIR') { err.code = 422 // Not sure about code here? Is 422 appropriate really? return; } else { throw e } } else { throw e } } } } async function processRequest(req, res) { if(!['GET', 'HEAD'].includes(req.method)) { res.code = 501 return } const url = new URL(req.url, `http://${req.headers.host}`) const pathname = url.pathname const err = {} // Bad, I know, but idk what else can be done // - I should do a createReadStream and then pipe this stream to the response! // - But then what if this stream errors out? I should send HTTP 500 but can't do so if I've already started sending a response // - I should not read the file when responding to a HEAD request! // - I shouldn't, but otherwise it's hard to guarantee that HEAD returns same exact status as GET would const contentMime = await getResponse(pathname, err) if(contentMime) { res.setHeader('Content-Type', contentMime.mime ?? 'application/octet-stream') if(req.method == 'GET') { res.end(contentMime.content) } else if(req.method == 'HEAD') { res.end() } } else { res.statusCode = err.code res.end() } } const server = createServer((req, res) =&gt; { const now = new Date(Date.now()) console.log(`${now.toISOString()} ${req.socket.remoteAddress} -&gt; ${req.method} ${req.url}`) processRequest(req, res).catch(e =&gt; { console.error(e) res.code = 500 res.end() }) }) server.on('error', e =&gt; console.error(e)) server.listen(port, host, () =&gt; console.log('Server listening')) </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T13:46:29.587", "Id": "267962", "Score": "2", "Tags": [ "javascript", "node.js", "http", "server" ], "Title": "Node.js Dumbserver" }
267962
<p>I'm a new DS student, and I get the basic concept of Standardisation, whilst I was learning we used StandardScaler in some algorithms, and not in others on the same dataset, and I'm still confused as where and to use it.</p> <p>I have other categorical features selected for the classifiers. Could you please review my code, and advise best practice for Linear, MultipleLinear, Logistic, KNN, and SVM in relation to Scaling?</p> <pre><code>import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Ass2Dataset.csv') X = dataset.iloc[0:50, -4].values y = dataset.iloc[0:50, -2].values X = X.reshape(-1,1) y = y.reshape(-1,1) from sklearn.impute import SimpleImputer imputer = SimpleImputer (missing_values=np.nan, strategy='mean') imputer.fit (X[:]) (X[:]) = imputer.transform((X[:])) imputer.fit (y[:]) (y[:]) = imputer.transform((y[:])) from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split (X, y, test_size = 0.3, random_state = 0) ## Scaling method used in LogisticRegression, KNN, and SVM algorithms. from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) ## LinearRegression method from sklearn.linear_model import LinearRegression regressor = LinearRegression () regressor.fit (X_train, y_train) ## SVM classification method from sklearn.svm import LinearSVC classifier = LinearSVC (random_state = 0, dual=False) classifier.fit(X_train, y_train) ##KNN method from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier (n_neighbors=5, metric = 'euclidean') print (regressor.predict([[134000]])) [[7864.97350536]] </code></pre> <p>Dataset for SL regression snippet: &quot;Before imputation&quot;</p> <pre><code> print (X) [130000. 130000. 152000. 109000. 136000. 136000. 136000. nan 131000. 131000. 108000. 108000. 164000. 164000. 164000. 209000. 209000. 209000. 61000. 90000. 90000. 90000. 90000. 98000. 90000. 90000. 90000. 98000. 122000. 156000. 92000. nan 79000. 92000. 92000. 92000. 92000. 110000. 110000. 110000. 110000. nan 110000. 111000. 90000. 90000. 119000. 258000. 258000. 326000.] print (y) [ 9109. 9694. 5344. 10030. 6650. 9863. 9064. 8508. 9591. 6653. 11344. 11283. 4708. 7643. 4484. 8639. 7251. 5804. 9221. 5856. 6458. 8993. 6208. nan 7274. 6657. 6355. 9758. 7628. 7953. 8565. 8601. 10938. 7032. 9147. 6670. nan 9820. 8940. 9031. 6514. 7967. 7972. 7187. 8023. nan 7193. 8112. 7461. 5440.] </code></pre> <p>Dataset snippet for LR, KNN, SVM. &quot;Before imputation&quot;</p> <pre><code> print (X) [['alfa-romero' 2 4 130000.0 9.0] ['alfa-romero' 2 4 130000.0 9.0] ['alfa-romero' 2 6 152000.0 9.0] ... ['volvo' 4 6 173000.0 nan] ['volvo' 4 6 145000.0 23.0] ['volvo' 4 4 141000.0 9.5]] print (y) ['yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'yes' 'no' 'yes' 'no' 'no' 'yes' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'no' 'yes' 'yes' 'yes' 'yes' 'yes'] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-16T13:16:59.290", "Id": "528589", "Score": "0", "body": "I would recommend asking this over at Cross Validated. Code Review is more for feedback on the implementation of your analytics pipeline itself (meaning the Python code itself). For the specific preprocessing steps required for certain classifiers, you definitely want Cross Validated." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-09-13T14:44:26.417", "Id": "267968", "Score": "0", "Tags": [ "python", "algorithm", "machine-learning" ], "Title": "To scale or not to scale in regression and classification algorithms" }
267968