body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm developing a API server in Go. My route handlers are becoming excessively long, especially when the response needs a lot of information.</p> <p>For the following response type:</p> <pre><code>// StateResponse is queried by the client to get the entire initial // database state. type StateResponse struct { StatusCode int `json:"status"` User store.User `json:"user"` Enrolled []store.Enrol `json:"enrolled"` Assessment []store.Assessment `json:"assessment"` Submissions []store.Submission `json:"submissions"` } </code></pre> <p>I have this handler:</p> <pre><code>func stateHandler(store *store.Store) http.HandlerFunc { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !request.IsAuthorized(r) { log.Println("Unauthorized") unauthorizedHandler().ServeHTTP(w, r) return } if r.Method != http.MethodGet { notFoundHandler().ServeHTTP(w, r) return } urlParams, ok := r.URL.Query()["email"] if !ok || len(urlParams) != 1 { log.Println("Invalid email") badRequestHandler("invalid email").ServeHTTP(w, r) return } email := urlParams[0] user, err := store.GetUserByEmail(email) if user == nil || err != nil { log.Printf("Could not find user: %v", err) notFoundHandler().ServeHTTP(w, r) return } enrolled, err := store.GetEnrolByUser(user.UID) if enrolled == nil || err != nil { log.Printf("Could not find enrolled: %v", err) notFoundHandler().ServeHTTP(w, r) return } assessments, err := store.GetAssessmentForUser(user.UID) if assessments == nil || err != nil { log.Printf("Could not find assessment: %v", err) notFoundHandler().ServeHTTP(w, r) return } submissions, err := store.GetSubmissionsForUser(user.UID) if submissions == nil || err != nil { log.Printf("Could not find submissions: %v", err) notFoundHandler().ServeHTTP(w, r) return } // Send response resp := StateResponse{ StatusCode: 200, User: *user, Enrolled: enrolled, Assessment: assessments, Submissions: submissions, } respBytes, err := json.Marshal(resp) if err != nil { unauthorizedHandler().ServeHTTP(w, r) return } w.Write(respBytes) }) } </code></pre> <p>I <em>know</em> this is imperfect. The error handling is repetitive. I tried using the <code>errWriter</code> technique from Rob Pikes <a href="https://blog.golang.org/errors-are-values" rel="nofollow noreferrer">"errors as values"</a> article, but I couldn't make it work since every database query (<code>store</code> functions, in this case) are slightly different.</p>
[]
[ { "body": "<p><strong>Some random notes:</strong></p>\n\n<ul>\n<li>Your use of <code>notFoundHandler().ServeHTTP(w, r)</code> is weird. Why do you have a function returning this if it doesn't take any params? You'd probably be better off just having a function <code>writeNotFound(w, r)</code>. This mirrors the approach of <code>net.http</code>, which already provides <a href=\"https://golang.org/pkg/net/http/#NotFound\" rel=\"nofollow noreferrer\">functions like this</a>.</li>\n<li>From a RESTful approach, you shouldn't be returning the <code>StatusCode</code> in the JSON. That should be the HTTP status code.</li>\n<li>This is minor, but what is an <code>Enrol</code>? Enrollment?</li>\n<li><code>if r.Method != http.MethodGet</code>, you should be returning a <code>405 Method Not Allowed</code> instead of a <code>404 Not Found</code></li>\n<li>If <code>json.Marshal</code> fails, you should return a <code>500 Internal Server Error</code> instead of an unauthorized</li>\n<li>Be careful with variables shadowing a package (<code>store *store.Store</code>). That can have unexpected consequences. Ideally you package name and struct should form a complete thought like <code>http.Server</code> (instead of <code>server.Server</code>). Unfortunately, in some scenarios this is difficult.</li>\n<li>Your store functions don't follow Go conventions. If you are returning <code>(X, error)</code> then you should <strong>only</strong> check <code>err != nil</code>. Either <code>err != nil</code> (and you ignore the first thing) or <code>err = nil</code> and the first thing is valid. Don't do <code>assessments == nil || err != nil</code>. This should just be <code>err != nil</code>. You may need to change how the <code>store</code> functions behave to conform to this pattern.</li>\n</ul>\n\n<p><strong>The overarching point</strong></p>\n\n<p>Repetitive error handling is an unfortunate consequence of some of the design decisions of Go (namely, a lack of parametric polymorphism). In this case however, even if you had generics (to pull out the repetitive error handling logic), you'd still need some way to bubble the <code>return</code> up to the <code>http.HandlerFunc</code>. And that would require something like:</p>\n\n<pre><code>if !tryQuery(func() (User, error) { return store.GetUserByEmail(email) }) {\n return\n}\n</code></pre>\n\n<p>Where <code>tryQuery</code> returns <code>false</code> if <code>store.GetUserByEmail(email)</code> returned an <code>error</code>. This is certainly shorter, but it's dubious that this is an improvement. You also couldn't write such a <code>tryQuery</code> currently in go because the first return type <code>User</code> would need to be generic. Sure, you could cast through <code>interface{}</code>, but that's a world of ugliness that you don't want to deal with. It would require you to do lots of casts, which incur a runtime cost and are (programmer) error prone.</p>\n\n<p>So what to do? Well, any refactoring you embark on will be a tradeoff. The go ethos often prefers more verbose, repetitive code because it's easier to follow. But this comes at a cost. Eventually code becomes hard to reason about and harder to test because units have many responsibilities.</p>\n\n<p>That said, I think there are some patterns you could use that would really help clear this code up. In the end, the code should be easier to read and easier to test.</p>\n\n<p>First, checks like \"is the user authorized\" is often better suited for middleware. This pattern will allow you write the authorization check once and then wrap every handler in this middleware that needs it:</p>\n\n<pre><code>func needsAuthorization(handler http.HandlerFunc) http.HandlerFunc {\n return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {\n if !request.IsAuthorized(r) {\n log.Println(\"Unauthorized\")\n writeUnauthorized(w, r)\n } else {\n handler(w, r)\n }\n })\n}\n</code></pre>\n\n<p>Then you can use it like so:</p>\n\n<pre><code>func stateHandler(store *store.Store) http.HandlerFunc {\n return needsAuthorization(func(w http.ResponseWriter, r *http.Request) {\n // This is only called if user is authorized\n // Check email, get assessments, etc.\n })\n}\n</code></pre>\n\n<p>This is appropriate for checks like authorization (and maybe checking the request method), but shouldn't be used for everything.</p>\n\n<p>Another option here (although sometimes frowned upon by the purists) is to use <a href=\"https://gobuffalo.io/en/docs/routing\" rel=\"nofollow noreferrer\">an existing HTTP framework</a> that handles routing (including method) and maybe already has utilities for injecting middleware. This is somewhat in conflict with Go's obvious philosophy as there is some magic introduced. As with refactoring , there are tradeoffs here. Frameworks abstract away some common patterns to enable more succinct business logic. For example, with a buffalo router you can do:</p>\n\n<pre><code>a.GET(\"/state\", stateHandler(store))\n</code></pre>\n\n<p>The meat of your problem still exists. All of the interaction with your models and constructing the response still is a lot of repetitive error handling. The ideal approach here would be an <code>Applicative</code> pattern which is capable of constructing data up until the point of an error. In Haskell, this would look something like:</p>\n\n<pre><code>user &lt;- getUserByEmail =&lt;&lt; getParam \"email\"\nreturn $ StateResponse &lt;$&gt; user &lt;*&gt; getEnrollments user &lt;*&gt; getAssessments user\n &lt;*&gt; getSubmissions user\n</code></pre>\n\n<p>The beauty here is that all of these steps (<code>user</code>, <code>getEnrollments user</code>, etc.) can fail. And when they do, the error is returned instead. But until one occurs, we just continue to construct the data. Note that this looks almost like how you build the <code>StateResponse</code> struct in Go, except it also does error handling.</p>\n\n<p>In Go, you'd have to duplicate some (trivial) code to achieve something like this. And I'm not sure it would be worth it. You'd end up with something like:</p>\n\n<pre><code>state := StateResponseBuilder{}\n\nstate.SetEmail(func() (string, bool) { return r.Url.Query()[\"email\"] })\nstate.SetUser(func() (store.User, error) { return store.GetUserByEmail(state.Email) })\nstate.SetEnrollments(func() ([]store.Enrollment, error) { return store.GetEnrollmentsByUser(state.User.UID) })\nstate.SetAssessments(func() ([]store.Assessment, error) { return store.GetAssessmentForUser(state.User.UID) })\nstate.SetSubmissions(func() ([]store.Submission, error) { return store.GetSubmissionsForUser(state.User.UID) })\n\nrespBytes, err := state.Build()\nif err != nil {\n // return error\n} else {\n w.Write(respBytes)\n}\n</code></pre>\n\n<p>The idea here is that <code>StateResponseBuilder</code> somewhat follows the Pike technique. Each <code>SetX</code> looks like this:</p>\n\n<pre><code>type StateResponseBuilder struct {\n Err error\n X X\n}\n\n\nfunc (s *StateResponseBuilder) SetX(f func() (X, error)) {\n if s.Err != nil {\n return\n }\n\n if x, err := f(); err != nil {\n self.Err = err\n } else {\n self.X = x\n }\n}\n</code></pre>\n\n<p>Your error short circuiting is handled by checking if <code>s.Err != nil</code> before running <code>f()</code>. <code>s.Err</code> is the first error we encountered or <code>nil</code> if everything so far as succeeded.</p>\n\n<p>You'll note this requires <em>a lot</em> of code repetition in the <code>SetX</code> methods. Furthermore, the resulting code is probably less obvious even though it lacks all the error checking.</p>\n\n<p>That said, such a pattern can be useful in certain contexts.</p>\n\n<p><strong>A better approach</strong></p>\n\n<p>A more suitable pattern, in my opinion, would be to separate concerns and use some indirection to make errors responsible for reporting themselves (instead of making your handler responsible for knowing how to report them). The big idea here is that currently your handler has many jobs. This is what is making it slightly unwieldy. You can separate its main jobs into two categories:</p>\n\n<ol>\n<li>HTTP related (specifically, translating errors/data to the appropriate constructs in HTTP)</li>\n<li>Interacting with <code>store</code></li>\n</ol>\n\n<p>If you separated these two, you could de-duplicate some of your repetitive HTTP error handling code. Further, this would abstract your controller logic away from HTTP so if you wanted to provide another kind of API (maybe some sort of custom protocol over TCP), you could do this fairly easily. Doing something like this would make your handler look like:</p>\n\n<pre><code>func stateHandler(store *store.Store) http.HandlerFunc {\n return needsAuthorization(onlyGet((http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n var email string\n\n emails := r.URL.Query()[\"email\"]\n if len(emails) == 1 {\n email = emails[0]\n }\n\n response, err := buildStateResponse(store, email)\n if err != nil {\n err.WriteHTTP(w)\n } else {\n w.Write(response)\n }\n })))\n}\n</code></pre>\n\n<p>We've done several things here. First, all the HTTP error handling has been reduced to one location. This should make logging much easier. All HTTP-related things are located <em>just</em> in the handler. Note that we did push some of this into the errors themselves. This kind of indirection allows us to not have to handle every case in the HTTP handler. The advantage here is if another error condition arises when you're working on <code>store</code>, you don't have to go through all of your HTTP handlers and handle outputting the error each place a <code>store</code> function is used. Doing this would require you to create a custom error <code>interface</code> that has <code>WriteHTTP</code>, but you could just as easily make this a function that takes an <code>error</code> as its first parameter. The simplicity of the pure controller logic speaks for itself:</p>\n\n<pre><code>// You may want to return the `StateResponse` here and handle serialization in the HTTP handler\nfunc buildStateRespones(store *store.Store, email string) ([]byte, error) {\n user, err := store.GetUserByEmail(email)\n if err != nil {\n return nil, err\n }\n\n enrolled, err := store.GetUserEnrollments(user.UID)\n if err != nil {\n return nil, err\n }\n\n assessments, err := store.GetUserAssessments(user.UID)\n if err != nil {\n return nil, err\n }\n\n submissions, err := store.GetUserSubmissions(user.UID)\n if err != nil {\n return nil, err\n }\n\n return json.Marshal(StateResponse{\n User: *user,\n Enrolled: enrollments,\n Assessment: assessments,\n Submissions: submissions,\n })\n}\n</code></pre>\n\n<p>You still need the error checks, but now you aren't trying to do so much inside them. This code should be much easier to follow. What's more, if the new error check proposal lands, this code will immediately be convertible to this <em>much more readable</em> form:</p>\n\n<pre><code>func buildStateRespones(store *store.Store, email string) (*StateResponse, error) {\n user := check store.GetUserByEmail(email)\n enrolled := check store.GetUserEnrollments(user.UID)\n assessments := check store.GetUserAssessments(user.UID)\n submissions := check store.GetUserSubmissions(user.UID)\n\n return &amp;StateResponse{\n User: *user,\n Enrolled: enrollments,\n Assessment: assessments,\n Submissions: submissions,\n }, nil\n}\n</code></pre>\n\n<p>Here we've separated business logic from protocol specific \"presentation\" logic. The result is that each separated part is now easier to reason about (and easier to unit test!).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T06:57:19.470", "Id": "212739", "ParentId": "212033", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T00:49:14.320", "Id": "212033", "Score": "3", "Tags": [ "go", "server" ], "Title": "Go API server - request handlers becoming excessively long" }
212033
<p>This is a programming challenge I set for myself a while back to create an AI that starts with no knowledge of anything whatsoever, and learns as you talk to it. (It can learn stuff like your name, how to say hello, goodbye, etc.)</p> <p>I tried to use the least amount of hard-coded responses as possible. I'm happy that it works, but I feel like the code behind it is very clumsy and... just not very good. The program is called Genesis. Tell me what you think!</p> <h3>Genesis.java</h3> <pre><code>package genesis; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintStream; import java.io.PrintWriter; import java.util.regex.Matcher; import java.util.regex.Pattern; public final class Genesis { public static final String name = "Genesis"; public static final String version = "1.0"; public static void main(String[] args) { try { new Genesis(); } catch(IOException e) { printError(new PrintWriter(System.err), e); } } private final FileManager fm; protected String last = null; public Genesis() throws IOException { log("Initializing " + toString() + "..."); log("Generating files..."); fm = new FileManager(this); log(toString() + " started on " + System.getProperty("os.name")); start(); stop(); } public void stop() { stop(0); } public void stop(int error) { if(error == 0) log(toString() + " shut down successfully!"); else log(toString() + " shut down with error code: " + error); if(fm != null) fm.close(); System.exit(error); } public void start() { try(BufferedReader r = new BufferedReader(new InputStreamReader(System.in))) { System.out.print("You: "); String s = r.readLine(); if(respond(s)) start(); } catch(Throwable t) { printError(t); } } public boolean respond(String s) { //decide how and what to respond, return if we should keep the program alive if(s.trim().equals("")) return true; //nothing to do, but keep the program alive String response = ""; if(last == null) { //first message must always be a greeting boolean newg = true; for(String r : fm.getResponses(ResponseType.GREETING)) { if(transform(s).equalsIgnoreCase(transform(r))) newg = false; //if this is a greeting that we know about, we dont need to store it again } if(newg) //store a new greeting for use in another session (or this one) fm.setResponse(ResponseType.GREETING, removeEndPunc(s)); //give a greeting back! System.out.println(response = (name + ": " + format(fm.getResponses(ResponseType.GREETING).get((int) (System.nanoTime() % fm.getResponses(ResponseType.GREETING).size()))))); } else { boolean notg = true; for(String r : fm.getResponses(ResponseType.GREETING)) { //check if THE LAST MESSAGE is another greeting if(transform(last).equalsIgnoreCase(transform(r))) notg = false; } boolean notf = true; for(String r : fm.getResponses(ResponseType.FAREWELL)) { //check if they're saying a known farewell if(transform(s).equalsIgnoreCase(transform(r))) notf = false; } if((!notf || s.equalsIgnoreCase("exit")) &amp;&amp; notg) { //if they're doing a farewell or saying "exit", and THE LAST MESSAGE is not a greeting boolean newf = true; for(String r : fm.getResponses(ResponseType.FAREWELL)) { //check if it's a new farewell if(transform(last).equalsIgnoreCase(transform(r))) newf = false; } if(newf) //if it's new, store it for another session (or this one) fm.setResponse(ResponseType.FAREWELL, removeEndPunc(last)); //say bye back System.out.println(response = (name + ": " + format(fm.getResponses(ResponseType.FAREWELL).get((int) (System.nanoTime() % fm.getResponses(ResponseType.FAREWELL).size()))))); return false; //exit the loop } } boolean containsLaugh = false; for(String r : fm.getResponses(ResponseType.LAUGH)) { //are they laughing? if(s.matches(".*?\\b" + r + "\\b.*?")) containsLaugh = true; } boolean laughIfPossible = false; int laugh = 0; for(char c : s.toCharArray()) { //very bad laugh detection: &gt;50% h's or l's if(c == 'h' || c == 'l') laugh++; } if(laugh &gt; s.toCharArray().length / 2) { //if &gt;50% h's or l's boolean newl = true; for(String r : fm.getResponses(ResponseType.LAUGH)) { //is this a laugh we know? if(transform(s).equalsIgnoreCase(transform(r))) newl = false; } if(newl) //if it's new, save it for later fm.setResponse(ResponseType.LAUGH, removeEndPunc(s)); laughIfPossible = true; //if there's nothing else to say later, laugh } if(!containsLaugh) { //if super serious business mode is on String[] set = s.split("(\\s+is\\s+|\\'s\\s+)"); //regex: split for every "is" or 's ('s as in contraction for is) try { //if it's math, solve it System.out.println(response = (name + ": " + solve(transform(set[1]).trim()))); } catch(Throwable t) { //it's not math String ek = transform(set[0]).toLowerCase(); //get the first part of the phrase if(ek.contains("what")) { //user is asking for information String k = transform(reversePerson(join(set, "is", 1).toLowerCase())); //get the object to look up for(String values : fm.getResponses(ResponseType.VALUE)) { if(transform(values.split("§=§")[0]).trim().equalsIgnoreCase(k)) //if we know the information, tell the user response = name + ": " + cap(k) + " is " + values.split("§=§")[1].trim() + punc(); } if(!response.equals("")) //only respond if we have something useful to say System.out.println(response); } else if(s.contains(" is ")) { //the user is telling us information String k = reversePerson(s.split(" is ")[0].toLowerCase().trim()); //the key to store String v = join(s.split(" is "), "is", 1).toLowerCase().trim(); //the value to store for the key fm.setResponse(ResponseType.VALUE, k + "§=§" + reversePerson(removeEndPunc(v))); //store the key and value System.out.println(response = (name + ": " + cap(k) + " is " + removeEndPunc(v) + punc())); //tell the user about our new information } } } if(response.trim().equals("") &amp;&amp; (laughIfPossible || containsLaugh)) //if we have nothing else to say, but we can laugh, laugh System.out.println(response = (name + ": " + cap(fm.getResponses(ResponseType.LAUGH).get((int) (System.nanoTime() % fm.getResponses(ResponseType.LAUGH).size()))))); //say a random laugh fm.log("You: " + s); //log what the user said fm.log(name + ": " + (response.replace(name + ": ", ""))); //log our response, make sure to include the name even if we didn't earlier last = s; //set the new last message return true; //keep the program alive } private static String join(String[] set, String medium, int offset) { //join an array together with a specified string in between starting at a specified offset String s = set[offset]; int i = 0; for(String part : set) { if(i &gt; offset) s = s + " " + medium + " " + part; i++; } return s; } private static String reversePerson(String s) { //reverse between 1st and 3rd person, so Genesis makes sense return s.replaceAll("\\byour\\b", "§§m§§y§§").replaceAll("\\byou\\b", "§§m§§e§§").replaceAll("\\bme\\b", "you").replaceAll("\\bmy\\b", "your").replaceAll("\\byours\\b", "§§mi§§ne§§").replaceAll("\\bmine\\b", "yours").replace("§§", "").trim(); } public static double solve(String c) { //solve math expressions Pattern p = Pattern.compile("(\\d+|\\d+\\.\\d+)\\s*(\\+|\\-|\\*|\\/|\\%|\\|)\\s*(\\d+|\\d+\\.\\d+).*"); //&lt;number&gt; &lt;+-*/%|&gt; &lt;number&gt; Matcher m = p.matcher(c); if(m.matches()) { //if this is a correct math expression Double d1 = Double.parseDouble(m.group(1)); Double d2 = Double.parseDouble(m.group(3)); while(c.contains("+") || c.contains("-") || c.contains("*") || c.contains("/") || c.contains("%") || c.contains("|")) { //checking for valid operations c = c.replaceAll("(\\d)\\.0(\\D)", "$1$2"); //replace all x.0 with just x (it looks better) m = p.matcher(c); if(!m.matches()) //this SHOULD match throw new ArithmeticException(); switch(m.group(2)) { //check the operation symbol and do math default: break; case "+": c = c.replaceAll("[" + d1 + "]\\s*\\+\\s*[" + d2 + "]", (d1 + d2) + ""); break; case "-": c = c.replaceAll("[" + d1 + "]\\s*\\-\\s*[" + d2 + "]", (d1 - d2) + ""); break; case "*": c = c.replaceAll("[" + d1 + "]\\s*\\*\\s*[" + d2 + "]", (d1 * d2) + ""); break; case "/": c = c.replaceAll("[" + d1 + "]\\s*\\/\\s*[" + d2 + "]", (d1 / d2) + ""); break; case "%": c = c.replaceAll("[" + d1 + "]\\s*%\\s*[" + d2 + "]", (d1 % d2) + ""); break; case "|": c = c.replaceAll("[" + d1 + "]\\s*\\|\\s*[" + d2 + "]", (Integer.parseInt((d1 + "").replace(".0", "")) | Integer.parseInt((d2 + "").replace(".0", ""))) + ""); break; } } } //else, maybe it's just a number (return the number)... or maybe it's not even math - if it is, return the parsed answer return Double.parseDouble(c); } private static String transform(String s) { //transform a string into something the program can read return s.toLowerCase().replace("?", "").replace(".", "").replace("!", "").replace(",", "").replace("_", "").replace("~", "").replace("`", "").replace("'", "").replace("\"", "").replace("\"", "").replace("\\", "").replace(":", "").replace(";", "").replace("the", " ").replace("teh", " ").replace("how do", "how can").replace("re", "").replace(" a ", " ").replace("is", "").replace("has", "").replace("get to", "go to").replaceAll("\\Bs\\b", "").replaceAll(" {2}?", "").trim(); } private static String removeEndPunc(String s) { return s.replaceAll("[!\\.\\?]+$", ""); //remove all !'s .'s and ?'s from the end of a string } private static String format(String s) { //add random punctuation, and capitalize the first character return cap(s) + punc(); } private static String cap(String s) { //capitalize the first letter of a given string String r = s.toUpperCase(); if(r.length() &gt; 1) r = s.replaceFirst(s.substring(0, 1), s.substring(0, 1).toUpperCase()); return r; } private static char punc() { //return random punctuation switch((int) System.nanoTime() % 5) { default: case 0: case 1: case 2: case 3: return '.'; case 4: return '!'; } } public FileManager getFileManager() { return fm; } public void printError(Throwable t) { printError(System.err, t); if(fm != null) printError(fm.getLogStream(), t); stop(1); } private static void printError(Object output, Throwable t) { PrintWriterStream out; if(output instanceof PrintWriter) out = new PrintWriterStream((PrintWriter) output); else if(output instanceof PrintStream) out = new PrintWriterStream((PrintStream) output); else throw new IllegalArgumentException("Output must be of type PrintWriter or PrintStream"); out.println(); out.println("A fatal error occurred: " + t.toString()); out.println(); out.println("-----=[General Stack Trace]=-----"); for(StackTraceElement s : t.getStackTrace()) //print the throwable's stack trace out.println(s.getClassName() + "." + s.getMethodName() + "() on line " + s.getLineNumber()); out.println("-----=[" + name + " Stack Trace]=-----"); out.println(); out.println("-----=[" + name + " Stack Trace]=-----"); boolean fault = false; for(StackTraceElement s : t.getStackTrace()) { //filter out the stack trace for only Genesis if(s.getClassName().startsWith("genesis")) { out.println(s.getClassName() + "." + s.getMethodName() + "() on line " + s.getLineNumber()); fault = true; } } if(!fault) //if it's not our fault, tell the user out.println("This doesn't look like a problem relating to " + name + ". Check the above general stack trace."); out.println("-----=[Genesis Stack Trace]=-----"); out.println(); out.println("-----=[Remote Stack Trace]=-----"); fault = false; for(StackTraceElement s : t.getStackTrace()) { //filter out the stack trace for only outside Genesis if(!s.getClassName().startsWith("genesis")) { out.println(s.getClassName() + "." + s.getMethodName() + "() on line " + s.getLineNumber()); fault = true; } } if(!fault) //if it's not their fault, tell the user out.println("This doesn't look like a problem with anything outside " + name + ". Check the above " + name + " stack trace."); out.println("-----=[Remote Stack Trace]=-----"); out.println(); } public void log(String message) { log(System.out, message); } public void log(PrintStream out, String message) { FileManager.log(out, message); if(fm != null) fm.log(message); } public String toString() { return name + " v" + version; } static class PrintWriterStream { //super hacky way of combining a PrintWriter and a PrintStream private PrintWriter w; private PrintStream s; PrintWriterStream(PrintWriter w) { //support for PrintWriter if(w == null) throw new NullPointerException(); this.w = w; } PrintWriterStream(PrintStream s) { //support for PrintStream if(s == null) throw new NullPointerException(); this.s = s; } void println() { if(w == null &amp;&amp; s != null) s.println(); else if(s == null &amp;&amp; w != null) w.println(); else throw new NullPointerException("No valid output"); } void println(String x) { if(w == null &amp;&amp; s != null) s.println(x); else if(s == null &amp;&amp; w != null) w.println(x); else throw new NullPointerException("No valid output"); } public void flush() { if(w == null &amp;&amp; s != null) s.flush(); else if(s == null &amp;&amp; w != null) w.flush(); else throw new NullPointerException("No valid output"); } } } </code></pre> <h3>FileManager.java</h3> <pre><code>package genesis; import genesis.Genesis.PrintWriterStream; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; public final class FileManager { private final Genesis g; public static final String folderPath = "Genesis/"; private final File folder = new File(folderPath); private final File log = new File(folderPath + "log.txt"); private final File resp = new File(folderPath + "responses.txt"); private final PrintWriter lout; private final PrintWriter rout; public FileManager(Genesis g) throws IOException { this.g = g; folder.mkdirs(); //make the Genesis folder if it doesn't exist checkFiles(); //make the files lout = new PrintWriter(new FileWriter(log, true)); rout = new PrintWriter(new FileWriter(resp, true)); } private void checkFiles() { //create new log and response files if they don't exist try { if (!log.exists()) log.createNewFile(); if (!resp.exists()) resp.createNewFile(); } catch (IOException e) { g.printError(e); } } public Genesis getGenesis() { return g; } public File getFolder() { return folder; } public File getLog() { return log; } public File getResponsesFile() { return resp; } public HashMap&lt;ResponseType, List&lt;String&gt;&gt; getResponses() { //get a hashmap of all responsetypes and responses for that type in list form checkFiles(); //make sure our files exist first HashMap&lt;ResponseType, List&lt;String&gt;&gt; res = new HashMap&lt;ResponseType, List&lt;String&gt;&gt;(); if (resp.length() == 0) //if we don't have anything, don't return anything return res; try (BufferedReader r = new BufferedReader(new FileReader(resp))) { String line; while ((line = r.readLine()) != null) { for (ResponseType rt : ResponseType.values()) { if (line.split("�")[0].equalsIgnoreCase(rt.name())) { //I could use a different character... but it kept changing back when I moved the project between computers String response = ""; for (int i = 1; i &lt; line.split("�").length; i++) response = line.split("�")[i].trim(); if (res.get(rt) == null) { List&lt;String&gt; list = new ArrayList&lt;String&gt;(); list.add(response); res.put(rt, list); } else res.get(rt).add(response); } } } } catch (IOException e) { g.printError(e); } return res; } public List&lt;String&gt; getResponses(ResponseType rt) { //get all the responses in list form for a certain response type checkFiles(); List&lt;String&gt; res = new ArrayList&lt;String&gt;(); if (resp.length() == 0) return res; try (BufferedReader r = new BufferedReader(new FileReader(resp))) { String line; while ((line = r.readLine()) != null) { if (line.split("�")[0].equalsIgnoreCase(rt.name())) res.add(line.split("�")[1].trim()); } } catch (Throwable t) { g.printError(t); } return res; } public void setResponse(ResponseType type, String response) { //set a response for a certain type response = response.trim(); try (BufferedReader r = new BufferedReader(new FileReader(resp))) { String s; while ((s = r.readLine()) != null) { if (s.equals(type.toString() + "� " + response)) return; } rout.println(type.toString() + "� " + response); rout.flush(); } catch (Throwable t) { g.printError(t); } } public void log(String message) { log(lout, message); } public static void log(Object output, String message) { PrintWriterStream out; if(output instanceof PrintWriter) out = new PrintWriterStream((PrintWriter) output); else if(output instanceof PrintStream) out = new PrintWriterStream((PrintStream) output); else throw new IllegalArgumentException("Output must be of type PrintWriter or PrintStream"); Calendar c = Calendar.getInstance(); String hour = c.get(Calendar.HOUR) + ""; String minute = c.get(Calendar.MINUTE) + ""; String second = c.get(Calendar.SECOND) + ""; int ampm = c.get(Calendar.AM_PM); if(Integer.parseInt(hour) &lt; 10) //keep the hours minutes and seconds 2 digits hour = "0" + hour; if(Integer.parseInt(minute) &lt; 10) minute = "0" + minute; if(Integer.parseInt(second) &lt; 10) second = "0" + second; String timestamp = "[" + hour + ":" + minute + ":" + second + ":" + (ampm == 0 ? "AM" : "PM") + "]"; out.println(timestamp + ": " + message); out.flush(); } public PrintWriter getLogStream() { return lout; } public PrintWriter getResponseStream() { return rout; } public void close() { //close the log and response file streams lout.close(); rout.close(); } } </code></pre> <h3>ResponseType.java</h3> <pre><code>package genesis; public enum ResponseType { GREETING, FAREWELL, VALUE, LAUGH; public String toString() { return name().toLowerCase().replaceFirst(name().substring(0, 1).toLowerCase(), name().substring(0, 1).toUpperCase()); } public static ResponseType getResponseType(String name) { for (ResponseType r : values()) { if(r.name().equalsIgnoreCase(name)) return r; } return null; } } </code></pre> <p>As a side note, you can compile this code yourself and export it as a runnable JAR file. It creates a folder called <code>Genesis</code> wherever the JAR is, which consists of a log.txt file and a responses.txt file. Log file is what you think it is, and responses file is for use by Genesis, so it knows how to respond to you over time.</p> <p>Rules for talking to it <em>correctly</em> are as follows:</p> <ul> <li>First message must be a greeting (hello/hi/etc)</li> <li>Last message must be a farewell (goodbye/bye/etc)</li> <li>After your farewell, type "exit" to exit the program correctly</li> </ul>
[]
[ { "body": "<p>Instead of using short variable names, I recommend you use descriptive ones.</p>\n\n<p>It is always better to use a more descriptive variable name than to use a short name which requires a comment to explain what it is.</p>\n\n<p>Also, I don’t suggest using the opposite of negation (!not) as this also can confuse the reader who is trying to make sense of the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T13:15:36.360", "Id": "212065", "ParentId": "212037", "Score": "1" } }, { "body": "<p><strong>Advice 1: Package names</strong></p>\n\n<p>The package name <code>genesis</code> is not quite informative what software it contains. The common notation is to use the reversed name of the web address of your company. For example, you could use <code>net.genesis.ai</code> for the package name.</p>\n\n<p><strong>Advice 2: <code>ResponseType</code></strong></p>\n\n<p>You could use the <a href=\"https://docs.oracle.com/javase/8/docs/api/java/lang/Enum.html#valueOf-java.lang.Class-java.lang.String-\" rel=\"nofollow noreferrer\"><code>valueOf</code></a> static method for converting a string to an corresponding enumeration:</p>\n\n<pre><code>public static ResponseType getResponseType(String name) {\n try {\n return ResponseType.valueOf(name);\n } catch (IllegalArgumentException ex) {\n return null;\n }\n}\n</code></pre>\n\n<p>What comes to <code>toString</code>, I suggest you prepend <code>@Override</code> to it: if someone makes a typo in the name <code>toString</code>, <code>@Override</code> will force your IDE (i.e., NetBeans) to underline it with red. Also, in the same method, you could save some typing:</p>\n\n<pre><code>@Override\npublic String toString() {\n char[] chars = name().toLowerCase().toCharArray();\n chars[0] = Character.toUpperCase(chars[0]);\n return new String(chars);\n}\n</code></pre>\n\n<p>Also, an enumeration may have satellite data:</p>\n\n<pre><code>public enum ResponseType {\n\n GREETING(\"Greeting\"),\n FAREWELL(\"Farewell\"), \n VALUE(\"Value\"), // &lt;- Note the comma.\n LAUGH(\"Laugh\"); // &lt;- Note the semicolon.\n\n private final String humanReadableName; // &lt;- That is were each enumeration knows its satellite data.\n\n ResponseType(String humanReadableName) {\n this.humanReadableName = humanReadableName;\n }\n\n public static ResponseType getResponseType(String name) {\n try {\n return ResponseType.valueOf(name);\n } catch (IllegalArgumentException ex) {\n // valueOf throws this when no suitable enumeration found.\n return null;\n }\n }\n}\n</code></pre>\n\n<p><strong>Advice 3</strong></p>\n\n<pre><code>public HashMap&lt;ResponseType, List&lt;String&gt;&gt; getResponses() { //get a hashmap of all responsetypes and responses for that type in list form\n ...\n HashMap&lt;ResponseType, List&lt;String&gt;&gt; res = new HashMap&lt;ResponseType, List&lt;String&gt;&gt;();\n</code></pre>\n\n<p>I suggest you program to interface, not implementation:</p>\n\n<pre><code>Map&lt;ResponseType, List&lt;String&gt;&gt; res = new HashMap&lt;ResponseType, List&lt;String&gt;&gt;();\n</code></pre>\n\n<p><strong>Advice 4</strong> </p>\n\n<p>As an addition to the 3rd advice, since Java 7 you can use so called <em>diamond inference</em>:</p>\n\n<pre><code>Map&lt;ResponseType, List&lt;String&gt;&gt; res = new HashMap&lt;&gt;();\n</code></pre>\n\n<p><strong>Advice 5</strong> </p>\n\n<p>There is inconsistency with placing a white space character between <code>if</code> and opening <code>(</code>: <code>if(</code> vs. <code>if (</code>. The common way is to place a white space character between the two tokens.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:03:53.807", "Id": "410050", "Score": "0", "body": "advice three should be `Map<ResponseType,`... probably what you intended to say." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T14:32:08.933", "Id": "212070", "ParentId": "212037", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T03:39:59.953", "Id": "212037", "Score": "3", "Tags": [ "java", "ai" ], "Title": "Genesis, an AI that learns as you talk to it" }
212037
<p>I wanted to practice using templates since I have no experience with them, so I implemented these sorting algorithms. </p> <p>Selection Sort:</p> <pre><code>template&lt;typename Container&gt; void selectionSort(Container&amp; numbers) { for (auto iter = std::begin(numbers), iterEnd = std::end(numbers); iter != iterEnd; ++iter) { auto minNum = minIndex(numbers, iter, iterEnd); std::swap(*iter, *minNum); } } template&lt;typename Container, typename Iter&gt; Iter minIndex(const Container&amp; numbers, Iter start, Iter end) { Iter minIdx = start; auto minNum = *start; while (++start != end) { if (*start &lt; minNum) { minNum = *start; minIdx = start; } } return minIdx; } </code></pre> <p>Insertion Sort:</p> <pre><code>template&lt;typename Container&gt; void insertionSort(Container&amp; numbers) { for (auto iter = std::begin(numbers) + 1, iterEnd = std::end(numbers); iter != iterEnd; ++iter) { if (*iter &lt; *(iter-1)) { resort(numbers, iter); } } } template&lt;typename Container, typename Iter&gt; void resort(Container&amp; numbers, Iter containerIter) { auto temp = *containerIter; while (containerIter != std::begin(numbers) &amp;&amp; temp &lt; *(containerIter-1)) { *containerIter = *(containerIter - 1); --containerIter; } *containerIter = temp; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T06:10:45.907", "Id": "409995", "Score": "0", "body": "Your includes are missing. Please add them to your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T12:47:42.453", "Id": "410229", "Score": "0", "body": "I don't see any question, just a statement along the lines of \"I did this\". That's great, but is there a more specific question regarding your implementation?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T23:40:33.323", "Id": "410313", "Score": "0", "body": "@Juho Sorry, I guess I was just looking for opinions on whether my use of templates were correct, as well as just general critiques one may have for my implementations." } ]
[ { "body": "<p>First tip: use more aggressive warnings, this way you would be warned by the compiler about passing unused parameters into functions, that is you would automatically made:</p>\n\n<pre><code>template&lt;typename Iter&gt;\nIter minIndex(Iter start, Iter end)\n</code></pre>\n\n<p>Another thing would be, to write your algorithms in similar way as the standard ones. That is avoid passing the reference to the container, but rather pass iterators into it. So your sort functions should look similarly to:</p>\n\n<pre><code>&lt;typename InputIt&gt;\nvoid someSort (InputIt first, InputIt last)\n</code></pre>\n\n<p>This will e.g. allow you to sort specific parts of your container with no extra effort.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T16:35:12.477", "Id": "212081", "ParentId": "212038", "Score": "3" } }, { "body": "<p>There is no need for <code>minIndex</code>, this functionality is already available in the standard. So you could do e.g.,:</p>\n\n<pre><code>template&lt;typename Container&gt;\nvoid selectionSort(Container&amp; numbers)\n{\n for (auto it = std::begin(numbers); it != std::end(numbers); ++it)\n {\n std::iter_swap(it, std::min_element(it, v.end()));\n }\n}\n</code></pre>\n\n<p>A similar comment holds for insertion sort, <a href=\"https://codereview.stackexchange.com/q/110793/40063\">see this question and one of its answers</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T12:46:35.827", "Id": "212138", "ParentId": "212038", "Score": "1" } } ]
{ "AcceptedAnswerId": "212081", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T03:44:08.370", "Id": "212038", "Score": "1", "Tags": [ "c++", "sorting", "template", "insertion-sort" ], "Title": "Insertion Sort and Selection Sort Implementation" }
212038
<p>I am trying to find all primes less than 2,000,000 and sum them together. My code currently takes 1'36" to run. Is there a faster way to get my solution?</p> <p>The logic I am following in this code is make a list of all primes I have found. Then check that every odd number less than 2,000,000 is not divisible by any of the primes in my list. If that is the case I am calling the number prime.</p> <pre><code>package main import ("fmt" "time" ) func find_primes(max int) []int { // list of all primes that we find var primes []int primes = append(primes, 2) var is_prime = true for i:=3; i&lt;=max; i++ { is_prime = false // only odds can be prime if i%2 != 0 { is_prime = true // should not be divisible by any previous // prime numbers for _, x := range primes { if i%x == 0 { is_prime = false break } } } if is_prime { primes = append(primes, i) } } return primes } // just sume up all of the primes func sum_primes(primes []int) int { var total int = 0 for _, x := range primes { total = total + x } return total } func main() { start := time.Now() // find all primes less than 2,000,000 primes := find_primes(2000000) sum := sum_primes(primes) fmt.Println(sum) t := time.Now() elapsed := t.Sub(start) fmt.Println(elapsed) } </code></pre>
[]
[ { "body": "<blockquote>\n <p>I am trying to find all primes less than 2,000,000 and sum them\n together. My code currently takes 1'36\" to run. Is there a faster way\n to get my solution?</p>\n</blockquote>\n\n<hr>\n\n<p>Yes. For example,</p>\n\n<pre><code>142913828922\n3.860761ms\n</code></pre>\n\n<p>versus your</p>\n\n<pre><code>142913828922\n1m35.090248409s\n</code></pre>\n\n<hr>\n\n<p><code>prime.go</code>:</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"time\"\n)\n\nconst (\n prime = 0x00\n notprime = 0xFF\n)\n\nfunc oddPrimes(n uint64) (sieve []uint8) {\n sieve = make([]uint8, (n+1)/2)\n sieve[0] = notprime\n p := uint64(3)\n for i := p * p; i &lt;= n; i = p * p {\n for j := i; j &lt;= n; j += 2 * p {\n sieve[j/2] = notprime\n }\n for p += 2; sieve[p/2] == notprime; p += 2 {\n }\n }\n return sieve\n}\n\nfunc sumPrimes(n uint64) uint64 {\n sum := uint64(0)\n if n &gt;= 2 {\n sum += 2\n }\n for i, p := range oddPrimes(n) {\n if p == prime {\n sum += 2*uint64(i) + 1\n }\n }\n return sum\n}\n\nfunc main() {\n start := time.Now()\n\n var n uint64 = 2000000 - 1\n sum := sumPrimes(n)\n fmt.Println(sum)\n\n fmt.Println(time.Since(start))\n}\n</code></pre>\n\n<hr>\n\n<p>Reference: <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes - Wikipedia</a> </p>\n\n<hr>\n\n<p>Go was designed for Google scale. Therefore, Go package <code>testing</code> includes benchmarking tools. For example,</p>\n\n<pre><code>$ go test -bench=. -benchmem\nBenchmarkPeterSO-8 500 3805125 ns/op 1007621 B/op 1 allocs/op\nBenchmarkNightman-8 1 95703259026 ns/op 5866752 B/op 31 allocs/op\n$ \n</code></pre>\n\n<hr>\n\n<blockquote>\n <p>Comment: You have presented an alternative solution, but haven't\n reviewed the code. Please explain your reasoning (how your solution\n works and why it is better than the original) so that the author and\n other readers can learn from your thought process. – <a href=\"https://codereview.stackexchange.com/users/35991/martin-r\">Martin\n R</a></p>\n</blockquote>\n\n<hr>\n\n<p>The thought process is simple, obvious, and well-known. </p>\n\n<p>The prime number problem is well-known.</p>\n\n<p>Therefore, <a href=\"https://en.wikipedia.org/wiki/Standing_on_the_shoulders_of_giants\" rel=\"nofollow noreferrer\">Standing on the shoulders of giants - Wikipdia</a>.</p>\n\n<p>\"If I have seen further it is by standing on the sholders [sic] of Giants.\" Isaac Newton</p>\n\n<p>For example, <a href=\"https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes\" rel=\"nofollow noreferrer\">Sieve of Eratosthenes - Wikipedia</a>.</p>\n\n<p>The algorithm given in the question is much slower than Eratosthenes' well-known algorithm, approximately 25,000 times slower.</p>\n\n<p>In real-world code reviews, code should be correct, maintainable, robust, reasonably efficient, and, most importantly, readable. The code in the question is not reasonably efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:48:03.717", "Id": "410005", "Score": "1", "body": "You have presented an alternative solution, but haven't reviewed the code. Please explain your reasoning (how your solution works and why it is better than the original) so that the author and other readers can learn from your thought process." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T06:30:23.310", "Id": "212044", "ParentId": "212039", "Score": "3" } } ]
{ "AcceptedAnswerId": "212044", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T04:15:22.397", "Id": "212039", "Score": "2", "Tags": [ "go" ], "Title": "Finding all prime numbers within a range" }
212039
<p>I'm trying to make a REST service using Spring Boot and Spring Data. I have written a query using <code>join</code> and have achieved the required o/p but I'm curious to know if that is a right way of doing it or I can do it with a better approach.</p> <p>Here is the query using <code>@Query</code> annotation:</p> <pre><code>@Query("select b.bookId, b.bookName, a.authorId, a.authorName, b.language, " + "g.genreId, g.genreName,b.goodReadReviews from Book b, Author a, " + "Genre g where b.author=a.authorId and b.genre=g.genreId and " + "a.authorId=?1 and g.genreId=?2") List&lt;Object[]&gt; findByAuthorIdAndGenreId(int authorId, int genreId); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:03:39.463", "Id": "409999", "Score": "0", "body": "There is no issue in your approach as Spring Data JPA doesn't provide any out-of-box support JOINs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T08:42:54.003", "Id": "410204", "Score": "0", "body": "Thank you @YogendraMishra. Can you please tell if Hibernate will provide a better approach for using join queries?" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T05:02:17.097", "Id": "212040", "Score": "1", "Tags": [ "java", "spring" ], "Title": "Join (custom) query in Spring Data JPA" }
212040
<p>I have been learning data structures and dynamic memory allocation in C. As a learning experience, I have written this linked list implementation. I really appreciate the feedback I've received on the previous code I've posted here and would love to hear any suggestions you all have on improvements I can make to this.</p> <p>I have abstracted the design to practice the use of "opaque pointers", and have thoroughly commented and described each function in the code. Tests for all functions are in <code>main.c</code></p> <p>Below are the source files and the CMakeLists file (which includes many runtime Clang sanitizers enabled). Alternatively, the code can be easily compiled with the following: <code>cc *.c -o linkedlist &amp;&amp; ./linkedlist</code></p> <p><strong>linkedlist.h</strong></p> <pre><code>#ifndef DATASTRUCTURES_LINKEDLIST_H #define DATASTRUCTURES_LINKEDLIST_H // Incomplete type used for "opaque pointer" struct Node; /* * I typedef this struct for ease of use in the header file. * There are both benefits and harms from assigning a typedef * to a struct but in this scenario I see more benefits. */ typedef struct Node Node; /** * Get node value (caller is responsible for ensuring node isn't NULL) * @param node * @return int value */ int get_node_val(const Node *node); /** * Set node value (caller is responsible for ensuring node isn't NULL) * @param node * @param val - int value */ void set_node_val(Node *node, int val); /*** * Allocates memory for a node, and assigns data to the new node * @param data - integer to store in the new node * @return newly allocated node */ Node *create_node(int data); /** * Appends a node to the end of the linked list * @param head - first node * @param to_add - node to add * @return head node */ Node *append_node(Node *head, Node *to_add); /** * Prepends a node to the beginning of the linked list * @param head - first node * @param to_add - node to add (becomes the new first node) * @return head node - should be reassigned to head */ Node *prepend_node(Node *head, Node *to_add); /** * Searches for a value in the linked list * @param head - first node * @param search_val - value to search for * @return instance of node if it exists, or NULL if it doesn't exist */ Node *search_node(const Node *head, int search_val); /** * Deletes the first occurence of "delete_val" from the linked list * @param head - first node * @param delete_val - value to delete from the linked list (may be head node) * @return head node - should be reassigned to head in case of first node being deleted */ Node *delete_node(Node *head, int delete_val); /** * Prints each node in the linked list * @param head - first node to start traversing from */ void print_all(const Node *head); /** * Frees all member of the linked list * @param head - first node to start traversing from */ void free_all(Node *head); #endif //DATASTRUCTURES_LINKEDLIST_H </code></pre> <p><strong>linkedlist.c</strong></p> <pre><code>#include &lt;malloc.h&gt; #include "linkedlist.h" #include "utils.h" struct Node { int value; struct Node *next; }; int get_node_val(const Node *node) { return node-&gt;value; } void set_node_val(Node *node, int val) { node-&gt;value = val; } static size_t node_size(void) { return sizeof(struct Node); } static void *allocate_node(void) { return malloc(node_size()); } Node *create_node(int data) { Node *new_node; if ((new_node = allocate_node()) == NULL) { gracefully_handle_failure(); } new_node-&gt;value = data; new_node-&gt;next = NULL; return new_node; } Node *append_node(Node *head, Node *to_add) { if (head == NULL) { return NULL; } Node *current = head; while (current-&gt;next) { current = current-&gt;next; } // At the end, now let's add our new node current-&gt;next = to_add; to_add-&gt;next = NULL; return head; } Node *prepend_node(Node *head, Node *to_add) { to_add-&gt;next = head; head = to_add; return head; } Node *search_node(const Node *head, int search_val) { for (const Node *current = head; current != NULL; current = current-&gt;next) { if (current-&gt;value == search_val) { return (Node *) current; } } return NULL; } Node *delete_node(Node *head, int delete_val) { // Taken from "Linus Torvalds - The mind behind Linux" Ted Talk // https://youtu.be/qrYt4bbEUrU Node **indirect = &amp;head; while ((*indirect)-&gt;value != delete_val) indirect = &amp;(*indirect)-&gt;next; *indirect = (*indirect)-&gt;next; return head; } void print_all(const Node *head) { for (const Node *current = head; current != NULL; current = current-&gt;next) { printf("%d -&gt; ", current-&gt;value); } puts("NULL"); } void free_all(Node *head) { for (Node *current = head; current != NULL; current = current-&gt;next) { free(head); } } </code></pre> <p><strong>main.c</strong></p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include "linkedlist.h" int main() { // These are simply tests for the Linked List Node *head = create_node(12); // Add 20 after head node (12) append_node(head, create_node(20)); // 12 -&gt; 20 -&gt; NULL // Prepend 30 before head node (12) head = prepend_node(head, create_node(30)); printf("Head is %d\n", get_node_val(head)); set_node_val(head, 32); // 32 -&gt; 12 -&gt; 20 -&gt; NULL print_all(head); head = delete_node(head, 32); // 12 -&gt; 20 -&gt; NULL if (search_node(head, 20)) { printf("%d found\n", 20); } print_all(head); free_all(head); return EXIT_SUCCESS; } </code></pre> <p><strong>CMakeLists.txt</strong></p> <pre><code># Improved version adapted from https://codereview.stackexchange.com/a/210770/78786 cmake_minimum_required(VERSION 3.13) project(DataStructures C) add_executable(${CMAKE_PROJECT_NAME} main.c linkedlist.c linkedlist.h utils.c utils.h) set(CMAKE_C_COMPILER clang) target_compile_features(${CMAKE_PROJECT_NAME} PRIVATE c_std_99) target_compile_options(${CMAKE_PROJECT_NAME} PRIVATE $&lt;$&lt;C_COMPILER_ID:Clang&gt;: -Weverything -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto -fvisibility=default&gt;) target_link_options(${CMAKE_PROJECT_NAME} PRIVATE $&lt;$&lt;C_COMPILER_ID:Clang&gt;: -fsanitize=undefined,integer,implicit-conversion,nullability,address,leak,cfi -flto&gt;) </code></pre>
[]
[ { "body": "<p>My review is focused on <code>linkedlist.c</code>:</p>\n\n<ul>\n<li>Some functions don't check for null pointer (<code>get_node_val</code>, <code>set_node_val</code>). While it's documented, other functions do check for null pointer.</li>\n<li>The functions to append and prepend nodes require the caller to call the function to create a node. It might be a better idea to create the node in the function and to return the newly-created node.</li>\n<li>The function <code>append</code> does not return the new node while the function <code>prepend</code> does.</li>\n<li>The data can only be an integer; having a void pointer on the listed data allows to have any type of data. However, this change would make your search function unusable.</li>\n<li>Printing the data is a way of handling the data. It seems that this is the role of the caller.</li>\n<li>You may want to consider having a function to return the length of the list.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:15:19.333", "Id": "410054", "Score": "0", "body": "Thanks for the advice. For get_node_val what would you suggest returning on error? The reason I made it not check is because I wasn’t sure what to return on null as the function returns an int. Maybe INT_MIN and set it aside as a reserved value." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:57:32.750", "Id": "410084", "Score": "3", "body": "NIce review. Detail: \"having a void pointer .... allows to have any type of data\". --> Using `void*` allows using various object pointers, but not any type." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T01:45:50.150", "Id": "410172", "Score": "1", "body": "@chux I sure wish you had said a little more" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:44:40.907", "Id": "410223", "Score": "1", "body": "For the function `get_node_value`, that's how I would do it :\n`int get_node_value (const Node *node, int * value)`\nThis way, in case of error you return an error code (as int) and you set the value pointer to NULL." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T17:25:32.707", "Id": "410273", "Score": "0", "body": "That makes sense, good idea @Nicolas" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T13:42:25.980", "Id": "212067", "ParentId": "212041", "Score": "6" } }, { "body": "<blockquote>\n <p>The data can only be an integer; having a void pointer on the listed data allows to have any type of data. ...</p>\n</blockquote>\n\n<p>I think the suggestion to move to <code>void*</code> is a very good one. It's a great next \nstep to take if you want to keep working on your codebase. </p>\n\n<blockquote>\n <p>... However, this change would make your search function unusable. </p>\n</blockquote>\n\n<p>To make the search function usable with <code>void*</code>, it makes the most sense to offload the comparison functionality to a consumer-supplied function. This is how <a href=\"https://linux.die.net/man/3/bsearch\" rel=\"nofollow noreferrer\">posix's <code>bsearch</code></a> funcitonality works: </p>\n\n<pre><code>int (*compar)(const void *, const void *)\n</code></pre>\n\n<p>The man page explains that </p>\n\n<blockquote>\n <p>The <code>compar</code> routine is expected to have two arguments which point to the key object and to an array member, in that order, and should return an integer less than, equal to, or greater than zero if the key object is found, respectively, to be less than, to match, or be greater than the array member</p>\n</blockquote>\n\n<p>The approach makes sense. If you don't know the type of the objects in your list, you can't compare them, and this is something that the consumer will have to do for you. Passing a function pointer is a pretty standard way to do so; <a href=\"https://linux.die.net/man/3/qsort\" rel=\"nofollow noreferrer\">qsort</a> works the same way. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T09:24:28.210", "Id": "410211", "Score": "1", "body": "Thanks for this great answer! You've lurked a long time, but I do hope to see more such contributions from you in future." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T02:11:31.963", "Id": "212113", "ParentId": "212041", "Score": "3" } }, { "body": "<p>Instead of using void* or function pointers, I would say a tagged union would also offer a safe way to allow for more flexible node data. </p>\n\n<p>Using a tagged union would ensure only the size of the largest element is allocated plus any needed padding to raise the length to an alignment boundary (Ref: C: A Reference Manual, 5th Ed., Sec. 5.7.2, p.162). Using the corresponding enum, appropriate data can be accessed when traversing the linked list. Searching can be implemented with separate functions for each supported type.</p>\n\n<p>A simple example to illustrate with 3 types:</p>\n\n<pre><code>enum Tag {\n INT_TYPE, FLOAT_TYPE, STRING_TYPE\n};\n\nstruct Node {\n enum Tag tag;\n union {\n int int_val;\n float float_val;\n char* string_val;\n };\n struct Node *next;\n};\n\n/* Searching methods which would take an argument and traverse the list,\naccessing data based on the type specified in the enum */\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T17:22:49.007", "Id": "212147", "ParentId": "212041", "Score": "0" } } ]
{ "AcceptedAnswerId": "212067", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T05:02:26.813", "Id": "212041", "Score": "4", "Tags": [ "c", "linked-list", "c99" ], "Title": "Linked List written in C" }
212041
<p>I recently began learning C# and I picked up <em>Head First C#</em> as a starting point. One of the first projects they have you build, without the code provided, is a racetrack betting app. The project first gives you the requirements, as well as some suggested implementations. I did not follow the suggestions too closely though as I think I found some simpler solutions. I would like any and all feedback.</p> <p>The App looks like this. The greyhounds are currently represented by empty <code>PictureBox</code>s.</p> <p><a href="https://i.stack.imgur.com/g2BBt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/g2BBt.png" alt="racetrack interface"></a></p> <p><strong>Requirements</strong>:</p> <ul> <li>The four white squares are the greyhounds, each in its own lane.</li> <li>There are three <code>RadioButton</code>s which represent the three people at the betting parlor. The selected <code>RadioButton</code> sets the name for the <code>Label</code> on the place bet line. </li> <li>There are two <code>NumericUpDown</code>s used to change the amount and dog before clicking the <code>placeBet</code> button.</li> <li>Placing a <code>Bet</code> updates the corresponding label for the currently selected individual. A <code>Person</code> can only have one <code>Bet</code> at a time. New <code>Bet</code>s override old ones.</li> <li>The <code>startRace</code> button starts the race and closes the betting.</li> <li><code>Bet</code>s are paid out automatically at the end of the race and then the track is open for betting again.</li> </ul> <hr> <p><strong>Form1.cs</strong></p> <pre><code>using System; using System.Windows.Forms; namespace RacetrackApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); minimumBetLabel.Text = "Minimum Bet: " + minimumBet; People[0].AssignRadioButtonAndLabel(personOne, personOneBetLabel); People[1].AssignRadioButtonAndLabel(personTwo, personTwoBetLabel); People[2].AssignRadioButtonAndLabel(personThree, personThreeBetLabel); Greyhounds[0].AssignPictureBox(dogOne); Greyhounds[1].AssignPictureBox(dogTwo); Greyhounds[2].AssignPictureBox(dogThree); Greyhounds[3].AssignPictureBox(dogFour); activePerson = People[0]; nameLabel.Text = activePerson.Name; } private const int minimumBet = 5; private bool racing = false; private Person[] People = { new Person("Joe", 50), new Person("Bob", 75), new Person("Alice", 100) }; private Greyhound[] Greyhounds = { new Greyhound(1), new Greyhound(2), new Greyhound(3), new Greyhound(4) }; private Person activePerson; private void CheckedChanged(object sender, EventArgs e) { if (sender as RadioButton == personOne) { activePerson = People[0]; } else if (sender as RadioButton == personTwo) { activePerson = People[1]; } else { activePerson = People[2]; } nameLabel.Text = activePerson.Name; } private void PlaceBet_Click(object sender, EventArgs e) { if (!racing) { activePerson.MakeBet((int)betNumber.Value, Greyhounds[(int)dogNumber.Value - 1]); } } private void StartRace_Click(object sender, EventArgs e) { if (!racing) { racing = true; timer1.Start(); } } private void Timer1_Tick(object sender, EventArgs e) { foreach (Greyhound greyhound in Greyhounds) { if (greyhound.Run()) { EndRace(greyhound); break; } } } private void EndRace(Greyhound winningGreyhound) { foreach (Person person in People) { person.CheckBet(winningGreyhound); } foreach (Greyhound greyhound in Greyhounds) { greyhound.ReturnToStart(); } timer1.Stop(); racing = false; } } } </code></pre> <p><code>Form1</code> just holds the objects and maintains the Interface interactions. </p> <hr> <p><strong>Person.cs</strong></p> <pre><code>using System.Windows.Forms; namespace RacetrackApp { public class Person { public Person(string name, int cash) { Name = name; Cash = cash; } public string Name { get; } public int Cash { get; private set; } public Bet Bet { get; private set; } public RadioButton MyRadioButton { get; private set; } public Label MyLabel { get; private set; } public void AssignRadioButtonAndLabel(RadioButton radioButton, Label label) { MyRadioButton = radioButton; MyLabel = label; MyRadioButton.Text = Name + " has $" + Cash; MyLabel.Text = null; } public void MakeBet(int amount, Greyhound greyhound) { if (!(Bet is null)) { Cash += Bet.Amount; } Cash -= amount; Bet = new Bet(amount, greyhound); MyLabel.Text = Name + " bets $" + Bet.Amount + " on Dog " + greyhound.IDNumber; } public void CheckBet(Greyhound greyhound) { if (!(Bet is null)) { if (greyhound == Bet.Greyhound) { Cash += Bet.Amount * 2; } MyRadioButton.Text = Name + " has $" + Cash; Bet = null; MyLabel.Text = null; } } } } </code></pre> <p><code>Person</code> maintains private state, like name, cash, an instance of <code>Bet</code> and reference to the UI elements directly related to them.</p> <hr> <p><strong>Bet.cs</strong></p> <pre><code>namespace RacetrackApp { public class Bet { public Bet(int amount, Greyhound greyhound) { Amount = amount; Greyhound = greyhound; } public int Amount { get; } public Greyhound Greyhound { get; } } } </code></pre> <p><code>Bet</code> is a simple data struct that is declared as a class so it can be <code>null</code>ed</p> <hr> <p><strong>Greyhound.cs</strong></p> <pre><code>using System; using System.Drawing; using System.Windows.Forms; namespace RacetrackApp { public class Greyhound { public Greyhound(int ID) =&gt; IDNumber = ID; public PictureBox PictureBox { get; private set; } public int IDNumber { get; } private static readonly Random random = new Random(); private const int StartingLine = 12; private const int FinishLine = 875; private const int MinSpeed = 10; private const int MaxSpeed = 35; public void AssignPictureBox(PictureBox pictureBox) =&gt; PictureBox = pictureBox; public void ReturnToStart() { int YLocation = PictureBox.Location.Y; PictureBox.Location = new Point(StartingLine, YLocation); } public bool Run() { int XLocation = random.Next(PictureBox.Location.X + MinSpeed, PictureBox.Location.X + MaxSpeed); int YLocation = PictureBox.Location.Y; if (XLocation &gt; FinishLine) { XLocation = FinishLine; PictureBox.Location = new Point(XLocation, YLocation); return true; } PictureBox.Location = new Point(XLocation, YLocation); return false; } } } </code></pre> <p><code>Greyhound</code> has a reference to it's own image (which is currently blank) and then, using <code>Random</code>, moves across the track. The <code>Run()</code> method returns <code>true</code> when the greyhound crosses the finish line. This is the thing I am least satisfied with my solution. If two dogs would both cross the finish line within the same tick the one that wins is the one that is indexed lower in the array. I chose this solution because I did not want to have ties and I can't imagine a tie-breaking system that wasn't too sophisticated for this simple exercise.</p> <p>I look forward to anything you can tell me to help with my approach to C#.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:23:22.527", "Id": "410099", "Score": "1", "body": "Your race only has 2^32 possible sequences. This is because of the `static Random` instance and all arguments to `.Next()` are deterministic. This is generally a good thing for *testing*, but not if you want truly random races every time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:42:10.480", "Id": "410105", "Score": "0", "body": "@BradM thank you for that truly useful observation. More importantly, would this effect the probability of one dog winning the race over there others?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:05:19.727", "Id": "410112", "Score": "1", "body": "\"Probability\" isn't the best word to describe this code because it is 100% deterministic based on the random seed (the default is the system timestamp). Using the `Random` class properly is deceptively complex for other reasons as well." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:10:38.263", "Id": "410114", "Score": "0", "body": "@BradM I was worried you would say that when you mentioned it was deterministic. Thank you. Sounds like something worthwhile for me to look into." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:16:21.290", "Id": "410117", "Score": "0", "body": "Check out my approach is shuffling a list inside `/src/core/Utilities.cs`. It should give some insight into handling these scenarios. https://github.com/bradmarder/MSEngine" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T23:11:52.180", "Id": "410154", "Score": "0", "body": "@BradM - you're right, but to be fair 2^32 is quite a lot... more than any human gambler could spot a pattern... ;-)" } ]
[ { "body": "<p>Some things you might like to think about. (Please don't be disheartened. Most of this is picky).</p>\n\n<p>I'd like to see the people and the greyhounds more separated from the form used for display. There's no real reason for a greyhound to know anything about a picture box for example - it should know how far it's run, then the form draws the picture box using that information. This is probably not something to worry much about at this stage in your learning, but as you write more programs, you'll thank yourself for keeping business/game logic and presentation separate. (I'm not familiar with the book you're using by the way, but it sounds like it has fun examples/exercises).</p>\n\n<p>However, given that you are letting the form run everything, I note that the <code>Assign</code> methods (particularly <code>AssignPictureBox</code>) are really just setters. <code>Greyhound.PictureBox</code> might just as well have public get and set if you're going to provide a method to set it anyway. (I like that you're trying to use encapsulation to keep the setter private, but if a method exists to set it anyway, encapsulation isn't working - let it be a public setter, if that's what it honestly is. It works much better for <code>Person.Cash</code> for example, where the setter is rightly private - nothing outside should be able to set how much cash a person has, only give or take cash when they win or lose a bet, so a private set is absolutely correct there).</p>\n\n<p><code>Bet</code> is good, I like that it's immutable. Just a thought while I'm looking at it: the usual data type for currency is <code>decimal</code>, rather than <code>int</code> (what if someone wants to bet $5.75?). No big deal, but it'd be a good habit to get into.</p>\n\n<p>Personally I <em>vastly</em> prefer using <code>var</code> whenever possible (i.e. local variables), for example <code>foreach (var person in People)</code>. There are good reasons for this (particularly making it easier to change the type of something without having to update everywhere it's used), though some people think it obscures information from the programmer and prefer not to use it. I think that misses the point, but I won't repeat the flame war about it here, just something for you to read about and make up your own mind. :-)</p>\n\n<p>I really like that you're naming your controls (if I ever again have to try to work out what <code>button1</code> does or what gets entered into <code>textBox2</code>, I'll scream) but I would recommend including what the control is in the name. <code>personOne</code> doesn't sound like a radio button, <code>personOneRadioButton</code> does, and it's easily distinguishable from <code>personOneLabel</code> and <code>personOneTextBox</code>, if such things existed.</p>\n\n<p><code>CheckedChanged</code> could definitely be improved by adding the <code>Person</code> as a <code>Tag</code> on the radio button. So, in your initialization code you'd do something like this:</p>\n\n<pre><code>personOneRadioButton.Tag = People[0];\npersonTwoRadioButton.Tag = People[1];\n...\n</code></pre>\n\n<p>Then, <code>CheckedChanged</code> doesn't need all those <code>if</code>s and <code>as</code>s, and becomes simply:</p>\n\n<pre><code>var rb = (RadioButton)sender;\nactivePerson = (Person)(rb.Tag);\nnameLabel.Text = activePerson.Name;\n</code></pre>\n\n<p>Unless I'm missing something, a person can make a bet they don't actually have enough money for? :-D Also, you don't show the generated code for the controls (which is fine), but I hope the betNumber <code>NumericUpDown</code> has a <code>MinValue</code> of 0, to prevent people placing negative bets and hoping they lose, right? :-D</p>\n\n<p>I like that you've thought about how to handle ties, or at least are aware of it. An alternative approach might be to let all the greyhounds run in every tick, then at the end of <code>Timer1_Tick</code>, look for the greyhound with the largest X position and award them the win if they're past the finish line. (Ties would still be possible, and could be resolved however you see fit, but currently the greyhounds near the top of the track get more chances to win. If this were gambling real money, punters would not like that!)</p>\n\n<p><code>Greyhound.Run()</code> is a little messy. There's a bit of code duplication, and the distance the greyhound ran that tick is mixed up with the picture box stuff, and two returns where there could be just one... looks like it works fine, but it could be cleaner. Something like:</p>\n\n<pre><code>var distanceRan = random.Next(MinSpeed, MaxSpeed);\nvar newX = Math.Max(PictureBox.Location.X + distanceRan, FinishLine);\nPictureBox.Location = new Point (newX, PictureBox.Location.Y);\nreturn newX &gt;= FinishLine;\n</code></pre>\n\n<p>(Given the suggestion above about deciding who wins, the <code>Math.Max</code> didn't ought to be necessary, nor returning a bool of whether the greyhound has won or not; but I wanted to demonstrate changing only the way the method is laid out (neater IMO), not what it does.)</p>\n\n<p>On the use of <code>Random</code> (as it was mentioned in the comments): personally I think what you've done is fine as-is. The clock is used as a seed in <code>new Random()</code> so it's not like every race will be the same, and there's no way to predict the outcome. It is very common for games to make sure a different seed is used each playthrough, but for everything after that to be deterministic - it helps with testing, replays, online multiplayer synchronization, etc. So I think it's fine. However, you may decide that for fairness or other reasons, that's not enough for you. In that case, you could use a new random seed each race, or for each greyhound, instead of just once.</p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T00:25:05.143", "Id": "212108", "ParentId": "212042", "Score": "1" } } ]
{ "AcceptedAnswerId": "212108", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T05:24:45.117", "Id": "212042", "Score": "5", "Tags": [ "c#", "beginner", "winforms" ], "Title": "A Day at the Races. Racetrack Betting App" }
212042
<p>I'm working on a simple statistics problem with <code>Pandas</code> and <code>sklearn</code>. I'm aware that my code is ugly, but how can I improve it?</p> <pre><code>import numpy as np import pandas as pd import matplotlib.pyplot as plt from datetime import datetime from sklearn.metrics import mean_squared_error from sklearn.linear_model import LinearRegression df = pd.read_csv("sphist.csv") df["Date"] = pd.to_datetime(df["Date"]) df.sort_values(["Date"], inplace=True) df["day_5"] = np.nan df["day_30"] = np.nan df["std_5"] = np.nan for i in range(30, len(df)): last_5 = df.iloc[i-5:i, 4] last_30 = df.iloc[i-30:i, 4] df.iloc[i, -3] = last_5.mean() df.iloc[i, -2] = last_30.mean() df.iloc[i, -1] = last_5.std() df = df.iloc[30:] df.dropna(axis=0, inplace=True) train = df[df["Date"] &lt; datetime(2013, 1, 1)] test = df[df["Date"] &gt;= datetime(2013, 1, 1)] # print(train.head(), test.head()) X_cols = ["day_5", "day_30", "std_5"] y_col = "Close" lr = LinearRegression() lr.fit(train[X_cols], train[y_col]) yhat = lr.predict(test[X_cols]) mse = mean_squared_error(yhat, test[y_col]) rmse = mse/len(yhat) score = lr.score(test[X_cols], test[y_col]) print(rmse, score) plt.scatter(yhat, test[y_col], c="k", s=1) plt.plot([.95*yhat.min(), 1.05*yhat.max()], [.95*yhat.min(), 1.05*yhat.max()], c="r") plt.show() </code></pre> <ol> <li>It relies on hard-code iloc indices, which is hard to read or maintain. How can I change it to column names/row names?</li> <li>The codes look messy. Any advice to improve it?</li> </ol>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:50:29.617", "Id": "410013", "Score": "1", "body": "It's hard to provide guidance on using column name without knowing what columns your CSV contains. Can you include an example (like the first 10 lines for instance) of your dataset?" } ]
[ { "body": "<h1>functions</h1>\n\n<p>This is 1 long script. Partition the code in logical blocks. This could be like this</p>\n\n<ul>\n<li>get the raw data</li>\n<li>summarize the data</li>\n<li>split the test- and train data</li>\n<li>get the result from the regression</li>\n<li>plot the results</li>\n</ul>\n\n<h1>magical values</h1>\n\n<p>there are some magical values in your code, for example <code>4</code> as the column, <code>datetime(2013, 1, 1)</code> as the threshold to split the data. Define them as variables (or parameters for the functions)</p>\n\n<h2>dummy data</h2>\n\n<p>to illustrate this, I use this dummy data</p>\n\n<pre><code>def generate_dummy_data(\n x_label=\"x\",\n date_label=\"date\",\n size=100,\n seed=0,\n start=\"20120101\",\n freq=\"7d\",\n):\n np.random.seed(seed)\n\n return pd.DataFrame(\n {\n \"Close\": np.random.randint(100, 200, size=size),\n x_label: np.random.randint(1000, 2000, size=size),\n date_label: pd.DatetimeIndex(start=start, freq=freq, periods=size),\n }\n )\n</code></pre>\n\n<h1>summarize</h1>\n\n<p>The rolling mean and std you do can be done with builtin pandas <a href=\"https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.rolling.html\" rel=\"nofollow noreferrer\">functionality</a></p>\n\n<p>You also change the raw data. It would be better to make this summary a different DataFrame, and not alter the original data.</p>\n\n<pre><code>def summarize(df, date_label, x_label, y_label=\"Close\"):\n return pd.DataFrame(\n {\n y_label: df[y_label],\n date_label: df[date_label],\n \"day_5\": df[x_label].rolling(5).mean(),\n \"std_5\": df[x_label].rolling(5).std(),\n \"day_30\": df[x_label].rolling(30).mean(),\n }\n ).dropna()\n</code></pre>\n\n<h1>regression</h1>\n\n<p>here I followed pep-8, and renamed <code>X_cols</code> to <code>x_cols</code></p>\n\n<pre><code>def regression(train, test, x_cols, y_col):\n lr = LinearRegression()\n lr.fit(train[x_cols], train[y_col])\n yhat = lr.predict(test[x_cols])\n mse = mean_squared_error(yhat, test[y_col])\n rmse = mse/len(yhat)\n score = lr.score(test[x_cols], test[y_col])\n\n return yhat, rmse, score\n</code></pre>\n\n<h1>main guard</h1>\n\n<p>If you put the calling code behind <code>if __name__ == \"__main__\":</code>, you can import this script in other code without running the analysis, and reuse the functions</p>\n\n<pre><code>if __name__ == \"__main__\":\n\n x_label = \"x\"\n date_label = \"date\"\n y_label = \"Close\"\n data = generate_dummy_data(\n x_label=x_label, date_label=date_label, y_label=y_label\n )\n\n summary = summarize(\n data, date_label=date_label, x_label=x_label, y_label=y_label\n )\n\n threshold = \"20130101\"\n\n train = summary.loc[summary[date_label] &lt; threshold]\n test = summary.loc[summary[date_label] &gt;= threshold]\n\n x_cols = [\"day_5\", \"std_5\", \"day_30\"]\n\n yhat, rmse, score = regression(train, test, x_cols, y_col)\n\n print(x_cols, rmse, score)\n\n plt.scatter(yhat, test[y_col], c=\"k\", s=1)\n plt.plot(\n [0.95 * yhat.min(), 1.05 * yhat.max()],\n [0.95 * yhat.min(), 1.05 * yhat.max()],\n c=\"r\",\n )\n plt.show()\n</code></pre>\n\n<p>If you want to compare what each of the 3 metrics do individually, you'll have to do something like this:</p>\n\n<pre><code>for x_label in x_cols:\n yhat, rmse, score = regression(train, test, [x_label], y_col)\n\n print(x_label, rmse, score)\n\n plt.scatter(yhat, test[y_col], c=\"k\", s=1)\n plt.plot([.95*yhat.min(), 1.05*yhat.max()], [.95*yhat.min(), 1.05*yhat.max()], c=\"r\")\n plt.show()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:00:19.893", "Id": "212083", "ParentId": "212043", "Score": "2" } } ]
{ "AcceptedAnswerId": "212083", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T05:47:04.433", "Id": "212043", "Score": "0", "Tags": [ "python", "pandas" ], "Title": "Linear Regression on Pandas" }
212043
<h1>The question</h1> <blockquote> <p>Given a sequence of integers as an array, determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array.</p> </blockquote> <h1>My java solution</h1> <pre><code>boolean almostIncreasingSequence(int[] sequence) { Integer[] arr = new Integer[sequence.length]; for(int ctr = 0; ctr &lt; sequence.length; ctr++) { arr[ctr] = Integer.valueOf(sequence[ctr]); // returns Integer value } System.out.println(&quot;Integer :: &quot; + arr); List&lt;Integer&gt; al = new ArrayList&lt;Integer&gt;(); // adding elements of array to arrayList. Collections.addAll(al, arr); System.out.println(&quot;list :: &quot; + al); int save, flag = 0; for(int i=0; i&lt;al.size(); i++) { save = al.get(i); al.remove(i); if(al.size()==1) return true; for(int j=0; j&lt;al.size()-1; j++) { if(al.get(j+1) &gt; al.get(j)) { flag = 0; continue; } else { flag = 1; break; } } if(flag == 0) { return true; } al.add(i,save); } if(flag == 1) return false; return true; } </code></pre> <p>Here, I have created 2 for loops because in the first loop I'm generating the list where each index will be removed and in the second loop I'm iterating over the new list which has removed the element.</p> <p>like sample array is {1,2,4,3} then in the first loop I'm creating an array which will be {2,4,3},{1,4,3},{1,2,3} and {1,2,4}. In the second loop I'm iterating over all these 4 arrays to compare each element.</p> <h1>The problem</h1> <p>For some of the test cases, it shows that it takes more than 3 seconds to execute this. But, I'm not sure where can I make a change to execute it faster. I don't have access to the test case.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:45:48.347", "Id": "410003", "Score": "1", "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 [ask] for examples, and revise the title accordingly." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T10:55:47.563", "Id": "410032", "Score": "0", "body": "Hi Virus and welcome to codereview! I took the liberty to change the title and restructure your question to make it clearer. If you think I changed it too much feel free to edit it again." } ]
[ { "body": "<p>I think your question only needs you to determine if there is more than one integer out of sequence in the array passed in. </p>\n\n<p>You could just loop through the array passed in and if you find an integer out of sequence count it, then jump over it. </p>\n\n<p>If you find a second integer out of sequence then return false, if you don't find another in the array then return true. You should be able to achieve this with one loop which will speed up your code..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T12:14:02.237", "Id": "410039", "Score": "1", "body": "I thought so too at first but that's not enough. Take the sequence [3,4,1,2] where you only see 1 drop yet you can't fix it by taking only 1 item out." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T11:38:25.190", "Id": "212059", "ParentId": "212046", "Score": "0" } }, { "body": "<p>You are repeating a lot of work.</p>\n\n<p>For example, let's take a look at the sequence [1,2,3,4,5].</p>\n\n<p>Your code does the following:<br>\n- copy it to a list<br>\n- remove \"1\" and check if {2,3,4,5} is sorted<br>\n- remove \"2\" and check if {1,3,4,5} is sorted<br>\n- remove \"3\" and check if {1,2,4,5} is sorted<br>\n- remove \"4\" and check if {1,2,3,5} is sorted<br>\n- remove \"5\" and check if {1,2,3,4} is sorted </p>\n\n<p>Instead, let's go over the entire sequence once and do something special on the first item that is smaller than the previous one.</p>\n\n<p>At some point into the loop we see the following where <code>sequence[i-1] &gt; sequence[i]</code></p>\n\n<blockquote>\n <p>{done part, a, sequence[i-1], sequence[i], c, remainder}</p>\n</blockquote>\n\n<p>The whole start of the sequence up to sequence[i-1] is strictly increasing (checked in earlier iterations of the loop). So what do we still need to check here to give a meaningful answer?</p>\n\n<p>Given that <code>sequence[i-1]&gt;sequence[i]</code> either one of those needs to be removed. So we have 2 cases:</p>\n\n<ul>\n<li>remove sequence[i-1] -> check if {a, sequence[i], c, remainder} is strictly increasing </li>\n<li>remove sequence[i] -> check if {a, sequence[i-1], c, remainder} is strictly increasing</li>\n</ul>\n\n<p>Note that in both cases we want to check if the remainder is strictly ascending. So the main loop will look something like this:</p>\n\n<pre><code>for(int i = 1; i &lt; sequence.length; i++){\n if (sequence[i - 1] &gt; sequence[i]) {\n // {..., a, sequence[i-1], sequence[i], c, remainder}\n //check if remainder is sorted\n for(int j = i+1; j &lt; sequence.length; j++){\n if (sequence[j - 1] &gt; sequence[j]) {\n return false;\n }\n }\n int a = sequence[i - 2];\n int c = sequence[i + 1];\n //remove i-1\n if (a &lt; sequence[i] &amp;&amp; sequence[i] &lt; c) {\n return true;\n }\n //remove i\n if (a &lt; sequence[i - 1] &amp;&amp; sequence[i - 1] &lt; c) {\n return true;\n }\n //neither removing i-1 or i fixed the strictly increasing rule\n return false;\n }\n}\n//entire list is strictly increasing\nreturn true;\n</code></pre>\n\n<p>There's still some edge cases that will cause trouble. This loop as it is now will throw an <code>ArrayIndexOutOfBoundsException</code> because we're accessing from sequence[i-2] up to sequence[i+1].</p>\n\n<p>Let's handle those cases before the loop to keep things as simple as possible and reduce the bounds for the loop:</p>\n\n<pre><code>//trivial case with up to 2 items\nif(sequence.length &lt; 3){\n return true;\n}\n//edge case first 3 items are descending\nif(sequence[0]&gt;sequence[1]\n &amp;&amp;sequence[1]&gt;sequence[2]) {\n return false;\n}\n//edge case last 3 items are descending\nint last = sequence.length-1;\nif(sequence[last-2]&gt;sequence[last-1]\n &amp;&amp;sequence[last-1]&gt;sequence[last]) {\n return false;\n}\nfor(int i = 2; i &lt; sequence.length-1; i++){ //skip first 2 and last item\n ...\n</code></pre>\n\n<p>With this we're no longer checking the same items over and over again and we no longer copy all the items into a list which should give you a major improvement in speed.</p>\n\n<hr>\n\n<p><strong>DISCLAIMER</strong> I have not tested this code. It's possible it contains typo's or other edge cases. Be sure to fully understand it instead of blindly copy-pasting.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T23:15:49.013", "Id": "410155", "Score": "0", "body": "If `seq[0] > seq[1] && seq[1] > seq[2]`, then `seq[0] > seq[2]` must be true, so can be removed from the _first 3 items are descending_ test. Ditto for the _last 3 items are descending_ test." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T08:17:17.713", "Id": "410198", "Score": "0", "body": "@AJNeufeld True, editted :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T13:07:14.513", "Id": "212064", "ParentId": "212046", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T07:19:39.243", "Id": "212046", "Score": "2", "Tags": [ "java", "performance" ], "Title": "Checking if a sequence is almost strictly increasing" }
212046
<p>I am using .NET Core 2.2, EF Core and C#. I have created a web API project.</p> <p>I was requested to do an Upsert (insert or update). The entities structure is:</p> <ul> <li><p>Movie</p></li> <li><p>User</p></li> <li><p>Rating: this is used to give a rating to a movie, so a new rating will have the MovieId (from Movie) the UserId (from User) and the Rating value.</p></li> </ul> <p>In the Web API controller I have this request for the result of the upsert:</p> <ul> <li><p>404 (if movie or user is not found) </p></li> <li><p>400 (if the rating is an invalid value, the values can be an integer from 1 to 5) </p></li> <li><p>200 (OK) </p></li> </ul> <p>So, according to the request, I have implemented this code, but it does not look correct according to the SOLID principles. Is there any way to refactor this an get a better code? Obviously: making one method for the update and other to create is not an option as it does not respect the request. </p> <p>This is the code:</p> <pre><code>[Route("apid/movies")] [ApiController] public class MoviesDController : ControllerBase { private readonly IRatingRepository _repository; private readonly IUserRepository _userRepository; private readonly IMovieRepository _movieRepository; public MoviesDController(IRatingRepository repository, IUserRepository userRepository, IMovieRepository movieRepository) { _repository = repository; _userRepository = userRepository; _movieRepository = movieRepository; } // POST: apid/movies [HttpPost] public IActionResult Upsert([FromBody] Rating rating) { if (!ModelState.IsValid) { return BadRequest(ModelState); } //1) Get the User var user = _userRepository.GetById(rating.UserId); if (user == null) { return NotFound("User not found..."); } //2) Get the Movie var movie = _movieRepository.GetById(rating.MovieId); if (movie == null) { return NotFound("Movie not found..."); } //3) Get Rating var existingRating = _repository.GetMovieRating(rating.UserId, rating.MovieId); if (existingRating == null) { //Insert _repository.InsertRating(rating); return Ok("Rating added"); } existingRating.RatingValue = rating.RatingValue; //Update _repository.UpdateRating(existingRating); return Ok("Rating updated"); } } </code></pre> <p>Thanks!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:49:19.710", "Id": "410012", "Score": "1", "body": "_it does not look correct according to the SOLID principles_ - how do you figure? If you know what is wrong what don't try improve it first? What makes think it's not SOLID exactly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:51:12.950", "Id": "410014", "Score": "0", "body": "That is my best code at moment actually. I have no ideas, as I normally write one method to insert and another to update." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-30T09:42:35.550", "Id": "427933", "Score": "0", "body": "If you're worried about SOLID; the big screaming problem for me is that theres too much logic in your controller.. Move that out to your Business Logic layer.." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T08:26:11.203", "Id": "212049", "Score": "0", "Tags": [ "c#", "asp.net-mvc", ".net-core", "asp.net-core-webapi" ], "Title": "Upsert with .Net Core Web API" }
212049
<h2>Purpose</h2> <p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1" rel="noreferrer"><code>ObservableCollection&lt;T&gt;</code></a> is not strictly a WPF class, but its intended purpose seems to be for use in WPF. It's the standard implementation of <a href="https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.inotifycollectionchanged" rel="noreferrer"><code>INotifyCollectionChanged</code></a>, an interface which is special-cased by some WPF widgets to provide efficient UI updates and to maintain state effectively. For example, if a <code>ListView</code> is showing an <code>INotifyCollectionChanged</code> then it updates its <code>SelectedIndex</code> automatically when the underlying collection changes.</p> <p>I wrote the following class as part of maintenance of an application which was exposing various <code>IEnumerable&lt;T&gt;</code> in its view-model and using the much less powerful <code>IPropertyChanged</code> to notify the <code>ListView</code> of changes to the model. It had to do manual updates of <code>SelectedIndex</code>, and this was a source of bugs.</p> <p><a href="https://docs.microsoft.com/en-us/dotnet/api/system.windows.data.collectionview" rel="noreferrer"><code>CollectionView</code></a> pretty much supports <code>Where</code> filters, but it doesn't support <code>Select</code> and is messy to chain. It might be possible to rewrite the application to use <code>CollectionView</code>, but it would be a more major change than a plugin replacement which mimics the Linq queries used in the old code to map the model to the view-model. I can replace <code>List</code> in the model with <code>ObservableCollection</code>, replace Linq <code>Select</code> in the view-model (to map model classes to view-model classes) with <code>SelectObservable</code>, and remove some <code>PropertyChanged</code> event dispatches and manual <code>SelectedIndex</code> tracking.</p> <h2>Code</h2> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Numerics; using System.Windows; namespace Org.Cheddarmonk.Utils { // The .Net standard library should have included some interface like this. ObservableCollection&lt;T&gt; "implements" it. public interface IObservableEnumerable&lt;T&gt; : IReadOnlyList&lt;T&gt;, INotifyCollectionChanged { } public static class ObservableEnumerable { public static IObservableEnumerable&lt;TResult&gt; SelectObservable&lt;TSource, TResult, TCollection&gt;(this TCollection collection, Func&lt;TSource, TResult&gt; selector) where TCollection : IReadOnlyList&lt;TSource&gt;, INotifyCollectionChanged { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return new ObservableSelectIterator&lt;TSource, TResult&gt;(collection, selector); } public static IObservableEnumerable&lt;TElement&gt; WhereObservable&lt;TElement, TCollection&gt;(this TCollection collection, Func&lt;TElement, bool&gt; predicate) where TCollection : IReadOnlyList&lt;TElement&gt;, INotifyCollectionChanged { if (collection == null) throw new ArgumentNullException(nameof(collection)); if (predicate == null) throw new ArgumentNullException(nameof(predicate)); return new ObservableWhereIterator&lt;TElement&gt;(collection, predicate); } public static IObservableEnumerable&lt;TCast&gt; OfTypeObservable&lt;TSource, TCast, TCollection&gt;(this TCollection collection) where TCollection : IReadOnlyList&lt;TSource&gt;, INotifyCollectionChanged { if (collection == null) throw new ArgumentNullException(nameof(collection)); return WhereObservable&lt;TSource, TCollection&gt;(collection, elt =&gt; elt is TCast). SelectObservable&lt;TSource, TCast, IObservableEnumerable&lt;TSource&gt;&gt;(elt =&gt; (TCast)(object)elt); } private class ObservableSelectIterator&lt;TSource, TResult&gt; : IObservableEnumerable&lt;TResult&gt; { private readonly INotifyCollectionChanged source; private readonly List&lt;TResult&gt; results; private readonly Func&lt;TSource, TResult&gt; selector; internal ObservableSelectIterator(IReadOnlyList&lt;TSource&gt; wrapped, Func&lt;TSource, TResult&gt; selector) { source = (INotifyCollectionChanged)wrapped; // Just to keep a hard reference around, lest an intermediate object in a chain get GC'd this.results = wrapped.Select(selector).ToList(); this.selector = selector; WeakEventManager&lt;INotifyCollectionChanged, NotifyCollectionChangedEventArgs&gt;.AddHandler( (INotifyCollectionChanged)wrapped, nameof(INotifyCollectionChanged.CollectionChanged), (sender, evt) =&gt; { var mangled = Mangle(evt); CollectionChanged?.Invoke(this, mangled); }); } public int Count =&gt; results.Count; public TResult this[int index] =&gt; results[index]; public IEnumerator&lt;TResult&gt; GetEnumerator() =&gt; results.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator(); #region Event handler public event NotifyCollectionChangedEventHandler CollectionChanged; private NotifyCollectionChangedEventArgs Mangle(NotifyCollectionChangedEventArgs evt) { int oldIndex = evt.OldStartingIndex; int newIndex = evt.NewStartingIndex; TResult[] removedItems = null; if (evt.OldItems != null) { removedItems = new TResult[evt.OldItems.Count]; results.CopyTo(oldIndex, removedItems, 0, evt.OldItems.Count); } TResult[] addedItems = evt.NewItems != null &amp;&amp; evt.Action != NotifyCollectionChangedAction.Move ? evt.NewItems.Cast&lt;TSource&gt;().Select(selector).ToArray() : null; // Unfortunately, as with so many WPF-related classes in the standard library, the useful constructor is internal-only. switch (evt.Action) { case NotifyCollectionChangedAction.Reset: results.Clear(); return evt; case NotifyCollectionChangedAction.Add: results.InsertRange(newIndex, addedItems); return new NotifyCollectionChangedEventArgs(evt.Action, addedItems, newIndex); case NotifyCollectionChangedAction.Remove: results.RemoveRange(oldIndex, evt.OldItems.Count); return new NotifyCollectionChangedEventArgs(evt.Action, removedItems, oldIndex); case NotifyCollectionChangedAction.Replace: results.RemoveRange(oldIndex, evt.OldItems.Count); results.InsertRange(newIndex, addedItems); return new NotifyCollectionChangedEventArgs(evt.Action, addedItems, removedItems, newIndex); case NotifyCollectionChangedAction.Move: results.RemoveRange(oldIndex, evt.OldItems.Count); results.InsertRange(newIndex, removedItems); return new NotifyCollectionChangedEventArgs(evt.Action, removedItems, newIndex, oldIndex); default: throw new NotImplementedException(); } } #endregion } private class ObservableWhereIterator&lt;TElement&gt; : IObservableEnumerable&lt;TElement&gt; { private readonly IReadOnlyList&lt;TElement&gt; wrapped; private readonly Func&lt;TElement, bool&gt; predicate; // For reasonably efficient lookups we cache the indices of the elements which meet the predicate. private BigInteger indices; internal ObservableWhereIterator(IReadOnlyList&lt;TElement&gt; wrapped, Func&lt;TElement, bool&gt; predicate) { this.wrapped = wrapped; this.predicate = predicate; indices = _Index(wrapped); WeakEventManager&lt;INotifyCollectionChanged, NotifyCollectionChangedEventArgs&gt;.AddHandler( (INotifyCollectionChanged)wrapped, nameof(INotifyCollectionChanged.CollectionChanged), (sender, evt) =&gt; { var mangled = Mangle(evt); if (mangled != null) CollectionChanged?.Invoke(this, mangled); }); } private BigInteger _Index(IEnumerable elts) =&gt; elts.Cast&lt;TElement&gt;().Aggregate((BigInteger.Zero, BigInteger.One), (accum, elt) =&gt; (accum.Item1 + (predicate(elt) ? accum.Item2 : 0), accum.Item2 &lt;&lt; 1)).Item1; public int Count =&gt; indices.PopCount(); public TElement this[int index] { get { if (index &lt; 0) throw new IndexOutOfRangeException($"Index {index} is invalid"); // We need to find the index in wrapped at which we have (index + 1) elements which meet the predicate. // For maximum efficiency we would have to rewrite to use a tree structure instead of BigInteger, but // I'm not convinced that it's worthwhile. int toSkip = index + 1; int wrappedIndex = 0; foreach (var b in indices.ToByteArray()) { int sliceCount = b.PopCount(); if (sliceCount &lt; toSkip) { toSkip -= sliceCount; wrappedIndex += 8; } else { for (byte slice = b; ; wrappedIndex++, slice &gt;&gt;= 1) { if ((slice &amp; 1) == 1) { toSkip--; if (toSkip == 0) return wrapped[wrappedIndex]; } } } } throw new IndexOutOfRangeException($"Index {index} is invalid; Count = {index + 1 - toSkip}"); } } public IEnumerator&lt;TElement&gt; GetEnumerator() =&gt; wrapped.Where(predicate).GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() =&gt; GetEnumerator(); #region Event handler public event NotifyCollectionChangedEventHandler CollectionChanged; private NotifyCollectionChangedEventArgs Mangle(NotifyCollectionChangedEventArgs evt) { IList liftItems(IList items) =&gt; items?.Cast&lt;TElement&gt;().Where(predicate).ToArray(); var newItems = liftItems(evt.NewItems); var oldItems = liftItems(evt.OldItems); var newMask = (BigInteger.One &lt;&lt; evt.NewStartingIndex) - 1; var oldMask = (BigInteger.One &lt;&lt; evt.OldStartingIndex) - 1; var newStartingIndex = (indices &amp; newMask).PopCount(); var oldStartingIndex = (indices &amp; oldMask).PopCount(); switch (evt.Action) { case NotifyCollectionChangedAction.Reset: indices = 0; return evt; case NotifyCollectionChangedAction.Add: indices = ((indices &amp; ~newMask) &lt;&lt; evt.NewItems.Count) | (_Index(evt.NewItems) &lt;&lt; evt.NewStartingIndex) | (indices &amp; newMask); return newItems.Count &gt; 0 ? new NotifyCollectionChangedEventArgs(evt.Action, newItems, newStartingIndex) : null; case NotifyCollectionChangedAction.Remove: indices = ((indices &gt;&gt; evt.OldItems.Count) &amp; ~oldMask) | (indices &amp; oldMask); return oldItems.Count &gt; 0 ? new NotifyCollectionChangedEventArgs(evt.Action, oldItems, oldStartingIndex) : null; case NotifyCollectionChangedAction.Replace: indices = (((indices &gt;&gt; evt.OldItems.Count) &amp; ~newMask) &lt;&lt; evt.NewItems.Count) | (_Index(evt.NewItems) &lt;&lt; evt.NewStartingIndex) | (indices &amp; newMask); if (oldItems.Count &gt; 0) { if (newItems.Count &gt; 0) return new NotifyCollectionChangedEventArgs(evt.Action, newItems, oldItems, newStartingIndex); return new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, oldItems, oldStartingIndex); } if (newItems.Count &gt; 0) { return new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, newItems, newStartingIndex); } return null; case NotifyCollectionChangedAction.Move: // Update indices in two steps, for the removal and then the insertion. var movedIndices = (indices &gt;&gt; evt.OldStartingIndex) &amp; ((BigInteger.One &lt;&lt; evt.OldItems.Count) - 1); indices = ((indices &gt;&gt; evt.OldItems.Count) &amp; ~oldMask) | (indices &amp; oldMask); indices = ((indices &amp; ~newMask) &lt;&lt; evt.NewItems.Count) | (movedIndices &lt;&lt; evt.NewStartingIndex) | (indices &amp; newMask); return oldItems.Count &gt; 0 ? new NotifyCollectionChangedEventArgs(evt.Action, oldItems, newStartingIndex, oldStartingIndex) : null; default: throw new NotImplementedException(); } } #endregion } } } </code></pre> <p>There is a dependency on some bit-twiddling code:</p> <pre><code>/// &lt;summary&gt;Population count: how many bits are 1?&lt;/summary&gt; public static int PopCount(this byte v) { int x = v - ((v &gt;&gt; 1) &amp; 0x55); x = (x &amp; 0x33) + ((x &gt;&gt; 2) &amp; 0x33); return (x + (x &gt;&gt; 4)) &amp; 0x0f; } /// &lt;summary&gt;Population count: how many bits are 1?&lt;/summary&gt; public static int PopCount(this uint v) { v = v - ((v &gt;&gt; 1) &amp; 0x55555555); v = (v &amp; 0x33333333) + ((v &gt;&gt; 2) &amp; 0x33333333); v = (v + (v &gt;&gt; 4) &amp; 0x0f0f0f0f) * 0x01010101; return (int)v &gt;&gt; 24; } /// &lt;summary&gt;Population count: how many bits differ from the sign bit?&lt;/summary&gt; public static int PopCount(this BigInteger n) { uint invert = (uint)(n.Sign &gt;&gt; 1); ReadOnlySpan&lt;byte&gt; rawBytes = n.ToByteArray(); var rawUints = System.Runtime.InteropServices.MemoryMarshal.Cast&lt;byte, uint&gt;(rawBytes); // 4 bytes to a uint. System.Diagnostics.Debug.Assert(rawUints.Length == rawBytes.Length &gt;&gt; 2); int popCount = 0; foreach (var u in rawUints) popCount += PopCount(u ^ invert); for (int off = rawUints.Length &lt;&lt; 2; off &lt; rawBytes.Length; off++) popCount += PopCount((rawBytes[off] ^ invert) &amp; 0xffu); return popCount; } </code></pre> <h2>Tests</h2> <pre><code>using NUnit.Framework; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; namespace Org.Cheddarmonk.Utils.Tests { [TestFixture] public class TestObservableEnumerable { [Test] public void ValidateTracker() { // This is to ensure that the tracker we use for testing the main classes isn't itself buggy. var raw = new ObservableCollection&lt;int&gt;(); var tracker = new ObservableTestTracker&lt;int&gt;(raw); for (int i = 0; i &lt; 5; i++) { raw.Add(i); tracker.AssertTrackingCorrect(); } // [0, 1, 2, 3, 4] raw.RemoveAt(2); tracker.AssertTrackingCorrect(); // [0, 1, 3, 4] raw.Move(2, 0); tracker.AssertTrackingCorrect(); // [3, 0, 1, 4] raw.Move(0, 2); tracker.AssertTrackingCorrect(); // [0, 1, 3, 4] raw[3] = 5; tracker.AssertTrackingCorrect(); // [0, 1, 3, 5] Assert.IsTrue(new int[] { 0, 1, 3, 5 }.SequenceEqual(raw)); raw.Clear(); tracker.AssertTrackingCorrect(); } [Test] public void TestSelect() { var raw = new ObservableCollection&lt;int&gt;(); var select = raw.SelectObservable&lt;int, int, ObservableCollection&lt;int&gt;&gt;(x =&gt; 3 * x + 1); var tracker = new ObservableTestTracker&lt;int&gt;(select); for (int i = 0; i &lt; 5; i++) { raw.Add(i); tracker.AssertTrackingCorrect(); } // [0, 1, 2, 3, 4] =&gt; [1, 4, 7, 10, 13] raw.RemoveAt(2); tracker.AssertTrackingCorrect(); // [0, 1, 3, 4] =&gt; [1, 4, 10, 13] raw.Move(2, 0); tracker.AssertTrackingCorrect(); // [3, 0, 1, 4] =&gt; [10, 1, 4, 13] raw.Move(0, 2); tracker.AssertTrackingCorrect(); // [0, 1, 3, 4] =&gt; [1, 4, 10, 13] raw[3] = 5; tracker.AssertTrackingCorrect(); // [0, 1, 3, 5] =&gt; [1, 4, 10, 16] Assert.IsTrue(new int[] { 0, 1, 3, 5 }.SequenceEqual(raw)); Assert.IsTrue(new int[] { 1, 4, 10, 16 }.SequenceEqual(select)); raw.Clear(); tracker.AssertTrackingCorrect(); } [Test] public void TestWhere() { var raw = new ObservableCollection&lt;int&gt;(); var where = raw.WhereObservable&lt;int, ObservableCollection&lt;int&gt;&gt;(x =&gt; (x &amp; 1) == 0); var tracker = new ObservableTestTracker&lt;int&gt;(where); for (int i = 0; i &lt; 5; i++) { raw.Add(i); tracker.AssertTrackingCorrect(); } // [0, 1, 2, 3, 4] =&gt; [0, 2, 4] raw.RemoveAt(2); tracker.AssertTrackingCorrect(); // [0, 1, 3, 4] =&gt; [0, 4] raw.Move(2, 0); tracker.AssertTrackingCorrect(); // [3, 0, 1, 4] =&gt; [0, 4] raw.Move(0, 2); tracker.AssertTrackingCorrect(); // [0, 1, 3, 4] =&gt; [0, 4] raw[3] = 5; tracker.AssertTrackingCorrect(); // [0, 1, 3, 5] =&gt; [0] raw[3] = 1; tracker.AssertTrackingCorrect(); // [0, 1, 3, 1] =&gt; [0] raw[2] = 6; tracker.AssertTrackingCorrect(); // [0, 1, 6, 1] =&gt; [0, 6] raw[2] = 4; tracker.AssertTrackingCorrect(); // [0, 1, 4, 1] =&gt; [0, 4] Assert.IsTrue(new int[] { 0, 1, 4, 1 }.SequenceEqual(raw)); Assert.IsTrue(new int[] { 0, 4 }.SequenceEqual(where)); raw.Clear(); tracker.AssertTrackingCorrect(); } } class ObservableTestTracker&lt;T&gt; { private readonly IReadOnlyList&lt;T&gt; source; private readonly IList&lt;T&gt; changeTracker; internal ObservableTestTracker(IReadOnlyList&lt;T&gt; source) { this.source = source; this.changeTracker = new ObservableCollection&lt;T&gt;(source); (source as INotifyCollectionChanged).CollectionChanged += source_CollectionChanged; } private void source_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Reset: changeTracker.Clear(); break; case NotifyCollectionChangedAction.Add: int i = e.NewStartingIndex; foreach (T obj in e.NewItems) changeTracker.Insert(i++, obj); break; case NotifyCollectionChangedAction.Remove: foreach (T obj in e.OldItems) { Assert.AreEqual(obj, changeTracker[e.OldStartingIndex]); changeTracker.RemoveAt(e.OldStartingIndex); } break; case NotifyCollectionChangedAction.Replace: case NotifyCollectionChangedAction.Move: // This is a remove followed by an add foreach (T obj in e.OldItems) { Assert.AreEqual(obj, changeTracker[e.OldStartingIndex]); changeTracker.RemoveAt(e.OldStartingIndex); } int j = e.NewStartingIndex; foreach (T obj in e.NewItems) changeTracker.Insert(j++, obj); break; default: throw new NotImplementedException(); } } public void AssertTrackingCorrect() { // Direct comparison as IEnumerable&lt;T&gt;. Assert.IsTrue(source.SequenceEqual(changeTracker)); // Assert that the elements returned by source[int] correspond to the elements returned by source.GetEnumerator(). { var byIndex = new List&lt;T&gt;(); for (int i = 0; i &lt; changeTracker.Count; i++) byIndex.Add(source[i]); // Assert that we can't get an extra item. try { byIndex.Add(source[changeTracker.Count]); Assert.Fail("Expected IndexOutOfRangeException or ArgumentOutOfRangeException"); } catch (ArgumentOutOfRangeException) { // This is what's specified in the MSDN for IList&lt;T&gt;. IReadOnlyList&lt;T&gt; doesn't document any exceptions at all. } catch (IndexOutOfRangeException) { // This makes more sense, and is what the documentation for IndexOutOfRangeException claims should be thrown. } catch (Exception ex) { Assert.Fail($"Expected IndexOutOfRangeException or ArgumentOutOfRangeException, caught {ex}"); } Assert.IsTrue(byIndex.SequenceEqual(changeTracker)); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T09:35:58.583", "Id": "410018", "Score": "0", "body": "Not a fan of `var`? Outch! The one-liner loops :-]" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T09:44:12.757", "Id": "410020", "Score": "0", "body": "I'm not sure I understand the purpose of this class... what is it that it can do better than the original `ObservableCollection` exactly?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T09:51:14.777", "Id": "410024", "Score": "1", "body": "@t3chb0t, it's like applying Linq's `Select` or `Where` to `ObservableCollection`, but instead of just getting an `IEnumerable` you get an `INotifyCollectionChanged`. The standard library sort-of provides `Where` with `CollectionView`, but doesn't (AFAIK) provide `Select`." } ]
[ { "body": "<p><code>Move</code> events in <code>ObservableSelectIterator</code> could be expensive if elements are shifted around near the start of the list, as <code>Remove</code> and <code>Insert</code> will end up shifting the whole collection. There might be a significant performance advantage to manually moving the elements 'in between' the start and end indices, if that is at-all a concern.</p>\n\n<p>Similarly with <code>Replace</code>, there is need only to perform a single removal or insertion, which would halve the amount of copying to be done. If the lists are the same length, then there is no need to move any of the other elements at all: this in particular is important, because it covers index assignment, which everyone expects to be constant-time.</p>\n\n<p>I figure the same is true of <code>ObservableWhereIteractor</code>, but I shan't pretend I've fully reviewed the big-twiddling in its <code>Mangle</code> method.</p>\n\n<hr />\n\n<p>Giving <code>Item1</code> and <code>Item2</code> half-meaningful names in <code>_Index</code> wouldn't hurt.</p>\n\n<pre><code>private BigInteger _Index(IEnumerable elts) =&gt; elts.Cast&lt;TElement&gt;().Aggregate((indices : BigInteger.Zero, bit : BigInteger.One), (accum, elt) =&gt; (accum.indices + (predicate(elt) ? accum.bit : 0), accum.bit &lt;&lt; 1)).indices;\n</code></pre>\n\n<hr />\n\n<p>Should you be checking for <code>-1</code> indices in the <code>NotifyCollectionChangedEventArgs</code>? Presumably <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.notifycollectionchangedeventargs.-ctor?view=netframework-4.7.2#System_Collections_Specialized_NotifyCollectionChangedEventArgs__ctor_System_Collections_Specialized_NotifyCollectionChangedAction_System_Collections_IList_System_Collections_IList_\" rel=\"nofollow noreferrer\">this constructor</a> is only provided to support unordered collections, but I can't work out if there are any meaningful guarantees.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-25T11:02:57.910", "Id": "418232", "Score": "0", "body": "Fair observations. I'm not too concerned about performance at present: my use case has on the order of ten or twenty items. The last question is a good one: in practice, AIUI, WPF never calls that constructor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-23T20:53:31.930", "Id": "216077", "ParentId": "212052", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T09:17:49.350", "Id": "212052", "Score": "12", "Tags": [ "c#", "linq", "wpf" ], "Title": "Linq for ObservableCollection" }
212052
<p>In this code I have declared <code>myPushData</code>, <code>myPushDataFilterd</code> and <code>myPushDataFilterd2</code> variables which are using in code. I am thinking this code could be more easy &amp; short </p> <pre><code>private async void SendPushNotificationHwCreate(string orgId, string classId, string sectionId) { var myPushData = new List&lt;pushTokens&gt;(); var myPushDataFilterd = new List&lt;pushTokens&gt;(); var myPushDataFilterd2 = new List&lt;pushTokens&gt;(); var abtDAL = new AboutDAL(); var orDetails = new Dictionary&lt;string, string&gt; { { "orgId",SISConst.LoggedInUser.LogInOrganizationID}, }; var response = await SisApi.Get("Homework/GetOrganizationName", orDetails); var jres = JArray.Parse(response); var orgName = jres[0]["Title"].Value&lt;string&gt;(); var dic = new Dictionary&lt;string, string&gt;(); dic.Add("id", orgId); dic.Add("classId", classId); dic.Add("sectionId", sectionId); var result = SisApi.Get("Notifications/GetPNToken", dic, out bool isSuccess); if (!string.IsNullOrEmpty(result)) { myPushData = JsonConvert.DeserializeObject&lt;List&lt;pushTokens&gt;&gt;(result); myPushDataFilterd= myPushData.Where(i =&gt; i.OrgClassLevelID == Convert.ToInt32(classId)).ToList(); if (!string.IsNullOrEmpty(sectionId)) myPushDataFilterd2= myPushDataFilterd.Where(i =&gt; i.OrgSectionLevelID == Convert.ToInt32(sectionId)).ToList(); } var pushTask = new Task(() =&gt; { if (isSuccess &amp;&amp; myPushDataFilterd2.Any()) { for (int index = 0; index &lt; myPushDataFilterd2.Count; index++) { var row = myPushDataFilterd2[index]; var osType = row.OSType; var to = row.PNToken; var studentId = row.StudentID; var jGcmData = new JObject(); var jData = new JObject(); var api = string.Empty; jData.Add("moduleName", "Homework"); jData.Add("classId", classId); jData.Add("sectionId", sectionId); jData.Add("bodyText", "New homework assigned"); jData.Add("organization", orgName); jData.Add("organizationId", orgId); jData.Add("studentId", studentId); jGcmData.Add("to", to); jGcmData.Add("data", jData); jGcmData.Add("priority", "high"); api = row.ServerKeyPush; if (string.IsNullOrEmpty(api)) api = SISConst.API_KeyAndroidFCM; var url = new Uri("https://fcm.googleapis.com/fcm/send"); try { using (var client = new HttpClient()) { client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.TryAddWithoutValidation( "Authorization", "key=" + api); var r = client.PostAsync(url, new StringContent(jGcmData.ToString(), Encoding.Default, "application/json")).Result; } } catch (Exception ex) { Toast.MakeText(Application.Context, "Something went wrong", ToastLength.Short).Show(); var objLog = new LogService(); objLog.MobileLog(ex, SISConst.UserName); } } } }); pushTask.Start(); } </code></pre> <p><code>SendPushNotificationHwCreate</code> is a method to send <em>notifications</em>, in <code>myPushData</code> I am getting records from all <code>class</code> &amp; <code>sections</code>. Now for filtering I am using above three variables which doesn't seems good way to do that. It looks like am making it complicated. Is this code could be reduced. Thank you.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T12:01:02.980", "Id": "410038", "Score": "2", "body": "Could you explain (in words) what this code is achieving, and could you elaborate on how this fits into the whole application? For example, is this a whole method, and what is it's job? Whence does `classId` come? It's hard to provide commentary when we can't see the concrete usage (e.g. the `//something..` might have important consequences for a review)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T12:54:19.767", "Id": "410041", "Score": "0", "body": "@VisualMelon - This method is for sending push notifications, sending class & section Ids while calling this method. Please see my edits. Thank you" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T16:03:15.700", "Id": "410060", "Score": "1", "body": "This is wrong on so many levels that I don't even know where to start... Not awating the final task? Is this really what you want? Using the `HttpClient` in a loop. Using `.Result` on `PostAsync`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T05:55:53.497", "Id": "410181", "Score": "0", "body": "@t3chb0t - Thank you for your input _Not awaiting final task_, what is final task? I will look at `.Result` as well." } ]
[ { "body": "<p>First doesn't seem like any of this code is used. I mean it gets called but nothing with the responses is used in the code following the calls.</p>\n\n<pre><code>var abtDAL = new AboutDAL();\nvar orDetails = new Dictionary&lt;string, string&gt;\n {\n { \"orgId\",SISConst.LoggedInUser.LogInOrganizationID},\n };\nvar response = await SisApi.Get(\"Homework/GetOrganizationName\", orDetails);\nvar jres = JArray.Parse(response);\nvar orgName = jres[0][\"Title\"].Value&lt;string&gt;();\n</code></pre>\n\n<p>Async void methods are a code smell, it's not recommended.</p>\n\n<p>Also on myPushDataFilterd you don't need to do ToList you can just leave them as IEnumerable. You won't need the var myPushDataFilterd2. </p>\n\n<p>You have what seems like a bug in your task code. You check for myPushData.Any() but are looping around the filtered pushdata. Also</p>\n\n<pre><code>var row = myPushData[index];\n</code></pre>\n\n<p>would be wrong because again looping around the filtered data. I assume you want the myPushDataFilterd2[index].</p>\n\n<p>Also more bugs you are checking string.IsNullOrEmpty(sectionId) to fill myPushDataFilterd2. If there is no sectionId passed in then myPushDataFilterd2 will be empty and your loop will just exit. I assume that is not what you want. </p>\n\n<p>HttpClient should be created once and then used for the entire loop and not created each time. </p>\n\n<p>I would move the entire task code into it's own method passing in parameters and making it async. I don't see the need to create a Task object and start it. </p>\n\n<p>Also move the check for Any and IsSuccessful out of the task. Why create an object that will not do anything? </p>\n\n<p>UPDATE based on comment</p>\n\n<pre><code>var pushTask = new Task(() =&gt;\n{\n if (isSuccess &amp;&amp; myPushDataFilterd2.Any())\n</code></pre>\n\n<p>should be changed to this <em>if you leaving it to create a task object</em></p>\n\n<pre><code>if (isSuccess &amp;&amp; myPushDataFilterd2.Any())\n{\n var pushTask = new Task(() =&gt;\n {\n</code></pre>\n\n<p>As there is no processing done in the task if either of those are false.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:05:34.117", "Id": "410051", "Score": "0", "body": "Thank you for your answer. So many things you have pointed but few I didn't get like in last `Why create an object that will not do anything?` and `I would move the entire task code into it's own method passing in parameters and making it async. I don't see the need to create a Task object and start it` Can you please modify my code" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:09:44.320", "Id": "410053", "Score": "0", "body": "You can move the if (isSuccess && myPushDataFilterd2.Any()) out side of the task object. No point in creating the task object if it's not going to do anything. Also instead of creating a task object to run the code just create another async task method and put that code in there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:16:11.673", "Id": "410055", "Score": "0", "body": "Thank you. My concern is _How you can say task object not doing anything_, in what situation it would do something. Also you can look at my updated code in question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:22:52.983", "Id": "410056", "Score": "0", "body": "I've updated the answer to show exactly what I was talking about." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T14:43:05.743", "Id": "212072", "ParentId": "212058", "Score": "3" } } ]
{ "AcceptedAnswerId": "212072", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T11:23:10.833", "Id": "212058", "Score": "-2", "Tags": [ "c#", "linq" ], "Title": "Filtering List data using LINQ" }
212058
<p>I tried my hand at making a numbered line list.</p> <p>I would like some feedback on my use of CSS and if this approach (using a numbered list) is considered a good solution.</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-css lang-css prettyprint-override"><code>body { background: black; } .terminal { background-color: black; padding: 0em; width: 70em; color: #99ffcc; } .terminal li { background: #313131; padding: 0.4em 0; counter-increment: li; } .terminal ol { background: #515151; counter-reset: li; list-style: none; } .terminal li::before { content: counter(li); padding-right: 1em; display: inline-block; width: 1em; margin-left: -1.5em; margin-right: 0.5em; text-align: right; direction: rtl; color: gray; } .terminal li:first-child { padding: 1em 0 0.5em 0; } .terminal li:last-child { padding: 0.5em 0 1em 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="terminal"&gt; &lt;ol&gt; &lt;li&gt;sudo apt-get update&lt;/li&gt; &lt;li&gt;sudo update-alternatives --install &amp;lt;bin command path&amp;gt; &amp;lt;command name&amp;gt; &amp;lt;link to executable&amp;gt; &amp;lt;priority&amp;gt;&lt;/li&gt; &lt;li&gt;mvn clean package&lt;/li&gt; &lt;li&gt;Example&lt;/li&gt; &lt;li&gt;Example&lt;/li&gt; &lt;li&gt;Example&lt;/li&gt; &lt;li&gt;Example&lt;/li&gt; &lt;li&gt;Example&lt;/li&gt; &lt;li&gt;Example&lt;/li&gt; &lt;li&gt;Example&lt;/li&gt; &lt;li&gt;Example&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p><em>'considered a good solution'</em> is subjective, and relative to the scope of your project, especially given there were no performance/compatibility concerns listed. IMO, you have a good solution here. Using <code>:before</code> or <code>:after</code> pseudo classes gives you inherent text selection boundaries which is great! (no one wants to copy line numbers when selecting code snippet text)</p>\n\n<p>However, if this was purely an example of accomplishing familiarity with counters is beyond me, so consider that you're example is intended for code snippets it might be best to keep it in a tag that <strong><em>best</em></strong> represents the content. For example <code>&lt;pre&gt;&lt;code&gt;</code>.</p>\n\n<p>This identifies sound page structure, which only good things come from that like SEO compliance and browser support. The good ole vendor pre-fix can be annoying to track, but they are there for a reason. Let the user experience content in a way that their preferred browser implements. (Not that you need a prefix here, just demonstrating why keeping it relative to the content can benefit users, as well as developers/site owners). And lastly, of course the accessibility argument. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-16T16:10:57.697", "Id": "213598", "ParentId": "212062", "Score": "1" } } ]
{ "AcceptedAnswerId": "213598", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T12:58:54.757", "Id": "212062", "Score": "4", "Tags": [ "html", "css" ], "Title": "Numbered lines list" }
212062
<p>I have been making C# software to write PDF files. </p> <p>It's intended to be simple to use, compact, efficient and also reasonably simple to understand, maintain and extend as required. </p> <p>The basic functionality supports multi-column layout with word-wrapping and justification, and the standard fonts.</p> <p>Currently, additional classes support TrueType embedded font subsets and PNG graphics files. The complete set of source files is on <a href="https://github.com/georgebarwood/pdf" rel="noreferrer">github here</a>.</p> <p>For now, please review the main class, PdfWriter below. Questions:</p> <p>(1) Any suggestions on useability ? How to document the public interface?</p> <p>(2) Any suggestions on coding style or approach?</p> <p>(3) Generally, how can I make it better?</p> <pre><code>using String = System.String; using IO = System.IO; using Generic = System.Collections.Generic; namespace Pdf { public class PdfWriter // class for writing PDF ( Portable Document Format ) files ( https://en.wikipedia.org/wiki/PDF ) . { // Example usage public static void Example1() { using( IO.FileStream fs = IO.File.Create( "Example1.pdf") ) { PdfWriter w = new Pdf.PdfWriter(); w.Title = "Hello World"; w.Fonts = Pdf.StandardFontFamily.Times(); // Sets font family ( optional, default is Helvetica ). // Default PageLayout (width, height, margins) may be adjusted here. w.SetColumns( 3, 5 ); // Sets pages to be formatted as 3 columns, 5pt space between columns. w.Initialise( fs ); // Creates first page, ready to write text. // Optional style settings. w.Justify = 2; // Causes text to be justified. w.SetFont( w.Fonts[0], 9 ); // Sets font and font size. for ( int i = 0; i &lt; 100; i += 1 ) w.Txt( "Some arbitrary text which is long enough to demonstrate word wrapping. " ); w.Finish(); } } // Example with an image and embedded font ( subset ). public static void Example2() { byte [] myImageBytes = Util.GetFile( @"c:\PdfFiles\666.png" ); byte [] freeSansBytes = Util.GetFile( @"c:\PdfFiles\FreeSans.ttf" ); using( IO.FileStream fs = IO.File.Create( "Example2.pdf") ) { PdfWriter w = new Pdf.PdfWriter(); w.Title = "Graphics and embedded font example"; w.Initialise( fs ); PdfImage myImage = ImageUtil.Add( w, myImageBytes ); w.LineAdvance = myImage.Height / 2 + 10; // Make space for the image w.NewLine(); w.LineAdvance = 15; // Restore LineAdvance to default value. w.CP.DrawImage( myImage, w.CP.X, w.CP.Y, 0.5f ); PdfFont freeSans = new TrueTypeFont( "DJGTGD+Sans", freeSansBytes ); w.SetFont( freeSans, 12 ); w.Txt( "Hello world" ); w.Finish(); } } // PDF spec is at https://www.adobe.com/content/dam/acom/en/devnet/pdf/pdfs/PDF32000_2008.pdf // Minimum additional files: PdfPage.cs, Deflator.cs, PdfFont.cs, PdfMetric.cs. // Other files: PdfTrueType.cs, TrueType.cs, PdfPng.cs, Inflator.cs, PDfOther.cs, Util.cs, Pdfwriter2.cs. public void SetColumns( int n, float colSpace ) { Columns = n; ColSpace = colSpace; LineLength = ( ( PageLayout.Width + colSpace - PageLayout.MarginRight - PageLayout.MarginLeft ) / n ) - colSpace; } public void Initialise( IO.Stream os ) { OS = os; Put( "%PDF-1.4\n" ); if ( CP == null ) { if ( Fonts == null ) Fonts = StandardFontFamily.Helvetica(); if ( _Font == null ) SetFont( Fonts[0], _FontSize ); NewPage0(); } } // Basic functions. public void Txt( String s ) { Txt( s,0,s.Length ); } // Write justified text, word-wrapping to new line or page as required. public void NewLine() { FlushWord(); FinishLine( false ); } // Force a new line. public void NewPage() { NewLine(); NewPage0(); } // Force a new page. // Functions to adjust text style. public void SetFont( PdfFont f, int fontSize ) { Word.Font( f, fontSize ); _Font = f; _FontSize = fontSize; } public void SetSuper( int x ) { Word.Super( x ); _Super = x; } public void SetColor( String color ) { Word.Color( color ); } public void SetOther( String other ) { Word.Other( other ); } // Properties. public PdfFont Font{ get{ return _Font; } } public int FontSize{ get{ return _FontSize; } } public int Super{ get{ return _Super; } } public bool PartialLine{ get{ return WordCharCount &gt; 0 || LineCharCount &gt; 0; } } // Public fields. public String Title; // Assign a string to set the PDF title. // Page parameters public PageLayout PageLayout = new PageLayout( 595, 842, 36 ); // Default is A4, margin 36 pt. public PdfPage CP; // Current page, see PdfPage.cs for interface. // Line parameters ( in pt ). public float LineLength = 523, LineAdvance=15, LineMarginBefore=0; public FontFamily Fonts; // Line justification parameter. public int Justify=0; // Justify values are 0=right ragged, 1=center, 2=justifed. // Streams, Lists and Buffers public IO.Stream OS; // Final output stream. public long OS_Total = 0; // Total bytes written to OS ( for xref table ), must be updated if writing direct to OS. public Generic.List&lt;PdfPage&gt; Pages = new Generic.List&lt;PdfPage&gt;(); public Generic.List&lt;DynObj&gt; DynObjs = new Generic.List&lt;DynObj&gt;(); public Generic.List&lt;long&gt; Xref = new Generic.List&lt;long&gt;(); // Compression option public bool Compress = true; // Set to false to make PDF easier to examine when testing or if compression not wanted. // Private fields. private PdfFont _Font; private int _FontSize=12, _Super; private WordBuffer Word = new WordBuffer(); private LineBuffer Line = new LineBuffer(); // Word and Line state, used to calculate line justification and word wrapping. private float LinePos, SpacePos, ColSpace; private int SpaceCount, WordCharCount, LineCharCount, Columns = 1, CurColumn = 0; private bool FirstLine; // End fields. public void InitFont( PdfFont f ) { f.GetObj( this ); } // Only needs to be called if a page font is set directly. public virtual void NewColumn() { if ( CurColumn+1 &lt; Columns ) { LineMarginBefore += LineLength + ColSpace; FirstLine = true; CurColumn += 1; } else { NewPage0(); } } public void NewPage0() // Start a new page ( without flushing word buffer, so current word can be carried over to next page ). { PdfPage old = CP, p = new PdfPage(); p.Layout = PageLayout; Pages.Add( p ); p.Number = Pages.Count; CP = p; FirstLine = true; LinePos = 0; SpaceCount = 0; LineCharCount = 0; CurColumn = 0; LineMarginBefore = 0; StartPage(); CP.InitTxtFrom( old ); } private void FinishLine( bool wrap ) // Writes the line buffer to a page. { float space = LineLength - LinePos; if ( wrap &amp;&amp; SpaceCount &gt; 0 ) space += ( LinePos - SpacePos ); float centerjustify = Justify == 1 ? space / 2 : 0; // Center justification int lineCharCount = LineCharCount; // GetSpace if needed. if ( !FirstLine &amp;&amp; CP.Y - LineAdvance &lt; CP.Layout.MarginBottom ) NewColumn(); if ( FirstLine ) { CP.Goto( centerjustify + CP.Layout.MarginLeft + LineMarginBefore, CP.Layout.Height - CP.Layout.MarginTop - LineAdvance ); FirstLine = false; } else { CP.Td( centerjustify + CP.Layout.MarginLeft + LineMarginBefore - CP.X, -LineAdvance ); } CP.SetCharSpacing( wrap &amp;&amp; Justify == 2 ? space / lineCharCount : 0 ); Line.Flush( CP ); LinePos = 0; SpaceCount = 0; LineCharCount = 0; } private void FlushWord() { Word.Flush( Line ); LineCharCount += WordCharCount; WordCharCount = 0; } private void WordAdd( String s, int start, int end ) // Append part of s to word buffer. { if ( start &gt;= end ) return; Word.Str( s, start, end ); } public void Txt( String s, int start, int end ) // Writes text word-wrapping to new line or page as required. { InitFont( _Font ); int i = start; while ( i &lt; end ) { char c = s[i]; int uc = System.Char.IsSurrogate( c ) ? char.ConvertToUtf32( s, i ) : c; float cwidth = _Font.Width( uc, _FontSize ); if ( LinePos + cwidth &gt; LineLength || c == '\n' ) { float carry = 0; // Amount carried to next line. if ( SpaceCount &gt; 0 &amp;&amp; c != '\n' ) { carry = LinePos - SpacePos; // Word wrap, current word is written to next line. } else { // No word wrap, flush the word buffer. WordAdd( s, start, i ); start = i; FlushWord(); } FinishLine( c != '\n' ); LinePos = carry; } LinePos += cwidth; i += 1; if ( c != '\n' ) WordCharCount += 1; if ( c == ' ' ) { WordAdd( s,start,i ); start = i; FlushWord(); SpacePos = LinePos; SpaceCount += 1; } else if ( System.Char.IsSurrogate( c ) ) i += 1; // Skip surrogate pair char } WordAdd( s, start, end ); } public virtual void StartPage() {} // Can be over-ridden to initialise the page ( e.g. set a background image, draw a border ) . public virtual void FinishPage() {} // Can be over-ridden to finalise the page ( e.g. write a page number ) . public virtual int WritePages(){ return PdfPage.WritePages( this, Pages ); } public virtual int WriteCatalog( int pagesobj ){ return PutObj( "&lt;&lt;/Type/Catalog/Pages " + pagesobj + " 0 R&gt;&gt;" ); } public virtual int WriteInfo() { if ( Title != null ) { int result = StartObj(); Put( "&lt;&lt;/Title" ); PutStr( Title ); Put ( "&gt;&gt;" ); EndObj(); return result; } return 0; } public virtual void Finish() { if ( PartialLine ) NewLine(); int catObj = WriteCatalog( WritePages() ); int infoObj = WriteInfo(); foreach( DynObj x in DynObjs ) x.WriteTo( this ); long startxref = OS_Total; int xc = Xref.Count + 1; Put( "xref\n0 " + xc + "\n0000000000 65535 f\n" ); for ( int i=0; i&lt;Xref.Count; i += 1 ) Put( Xref[i].ToString( "D10" ) + " 00000 n\n" ); Put( "trailer\n&lt;&lt;/Size " + xc + "/Root " + catObj + " 0 R" + ( infoObj == 0 ? "" : "/Info " + infoObj ) + " 0 R" + "&gt;&gt;\nstartxref\n" + startxref + "\n%%EOF\n" ); } // Low level functions for PDF creation. public void Put( byte b ) { OS.WriteByte( b ); OS_Total += 1; } public void Put( byte [] b ) { OS.Write( b, 0, b.Length ); OS_Total += b.Length; } public void Put( string s ) { for ( int i=0; i &lt; s.Length; i += 1 ) OS.WriteByte( ( byte ) s[i] ); OS_Total += s.Length; } public void PutStrByte( byte b ) { if ( b == '(' || b == '\\' || b == ')' ) Put( ( byte ) '\\' ); if ( b == 13 ) Put( @"\015" ); // Octal escape must be used for 13, see spec, bottom of page 15. else Put( b ); } public static bool IsAscii( String s ) { for ( int i = 0; i &lt; s.Length; i += 1 ) if ( s[i] &gt; 127 ) return false; return true; } public void PutStr( String s ) { Put( (byte) '(' ); if ( IsAscii (s) ) { for ( int i=0; i &lt; s.Length; i += 1 ) PutStrByte( (byte) s[i] ); } else { Put( 254 ); Put( 255 ); // Byte order marker System.Text.Encoding enc = System.Text.Encoding.BigEndianUnicode; byte [] b = enc.GetBytes( s ); for ( int i = 0; i &lt; b.Length; i += 1 ) PutStrByte( b[i] ); } Put( (byte) ')' ); } public int AllocObj() { Xref.Add( 0 ); return Xref.Count; } public void AllocDynObj( DynObj x ) { if ( x.Obj == 0 ) { x.Obj = AllocObj(); DynObjs.Add( x ); } } public void StartObj( int ObjNum ) { Xref[ ObjNum-1 ] = OS_Total; Put( ObjNum + " 0 obj\n" ); } public void EndObj() { Put( "\nendobj\n" ); } public int StartObj() { int obj = AllocObj(); StartObj( obj ); return obj; } public int PutObj( string s ) { int obj = StartObj(); Put( s ); EndObj(); return obj; } // Compression functions public int PutStream( byte [] data ) { int result = StartObj(); Put( "&lt;&lt;" ); if ( Compress ) { Put( "/Filter/FlateDecode" ); #if ( UseZLib ) { data = Deflate( data ); Put( "/Length " + data.Length + "&gt;&gt;stream\n" ); Put( data ); } #else { MemoryBitStream bb = new MemoryBitStream(); Deflator.Deflate( data, bb, 1 ); int clen = bb.ByteSize(); Put( "/Length " + clen + "&gt;&gt;stream\n" ); bb.CopyTo( OS ); OS_Total += clen; } #endif } else { Put( "/Length " + data.Length + "&gt;&gt;stream\n" ); Put( data ); } Put( "\nendstream" ); EndObj(); return result; } public static byte [] Deflate( byte [] data ) { #if ( UseZLib ) IO.MemoryStream cs = new IO.MemoryStream(); Zlib.ZDeflaterOutputStream zip = new Zlib.ZDeflaterOutputStream( cs ); zip.Write( data, 0, data.Length ); zip.Finish(); return cs.ToArray(); #else MemoryBitStream bb = new MemoryBitStream(); Deflator.Deflate( data, bb, 1 ); return bb.ToArray(); #endif } // WordBuffer and LineBuffer are used to implement text justification / line wrapping. private struct TextElem { public int Kind; public System.Object X; public int I1, I2; } private class WordBuffer : Generic.List&lt;TextElem&gt; { public void Str( String x, int i1, int i2 ) { this.Add( new TextElem{ Kind=0, X = x, I1 = i1, I2 = i2 } ); } public void Font( PdfFont x, int i1 ) { this.Add( new TextElem{ Kind=1, X = x, I1 = i1 } ); } public void Super( int i1 ) { this.Add( new TextElem{ Kind=2, I1 = i1 } ); } public void Color( String x ) { this.Add( new TextElem{ Kind=3, X = x } ); } public void Other( String x ) { this.Add( new TextElem{ Kind=4, X = x } ); } public void Flush( LineBuffer b ) { foreach ( TextElem e in this ) b.Add( e ); Clear(); } } private class LineBuffer : Generic.List&lt;TextElem&gt; { public void Flush( PdfPage p ) { foreach ( TextElem e in this ) { switch ( e.Kind ) { case 0: p.Txt( ( String ) e.X, e.I1, e.I2 ); break; case 1: p.SetFont( ( PdfFont ) e.X, e.I1 ); break; case 2: p.SetSuper( e.I1 ); break; case 3: p.SetColor( ( String ) e.X ); break; case 4: p.SetOther( ( String ) e.X ); break; } } Clear(); } } } // End class PdfWriter } // namespace </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T23:14:04.463", "Id": "411362", "Score": "1", "body": "Not strictly on-topic, but I'm wondering if you would mind making `Util.cs` available in the github repo? I've had to dip into PDF now and then, and I've really enjoyed looking through your questioned lately, but I'm too lazy to second guess the implementations of the utility methods." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T06:22:52.413", "Id": "411373", "Score": "2", "body": "@VisualMelon Sure, that was an oversight, I have now uploaded Util.cs" } ]
[ { "body": "<p>Given that the <code>PdfWriter</code> holds a reference to an <code>IDisposable</code> resource (the <code>Stream</code>), it's good practice to implement <code>IDisposable</code>. Note that Stream is a special case of rule <a href=\"https://docs.microsoft.com/en-us/visualstudio/code-quality/ca2213-disposable-fields-should-be-disposed?view=vs-2019\" rel=\"noreferrer\">CA2213</a>.</p>\n\n<p>I've also noticed that all of your examples call both <code>Initialise</code> and <code>Finish</code>. If that's the case, I'd argue for a factory method to create the writer and call <code>Finish</code> within the <code>Dispose</code> method of <code>PdfWriter</code>. That means your usage could become:</p>\n\n<pre><code>using (IO.FileStream fs = IO.File.Create(\"Example1.pdf\"))\nusing (PdfWriter writer = PdfWriter.Create(fs, new PdfWriterOptions \n { \n Fonts = Pdf.StandardFontFamily.Times() \n }))\n{\n // The actual writing.\n}\n</code></pre>\n\n<p>That saves the consumer from having to remember to call two methods every time they use the class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-15T11:15:01.633", "Id": "226166", "ParentId": "212063", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T13:03:36.517", "Id": "212063", "Score": "11", "Tags": [ "c#", "api", "pdf" ], "Title": "Writing PDF files in C#" }
212063
<p>I implemented KMP pattern matching algorithm in Scala. My code works but it looks more imperative and a scala translation of C/C++ implementation.</p> <p>I am not able to figure out how to manage multiple indexes and then update them conditionally. Following is the code with some explanation, kindly suggest how to write it in scala way.</p> <p>KMP algo has two parts .</p> <p>first one is where we create an array which will have information of how many character we can skip in pattern if find a mismatch.</p> <p>example -</p> <pre><code>AAAA -&gt; 0,1,2,3 ABCDE -&gt; 0,0,0,0,0 AABAACAABAA -&gt; 0,1,0,1,2,0,1,2,3,4,5 </code></pre> <p>Following is code to build this array from patten string</p> <pre><code>def buildLookupTable(s: String): ArrayBuffer[Int] = { val lookupTable = ArrayBuffer.fill(s.length)(-1) lookupTable(0) = 0 // first char always 0 var len = 0 var i = 1 while( i &lt; s.length) { if (s(i) == s(len)) { len += 1 lookupTable(i) = len i += 1 } else { // mismatch if (len == 0) { lookupTable(i) = 0; i= i+1 } else { len = lookupTable(len-1) } } } lookupTable } </code></pre> <p>Once we have this array we can use this to find occurences of a pattern. Something like following </p> <pre><code>def searchPattern(s: String, p: String): Unit = { if (p.length &gt; s.length) println("bad input") else if (p == s) println("same strings") else { val lookupTable = buildLookupTable(p) var i= 0 // for s var j= 0 // for p while (i &lt; s.length) { if (s(i) == p(j)) { i += 1 j += 1 } if (j == p.length) { println(s"pattern found at ${i-j}") j = lookupTable(j-1) } else { if (i &lt; s.length &amp;&amp; s(i) != p(j)) { if (j != 0) j = lookupTable(j-1) else i+=1 } } } } } </code></pre> <p>This code works for the tests cases I have. But its not beautiful scala code. Kindly suggest the right approach to look at this problem and solve it functional way. </p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T13:56:26.407", "Id": "212068", "Score": "1", "Tags": [ "algorithm", "strings", "interview-questions", "functional-programming", "scala" ], "Title": "KMP algorithm in scala" }
212068
<p>I made this code because, I figured that it might be an interesting concept, and that it would be nice to see it work. It enables the toggling of strict mode in any string of code.</p> <p>It even allows you to set a scope to run it through, although it does use eval.</p> <p>Examples: </p> <pre><code>toggleableStrict("var a = 1; console.log(b) 'toggle strict'; console.log(a);")() toggleableStrict("var a = 1; console.log(a) 'toggle strict'; console.log(a);")() </code></pre> <p>These produce the following functions: </p> <pre><code>function anonymous(_a,_b ) { ;with(_a) { this.addGlobalSource((() =&gt; { "use strict"; var a = 1; console.log(b) return (_, no_result) =&gt; { try{ return eval(_) || no_result; } catch(e) { return no_result } } })()) } ;with(_b) { this.addGlobalSource((() =&gt; { ; console.log(a); return (_, no_result) =&gt; { try{ return eval(_) || no_result; } catch(e) { return no_result } } })()) } } function anonymous(_a,_b ) { ;with(_a) { this.addGlobalSource((() =&gt; { "use strict"; var a = 1; console.log(a) return (_, no_result) =&gt; { try{ return eval(_) || no_result; } catch(e) { return no_result } } })()) } ;with(_b) { this.addGlobalSource((() =&gt; { ; console.log(a); return (_, no_result) =&gt; { try{ return eval(_) || no_result; } catch(e) { return no_result } } })()) } } </code></pre> <p>Which are then wrapped in a function that is returned to the user.</p> <h2>Code:</h2> <pre><code>function toggleableStrict(code, startstrict = true) { const globalThis = (0, eval)('this') const deburr = function() { const b = function(a) { return (b) =&gt; null == a ? void 0 : a[b] }({ "\u00c0": "A", "\u00c1": "A", "\u00c2": "A", "\u00c3": "A", "\u00c4": "A", "\u00c5": "A", "\u00e0": "a", "\u00e1": "a", "\u00e2": "a", "\u00e3": "a", "\u00e4": "a", "\u00e5": "a", "\u00c7": "C", "\u00e7": "c", "\u00d0": "D", "\u00f0": "d", "\u00c8": "E", "\u00c9": "E", "\u00ca": "E", "\u00cb": "E", "\u00e8": "e", "\u00e9": "e", "\u00ea": "e", "\u00eb": "e", "\u00cc": "I", "\u00cd": "I", "\u00ce": "I", "\u00cf": "I", "\u00ec": "i", "\u00ed": "i", "\u00ee": "i", "\u00ef": "i", "\u00d1": "N", "\u00f1": "n", "\u00d2": "O", "\u00d3": "O", "\u00d4": "O", "\u00d5": "O", "\u00d6": "O", "\u00d8": "O", "\u00f2": "o", "\u00f3": "o", "\u00f4": "o", "\u00f5": "o", "\u00f6": "o", "\u00f8": "o", "\u00d9": "U", "\u00da": "U", "\u00db": "U", "\u00dc": "U", "\u00f9": "u", "\u00fa": "u", "\u00fb": "u", "\u00fc": "u", "\u00dd": "Y", "\u00fd": "y", "\u00ff": "y", "\u00c6": "Ae", "\u00e6": "ae", "\u00de": "Th", "\u00fe": "th", "\u00df": "ss", "\u0100": "A", "\u0102": "A", "\u0104": "A", "\u0101": "a", "\u0103": "a", "\u0105": "a", "\u0106": "C", "\u0108": "C", "\u010a": "C", "\u010c": "C", "\u0107": "c", "\u0109": "c", "\u010b": "c", "\u010d": "c", "\u010e": "D", "\u0110": "D", "\u010f": "d", "\u0111": "d", "\u0112": "E", "\u0114": "E", "\u0116": "E", "\u0118": "E", "\u011a": "E", "\u0113": "e", "\u0115": "e", "\u0117": "e", "\u0119": "e", "\u011b": "e", "\u011c": "G", "\u011e": "G", "\u0120": "G", "\u0122": "G", "\u011d": "g", "\u011f": "g", "\u0121": "g", "\u0123": "g", "\u0124": "H", "\u0126": "H", "\u0125": "h", "\u0127": "h", "\u0128": "I", "\u012a": "I", "\u012c": "I", "\u012e": "I", "\u0130": "I", "\u0129": "i", "\u012b": "i", "\u012d": "i", "\u012f": "i", "\u0131": "i", "\u0134": "J", "\u0135": "j", "\u0136": "K", "\u0137": "k", "\u0138": "k", "\u0139": "L", "\u013b": "L", "\u013d": "L", "\u013f": "L", "\u0141": "L", "\u013a": "l", "\u013c": "l", "\u013e": "l", "\u0140": "l", "\u0142": "l", "\u0143": "N", "\u0145": "N", "\u0147": "N", "\u014a": "N", "\u0144": "n", "\u0146": "n", "\u0148": "n", "\u014b": "n", "\u014c": "O", "\u014e": "O", "\u0150": "O", "\u014d": "o", "\u014f": "o", "\u0151": "o", "\u0154": "R", "\u0156": "R", "\u0158": "R", "\u0155": "r", "\u0157": "r", "\u0159": "r", "\u015a": "S", "\u015c": "S", "\u015e": "S", "\u0160": "S", "\u015b": "s", "\u015d": "s", "\u015f": "s", "\u0161": "s", "\u0162": "T", "\u0164": "T", "\u0166": "T", "\u0163": "t", "\u0165": "t", "\u0167": "t", "\u0168": "U", "\u016a": "U", "\u016c": "U", "\u016e": "U", "\u0170": "U", "\u0172": "U", "\u0169": "u", "\u016b": "u", "\u016d": "u", "\u016f": "u", "\u0171": "u", "\u0173": "u", "\u0174": "W", "\u0175": "w", "\u0176": "Y", "\u0177": "y", "\u0178": "Y", "\u0179": "Z", "\u017b": "Z", "\u017d": "Z", "\u017a": "z", "\u017c": "z", "\u017e": "z", "\u0132": "IJ", "\u0133": "ij", "\u0152": "Oe", "\u0153": "oe", "\u0149": "'n", "\u017f": "s" }), c = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g, d = /[\u0300-\u036f\ufe20-\ufe2f\u20d0-\u20ff]/g; return function(a) { return a &amp;&amp; a.replace(c, b).replace(d, "") } }(); function createProxyGlobalAndUpdater(global, strict, sources) { strict = Boolean(strict) let allowed = null; let no_result = Symbol("no result"); let proxy = Proxy.revocable(global, { get: function(target, property, receiver) { if (property == "this") { return 1; } else if ((property == '_a' || property == '_b') &amp;&amp; arguments.callee.caller == allowed) { return proxy; } else if (property == 'addGlobalSource' &amp;&amp; arguments.callee.caller == allowed) { return (source) =&gt; { sources.push(source.bind(global)); } } return target[property] || globalThis[property] || (deburr(String(property)).replace(/[_a-z][_a-z0-9]*/i, "") == "" ? (sources.map((source) =&gt; source(property)).filter(a =&gt; typeof a != "undefined")[0]) : undefined) }, set: (target, property, value) =&gt; { return target[property] = value; }, has: (target, property, receiver) =&gt; { return !strict || property in target || ((property == '_a' || property == '_b')) || ((deburr(String(property)).replace(/[_a-z][_a-z0-9]*/i, "") == "" &amp;&amp; arguments.callee.caller == allowed ? (sources.map((source) =&gt; source(property, no_result)).filter(a =&gt; typeof a != "undefined")[0]) : undefined) != undefined) }, getOwnPropertyDescriptor: (target, property) =&gt; { return Object.getOwnPropertyDescriptor(target, property) } }) return [proxy.proxy, (a) =&gt; { allowed = a }, proxy.revoke]; } let chunks = code.split(/('toggle strict'|"toggle strict")/).filter((item) =&gt; { return !/('toggle strict'|"toggle strict")/.test(item) }); for (var i = 0; i &lt; chunks.length; i++) { if (i % 2 == 0) { chunks[i] = ` ;with(_a) { this.addGlobalSource((() =&gt; { "use strict"; ${chunks[i]} return (_, no_result) =&gt; { try{ return eval(_) || no_result; } catch(e) { return no_result } } })()) }` } else { chunks[i] = ` ;with(_b) { this.addGlobalSource((() =&gt; { ${chunks[i]} return (_, no_result) =&gt; { try{ return eval(_) || no_result; } catch(e) { return no_result } } })()) }` } } let func = Function("_a", "_b", chunks.join('')) let scope_evals = []; let sources = []; let [firstProxy, firstUpdate] = createProxyGlobalAndUpdater(this, true, sources); let [secondProxy, secondUpdate] = createProxyGlobalAndUpdater(this, false, sources) firstUpdate(func); secondUpdate(func); let args = [firstProxy, secondProxy]; let togglestrict = { ['toggle-strict']() { func.bind(firstProxy)(...args, ...arguments) } } ["toggle-strict"]; Object.defineProperty(togglestrict, "setScopeWithEval", { value: function setScopeWithEval(func) { scope_evals.push(func) } }) Object.defineProperty(togglestrict, "toString", { value: function toString() { return `function ${this.name}() { [shim code] }` } }) Object.defineProperty(togglestrict.toString, "toString", { value: togglestrict.toString }) return togglestrict; } </code></pre> <p><sub>Credits to Lodash for the deburr function</sub></p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T14:49:40.987", "Id": "410046", "Score": "0", "body": "if it is throwing then it belongs on stackoverflow, not code review. that said, the fact that this contains obfuscated code and is completely unreadable means i would never use this. why would you want to toggle strict mode anyway..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T14:50:23.980", "Id": "410047", "Score": "1", "body": "@iwrestledabearonce It's throwing because you're running code that would throw anyhow... if you try `console.log(b)` without `b` defined, it **will** throw in strict mode." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T14:53:37.293", "Id": "410048", "Score": "1", "body": "And it's not obfuscated, that's the implementation of deburr" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:10:36.483", "Id": "410069", "Score": "0", "body": "Where is `globalThis` defined? What is the purpose of the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:11:55.533", "Id": "410070", "Score": "0", "body": "globalThis is the... aww that's probably a browser thing. Might not be in node. It's the global this, or in the case of browsers, the window. Yeah, it's not in node." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:20:54.547", "Id": "410072", "Score": "0", "body": "@FreezePhoenix Substituted `this` for `globalThis` at `return target[property] || this[property] || ..` executed `toggleableStrict(\"var a = 1; 'toggle strict'; console.log(a); console.log(b)\")()` at `console`, result at Mozilla is `ReferenceError: b is not defined`. What is the purpose of the function? What does the code attempt to solve?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:21:26.780", "Id": "410073", "Score": "0", "body": "@guest271314 Do you know what strict mode is?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:22:32.590", "Id": "410075", "Score": "0", "body": "@FreezePhoenix Yes. Though what is the ultimate purpose of the function? To insert or remove `'use strict'` into or from a function body?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:30:09.123", "Id": "410077", "Score": "0", "body": "The point of the function is that you can turn on and off strict mode. The point is, there are benifits to both." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:33:04.540", "Id": "410078", "Score": "0", "body": "Ok. I'll admit there was a bug with it erroring there. However: `toggleableStrict(\"var a = 1; console.log(b) 'toggle strict'; console.log(a);\")()` this should error." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:34:16.003", "Id": "410079", "Score": "0", "body": "Cannot the function be converted to a string and the string `'use strict'` can be inserted into or removed from the function body using `RegExp`? Or does the function perform any tasks other than inserting and removing the string `'use strict'` from a given function body?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:37:14.250", "Id": "410081", "Score": "0", "body": "Ok. Simply adding and removing it does not work, it only pays attention to it if it is the first expression in a scope. Also, in vanilla, you can't turn on and off strict mode. The point of this, is that it creates scope proxies to mimic (and enhance) strict and loose modes of JS." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:44:11.523", "Id": "410082", "Score": "1", "body": "Yes, `'use strict'` can be inserted or removed from the function body using `String` and `RegExp` methods, given the current implementation uses string methods anyway? At first glance the code appears to be unnecessarily verbose. `new Function` could probably be substituted for `eval()` usage. Can you include test cases for the prospective functionality of the function at the question? Utilizing block scope https://stackoverflow.com/a/45260422/ or `try..catch..finally` could possibly be substituted for the current implementation, given the purpose of the function?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:50:27.557", "Id": "410083", "Score": "0", "body": "Even if you insert or remove it, you cannot toggle it while in the middle of execution. That is what this allows" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:57:52.490", "Id": "410085", "Score": "0", "body": "What do you mean by \"in the middle of execution\"? The function is altered before execution, correct?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:59:32.840", "Id": "410086", "Score": "0", "body": "No... it is not. And I just tested, block scope will not work. It toggles strict mode in the middle of execution, meaning that you exit strict mode, which you would not normally be able to do." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T18:06:10.577", "Id": "410087", "Score": "0", "body": "@FreezePhoenix Not gathering the purpose of the function at the question. Yes, block scope allows separate scopes for separate functionality. Am still not sure what is meant by \"in the middle of execution\". The code at the OP uses string input, where `'use strict';` can be inserted into or removed from the string version of code, including insertion of block scope within the input string at any place within the string. That simplifies the necessary code to `RegExp.prototype.replace()`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T18:07:21.270", "Id": "410088", "Score": "0", "body": "Yes, but the thing is, in vanilla js, either the whole function body is strict, or the whole thing isn't. This allows you to have sections of it that are strict, and sections that are not" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T18:08:29.283", "Id": "410089", "Score": "0", "body": "@FreezePhoenix What do you mean by \"vanilla js\"? The code at the question is ES6, where block scope can be used or not used at any portion of the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T18:09:14.617", "Id": "410090", "Score": "2", "body": "`{'use strict';console.log(b = 1)}` according to what you're saying, this code to the left should error. Thing is, it doesn't. Because it never enters strict mode. Because block scope is not considered a valid area to enter strict mode." } ]
[ { "body": "<h1>But why?</h1>\n\n<p>This is a clever trick but is terrible code. </p>\n\n<p>Bad naming, poor use of appropriate declaration types <code>const</code>, <code>var</code> and <code>let</code>, full of redundant code, full of bugs, inappropriate use of logic operators (Strict equality rather than <code>==</code>) and so long winded it looks like it's deliberately obfuscated.</p>\n\n<h2>Redundant</h2>\n\n<ul>\n<li><code>strict = Boolean(strict)</code> this is in a function only called from within. You only ever pass a boolean.</li>\n<li>You create a <code>revocable</code> proxy on the object <code>global</code> at the end of the function you return the <code>revoke</code> function as the third item in an array. Yet the calling function ignores the revoke function, not even keeping a reference. The function is thus never used. So why use a revocable proxy in the first place, and why return it when its not used.</li>\n<li>Each time you call <code>deburr</code> you create a new string, eg <code>deburr(String(property))</code> If its that important why are you not doing it within the function <code>deburr</code></li>\n<li>No reason to use the name <code>toggle-strict</code>. It forces you to use bracket notation for no reason. You could have used <code>toggleStrict</code></li>\n<li>Use <code>Object.defineProperties(</code> when creating several properties, rather than many lines of <code>defineProperty</code></li>\n<li>Redefining a function name is redundant. <code>Object.definePropertie(togglestrict, \"setScopeWithEval\", { value: function setScopeWithEval(func) {</code> the second function name is not needed as yoiu do not use it at any point.</li>\n<li>I do not understand why you assign <code>togglestrict.toString</code> to itself??? You effectively do <code>togglestrict.toString.toString = togglestrict.toString;</code> Is here a reason??</li>\n<li>The whole last section is just so strange, I can not workout the reasoning. It can be replaced with just a few lines. See Example A</li>\n<li>The loop iterating the chunks is duplicating the string, when only the global name and the directive \"use strict\" change. See Example B</li>\n</ul>\n\n<h2>Bugs.</h2>\n\n<ul>\n<li>This code will not work in a module as modules are automatically in strict mode.</li>\n<li>This code will not work within a function, or javascript that is in strict mode as <code>with</code> is prohibited in strict mode.</li>\n<li>The <code>set</code> handler on the global proxy needs to return <code>true</code> or will throw an error in strict mode. eg <code>toggleableStrict(\"b = 2;'toggle strict';b=false;'toggle strict';b=false;\")</code></li>\n<li>When not in strict mode the <code>set</code> handler incorrectly sets false to <code>undefined</code> <code>toggleableStrict(\"b = 2;'toggle strict';b=false;console.log('b: '+b)\")()</code> output <code>b: undefined</code></li>\n<li>Throws syntax error for <code>toggleableStrict(\"(()=&gt;{'toggle strict';console.log('hi there');})()\");</code></li>\n</ul>\n\n<p>There are plenty more bugs, but you get the picture. I get the feeling you have not done any form of rigorous testing on this code.</p>\n\n<h2>Problems.</h2>\n\n<ol>\n<li><p>Testing the code I found it hard to know if I was in strict mode or not. As it is toggled, it easy to lose track of just how many toggles had been performed. </p></li>\n<li><p>Not for development. It is next to useless as a development tool as you lose the ability to trace errors effectively. I can see no reason why someone would use this in release code.</p></li>\n<li><p>Unmanageable. This is so poorly written that it was next to impossible to work out what it was doing. In fact I gave up on what <code>deburr</code> does, and after seeing the proxy was a mess I did not bother going further into that. I am sure there are many more issues associated.</p></li>\n</ol>\n\n<h2>Examples</h2>\n\n<p>Examples as referenced above</p>\n\n<h3>Example A</h3>\n\n<pre><code>// you had...\nlet togglestrict = {\n ['toggle-strict']() {\n func.bind(firstProxy)(...args, ...arguments)\n }\n} [\"toggle-strict\"];\nObject.defineProperty(togglestrict, \"setScopeWithEval\", {\n value: function setScopeWithEval(func) {\n scope_evals.push(func)\n }\n})\nObject.defineProperty(togglestrict, \"toString\", {\n value: function toString() { return `function ${this.name}() { [shim code] }` }\n})\nObject.defineProperty(togglestrict.toString, \"toString\", {\n value: togglestrict.toString\n})\nreturn togglestrict;\n\n//======================================================================================\n// Can be writen as\nreturn Object.defineProperties(() =&gt; { func.bind(firstProxy)(...args, ...arguments) }, {\n setScopeWithEval : {value : (func) =&gt; {scope_evals.push(func)}},\n toString : {value : () =&gt; `function toggle-strict() { [shim code] }`},\n}); \n</code></pre>\n\n<h3>Example B</h3>\n\n<pre><code>// you had\nfor (var i = 0; i &lt; chunks.length; i++) {\n if (i % 2 == 0) {\n chunks[i] = `\n ;with(_a) {\n this.addGlobalSource((() =&gt; {\n \"use strict\";\n ${chunks[i]}\n return (_, no_result) =&gt; {\n try{\n return eval(_) || no_result;\n } catch(e) {\n return no_result\n }\n }\n })())\n }`\n } else {\n chunks[i] = `\n ;with(_b) {\n this.addGlobalSource((() =&gt; {\n ${chunks[i]}\n return (_, no_result) =&gt; {\n try{\n return eval(_) || no_result;\n } catch(e) {\n return no_result\n }\n }\n })())\n }`\n }\n}\n\n//======================================================================================\n// can be\nfor (let i = 0; i &lt; chunks.length; i++) {\n chunks[i] = `\n ;with(_${i % 2 ? \"b\" : \"a\"}) {\n this.addGlobalSource((() =&gt; {\n ${i % 2 ? \"\" : \"'use strict';\"}\n ${chunks[i]}\n return (_, no_result) =&gt; {\n try{\n return eval(_) || no_result;\n } catch(e) {\n return no_result\n }\n }\n })())\n }`;\n\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:10:15.053", "Id": "410237", "Score": "0", "body": "deburr is the same function as `_.deburr`. And yes, just last night I thought of making some global that would make it possible to determine whether or not it is in strict mode... Also, the point is that the code is run outside of strict mode... so it shouldn't be subject to the restrictions of strict mode itself." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T17:24:21.820", "Id": "410272", "Score": "1", "body": "@FreezePhoenix Strict mode is unavoidable in modules. Also the toggle is unusable as it adds ambiguity to the scope. Consider `toggleableStrict(`var b=2; 'toggle strict'; log(b);`)();` It throws `b as undefined`, more dangerously `b` may be in a higher scope, thus after the toggle you access the outer `b` not the one in the same apparent scope. However the major problem is block continuity eg `{'toggle-strict'}` throws in your function and never runs the code. Toggle is limited to top level scope only. Much easier to just use the old fashioned approach `(function(){\"use strict\"; log(b)})()`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T17:49:33.047", "Id": "410277", "Score": "0", "body": "Actually, that first one shouldn't log b as undefined... it accesses it as 2. And yeah, I'll have to figure out how to change the proxy. It shouldn't use 2 proxies, just 1 proxy with a flag, indicating strict or not, and exposing a function that toggles it. This would also eliminate the need to use regex, and fix the scope continuity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T17:57:00.907", "Id": "410279", "Score": "0", "body": "I'd also have to expose an immuteable value that says whether or not it is strict." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T20:02:52.133", "Id": "410292", "Score": "0", "body": "@FreezePhoenix My bad, was meant to be `let b=2; \"toggle strict\"; log(b); \"toggle strict\"; log(b)` throws on the second log" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:37:22.453", "Id": "410773", "Score": "0", "body": "Are you quite sure modules are by default in strict mode? It seemed to work for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:25:27.820", "Id": "410791", "Score": "0", "body": "@FreezePhoenix Re modules and strict mode acording to MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:04:54.423", "Id": "410827", "Score": "0", "body": "... I wonder if that's circumventable using `eval`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T18:51:02.160", "Id": "410843", "Score": "0", "body": "@FreezePhoenix I should hope not. Strict mode will one day be all there is. It fixes a major flaw in the language. Modules are the path to removing the flaw without breaking a zillion web pages. Nobody should ever write JS that is not strict (even without the directive) and modules will enforce that rule for the betterment of the language." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T01:45:47.087", "Id": "410890", "Score": "0", "body": "Yeah, I know. I just don't know why `with` is disallowed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T02:13:13.357", "Id": "410894", "Score": "0", "body": "@FreezePhoenix The argument against `with` is weak and is based on a negative assumption it will cause confusion (AKA inept coders). The reality is that the global scope is run within a `with` block eg `with(window) { /*all JS code*/ }` so we use all the time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T13:40:03.003", "Id": "410975", "Score": "0", "body": "Huh... `'use strict';(0, eval)('with({}) {1}')` gives `1`... implying that you can evade strict mode with eval." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T08:43:58.147", "Id": "212124", "ParentId": "212071", "Score": "3" } } ]
{ "AcceptedAnswerId": "212124", "CommentCount": "20", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T14:37:19.317", "Id": "212071", "Score": "2", "Tags": [ "javascript", "ecmascript-6" ], "Title": "Toggling Strict mode in JS" }
212071
<p>I have Python code to copy the Files locally on the Server from one Directory to another using rsync and subprocess module, this is just in continuation of the post from <a href="https://stackoverflow.com/questions/54197194/how-to-copy-only-the-changed-file-contents-on-the-already-existed-destination-fi">this post</a> where I tried to get various insight but opted to use below code finally.</p> <p>Please advise if this further can be improved or optimized in pythonic way and help to provide your esteemed reviews please.</p> <pre><code>#!/bin/python3 import os import glob import datetime import subprocess def Copy_Logs(): # Variable Declaration to get the month and Curr_date_month Info_month = datetime.datetime.now().strftime("%B") Curr_date_month = datetime.datetime.now().strftime("%b_%d_%y") Sourcedir = "/data1/logs" Destdir = "/data2/logs/" ###### End of your variable section ####################### # The result of the below glob _is_ a full path for filename in glob.glob("{2}/{0}/{1}/*.txt".format(Info_month, Curr_date_month, Sourcedir)): if os.path.getsize(filename) &gt; 0: if not os.path.exists(Destdir + os.path.basename(filename)): subprocess.call(['rsync', '-avz', '--min-size=1', filename, Destdir ]) if __name__ == '__main__': Copy_Logs() </code></pre>
[]
[ { "body": "<p>You're calling <code>now()</code> twice - what will happen if the month changes between those two calls? </p>\n\n<p>Your code skips all files that exist, even though your linked question indicates that you need to update changed files. </p>\n\n<p>Your code checks that file is non-empty, but rsync is already doing this for you with <code>--min-size=1</code>.</p>\n\n<p>More generally, before you code up file-sync logic, it's best to read the rsync man page and see if your problem is already solved. Syncing files is a task full of corner cases and gotchas; life is too short for you to find them all. Just let rsync take care of it, whenever possible.</p>\n\n<p>The code below will update changed files while skipping unchanged files (as in your problem description). If you want to copy only new, non-existing files (as in your posted code), add <code>--ignore-existing</code> to the rsync options.</p>\n\n<pre><code>import datetime\nimport subprocess\n\ndef Copy_Logs():\n Sourcedir = datetime.datetime.now().strftime(\"/data1/logs/%B/%b_%d_%y/\")\n Destdir = \"/data2/logs/\"\n subprocess.call(['rsync', '-avz', '--min-size=1', '--include=*.txt', '--exclude=*', Sourcedir, Destdir ])\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T01:05:51.093", "Id": "410168", "Score": "3", "body": "This is a good answer! I'd recommend using PEP8 names though (`copy_logs`, `source_dir`, and `dest_dir`). It may also be prudent to note that you may be able to achieve this with a bash oneliner like `rsync -avz --min-size=1 --include=*.txt --exclude=* /data/logs/$(date \"+%B/%b_%d_%y/\") /data2/logs/`. Don't pull out Python when you don't need to!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T01:27:11.803", "Id": "410171", "Score": "2", "body": "If this isn't part of some larger Python project, you're absolutely right and there's no reason to use more than rsync and a shell. I will point out that your one-liner should quote the wildcards (yes, they'll almost never get interpolated by the shell as-is, but will it ever be baffling on the day that you have a file named `--exclude=`!) and doesn't need to quote the date format: `rsync -avz --min-size=1 --include=\"*.txt\" --exclude=\"*\" /data1/logs/$(date +%B/%b_%d_%y/) /data2/logs/`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T03:47:01.167", "Id": "410174", "Score": "0", "body": "@OhMyGoodness, thanks for giving the nice and precise details, However, current code I have do not skips all the files it only skips the empty files as I test the code by running it on my data but its current not to use own method while rsync is taking care that already." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T03:48:32.937", "Id": "410175", "Score": "0", "body": "@BaileyParker, many thanks for a suggesting a nice one liner i'll keep that handy though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T04:01:08.227", "Id": "410176", "Score": "0", "body": "@krock1516 I don't understand how this doesn't skip existing files. What does `if not os.path.exists(Destdir + os.path.basename(filename)):` do? It tests that the file does not exist..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T04:12:16.570", "Id": "410178", "Score": "0", "body": "@OhMyGoodness, my bad yes it skips existing files if its already exists on the Detdir However if there is new data on the source then rsync will take cares ,now I know that its not needed as you said." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T22:22:48.510", "Id": "212104", "ParentId": "212074", "Score": "6" } } ]
{ "AcceptedAnswerId": "212104", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:13:30.337", "Id": "212074", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "Copying files locally with rsync and subprocess" }
212074
<p>This is a code for an android thread. This is a tcp server and gets data from socket, maps it to an object and sends that object back to the main service. If there is anything I'm doing wrong or if something can be done better, I would really appreciate comments.</p> <pre><code>public class SocketManager extends Thread { Handler mHandlerThread; private final int MAX_MESSAGE_LENGTH = 2048; private final int PORT = 2500; private ServerSocket serverSocket = null; private Socket socket = null; private DataInputStream in = null; private DataOutputStream out = null; private GPSFields gps; private ObjectMapper mObjectMapper; private final String APPNAME = "My App"; public SocketManager(Handler mHandlerThread) { this.mHandlerThread = mHandlerThread; } @Override public void run() { int messageLength = 0; gps = new GPSFields(); byte buffer[] = new byte[MAX_MESSAGE_LENGTH]; mObjectMapper = new ObjectMapper(); mObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); try { openSocket(); } catch(Exception e) { Log.d(APPNAME, e.toString()); } while(true) { try { if(socket.isClosed()) { openSocket(); } else { messageLength = in.readShort(); if (messageLength &gt; 0 &amp;&amp; messageLength &lt; MAX_MESSAGE_LENGTH) { in.read(buffer, 0, messageLength); gps = mObjectMapper.readValue(new String(buffer), GPSFields.class); if (gps != null) { out.write(1); Message message = new Message(); message.obj = gps; mHandlerThread.sendMessage(message); Log.d(APPNAME, "Received Latitude: " + gps.getLatitude() + " Longitude: " + gps.getLongitude()); } else { out.write(0); } } else { out.write(0); } } } catch (Exception e) { closeSocket(); Log.d(APPNAME, e.toString()); } } } private void closeSocket() { try { socket.close(); serverSocket.close(); }catch (Exception e){ Log.d(APPNAME, e.toString()); } } private void openSocket() { try { serverSocket = new ServerSocket(PORT); socket = new Socket(); socket = serverSocket.accept(); in = new DataInputStream(socket.getInputStream()); out = new DataOutputStream(socket.getOutputStream()); }catch (Exception e){ Log.d(APPNAME, e.toString()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T16:15:13.910", "Id": "410063", "Score": "1", "body": "Welcome to Code Review! The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:36:52.453", "Id": "410080", "Score": "0", "body": "What's `ObjectMapper`? Please provide more context for this code." } ]
[ { "body": "<ul>\n<li><p>When <code>messageLength</code> happens to be too large the code just loops around to the next <code>messageLength = in.readShort();</code>. However, the message body is still there, and <code>readShort</code> will pull the short from it. Chances are, it would be interpreted as a valid message length, and the stream gets irrecoverably out of sync.</p>\n\n<p>You must discard the entire message by reading it.</p></li>\n<li><p><code>DataInputStream.read()</code> hey return less bytes than requested. Yet again, the stream gets out of sync. You must read the message body in the loop, until it is consumed entirely.</p></li>\n<li><p>Closing the server socket every time a data socket fails seems drastic. There is nothing wrong with the server socket, and could be reused. It may need to be reopened only if <code>accept</code> fails.</p></li>\n<li><p>I recommend to move <code>openSocket</code> call to the exception clause:</p>\n\n<pre><code> while (True) {\n try {\n messageLength = in.readShort();\n ....\n } catch(Exception e) {\n closeSocket();\n Log.d(APPNAME, e.toString());\n openSocket();\n }\n</code></pre>\n\n<p>One nesting level down.</p></li>\n<li><p>You may want to be more precise about exceptions. It is very well possible that the exception has nothing to do with the socket (e.g. may <code>sendMessage</code> throw? was it a keyboard interrupt? <code>ObjectMapper</code> throw? something else? It is impossible to tell from the given code). In such cases different recovery is necessary, but the socket should likely remain intact.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:24:05.500", "Id": "212086", "ParentId": "212076", "Score": "0" } } ]
{ "AcceptedAnswerId": "212086", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:43:02.920", "Id": "212076", "Score": "0", "Tags": [ "java", "android", "socket" ], "Title": "Android TCP server that maps data to an object and sends it to a service" }
212076
<p>There is a web app. My first attempt to use NHL API have been reviewed <a href="https://codereview.stackexchange.com/questions/209002/command-line-nhl-skaters-stats-tool">here</a>. I'm interested in any kind of refactoring of this code. But I have some questions that I want to point at specifically.</p> <p>First of all, is this a right approach to have all this dirty work for a 'views' in a 'services.py' file? I started with just putting all of these methods in the 'views', but it gets really messy and it was obvious that I should have made views simpler.</p> <p>The more fundamental question is optimization for performance. There is a lot of loops going on just to prepare two lists for 'players' template. And then two loops(~85 and 800+items) to make tables shown. And top this with some JS scrips. Sorting, paginating, parsing, auto numbered column. So the page is REALLY slow. I couldn't see that I could make it much faster without totally changed approach. Am I right? </p> <p>I see the way to make it faster. Have a scheduler to scrape all of this stats and write it to the DB. Now I have a command to write info only to 'name' and 'nhl_id' fields of the Player model. Didn't want to depend so much on DB and tried to fetch most of the info from API directly. Because I've thought I could manage to get all of the needed stats from one endpoint. </p> <p>Individual player pages loading fast enough, but there is another problem. I couldn't find the endpoint with FW stats present (individual endpoint for a player). This also can be solved if I had all of the stats in the model (there is FW stat in the endpoint with a list of all NHL players combined) </p> <p>views.py</p> <pre><code>import requests from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from . import services from .models import Player def home(request): return render(request, 'players/home.html', {'title': 'Home'}) def about(request): return render(request, 'players/about.html', {'title': 'About'}) def players(request): context = { 'goalies': services.goalies_list(request), 'skaters': services.skaters_list(request), } return render(request, 'players/players.html', context) def search(request): if 'q' in request.GET and request.GET['q']: q = request.GET['q'] result = Player.objects.filter(name__icontains=q) result_list = result.values() for item in result_list: if services.is_favorite(request, item['nhl_id']): item['is_favorite'] = True context = { 'players': result_list, 'query': q, } return render(request, 'players/search_results.html', context) else: return HttpResponse('Please submit a search term.') def player_detail(request, slug, nhl_id): bio = services.season_stats(nhl_id) context = { 'is_favorite': services.is_favorite(request, nhl_id), 'player': services.get_player(nhl_id), 'bio': bio, 'stats': bio['stats'][0]['splits'][0]['stat'], 'total': services.career_stats(nhl_id), 'sbs_stats': services.sbs_stats(nhl_id), 'last_gms': services.gamelog(nhl_id)[:5], 'countries': services.COUNTRIES, 'team': services.TEAM_ABBR, } return render(request, 'players/player_detail.html', context) def player_gamelog(request, slug, nhl_id): context = { 'bio': services.season_stats(nhl_id), 'gamelog': services.gamelog(nhl_id), 'team': services.TEAM_ABBR, } return render(request, 'players/player_gamelog.html', context) def player_favorite(request, slug, nhl_id): player = services.get_player(nhl_id) if player.favorite.filter(id=request.user.id).exists(): player.favorite.remove(request.user) else: player.favorite.add(request.user) return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/')) def favorites(request): user = request.user favorites = user.favorite.all() context = { 'favorites': favorites, } return render(request, 'players/favorites.html', context) def teams(request): response = requests.get(services.URL_TEAMS.format('')) context = { 'teams': response.json()['teams'], } return render(request, 'players/teams.html', context) # 'Defencemen', 'Forwards', 'tab2', 'tab3' should probably be declared as a constants def team_detail(request, slug, team_id): response = requests.get(services.URL_TEAMS.format(team_id)) rost = services.roster(request, slug, team_id) context = { 'goalies': services.roster_position(request, rost, services.POSITIONS[0], slug, team_id), 'skaters': [ { 'type': 'Defencemen', 'list': services.roster_position(request, rost, services.POSITIONS[1], slug, team_id), 'table_id': 'tab6', }, { 'type': 'Forwards', 'list': services.roster_position(request, rost, services.POSITIONS[2:], slug, team_id), 'table_id': 'tab7', } ], 'team': response.json()['teams'][0], } return render(request, 'players/team_detail.html', context) </code></pre> <p>services.py</p> <pre><code>import datetime import requests from django.shortcuts import get_object_or_404 from .models import Player URL = 'http://www.nhl.com/stats/rest/{}' PL_STAT_URL_BASE = 'https://statsapi.web.nhl.com/api/v1/people/' URL_TEAMS = 'https://statsapi.web.nhl.com/api/v1/teams/{}' PL_TYPE1 = 'goalies' PL_TYPE2 = 'skaters' POSITIONS = ['G', 'D', 'C', 'LW', 'RW', 'L', 'R'] WING = 'W' NHL = 'National Hockey League' REP_TYPE1 = 'goaliesummary' REP_TYPE2 = 'skatersummary' REP_TYPE3 = 'realtime' REP_TYPE4 = 'timeonice' STAT_TYPE1 = 'statsSingleSeason' STAT_TYPE2 = 'yearByYear' STAT_TYPE3 = 'careerRegularSeason' STAT_TYPE4 = 'gameLog' COUNTRIES = { 'RUS': 'Russia', 'CAN': 'Canada', 'USA': 'USA', 'CZE': 'Czech Republic', 'CHE': 'Switzerland', 'SWE': 'Sweden', 'FIN': 'Finland', 'DEU': 'Germany', 'DNK': 'Denmark', 'AUT': 'Austria', 'LVA': 'Latvia', 'SVN': 'Slovenia', 'SVK': 'Slovakia', 'NLD': 'Netherlands', 'AUS': 'Australia', 'GBR': 'Great Britain', } TEAM_ABBR = { 1: 'NJD', 2: 'NYI', 3: 'NYR', 4: 'PHI', 5: 'PIT', 6: 'BOS', 7: 'BUF', 8: 'MTL', 9: 'OTT', 10: 'TOR', 11: '', 12: 'CAR', 13: 'FLA', 14: 'TBL', 15: 'WSH', 16: 'CHI', 17: 'DET', 18: 'NSH', 19: 'STL', 20: 'CGY', 21: 'COL', 22: 'EDM', 23: 'VAN', 24: 'ANA', 25: 'DAL', 26: 'LAK', 27: '', 28: 'SJS', 29: 'CBJ', 30: 'MIN', 52: 'WPG', 53: 'ARI', 54: 'VGK', } HEIGHT_CONVERT = { 65: "5' 5\"", 66: "5' 6\"", 67: "5' 7\"", 68: "5' 8\"", 69: "5' 9\"", 70: "5' 10\"", 71: "5' 11\"", 72: "6' 0\"", 73: "6' 1\"", 74: "6' 2\"", 75: "6' 3\"", 76: "6' 4\"", 77: "6' 5\"", 78: "6' 6\"", 79: "6' 7\"", 80: "6' 8\"", 81: "6' 9\"", 82: "6' 10\"", } def time_from_sec(time): min_, sec = divmod(time, 60) min_ = int(min_) sec = str(int(sec)).zfill(2) return f'{min_}:{sec}'.rjust(5, '0') def time_to_sec(time): min_sec = time.split(':') return int(min_sec[0])*60 + int(min_sec[1]) def players_resp(rep_type, pl_type): params = { 'isAggregate': 'false', 'reportType': 'season', 'isGame': 'false', 'reportName': rep_type, 'cayenneExp': 'gameTypeId=2 and seasonId=20182019', } return requests.get(URL.format(pl_type), params=params) def player_info_resp(st_type, nhl_id): api_end = f'?hydrate=stats(splits={st_type})' url = ''.join([PL_STAT_URL_BASE, str(nhl_id), api_end]) response = requests.get(url) response.raise_for_status() return response def init_list(request, response, list_name): user = request.user favorites = user.favorite.all() for player in response: player['playerHeight'] = HEIGHT_CONVERT[player['playerHeight']] if player['playerPositionCode'] in POSITIONS[5:]: player['playerPositionCode'] += WING if player['playerDraftOverallPickNo'] is None: player['playerDraftOverallPickNo'] = '—' player['playerDraftYear'] = '—' if len(player['playerTeamsPlayedFor']) &gt; 3: player['playerTeamsPlayedFor'] = ( player['playerTeamsPlayedFor'].split(',')[-1] ) for item in favorites: if player['playerName'] == item.name: player['is_favorite'] = True list_name.append(player) return list_name def get_player(nhl_id): return get_object_or_404(Player, nhl_id=nhl_id) def goalies_list(request): goalies = [] goalies_summ = players_resp(REP_TYPE1, PL_TYPE1).json()['data'] return init_list(request, goalies_summ, goalies) def skaters_list(request): skaters = [] summary = players_resp(REP_TYPE2, PL_TYPE2).json()['data'] realtime = players_resp(REP_TYPE3, PL_TYPE2).json()['data'] toi = players_resp(REP_TYPE4, PL_TYPE2).json()['data'] init_list(request, summary, skaters) for count, player in enumerate(realtime): skaters[count]['hits'] = player['hits'] skaters[count]['blockedShots'] = player['blockedShots'] skaters[count]['faceoffsWon'] = player['faceoffsWon'] for count, player in enumerate(toi): skaters[count]['timeOnIcePerGame'] = ( time_from_sec(player['timeOnIcePerGame']) ) skaters[count]['ppTimeOnIcePerGame'] = ( time_from_sec(player['ppTimeOnIcePerGame']) ) skaters[count]['shTimeOnIcePerGame'] = ( time_from_sec(player['shTimeOnIcePerGame']) ) return skaters def gamelog(nhl_id): log = [] response = player_info_resp(STAT_TYPE4, nhl_id) log_json = response.json()['people'][0]['stats'][0]['splits'] for game in log_json: game['date'] = date_convert(game['date']) log.append(game) return log def date_convert(date): datetime_obj = datetime.datetime.strptime(date, '%Y-%m-%d') return datetime_obj.strftime('%b %e') def is_favorite(request, nhl_id): player = get_player(nhl_id) favor = False if player.favorite.filter(id=request.user.id).exists(): favor = True return favor def season_stats(nhl_id): response = player_info_resp(STAT_TYPE1, nhl_id) return response.json()['people'][0] def career_stats(nhl_id): response = player_info_resp(STAT_TYPE3, nhl_id) return response.json()['people'][0]['stats'][0]['splits'][0]['stat'] def sbs_stats(nhl_id): seasons = [] player = player_info_resp(STAT_TYPE2, nhl_id).json() seasons_json = player['people'][0]['stats'][0]['splits'] position = player['people'][0]['primaryPosition']['code'] for season in seasons_json: if season['league']['name'] == NHL: season['season'] = format_season(season['season']) # Getting an average TOI from total if position in POSITIONS[1:]: season['stat']['timeOnIce'] = ( time_from_sec(time_to_sec(season['stat']['timeOnIce']) /season['stat']['games']) ) season['stat']['powerPlayTimeOnIce'] = ( time_from_sec(time_to_sec(season['stat']['powerPlayTimeOnIce']) /season['stat']['games']) ) season['stat']['shortHandedTimeOnIce'] = ( time_from_sec(time_to_sec(season['stat']['shortHandedTimeOnIce']) /season['stat']['games']) ) seasons.append(season) return seasons def format_season(season): return f'{season[:4]}-{season[6:]}' def roster(request, slug, team_id): players = goalies_list(request) + skaters_list(request) team_roster = [player for player in players if player['playerTeamsPlayedFor'] == TEAM_ABBR[team_id]] return team_roster def roster_position(request, rost, pos, slug, team_id): return [player for player in rost if player['playerPositionCode'] in pos] </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-21T11:08:24.873", "Id": "413835", "Score": "0", "body": "I'm kinda surprised that there are no reviews of the code, I like Bailey's answer though." } ]
[ { "body": "<p>At a high level you definitely have the right idea about pulling things out of your views. In MVC, we generally keep business logic out of views. That includes things like calculating player stats and information, so this definitely seems like a good choice.</p>\n\n<p>I can fairly confidently say you correctly identify the actual speed issue (but you dismiss it). Speaking very generally, unless you're doing something super crazy, a couple of loops with a few hundred items aren't going to cause much of a problem. This can only truly be confirmed by profiling, but if there are pages that require API requests to 800 different URLs, then that's almost surely your bottleneck.</p>\n\n<p>If you wanted to confirm this, you could place a proxy (that ignores <code>Cache-Control</code>/<code>Expires</code> as the API endpoints may not properly set it--see <a href=\"http://www.squid-cache.org/\" rel=\"nofollow noreferrer\">Squid</a>) between the NHL site and your app. This will make those 800+ requests MUCH faster. Your site should speed up significantly. As a quick temporary solution, this is actually pretty decent as you'll likely get a decent speed boost for free. You'll probably want to configure Squid to cache responses for a few hours.</p>\n\n<p>Another easier way to achieve this would be to decorate your <code>services</code> functions with a caching decorator. This isn't as good as the proxy, because unless it persists to disk, your cache won't survive rebooting the server, but this doesn't require learning how to setup Squid.</p>\n\n<p>In the long run, I'd recommend running the functions in <code>services</code> periodically in a separate worker process which saves results to a DB. Then, in your webapp, query your own DB for the results you need. Why?</p>\n\n<p>For one, the NHL site probably doesn't appreciate you sending 800-some requests (this is a guess from your numbers, I didn't read the code too carefully) EVERY time someone visits a page on your site. Depending on how much traffic you get, it could cause them to block or throttle you. They may even impose global rate limits. Part of being a good API consumer is caching things so you don't have to tax the API.</p>\n\n<p>Secondly, your webserver can only handle so many TCP connections. IIRC <code>requests</code> does keepalive and connection pooling, but your web server runs across multiple processes these might not be shared. In any event, any outbound requests beyond those absolutely necessary (which, as I argue above, is none) will decrease your capacity to handle incoming traffic.</p>\n\n<p>Third, if you want to do any analytics on your end that does take a non-negligible amount of time (say, some sort of fancy predictions using regressions or other models), doing it outside incoming web requests means your site won't become any slower if you choose to add something like this.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T07:06:57.380", "Id": "410190", "Score": "0", "body": "You said > I'd recommend running the functions in services periodically in a separate worker process which saves results to a DB" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T07:10:30.933", "Id": "410191", "Score": "0", "body": "I should probably run these functions from the script in the command folder? I currently have one. It looks like this: https://yadi.sk/i/H6XcMcqkJaGLdQ" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T07:14:50.940", "Id": "410192", "Score": "0", "body": "About profiling. I started to dig into this yesterday. I found the interesting answer by @meshy here - https://stackoverflow.com/questions/17751163/django-display-time-it-took-to-load-a-page-on-every-page" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T07:16:31.493", "Id": "410193", "Score": "0", "body": "https://bitbucket.org/brodie/geordi - But Geordi did not work for me, I should probably find another way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:09:20.380", "Id": "410215", "Score": "0", "body": "According to django-silk, players views takes 3500-4200ms to load. player-detail takes 1200-2000ms." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T01:00:51.310", "Id": "212109", "ParentId": "212078", "Score": "3" } } ]
{ "AcceptedAnswerId": "212109", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T15:59:32.613", "Id": "212078", "Score": "5", "Tags": [ "python", "beginner", "python-3.x", "api", "django" ], "Title": "NHL Stats web app" }
212078
<p>The following function receives a vector of positive integers and list of brackets. The function returns a data frame with a logical vector for each bracket indicating whether a given element of a vector falls within that bracket.</p> <h1>Background</h1> <h2>Received arguments</h2> <ul> <li><p>Vector <code>x</code> consisting of unique positive integers, usually corresponding to:</p> <pre><code>1:6000 c(1:100, 753:4000) </code></pre></li> <li><p>List of <code>bracket</code>s, for instance:</p> <pre><code>list(c(1, 325), c(1, 651), c(1, 976), c(1, 1301), c(1, 1626), c(1, 1952)) </code></pre></li> </ul> <h2>Behaviour</h2> <ul> <li>For each of the brackets, the function creates a column <code>int_brakcet_value</code> consisting of <code>TRUE</code> / <code>FALSE</code> values indicating whether <code>i</code> element of vector falls within the designed bracket</li> </ul> <h1>Function</h1> <pre><code>assign_interval &lt;- function(x, brackets) { do.call("cbind", lapply( X = brackets, FUN = function(bracket) { findInterval(x = x, vec = bracket, rightmost.closed = TRUE) } )) -&gt; int_dta # Create friendly names int_nms &lt;- lapply( X = brackets, FUN = function(brc) { paste0("int_", paste0(brc, collapse = "_")) } ) # Set friendly names int_dta &lt;- setNames(object = as.data.frame(int_dta), nm = unlist(int_nms)) # Replace findInterval outputs with T/F apply(X = int_dta, MARGIN = 2, FUN = function(col) { ifelse(col == 1, TRUE, FALSE) }) -&gt; int_dta dta_res &lt;- data.frame(int_dta) rownames(dta_res) &lt;- x return(dta_res) } </code></pre> <h1>Tests</h1> <pre><code>x &lt;- 1:6505 res &lt;- assign_interval(x = x, brackets = list(c(1, 325), c(1, 651), c(1, 976), c(1, 1301), c(1, 1626), c(1, 1952))) </code></pre>
[]
[ { "body": "<p>Maybe it is overkill to use <code>findInterval</code> when your brackets only have two values (a min and a max). I would suggest this much shorter function based on two <code>outer</code> calls with <code>&gt;=</code> and <code>&lt;=</code>. As you probably know, <code>outer</code> is efficient in that it can take advantage of vectorized functions, so here only a single call to <code>&lt;=</code> and <code>&gt;=</code> will be made:</p>\n\n<pre><code>assign_interval2 &lt;- function(x, brackets) {\n stopifnot(all(lengths(brackets) == 2L))\n lower_bounds &lt;- sapply(brackets, head, 1)\n upper_bounds &lt;- sapply(brackets, tail, 1)\n outer(x, lower_bounds, \"&gt;=\") &amp; outer(x, upper_bounds, \"&lt;=\")\n}\n</code></pre>\n\n<p>The results are the same and benchmarks suggest this is also a bit faster:</p>\n\n<pre><code>x &lt;- 1:6505\nbrackets &lt;- list(c(1, 325), c(1, 651), c(1, 976),\n c(1, 1301), c(1, 1626), c(1, 1952))\n\nres1 &lt;- assign_interval(x = x, brackets = brackets)\nres2 &lt;- assign_interval2(x = x, brackets = brackets)\nany(res1 != res2)\n# [1] FALSE\n\nlibrary(microbenchmark)\nmicrobenchmark(\n assign_interval(x = x, brackets = brackets),\n assign_interval2(x = x, brackets = brackets)\n)\n\n# Unit: milliseconds\n# expr min lq mean\n# assign_interval(x = x, brackets = brackets) 7.851050 11.278404 15.300305\n# assign_interval2(x = x, brackets = brackets) 1.373723 1.628319 3.134719\n# median uq max neval\n# 13.099052 14.4824 152.33409 100\n# 2.192194 3.2971 13.70505 100\n</code></pre>\n\n<hr>\n\n<p>That being said, let's review your code and see if we can make small suggestions to improve your code while staying true to your implementation. </p>\n\n<p>Instead of the <code>do.call(\"cbind\", lapply(...))</code>, you could use <code>sapply</code>. The <code>s</code> in <code>sapply</code> is meant to do that exactly that: <code>s</code>implify the output by binding the pieces together. It comes at a very small (time) performance cost which should not affect you much here considering you do not have many <code>brackets</code>. I also notice that you are using the <code>-&gt;</code> assignment operator which is not often used by R programmers hence not recommended.</p>\n\n<pre><code>dat &lt;- sapply(brackets, findInterval, x = x, rightmost.closed = TRUE)\n</code></pre>\n\n<p>For the friendly names, I think the following would read better:</p>\n\n<pre><code>lower_bounds &lt;- sapply(brackets, head, 1)\nupper_bounds &lt;- sapply(brackets, tail, 1)\nfriendly_names &lt;- paste(\"int\", lower_bounds, upper_bounds, sep = \"_\")\n</code></pre>\n\n<p>Next, a call to <code>setNames</code>is a bit inefficient as it copies your data to a separate space in memory. Instead, you should use the <code>colnames&lt;-</code> function so it only modifies the attribute of your existing object.</p>\n\n<pre><code>colnames(int_dta) &lt;- friendly_names\n</code></pre>\n\n<p>Next, the use of <code>apply</code> is pretty inefficient as it loops on the columns. Instead you could just do:</p>\n\n<pre><code>int_dta &lt;- int_dta == 1L\n</code></pre>\n\n<p>to convert to a matrix of <code>TRUE/FALSE</code>.</p>\n\n<p>At the end, you are again making an unnecessary copy of your data. You can just change the rownames of your current object, then return it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T23:43:10.307", "Id": "212106", "ParentId": "212084", "Score": "2" } } ]
{ "AcceptedAnswerId": "212106", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:14:49.633", "Id": "212084", "Score": "1", "Tags": [ "r" ], "Title": "Using findInterval to assign vector elements to corresponding brackets" }
212084
<p>Inspired by <a href="http://datagenetics.com/blog/april2009/index.html" rel="nofollow noreferrer">this</a> article.</p> <p>I've been trying to learn more C# and OOP. Here is my take on a genetic algorithm as described in the article. Here are some of the results</p> <ul> <li>flower</li> </ul> <p><a href="https://i.stack.imgur.com/Wz01I.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Wz01I.png" alt="flower"></a></p> <ul> <li>jelly</li> </ul> <p><a href="https://i.stack.imgur.com/SsuzM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SsuzM.png" alt="jelly"></a></p> <ul> <li>lighthouse</li> </ul> <p><a href="https://i.stack.imgur.com/AqOQW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/AqOQW.png" alt="lighthouse"></a></p> <ul> <li><a href="https://ibb.co/FbCzJ2r" rel="nofollow noreferrer">beach</a></li> </ul> <p>It takes a picture, and generates 10 images composed of 32 random rectangles. It scores the 10 images based on the average color distance of each corresponding point between the target image and the generated image. Then, it eliminates the two weakest scoring images, and replaces them with "cross pollinated" images from a random pair of the 8 remaining images. Finally, a random bit is flipped to add some mutation.</p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Gene { public partial class Form1 : Form { public Form1() { InitializeComponent(); } static int numberOfGenomes = 10; static int numberOfChromosomes = 32; static int numberOfProperties = 8; static int numberOfBitsPerProp = 8; static int chromosomeStringLength = numberOfProperties * numberOfBitsPerProp; static Size imageSize = new Size(255, 255); Bitmap originalImage; static DirectBitmap target; //binary to gray to binary public static class Gray { //example usage: Convert.ToString((long) grayEncode(i), 2).PadLeft(8,'0') //gray encode 0-255 to 0000 0000-1000 0000 public static ulong GrayEncode(ulong n) { return n ^ (n &gt;&gt; 1); } public static ulong GrayDecode(ulong n) { ulong temp = n ^ (n &gt;&gt; 8); temp ^= (temp &gt;&gt; 4); temp ^= (temp &gt;&gt; 2); temp ^= (temp &gt;&gt; 1); return temp; } } private static readonly Random r = new Random(); private static readonly object syncLock = new object(); public static int RandomNumber(int min, int max) { lock (syncLock) { return r.Next(min, max); } } //a chromosome is the individual rectangle public class Chromosome { //Gene Fields // all values are 0-255 private ulong x; private ulong y; private ulong width; private ulong height; private ulong alpha; private ulong red; private ulong green; private ulong blue; private string chromosomestring; private Rectangle rectangle; private Color rectanglecolor; readonly int rmin = 0; readonly int rmax = 255; //Constructor public Chromosome() { RandomizeGenes(); GenerateShape(); EncodeChromosomeString(); } //Gene Properties public ulong X { get =&gt; x; set =&gt; x = value; } public ulong Y { get =&gt; y; set =&gt; y = value; } public ulong Width { get =&gt; width; set =&gt; width = value; } public ulong Height { get =&gt; height; set =&gt; height = value; } public ulong Alpha { get =&gt; alpha; set =&gt; alpha = value; } public ulong Red { get =&gt; red; set =&gt; red = value; } public ulong Green { get =&gt; green; set =&gt; green = value; } public ulong Blue { get =&gt; blue; set =&gt; blue = value; } public string Chromosomestring { get =&gt; chromosomestring; set =&gt; chromosomestring = value; } public Rectangle Rectangle { get =&gt; rectangle; set =&gt; rectangle = value; } public Color RectangleColor { get =&gt; rectanglecolor; set =&gt; rectanglecolor = value; } //Methods public void RandomizeGenes() { x = (ulong)RandomNumber(rmin, rmax); y = (ulong)RandomNumber(rmin, rmax); width = (ulong)RandomNumber(rmin, imageSize.Width - (int)x); height = (ulong)RandomNumber(rmin, imageSize.Height - (int)y); alpha = (ulong)RandomNumber(rmin, rmax); red = (ulong)RandomNumber(rmin, rmax); green = (ulong)RandomNumber(rmin, rmax); blue = (ulong)RandomNumber(rmin, rmax); } public void EncodeChromosomeString() { chromosomestring = Convert.ToString((long)Gray.GrayEncode(x), 2).PadLeft(8,'0')+ Convert.ToString((long)Gray.GrayEncode(y), 2).PadLeft(8, '0') + Convert.ToString((long)Gray.GrayEncode(width), 2).PadLeft(8, '0') + Convert.ToString((long)Gray.GrayEncode(height), 2).PadLeft(8, '0') + Convert.ToString((long)Gray.GrayEncode(alpha), 2).PadLeft(8, '0') + Convert.ToString((long)Gray.GrayEncode(red), 2).PadLeft(8, '0') + Convert.ToString((long)Gray.GrayEncode(green), 2).PadLeft(8, '0') + Convert.ToString((long)Gray.GrayEncode(blue), 2).PadLeft(8, '0'); } public void GenerateShape() { rectangle = new Rectangle((int) x, (int)y, (int)width, (int)height); rectanglecolor = Color.FromArgb((int)alpha, (int)red, (int)green, (int)blue); } //decode chromosome string to set other chromosome properties public void DecodeChromosomeString() { x = Gray.GrayDecode(Convert.ToUInt32(chromosomestring.Substring(0, 8),2)); y = Gray.GrayDecode(Convert.ToUInt32(chromosomestring.Substring(8, 8), 2)); width = Gray.GrayDecode(Convert.ToUInt32(chromosomestring.Substring(16, 8), 2)); height = Gray.GrayDecode(Convert.ToUInt32(chromosomestring.Substring(24, 8), 2)); alpha = Gray.GrayDecode(Convert.ToUInt32(chromosomestring.Substring(32, 8), 2)); red = Gray.GrayDecode(Convert.ToUInt32(chromosomestring.Substring(40, 8), 2)); green = Gray.GrayDecode(Convert.ToUInt32(chromosomestring.Substring(48, 8), 2)); blue = Gray.GrayDecode(Convert.ToUInt32(chromosomestring.Substring(56, 8), 2)); GenerateShape(); } //not used. for experimentation. public void MutateChromosome() { var length = chromosomestring.Length; var randomGenePosition = r.Next(0, length); char gene = chromosomestring[randomGenePosition]; if (gene.Equals('0')) { gene = '1'; } else { gene = '0'; } char[] mutatedChromosome = new char[chromosomestring.Length]; for (int i = 0; i &lt; chromosomestring.Length; i++) { if (i == randomGenePosition) { mutatedChromosome[i] = gene; } else { mutatedChromosome[i] = chromosomestring[i]; } } chromosomestring = new string(mutatedChromosome); return; } } // a genome is 32 chromosomes(rectangles) public class Genome { private Chromosome[] chromosomes = new Chromosome[numberOfChromosomes]; private string genomestring; public Chromosome[] Chromosomes { get =&gt; chromosomes; set =&gt; chromosomes = value; } public string Genomestring { get =&gt; genomestring; set =&gt; genomestring = value; } public Genome() { CreateChromosomes(); EncodeGenome(); } public void EncodeGenome() { for (int i = 0; i &lt; numberOfChromosomes; i++) { Genomestring += chromosomes[i].Chromosomestring; } } public void CreateChromosomes() { for (int i = 0; i &lt; numberOfChromosomes; i++) { chromosomes[i] = new Chromosome(); } } public void MutateGenome() { var length = genomestring.Length; var randomGenePosition = r.Next(0, length); char protein = genomestring[randomGenePosition]; if (protein.Equals('0')) { protein = '1'; } else { protein = '0'; } char[] mutatedGenome = new char[genomestring.Length]; for (int i = 0; i &lt; genomestring.Length; i++) { if (i == randomGenePosition) { mutatedGenome[i] = protein; } else { mutatedGenome[i] = genomestring[i]; } } genomestring = new string(mutatedGenome); return; } public void DecodeGenomeString() { //use after mutating: //split genomestring into chromosomestrings //then decode the chromosomestrings //so that the chromosome properties update with mutated chromosome. for (int i = 0; i &lt; numberOfChromosomes; i++) { chromosomes[i].Chromosomestring = genomestring.Substring(i*chromosomeStringLength, chromosomeStringLength); chromosomes[i].DecodeChromosomeString(); chromosomes[i].EncodeChromosomeString(); } } } // there are 10 genomes in the gene pool public class GenePool { private Genome[] pool = new Genome[numberOfGenomes]; private DirectBitmap[] directBitmaps = new DirectBitmap[numberOfGenomes]; private double[] score = new double[numberOfGenomes]; private List&lt;int&gt; scoredIndex; public Genome[] Pool { get =&gt; pool; set =&gt; pool = value; } public DirectBitmap[] DirectBitmaps { get =&gt; directBitmaps; set =&gt; directBitmaps = value; } public double[] Score { get =&gt; score; set =&gt; score = value; } public List&lt;int&gt; ScoredIndex { get =&gt; scoredIndex; set =&gt; scoredIndex = value; } //Populate the Pool public GenePool() { CreatePool(); } public void CreatePool() { for (int i = 0; i &lt; numberOfGenomes; i++) { Pool[i] = new Genome(); } } public void DrawGenomes() { //draw the decoded genomes to direct bitmaps for (int i = 0; i &lt; numberOfGenomes; i++) { directBitmaps[i] = new DirectBitmap(imageSize.Width, imageSize.Height); using(var g = Graphics.FromImage(directBitmaps[i].Bitmap)) { g.FillRectangle(new SolidBrush(Color.Black), 0, 0, imageSize.Width, imageSize.Height); for (int j = 0; j &lt; numberOfChromosomes; j++) { g.FillRectangle(new SolidBrush(pool[i].Chromosomes[j].RectangleColor), pool[i].Chromosomes[j].Rectangle); } } } } public void ScoreGenomes() { for (int i = 0; i &lt; numberOfGenomes; i++) { double sum = 0; double pointscore = 0; for (int j = 0; j &lt; imageSize.Width; j++) { for (int k = 0; k &lt; imageSize.Height; k++) { sum += ColorDistance(directBitmaps[i].GetPixel(j, k),target.GetPixel(j,k)); } } pointscore = sum / (imageSize.Width * imageSize.Height); score[i] = pointscore; } } public void SortScores() { List&lt;double&gt; A = new List&lt;double&gt;(); for (int i = 0; i &lt; score.Length; i++) { A.Add(score[i]); } var sorted = A .Select((x, i) =&gt; new KeyValuePair&lt;double, int&gt;(x, i)) .OrderBy(x =&gt; x.Key) .ToList(); List&lt;double&gt; B = sorted.Select(x =&gt; x.Key).ToList(); scoredIndex = sorted.Select(x =&gt; x.Value).ToList(); //the weakest scoring genomes are at the following: //weakest = scoredIndex[numberOfGenomes-1]; //weaker = scoredIndex[numberOfGenomes - 2]; } public void CrossPollElim() { //crosspollinate to create 2 new genomes, replace the genomes with the lowest score. //select 2 random genomes (not the weakest- 0-7, 8 and 9 are weakest) int temp1, temp2; int parent1, parent2; int cut; string head1, head2; string tail1, tail2; string child1, child2; temp1 = r.Next(0, numberOfGenomes-2); temp2 = r.Next(0, numberOfGenomes-2); while (temp1 == temp2) { temp2 = r.Next(0, 8); } parent1 = scoredIndex[temp1]; parent2 = scoredIndex[temp2]; cut = r.Next(0, pool[0].Genomestring.Length - 1); head1 = pool[parent1].Genomestring.Substring(0, cut); head2 = pool[parent2].Genomestring.Substring(0, cut); tail1 = pool[parent1].Genomestring.Substring(cut); tail2 = pool[parent2].Genomestring.Substring(cut); child1 = head1 + tail2; child2 = head2 + tail1; pool[scoredIndex[numberOfGenomes - 1]].Genomestring = child1; pool[scoredIndex[numberOfGenomes - 2]].Genomestring = child2; } public void SelectOneAndMutate() { var randomGenome = r.Next(0, numberOfGenomes); pool[randomGenome].MutateGenome(); } } public static double ColorDistance(Color c1, Color c2) { long rmean = ((long)c1.R + (long)c2.R) / 2; long r = (long)c1.R - (long)c2.R; long g = (long)c1.G - (long)c2.G; long b = (long)c1.B - (long)c2.B; return Math.Sqrt((((512 + rmean) * r * r) &gt;&gt; 8) + 4 * g * g + (((767 - rmean) * b * b) &gt;&gt; 8)); } public class DirectBitmap : IDisposable { public Bitmap Bitmap { get; private set; } public Int32[] Bits { get; private set; } public bool Disposed { get; private set; } public int Height { get; private set; } public int Width { get; private set; } protected GCHandle BitsHandle { get; private set; } public DirectBitmap(int width, int height) { Width = width; Height = height; Bits = new Int32[width * height]; BitsHandle = GCHandle.Alloc(Bits, GCHandleType.Pinned); Bitmap = new Bitmap(width, height, width * 4, PixelFormat.Format32bppPArgb, BitsHandle.AddrOfPinnedObject()); } public void SetPixel(int x, int y, Color colour) { int index = x + (y * Width); int col = colour.ToArgb(); Bits[index] = col; } public Color GetPixel(int x, int y) { int index = x + (y * Width); int col = Bits[index]; Color result = Color.FromArgb(col); return result; } public void Dispose() { if (Disposed) return; Disposed = true; Bitmap.Dispose(); BitsHandle.Free(); } } //sets target image to stretched bitmap of orignal //then sets picturebox1 image to target image private void OpenImage(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { originalImage = new Bitmap(openFileDialog1.FileName); } target = new DirectBitmap(imageSize.Width, imageSize.Height); using(var g = Graphics.FromImage(target.Bitmap)) { g.DrawImage(originalImage,0,0,imageSize.Width,imageSize.Height); } pictureBox1.Image = target.Bitmap; originalImage.Dispose(); } //gene pool with 10 genomes which each have 32 chromosomes(rectangles) GenePool gp; private void CreateGenePool_Click(object sender, EventArgs e) { GpCreate(); } private void Step_Click(object sender, EventArgs e) { Evolve(2000); } public void GpCreate() { gp = new GenePool(); } public void Evolve(int iterations) { for (int k = 0; k &lt; iterations; k++) { for (int i = 0; i &lt; numberOfGenomes; i++) { if (gp.DirectBitmaps[i] != null) { gp.DirectBitmaps[i].Dispose(); } else { continue; } } gp.DrawGenomes(); gp.ScoreGenomes(); gp.SortScores(); pictureBox2.Image = gp.DirectBitmaps[gp.ScoredIndex[0]].Bitmap; pictureBox3.Image = gp.DirectBitmaps[gp.ScoredIndex[1]].Bitmap; pictureBox4.Image = gp.DirectBitmaps[gp.ScoredIndex[2]].Bitmap; pictureBox5.Image = gp.DirectBitmaps[gp.ScoredIndex[3]].Bitmap; pictureBox6.Image = gp.DirectBitmaps[gp.ScoredIndex[4]].Bitmap; pictureBox7.Image = gp.DirectBitmaps[gp.ScoredIndex[5]].Bitmap; pictureBox8.Image = gp.DirectBitmaps[gp.ScoredIndex[6]].Bitmap; pictureBox9.Image = gp.DirectBitmaps[gp.ScoredIndex[7]].Bitmap; pictureBox10.Image = gp.DirectBitmaps[gp.ScoredIndex[8]].Bitmap; pictureBox11.Image = gp.DirectBitmaps[gp.ScoredIndex[9]].Bitmap; pictureBox2.Refresh(); pictureBox3.Refresh(); pictureBox4.Refresh(); pictureBox5.Refresh(); pictureBox6.Refresh(); pictureBox7.Refresh(); pictureBox8.Refresh(); pictureBox9.Refresh(); pictureBox10.Refresh(); pictureBox11.Refresh(); gp.CrossPollElim(); gp.SelectOneAndMutate(); for (int i = 0; i &lt; numberOfGenomes; i++) { gp.Pool[i].DecodeGenomeString(); } } } } } </code></pre> <p>All feedback is welcome. I will answer what questions you have.</p> <p>I am satisfied with the performance, and can get some nice computer generated paintings of certain things. There's a strong success bias towards rectangular things or scenes with a lot of horizontal and vertical lines. </p> <p>I think it could be faster. After 2000 iterations, the generated image begins to resemble the target image.</p> <p>When I set the evolution loop to 100 000, it starts to consume more memory, but if I set it to 10 000 the memory usage goes down after completing a "step" and it doesn't accumulate when I step again. </p> <p>I am looking into multithreading or using a background worker so that the UI doesn't become unresponsive during the evolution. My first attempt at doing so caused some cross threading issues when refreshing the picture box, but I am continuing to look into it.</p> <p>I would also like to have a start and a stop button, so it can just run and evolve continuously until I press stop.</p> <p>I also plan to make a new program similar to this, but with more shapes you can select and with controls and displays of whats going on behind the scenes. </p> <p>Some things I am interested in:</p> <ul> <li>Is there anything I did that is blatantly the wrong way of doing it?</li> <li>Are there any techniques I could use that I have not used that would improve the program? </li> <li>Do you see any way to improve the performance or speed?</li> </ul> <p>Here is the designer code (ignore the progress bar/background worker, I'm still implementing it):</p> <pre><code>partial class Form1 { /// &lt;summary&gt; /// Required designer variable. /// &lt;/summary&gt; private System.ComponentModel.IContainer components = null; /// &lt;summary&gt; /// Clean up any resources being used. /// &lt;/summary&gt; /// &lt;param name="disposing"&gt;true if managed resources should be disposed; otherwise, false.&lt;/param&gt; protected override void Dispose(bool disposing) { if (disposing &amp;&amp; (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// &lt;summary&gt; /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// &lt;/summary&gt; private void InitializeComponent() { this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.OpenImageButton = new System.Windows.Forms.Button(); this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.CreateGenePool = new System.Windows.Forms.Button(); this.Step = new System.Windows.Forms.Button(); this.backgroundWorker1 = new System.ComponentModel.BackgroundWorker(); this.progressBar1 = new System.Windows.Forms.ProgressBar(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.pictureBox4 = new System.Windows.Forms.PictureBox(); this.pictureBox5 = new System.Windows.Forms.PictureBox(); this.pictureBox6 = new System.Windows.Forms.PictureBox(); this.pictureBox7 = new System.Windows.Forms.PictureBox(); this.pictureBox8 = new System.Windows.Forms.PictureBox(); this.pictureBox9 = new System.Windows.Forms.PictureBox(); this.pictureBox10 = new System.Windows.Forms.PictureBox(); this.pictureBox11 = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox7)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox8)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox9)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox10)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox11)).BeginInit(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.Location = new System.Drawing.Point(0, 0); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(255, 255); this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // OpenImageButton // this.OpenImageButton.Location = new System.Drawing.Point(12, 261); this.OpenImageButton.Name = "OpenImageButton"; this.OpenImageButton.Size = new System.Drawing.Size(75, 23); this.OpenImageButton.TabIndex = 1; this.OpenImageButton.Text = "Open Image"; this.OpenImageButton.UseVisualStyleBackColor = true; this.OpenImageButton.Click += new System.EventHandler(this.OpenImage); // // openFileDialog1 // this.openFileDialog1.FileName = "openFileDialog1"; this.openFileDialog1.Filter = "JPEG Files (*.jpg)|*.jpg|PNG Files (*.png)|*.png|BMP Files (*.bmp)|*.bmp|All file" + "s (*.*)|*.*"; this.openFileDialog1.Title = "Select an Image File"; // // pictureBox2 // this.pictureBox2.Location = new System.Drawing.Point(256, 0); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(255, 255); this.pictureBox2.TabIndex = 2; this.pictureBox2.TabStop = false; // // CreateGenePool // this.CreateGenePool.Location = new System.Drawing.Point(256, 261); this.CreateGenePool.Name = "CreateGenePool"; this.CreateGenePool.Size = new System.Drawing.Size(124, 23); this.CreateGenePool.TabIndex = 3; this.CreateGenePool.Text = "Create Gene Pool"; this.CreateGenePool.UseVisualStyleBackColor = true; this.CreateGenePool.Click += new System.EventHandler(this.CreateGenePool_Click); // // Step // this.Step.Location = new System.Drawing.Point(386, 261); this.Step.Name = "Step"; this.Step.Size = new System.Drawing.Size(38, 23); this.Step.TabIndex = 4; this.Step.Text = "Step"; this.Step.UseVisualStyleBackColor = true; this.Step.Click += new System.EventHandler(this.Step_Click); // // progressBar1 // this.progressBar1.Location = new System.Drawing.Point(431, 261); this.progressBar1.Name = "progressBar1"; this.progressBar1.Size = new System.Drawing.Size(69, 23); this.progressBar1.TabIndex = 5; // // pictureBox3 // this.pictureBox3.Location = new System.Drawing.Point(512, 0); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(255, 255); this.pictureBox3.TabIndex = 6; this.pictureBox3.TabStop = false; // // pictureBox4 // this.pictureBox4.Location = new System.Drawing.Point(768, 0); this.pictureBox4.Name = "pictureBox4"; this.pictureBox4.Size = new System.Drawing.Size(255, 255); this.pictureBox4.TabIndex = 7; this.pictureBox4.TabStop = false; // // pictureBox5 // this.pictureBox5.Location = new System.Drawing.Point(1024, 0); this.pictureBox5.Name = "pictureBox5"; this.pictureBox5.Size = new System.Drawing.Size(255, 255); this.pictureBox5.TabIndex = 8; this.pictureBox5.TabStop = false; // // pictureBox6 // this.pictureBox6.Location = new System.Drawing.Point(512, 256); this.pictureBox6.Name = "pictureBox6"; this.pictureBox6.Size = new System.Drawing.Size(255, 255); this.pictureBox6.TabIndex = 9; this.pictureBox6.TabStop = false; // // pictureBox7 // this.pictureBox7.Location = new System.Drawing.Point(768, 256); this.pictureBox7.Name = "pictureBox7"; this.pictureBox7.Size = new System.Drawing.Size(255, 255); this.pictureBox7.TabIndex = 10; this.pictureBox7.TabStop = false; // // pictureBox8 // this.pictureBox8.Location = new System.Drawing.Point(1024, 256); this.pictureBox8.Name = "pictureBox8"; this.pictureBox8.Size = new System.Drawing.Size(255, 255); this.pictureBox8.TabIndex = 11; this.pictureBox8.TabStop = false; // // pictureBox9 // this.pictureBox9.Location = new System.Drawing.Point(512, 512); this.pictureBox9.Name = "pictureBox9"; this.pictureBox9.Size = new System.Drawing.Size(255, 255); this.pictureBox9.TabIndex = 12; this.pictureBox9.TabStop = false; // // pictureBox10 // this.pictureBox10.Location = new System.Drawing.Point(768, 512); this.pictureBox10.Name = "pictureBox10"; this.pictureBox10.Size = new System.Drawing.Size(255, 255); this.pictureBox10.TabIndex = 13; this.pictureBox10.TabStop = false; // // pictureBox11 // this.pictureBox11.Location = new System.Drawing.Point(1024, 512); this.pictureBox11.Name = "pictureBox11"; this.pictureBox11.Size = new System.Drawing.Size(255, 255); this.pictureBox11.TabIndex = 14; this.pictureBox11.TabStop = false; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1279, 767); this.Controls.Add(this.pictureBox11); this.Controls.Add(this.pictureBox10); this.Controls.Add(this.pictureBox9); this.Controls.Add(this.pictureBox8); this.Controls.Add(this.pictureBox7); this.Controls.Add(this.pictureBox6); this.Controls.Add(this.pictureBox5); this.Controls.Add(this.pictureBox4); this.Controls.Add(this.pictureBox3); this.Controls.Add(this.progressBar1); this.Controls.Add(this.Step); this.Controls.Add(this.CreateGenePool); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.OpenImageButton); this.Controls.Add(this.pictureBox1); this.Name = "Form1"; this.Text = "Form1"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox4)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox5)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox6)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox7)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox8)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox9)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox10)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox11)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Button OpenImageButton; private System.Windows.Forms.OpenFileDialog openFileDialog1; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.Button CreateGenePool; private System.Windows.Forms.Button Step; private System.ComponentModel.BackgroundWorker backgroundWorker1; private System.Windows.Forms.ProgressBar progressBar1; private System.Windows.Forms.PictureBox pictureBox3; private System.Windows.Forms.PictureBox pictureBox4; private System.Windows.Forms.PictureBox pictureBox5; private System.Windows.Forms.PictureBox pictureBox6; private System.Windows.Forms.PictureBox pictureBox7; private System.Windows.Forms.PictureBox pictureBox8; private System.Windows.Forms.PictureBox pictureBox9; private System.Windows.Forms.PictureBox pictureBox10; private System.Windows.Forms.PictureBox pictureBox11; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:11:31.977", "Id": "410391", "Score": "1", "body": "Do you happen to have it on GitHub or could add the designer code too? I'd like to run it ;-] Oh, and links to the original images you tested it with would be great too so we can compare the performance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:26:51.417", "Id": "410394", "Score": "1", "body": "I added the designer code. The original images were just the Sample Pictures in My Pictures folder, I think if you just google \"windows 7 jelly fish/hydrangea/lighthouse picture\" you can find them. I also added a line to start the bitmap with a black background, it seems to go a little faster than a white/empty background. I also added the 9 other picture boxes to display each individual in the gene pool as they change. After around 2000 iterations, which is what I have the button set to, it starts to look pretty close as far as colors and rough shapes go." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:37:07.117", "Id": "410397", "Score": "1", "body": "cool :D, I should mention that first you open a target image, then create the gene pool, then step. You can step again after, or open a new image and see how it adapts to that from the previous image. The Create gene pool button is probably unnecessary but for making sure everything works it made sense. I had a console output for debugging but that's unnecessary too. OH and because it's not on a background worker yet, click continue when it cries about pumping windows messages, it'll keep going." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:51:08.323", "Id": "410401", "Score": "1", "body": "I've let ReSharper profiler measure it and currently as far as calculations are concerned the `ColorDistance` is the most time consuming method which is called millions of times and consequently of course `ScoreGenomes` ;-) mhmm there should be a way to paralleize it..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:59:07.557", "Id": "410403", "Score": "0", "body": "Interesting, I'm going to check out ReSharper I hadn't heard of it. That sort of makes sense, its a bunch of double and long arithmetic and math for each of the 65025 points that it compares. That is the bulk of the scoring method too. I've read about several different color comparison methods. I might try to implement some other color distance calculations. It's a trade off though, RGB difference is less accurate, RGB^2 difference is more accurate but more math, and the human vision color channel weighting is even more accurate but with more math." } ]
[ { "body": "<p>I have two small sugestions...</p>\n\n<hr>\n\n<p>Without using different math in <code>ColorDistance</code> which is the <em>bottleneck</em> (according to ReShaprer profiler (dotTrace)) as a quick speed improvement you can paralleize <code>ScoreGenoms</code> by using <code>Parallel.For</code> replacing the original <code>for</code></p>\n\n<pre><code>Parallel.For(0, numberOfGenomes, i =&gt; \n{\n ...\n})\n</code></pre>\n\n<hr>\n\n<p><code>Evolve</code> on the other hand could use <code>Application.DoEvents();</code> at the end of the the outher loop to quickly fix the unresponsive UI (until it runs in a task...)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:38:10.970", "Id": "410407", "Score": "0", "body": "Thank you so much I appreciate the feedback! I will try those out, I haven't come across them before. So, as far as the object oriented approach goes, does it look OK? Am I on the right path? I know I haven't really used any interfaces or inheritance, but I didn't really feel like I needed to in order to achieve these results." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:49:00.793", "Id": "410413", "Score": "2", "body": "@jreese I just took a quick look at it so I think I'll add more comments later when I've studied the algorithm and the application as this is quite interesting and a little bit complex at first. I'll let you know when I've done some changes... although others might be quicker than me ;-] anyway... as far as design is concerned there is plenty room for improvement but I first need to take a closer look. As a matter of fact you never need any special design to achieve the desired results. The only reason why we carefuly design our apps is because we want them to be maintainable & testable ;-)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:05:13.790", "Id": "212225", "ParentId": "212087", "Score": "2" } }, { "body": "<h3>Optimization</h3>\n\n<p>You can achieve a significant perfomance improvement by using a so-called 'dirty rectangles' approach. Instead of calculating the color-distance of every single pixel every single time, you only need to recalculate the distance of pixels that have been modified. Every step, you're eliminating two genomes, so they will have to be fully recalculated. You're also mutating another genome, which only affects a single property of a single rectangle, so you only need to recalculate pixels affected by that change. All the other genomes are unaffected, so they don't need to be recalculated at all. Some quick testing shows that this can make things up to 10x faster.</p>\n\n<h3>Design</h3>\n\n<p>The <code>Chromosome</code>, <code>Genome</code> and <code>Genepool</code> classes are tightly coupled to <code>Form1</code>. They're also difficult to use correctly due to various implicit assumptions and a lack of protection against inconsistent state:</p>\n\n<ul>\n<li>Instead of depending on 'constants' in <code>Form1</code>, pass in the number of chromosomes and genomes via the relevant constructors: <code>new Genepool(genomeCount: 10, chromosomeCount: 32)</code>. The same goes for <code>Random</code> - pass it to the constructors or methods that need it. This makes dependencies clearly visible, and makes it easier to reuse these classes in a different context.</li>\n<li>Instead of setting <code>Chromosomestring</code> and then having to call <code>DecodeChromosomeString</code>, create a <code>void Decode(string chromosomeString)</code> method. This forces a caller to provide the required data. And instead of calling <code>EncodeChromosomeString</code> and then fetching <code>Chromosomestring</code>, create a method <code>string Encode()</code> that returns that string directly. This clearly presents the resulting data to the caller.</li>\n<li><code>Chromosome.Rectangle</code> and <code>Chromosome.RectangleColor</code> can easily go out-of-sync with the properties they depend on. All properties having public setters doesn't exactly make it easy to maintain a consistent state. Creating a rectangle or color upon request (such as <code>public Rectangle Rectangle =&gt; new Rectangle(X, Y, Width, Height);</code>) would simplify this.</li>\n</ul>\n\n<h3>Other notes</h3>\n\n<ul>\n<li>C# supports auto-properties, so you don't explicitly need to define a backing field: <code>public int X { get; set; }</code>. The setter can be left out or made private for read-only properties or properties that should only be modified from within the class itself. Nowadays it's also possible to initialize properties: <code>public string Name { get; set; } = \"Unknown\";</code>.</li>\n<li>Why are all <code>Chromosome</code> properties of type <code>ulong</code>? There's a comment stating they'll only have values ranging from 0-255, so <code>byte</code> seems more appropriate. Otherwise, <code>int</code> is typically used by default.</li>\n<li>You may want to document the purpose of <code>GrayEncode</code> and <code>GrayDecode</code>. Apparently Gray encoding reduces the frequency of 'radical' mutations?</li>\n<li>Instead of doing <code>for (int i = 0; i &lt; constantName; i++)</code>, consider doing <code>for (int i = 0; i &lt; array.Length; i++)</code>. That'll work regardless of whether <code>array</code> was initialized using a constant or a more dynamic value.</li>\n<li><code>Genepool</code> creates and contains a bunch of bitmaps, but <code>Form1.Evolve</code> disposes them. It's better to clearly define 'ownership'. In this case, <code>Genepool</code> creates and uses these images, so it should also dispose them (and so it should also implement <code>IDisposable</code> itself).</li>\n<li>Why create new bitmaps instead of reusing old ones?</li>\n<li><code>SolidBrush</code>es should be disposed. For common colors, you can use <code>Brushes.&lt;colorname&gt;</code> instead of creating a new brush.</li>\n</ul>\n\n<p><code>Genome.MutateGenome</code> can be simplified to:</p>\n\n<pre><code>var chars = genomestring.ToCharArray();\nvar mutationIndex = r.Next(0, chars.Length);\nchars[mutationIndex] = chars[mutationIndex] == '0' ? '1' : '0';\ngenomestring = new string(chars);\n</code></pre>\n\n<p><code>GenePool.SortScores</code> can be simplified to:</p>\n\n<pre><code>scoredIndex = score\n .Select((score, index) =&gt; new { score, index })\n .OrderBy(scoring =&gt; scoring.score)\n .Select(scoring =&gt; scoring.index)\n .ToList();\n</code></pre>\n\n<p>The anonymous object (<code>new { score, index }</code>) lets you use more descriptive field names than <code>Key</code> and <code>Value</code>, but otherwise serves the same purpose.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:38:13.247", "Id": "411115", "Score": "0", "body": "Pieter, this is great! thank you. This is exactly the kind of feed back I was hoping for. It's a lot to go through, and I will post an update in the future. The dirty rectangle is a great idea! It seems so obvious, I've done similar things in other projects with drawing a game tile board. I will try to implement the structural design changes. As for some of the notes - I right clicked and used the auto refactoring to make the properties, your'e right though I could clean them all up. I used ulong because the gray encoding took in ulong, and the gray encoding was working." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T13:40:58.177", "Id": "411117", "Score": "0", "body": "gray encoding is to prevent \"hamming walls\", two mutations must occur for \"1.9\" to mutate into \"2.0\", 1 to 2, and 9 to 0. gray code makes it so that one mutation can more smoothly mutate up and down a range without getting stuck on a place where two mutations would have been necessary. Gray encoding is commonly used for this type of genetic evolutionary algorithm. The bitmaps gave me a headache! I will see what I can do about reusing and managing the disposal better. Initially I had a lot of issues with memory usage from the bitmaps. Thanks again! I'll post again to show progress." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T01:28:02.390", "Id": "212500", "ParentId": "212087", "Score": "3" } } ]
{ "AcceptedAnswerId": "212500", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:42:43.520", "Id": "212087", "Score": "5", "Tags": [ "c#", "image", "winforms", "graphics", "genetic-algorithm" ], "Title": "Portrait Painting Genetic Algorithm" }
212087
<p>I'm putting together an example for students where I would like to show how we can optimize even such basic algorithm like a binary search with respect to hardware. I do not consider threads. I wrote it in C++ and the whole example can be found <a href="https://github.com/RadimBaca/binary-search" rel="nofollow noreferrer">here</a>. I'm trying to show some examples of the prefetching. </p> <p><strong>Test data</strong> If we would like to see the effects of the optimizations proposed in the following examples, then it is necessary to use data that are not in the CPU cache.</p> <p>We are going to test it using some code like this</p> <pre><code>// arr - array with at least 100MB of values // test_arr - array with values that we are going to search in arr // test_count - size of the test_arr for (auto i = 0u; i &lt; test_count; ++i) { auto position = binarySearch(item_count, arr, test_arr[i]); } </code></pre> <p><em>Size</em> - If the <code>arr</code> array is significantly larger then largest CPU cache then most of the array won't be stored there and we will inevitably experience the L2 cache misses during the run. L2 cache misses are slow and it will become the major bottleneck of our binary search algorithm.</p> <p><em>Randomness</em> - It is better to have data in the <code>test_arr</code> that accesses the <code>arr</code> randomly, otherwise, the basic binary search algorithm will benefit from data access locality.</p> <p>Please note that the L2 cache misses can be experienced even on a small array in some complex algorithm which works with a lot of data. In other words, we need a large array only for the purpose of testing, but the optimization can be useful everywhere where expect the binary search to happen on a data outside of CPU cache.</p> <p><strong>The basic algorithm</strong> It is something along these lines:</p> <pre><code>using Type = int64_t; int binarySearch_basic(size_t item_count, const Type arr[], int search) { int l = 0; int r = item_count - 1; while (l &lt;= r) { int m = l + ((r - l) &gt;&gt; 1); if (arr[m] == search) return m; if (arr[m] &lt; search) l = m + 1; else r = m - 1; } return -1; } </code></pre> <p><strong>Prefetch</strong> The first optimization simply try to prefetch possible memory in advance</p> <pre><code>int binarySearch_basic(size_t item_count, const Type arr[], int search) { int l = 0; int r = item_count - 1; while (l &lt;= r) { int m1 = arr[l + ((r - l) &gt;&gt; 2)]; // new code int m2 = arr[r - ((r - l) &gt;&gt; 2)]; // new code int m = l + ((r - l) &gt;&gt; 1); if (arr[m] == search) return m; if (arr[m] &lt; search) l = m + 1; else r = m - 1; } return -1; } </code></pre> <p><strong>More items per iteration</strong> The second optimization is a little bit more sophisticated. It accesses more than one item per iteration which allows read more relevant data per CPU L2 cache miss wait.</p> <pre><code>int binarySearch_duo(size_t item_count, const Type arr[], int search) { int l = 0; int r = item_count - 1; while (r - l &gt; 3) { int delta = (r - l) / 3; int m1 = l + delta; int m2 = r - delta; if (arr[m1] == search) return m1; if (arr[m2] == search) return m2; if (arr[m1] &lt; search) { if (arr[m2] &lt; search) { l = m2 + 1; } else { r = m2 - 1; l = m1 + 1; } } else { r = m1 - 1; } } for (int i = l; i &lt;= r; i++) { if (arr[i] == search) return i; } return -1; } </code></pre> <p>Of course, this approach can be done with more accesses per iteration (I'm testing three as well in my demo). There are some infinite loop issues if the <code>(l,r)</code> interval is very small (less then three), therefore, I finish the remaining items by a simple sequential search to keep the main iteration clean and simple.</p> <p>I was doing my tests with Visual Studio 2017 C++ compiler. </p> <p>I have several questions:</p> <ul> <li>Are there any other possible significant optimizations that could help the algorithm?</li> <li>Is my explanation of the improvement of the last algorithm correct? (is it really due to the fact that the CPU read in parallel two data items; therefore, he waits for it just once not twice like in the first algorithm).</li> <li>Are there any other comments about my code?</li> </ul> <p><strong>CONCLUSION</strong></p> <p>It seems that my assumptions regarding the architecture is wrong and the measurable slowdown in the case of MSVC compiler is caused mainly due to the bad condition order. Thanks all to contribute to this disscussion!</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:41:17.990", "Id": "410135", "Score": "1", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. There is no immediate problem, but if you add more code we'll have to rollback the edit. Should your code be improved over time, post a follow-up question linking back to this one instead. Give it some time though." } ]
[ { "body": "<p>How did you measure the performance of your code (test code, hardware, compiler, etc.)? Without that it is impossible to get into optimization. Depending on chosen compiler I was sort of able to reproduce your results, see <a href=\"http://quick-bench.com/cT8FjqPov65tetBZiSSEb5wlOHA\" rel=\"nofollow noreferrer\">this quick bench</a>- for clang 7.0.0 the fancy algorithm is indeed faster. That being said with gcc the basic one is a lot faster (outperforming fancy algorithm in both clang and gcc).<br>\nWith that in mind, you can optimize your algorithm for different array sizes quite easily (benchmarking on your specific setup), by choosing fastest of the 3 for specific sizes. </p>\n\n<p>As far as the code is concerned, there are a couple of things you can improve. </p>\n\n<p>You could rewrite your algorithms so that they accept iterators, just like all the algorithms from standard library, that will drastically improve their flexibility without added effort (and most probably without degrading performance, but you should measure it anyway).\nApart from that, you should avoid implicit conversions, e.g. here:</p>\n\n<pre><code>int r = item_count - 1;\n</code></pre>\n\n<p>You should also prefer to keep the bodies of your functions short, it's hard to understand what <code>binarySearch_duo</code> actually does (you could easily extract body of the loop etc). Also, avoid magic constants, where does the seven in: <code>while (r - l &gt; 7) {</code> come from?</p>\n\n<p>Edit: I've created one more benchmark for this, this time as proposed by OP, that is with huge array size (actually a vector) and made the access to the elements of the array random, see <a href=\"http://quick-bench.com/_4FfE1Xo3gHe4gRGyerHm0hDBhE\" rel=\"nofollow noreferrer\">here</a>- this time with gcc fancy version is as good as basic. The lesson should probably be: compiler is usually at least as smart as you are :).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:12:33.883", "Id": "410115", "Score": "0", "body": "You are using a small array that fits into the L2 cache (the CPU type is unknown). You can try to extend the size of the array to 1M to see the fancy code to win. However, it is still quite a small array and L2 cache misses do not occur significantly often. The number 7 is not important for the performance, it can be any small number lager than 3. I selected 7 since it approximately corresponds to one 64 cache line." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:29:35.327", "Id": "410120", "Score": "2", "body": "Not necessarily, gcc even after increasing the count of elements in the array to `10^6` elements produces better times for basic implementation. What I'm trying to say is that your results will vary depending on your benchmark and if you won't provide reliable way to measure performance, then it's tough to recommend further optimisations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:30:56.093", "Id": "410121", "Score": "0", "body": "You are right. It is true that I did not specify the benchmark clearly here. I'll update the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:06:09.727", "Id": "410124", "Score": "0", "body": "I have updated the question. I hope it is more clear now. Thank you for your recommendations." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:13:31.070", "Id": "410126", "Score": "0", "body": "Concerning your benchmark - it is not large enough and also the queries into the array are not random." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:33:34.033", "Id": "410129", "Score": "0", "body": "There, made it huge and random. It's really awesome (at least for me) that gcc is still able to match performance of the fancy algorithm." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:40:22.877", "Id": "410134", "Score": "0", "body": "I did my tests with CLang and it is really almost the same. However, I would say that the result of the optimized version is as bad as the basic one with CLang. With MSVC 14.1 I get much better results with optimized code. Interesting, I have to investigate this. Thank you for pointing this out." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:37:08.677", "Id": "212096", "ParentId": "212088", "Score": "8" } }, { "body": "<p>In reply to \"Are there any other possible significant optimizations that could help the algorithm?\"</p>\n\n<p>I don't know, and it may have no effect at all, or even reduce performance, but I would like to know if reducing the apparent number of array operations improves performance, for example change</p>\n\n<pre><code> if (arr[m1] == search) return m1;\n if (arr[m2] == search) return m2;\n\n if (arr[m1] &lt; search) {\n if (arr[m2] &lt; search) {\n</code></pre>\n\n<p>to</p>\n\n<pre><code> Type am1 = arr[m1], am2 = arr[m2];\n if (am1 == search) return m1;\n if (am2 == search) return m2;\n\n if (am1 &lt; search) {\n if (am2 &lt; search) {\n</code></pre>\n\n<p>Apart from that, with regard to \"Are there any other comments about my code?\" could I suggest using say <code>left</code> and <code>right</code> instead of <code>l</code> and <code>r</code> as variable names. <code>l</code> is very easy to mistake for <code>1</code>!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T22:23:23.307", "Id": "212105", "ParentId": "212088", "Score": "1" } }, { "body": "<h1>Prefetch version does nothing with optimizer turned on.</h1>\n\n<p>Since you are not using m1 and m2, compiler will eliminate them. You get identical codegen see <a href=\"https://godbolt.org/z/wahP5j\" rel=\"nofollow noreferrer\">here</a></p>\n\n<h1>Branchs</h1>\n\n<p>Rearranging the conditions appear to speed up the code by 20%, making basic case almost the same as duo version. Note the conditions are already swapped for duo version, this may explain some of its performance. It appears the less than branch is more common and allow other condition to be skipped.</p>\n\n<pre><code>if (arr[m] &lt; search) l = m + 1;\nelse if (arr[m] == search) return m;\nelse r = m - 1;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T07:04:08.267", "Id": "410349", "Score": "0", "body": "True, I agree. The main issue here is why MSVC compiler is so bad on the basic version when compared to CLang/Gcc or when compared to the duo version (and note that it is only the case of MSVC on out of the CPU data)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T05:49:32.943", "Id": "410905", "Score": "0", "body": "@RadimBača oh I just had an interesting observation. See my edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:30:10.857", "Id": "410916", "Score": "0", "body": "Yes, you are right! The order of the conditions seems to cause significant slowdown. There are still some questions left but thank you for the observation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:28:20.727", "Id": "410938", "Score": "0", "body": "The careful calculation of mean isn't a performance hack - it's to ensure correctness (avoiding overflow)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:35:10.280", "Id": "410940", "Score": "0", "body": "See [The curious case of Binary Search — The famous bug that remained undetected for 20 years](https://thebittheories.com/the-curious-case-of-binary-search-the-famous-bug-that-remained-undetected-for-20-years-973e89fc212?gi=314801aff944), for instance." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T01:11:15.117", "Id": "212180", "ParentId": "212088", "Score": "3" } } ]
{ "AcceptedAnswerId": "212096", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:43:24.690", "Id": "212088", "Score": "6", "Tags": [ "c++", "performance", "binary-search" ], "Title": "Binary search for students" }
212088
<p>Given a <code>DbSet&lt;Client&gt;</code> from an Entity Framework 6 <code>DbContext</code>, I need to count the number of related <code>Ticket</code>s of each type: <code>Open</code>, <code>Responded</code>, and <code>Resolved</code>. </p> <p>The below code works, and results in only one query (according to <code>DbContext.Database.Log</code>), as desired. However, the fact that the call to <code>GroupBy</code> results in an <code>IGrouping&lt;Client, ICollection&lt;Ticket&gt;&gt;</code>, which is also an <code>IEnumerable&lt;ICollection&lt;Ticket&gt;&gt;</code>, requires me to call <code>FirstOrDefault()</code>, even though there is always only one <code>ICollection&lt;Ticket&gt;</code>. </p> <p>I've never used <code>GroupBy</code> before, so I'm willing to bet I'm just misusing it. </p> <pre><code>public IEnumerable&lt;DashboardItemViewModel&gt; GetItems(IQueryable&lt;Client&gt; clients) { return clients .Where(cli =&gt; cli.IsActive) .GroupBy(cli =&gt; cli, cli =&gt; cli.Tickets) .Select(grp =&gt; new DashboardItemViewModel { Id = grp.Key.Id, Name = grp.Key.Name, Open = grp.FirstOrDefault().Count(t =&gt; t.Status == StatusType.Open &amp;&amp; !t.IsArchived), Responded = grp.FirstOrDefault().Count(t =&gt; t.Status == StatusType.Responded &amp;&amp; !t.IsArchived), Resolved = grp.FirstOrDefault().Count(t =&gt; t.Status == StatusType.Resolved &amp;&amp; !t.IsArchived), }); } public enum StatusType { Open, Responded, Resolved, }; public class DashboardItemViewModel { public int Id { get; set; } public string Name { get; set; } public int Open { get; set; } public int Responded { get; set; } public int Resolved { get; set; } } public class Client { public int Id { get; set; } public string Name { get; set; } public bool IsActive { get; set; } public virtual ICollection&lt;Ticket&gt; Tickets { get; set; } } public class Ticket { public int Id { get; set; } public StatusType Status { get; set; } public bool IsArchived { get; set; } public virtual Client Client { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T00:14:56.427", "Id": "410161", "Score": "0", "body": "@tinstaafl I don't see how that's relevant." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T00:19:10.203", "Id": "410164", "Score": "0", "body": "@tinstaafl Obviously my question is unclear. What can I explain? \"How to retrieve a single result\" and \"counting related records with GroupBy\" seem like very different things." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:14:17.110", "Id": "410257", "Score": "0", "body": "*The below code works* -- Really? Doesn't `GroupBy(cli => cli, cli => cli.Tickets)` thow an exception? That would mean that `clients` is not an `IQueryable` originating from a `DbSet` but actually is an `IEnumerable`. Both with EF6 and EF-core, grouping by a collection should throw an exception. BTW, please indicate which EF version this is." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:18:13.490", "Id": "410258", "Score": "0", "body": "@GertArnold Really. Wouldn't it only be grouping by a collection if a collection is the key? It's EF6, I'll edit the post when I get a chance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:22:24.323", "Id": "410259", "Score": "0", "body": "Yes you're right, I missed the `cli => cli`." } ]
[ { "body": "<p>Your code does not work the way you think it does.</p>\n\n<blockquote>\n<pre><code>.GroupBy(cli =&gt; cli, cli =&gt; cli.Tickets)\n</code></pre>\n</blockquote>\n\n<p>This is not grouping anything because you are using the entire object as a key and since you are not providing any comparer for them each group will have exactly one item, itself.</p>\n\n<blockquote>\n<pre><code>.Select(grp =&gt;\n</code></pre>\n</blockquote>\n\n<p>Then from each one-itemed-group you select its single item with </p>\n\n<blockquote>\n<pre><code>grp.FirstOrDefault().Count(t =&gt; t.Status == StatusType.Open\n</code></pre>\n</blockquote>\n\n<p>This is probably very inefficient because the grouping isn't grouping anything and works like a <code>SELECT * FROM Table</code>.</p>\n\n<p>Instead you should rather be doing this. Select tickets from active clients, group them by their <code>Status</code>, calculate their <code>Count</code> and then create the view-model.</p>\n\n<pre><code> var ticketGroups = tickets\n .Where(ticket =&gt; ticket.Client.IsActive) \n .GroupBy(ticket =&gt; ticket.Status, tickets =&gt; tickets.Count())\n .ToList();\n\n return new DashboardItemViewModel\n {\n Id = grp.Key.Id,\n Name = grp.Key.Name,\n Open = ticketGroups.SingleOrDefault(tg =&gt; tg.Key == StatusType.Open &amp;&amp; !tg.IsArchived),\n Responded = ticketGroups.SingleOrDefault(tg =&gt; tg.Status == StatusType.Responded &amp;&amp; !tg.IsArchived),\n Resolved = ticketGroups.SingleOrDefault(tg =&gt; tg.Status == StatusType.Resolved &amp;&amp; !tg.IsArchived),\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:47:46.273", "Id": "410246", "Score": "0", "body": "Your code doesn't use a `DbSet<Client>` at all and doesn't return an `IEnumerable<DashboardItemViewModel>`. Could you please update your answer or explain your reasoning?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T09:13:10.153", "Id": "212127", "ParentId": "212089", "Score": "1" } }, { "body": "<p>You don't need the grouping at the <code>Client</code> level. No grouping at all, actually. Don't worry, <a href=\"https://stackoverflow.com/a/53951571/861716\">this is a common mistake</a> when people want grouping/aggregation in child collections. Per client, the <code>Tickets</code> can be counted: </p>\n\n<pre><code>return clients\n .Where(cli =&gt; cli.IsActive)\n .Select(cli =&gt; new DashboardItemViewModel\n {\n Id = cli.Id,\n Name = cli.Name,\n Open = cli.Tickets.Count(t =&gt; t.Status == StatusType.Open &amp;&amp; !t.IsArchived),\n Responded = cli.Tickets.Count(t =&gt; t.Status == StatusType.Responded &amp;&amp; !t.IsArchived),\n Resolved = cli.Tickets.Count(t =&gt; t.Status == StatusType.Resolved &amp;&amp; !t.IsArchived),\n });\n</code></pre>\n\n<p>Or in query syntax, so we can benefit from the <code>let</code> statement:</p>\n\n<pre><code>return from cli in clients\n where cli.IsActive\n let activeTickets = cli.Tickets.Where(t =&gt; !t.IsArchived)\n select new DashboardItemViewModel\n {\n Id = cli.Id,\n Name = cli.Name,\n Open = activeTickets.Count(t =&gt; t.Status == StatusType.Open),\n Responded = activeTickets.Count(t =&gt; t.Status == StatusType.Responded),\n Resolved = activeTickets.Count(t =&gt; t.Status == StatusType.Resolved)\n };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:10:47.097", "Id": "410288", "Score": "0", "body": "Makes sense, thanks. Do you have any idea if [SQL Server](https://hastebin.com/osupatapay.sql) will optimize those counts, i.e. loop once (like [this](https://hastebin.com/lohijapupi.cs) rather than once for each `StatusType` (like [this](https://hastebin.com/fozijijegi.cs))? If not, there's the possibility of doing the counting myself, rather than asking the database to... Also, is the benefit of `let` just clarity?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T20:04:32.510", "Id": "410293", "Score": "0", "body": "I can't see your links, but `let` doesn't improve the generated SQL. It's for clarity and for preventing repetitive code. The generated SQL will contain three `COUNT` subqueries. In a similar query I see that each subquey is executed separately. If there's a performance issue you could try to improve that by fetching an anon. type with `StatusTypes = activeTickets.Select(t => tStatusType)` and do grouping/counting of `StatusTypes` in memory. Can't tell if that will be any better." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T20:07:41.903", "Id": "410294", "Score": "0", "body": "... If there are many tickets per client the amount of data going over the wire may be significantly larger than a (maybe) slower counting query returning 3 numbers per client." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T20:45:17.420", "Id": "410299", "Score": "0", "body": "Sorry about that, not sure what's wrong with hastebin. The links were just examples to make sure what I was talking about was clear, but I think it's safe to say you understand. Thanks for your help, I'll go ahead and mark this as the solution." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:39:25.527", "Id": "212146", "ParentId": "212089", "Score": "2" } } ]
{ "AcceptedAnswerId": "212146", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T17:48:51.227", "Id": "212089", "Score": "1", "Tags": [ "c#", "linq", "entity-framework" ], "Title": "Using IQueryable.GroupBy to count related database entities" }
212089
<p>I am writing a bash script to mount openshift service accounts into kubernetes objects. The right <code>secret</code> to use is highlighted in this text: </p> <pre> $ oc describe sa sa-build-webhook-realworld Name: sa-build-webhook-realworld Namespace: your-eng2 Labels: app=sa-build-webhook-realworld Annotations: &lt;none&gt; Image pull secrets: sa-build-webhook-realworld-dockercfg-4qz9g Mountable secrets: <b>sa-build-webhook-realworld-token-bqtnw</b> sa-build-webhook-realworld-dockercfg-4qz9g Tokens: sa-build-webhook-realworld-token-bqtnw sa-build-webhook-realworld-token-k7lq8 Events: &lt;none&gt; </pre> <p>I want the code to be reasonably robust so I am thinking of this as a job for awk where I need "anything in column 2 that is a 'Mountable secret' that isn't the docker secret". Here is the logic I have come up with:</p> <pre><code>MOUNTABLE_SECRETS='Mountable secrets:' SECRET_NAME=$(\ oc describe sa sa-build-webhook-realworld \ | sed $(printf 's/./&amp;,/%s' ${#MOUNTABLE_SECRETS}) \ | awk 'BEGIN{FS=OFS=","} {if ($1 ~ /^[ \t]*$/) $1=ch; else ch=$1} 1' \ | grep "$MOUNTABLE_SECRETS" \ | sed 's/[, ]*//g' \ | awk -F':' '{print $2}' \ | grep -v docker \ | grep token) echo "SECRET_NAME=$SECRET_NAME" </code></pre> <p>Basically, I insert a character just beyond the width of that phrase to cut the table in half, copy cells on the left into blanks below, then select the second column then grep what I am looking for. </p> <p>To my mind, it breaks things into pieces that can be understood. It works, but past experiences have taught me that someone looking to maintain that may not be best pleased. Since performance is not an issue what I am really aiming for is maintainability. I also want portability and I am looking to stick with to typical bash and coreutils tools. </p> <p>How might I improve that script? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T18:53:51.197", "Id": "410094", "Score": "0", "body": "macOS comes with Python 2 pre-installed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T18:55:47.940", "Id": "410095", "Score": "0", "body": "fair enough but i am disinterested in worrying about the three major OSes and major linux distros. clearly someone submitting answers in whatever they think is a good fit works for me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T06:30:53.870", "Id": "410183", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see [what you may and may not do after receiving answers](http://meta.codereview.stackexchange.com/a/1765)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T06:33:23.020", "Id": "410184", "Score": "0", "body": "okay thanks for the advice and edit you could have saved yourself a few seconds by just pointing out what you said and i would have edited it myself :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T06:42:15.913", "Id": "410185", "Score": "0", "body": "Don't worry, we have a [bot for that](https://chat.stackexchange.com/transcript/message/48664370#48664370). :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T06:43:08.223", "Id": "410186", "Score": "0", "body": "as per the meta link i am advised to post a link to the code that i used and its revisions. currently, the code is in a how-to wiki page on github so its versioned and can be seen at https://github.com/ocd-scm/ocd-meta/wiki/Minishift/_history and the latest code is at version https://github.com/ocd-scm/ocd-meta/wiki/Minishift/ec200b236a73251459061aab0ee43010221d7911" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T06:59:44.007", "Id": "410188", "Score": "1", "body": "cool was the comment also a bot or handcrafted? my initial reading of it was that it was a bit harsh. i totally get why edits are not a good thing having read the meta post so i have absolutely no quibble over the bot reverting changes. yet i had a strong negative emotional response to being 'told off' when trying to share the joy of the solution. i would recommend something like \"Thanks for attempting to refine your question by incorporating feedback from answers, yet doing so goes against the Question + Answer style of Code Review so we automatically revert such changes. Please see ...\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T08:11:25.620", "Id": "410197", "Score": "1", "body": "@simbo1905 It's [from a list of common comment](https://codereview.meta.stackexchange.com/a/4978/21002). Sorry if it was a bit harsh, that was not my intention. Feel free to add the \"Thanks for attempting …\" to the post, that would be a nice addition :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T18:19:51.650", "Id": "410281", "Score": "0", "body": "Zeta talked about adding it, not modifying the existing one. I've rolled back your edit on that meta. If you want the comment to be included, post a new answer with the comment in it on the linked question." } ]
[ { "body": "<p>Your idea to transform the table so that the implied keys explicitly appear on every row is an interesting one, but I think that it is overcomplicated.</p>\n\n<p>The backslashes to indicate continuation lines are actually superfluous here, since an unfinished <code>$(</code> substitution automatically causes the command to be incomplete. Similarly, ending a line with a <code>|</code> pipe would also cause the command to be continued, so that would be a better convention to follow than putting the <code>|</code> at the beginning of the following line.</p>\n\n<p>In general, any combination of <code>sed</code>, <code>awk</code>, and <code>grep</code> would be better expressed using just an AWK script. The AWK script below reads a key and value if there is a colon on a line, or just a value if there is no colon.</p>\n\n<pre><code>SECRET_NAME=$(\n oc describe sa sa-build-webhook-realworld |\n awk -F: '\n $2 { KEY=$1 ; VALUE=$2; sub(\"^ *\", \"\", VALUE); }\n !$2 { VALUE=$1; sub(\"^ *\", \"\", VALUE); }\n KEY==\"Mountable secrets\" &amp;&amp; VALUE !~ /docker/ { print VALUE }\n '\n)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:25:56.633", "Id": "410100", "Score": "1", "body": "it’s a work of art!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T23:30:12.587", "Id": "410156", "Score": "1", "body": "can speed it up about 3x by not copying or trimming unused values: `awk -F': *' '$2 { KEY=$1 } KEY==\"Mountable secrets\" && $NF !~ /docker/ { print $NF }'`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T00:17:47.127", "Id": "410163", "Score": "2", "body": "@OhMyGoodness why not a separate answer?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T01:06:38.357", "Id": "410169", "Score": "1", "body": "It's only a refinement of what @200_success wrote; the algorithm is the same and he took the trouble to write good advice besides. He deserves the answer credit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T06:14:46.247", "Id": "410182", "Score": "0", "body": "okay i accepted the answer, i went with the `-F' *'` enhancement that allowed me to remove both sub calls. what an amazing thing awk is i am going to take the advice of not mixing awk with sed and grep ever. also the tip about sub shell continuations and even the formatting of awk blocks rocks. this experience has been a joy i really appreciate both your time you folks are awesome!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T19:20:24.510", "Id": "212095", "ParentId": "212092", "Score": "5" } } ]
{ "AcceptedAnswerId": "212095", "CommentCount": "9", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T18:41:54.520", "Id": "212092", "Score": "4", "Tags": [ "bash", "linux", "awk", "sed" ], "Title": "Select second field in text table with shell script" }
212092
<p>My brain is fried from looking from looking at this for so long. Is there a more efficient way to do this code block. We have the ability to use es6 code too if that helps. </p> <p>First it tries to set quantity to <code>itemTemplateIDQty.value</code> if <code>itemTemplateQty</code> is not valid and <code>itemTemplateIDQty</code> is valid. Then it basically checks the opposite and sets quantity to <code>itemTemplateQty.value</code>. I'm thinking since in that else block, I am simply checking the exact opposite, I shouldn't need to retype all that code again. Also I'm wondering if I can remove a lot of code by using something like <code>quantity = itemTemplateIDQty.value || 1;</code>.</p> <p><strong>Update</strong> I'll try to sum up the code more clearly. The default value for <code>quantity</code> should be 1 if all the checks fail. First if there are no classes of <code>itemTemplateQty</code> found and 1+ classes of <code>'itemTemplateQty' + itemId</code> found then set quantity to the value of the first class found of <code>'itemTemplateQty' + itemId</code>. If that check fails, then check if no classes of <code>'itemTemplateQty' + itemId</code> are found and 1+ classes of <code>itemTemplateQty</code> are found, set <code>quantity</code> to the value of the first class of <code>itemTemplateQty</code>.</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>let itemId = 5; let isDynamicRecommendation = false; let itemTemplateQty = document.getElementsByClassName('itemTemplateQty').length &gt; 0 ? document.getElementsByClassName('itemTemplateQty') : null; let itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemId).length &gt; 0 ? document.getElementsByClassName('itemTemplateQty' + itemId) : null; let quantity = 1; if (!isDynamicRecommendation) { if ((itemTemplateQty === null || itemTemplateQty.value == null || Number.parseInt(itemTemplateQty.value) &lt;= 0) &amp;&amp; (itemTemplateIDQty !== null &amp;&amp; itemTemplateIDQty.value !== undefined &amp;&amp; itemTemplateIDQty.value !== null &amp;&amp; Number.parseInt(itemTemplateIDQty.value) &gt; 0)) { quantity = itemTemplateIDQty.value; } else if ((itemTemplateIDQty === null || itemTemplateIDQty.value == null || Number.parseInt(itemTemplateIDQty.value) &lt;= 0) &amp;&amp; (itemTemplateQty !== null &amp;&amp; itemTemplateQty.value !== undefined &amp;&amp; itemTemplateQty.value !== null &amp;&amp; Number.parseInt(itemTemplateQty.value) &gt; 0)) { quantity = itemTemplateQty.value; } } console.log("quantity: ", quantity);</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:12:12.303", "Id": "410125", "Score": "1", "body": "Hey, welcome to Code Review! Please add some more information about what this code does and what the objects in it are (preferably with definitions). Don't forget to take the [tour] and have a look at our [help] which contains a lot on what makes a good question here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:33:38.990", "Id": "410130", "Score": "0", "body": "I added more details to the question. Let me know if anything else is needed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:34:18.857", "Id": "410131", "Score": "2", "body": "As Graipher said, you should provide more context for this code — ideally a live demo including the HTML form (press Ctrl-M in the question editor to make one). How many elements of class `itemTemplateQty` and `itemTemplateQty123` should there be? What is the expected behavior if there are none, or if there are more than one?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:36:04.130", "Id": "410132", "Score": "3", "body": "Instead of reiterating what the code does, try telling us what goal of the code is, as if talking to a non-technical person." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T04:05:50.330", "Id": "410177", "Score": "2", "body": "The current question title, which states your concerns about the code, is too general to be useful here. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly." } ]
[ { "body": "<p><code>.getElementsByClassName()</code> returns an <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection\" rel=\"nofollow noreferrer\"><code>HTMLCollection</code></a>, not a single element. You can use bracket notation <code>[n]</code> to get an element at index <code>n</code> of the collection returned.</p>\n\n<p>One <code>if</code> statement can be used to evalaute <code>!itemData.isDynamicRecommendation</code>. One <code>if..else..if</code> can be used to evaluate <code>itemTemplateQty[0] &amp;&amp; itemTemplateQty[0].value &lt;= 0</code> or <code>itemTemplateIDQty[0] &amp;&amp; itemTemplateIDQty[0].value &lt;= 0</code>.</p>\n\n<p>To convert the string <code>.value</code> to an integer you can use <code>+</code> operator preceding <code>+itemTemplateQty[0].value.value</code> or alternatively use <code>.valueAsNumber</code>.</p>\n\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>let itemData = 5;\nlet isDynamicRecommendation = false;\n\nlet itemTemplateQty = document.getElementsByClassName('itemTemplateQty')[0];\nlet itemTemplateIDQty = document.getElementsByClassName('itemTemplateQty' + itemData)[0];\nlet quantity = 1;\nif (!isDynamicRecommendation) {\n if (itemTemplateQty &amp;&amp; itemTemplateQty.value &lt;= 0) {\n quantity = +itemTemplateQty.value;\n } else if (itemTemplateIDQty &amp;&amp; itemTemplateIDQty.value &lt;= 0) {\n quantity = +itemTemplateIDQty.value;\n }\n}\n\nconsole.log({quantity});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:45:53.587", "Id": "410136", "Score": "0", "body": "Wouldn't you want this and the next one to be `||` not `&&`? `if (itemTemplateQty && itemTemplateQty[0].value <= 0) {`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:47:28.383", "Id": "410137", "Score": "0", "body": "@dmikester1 Not sure what you mean?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:48:13.323", "Id": "410138", "Score": "0", "body": "the if and else if should have or's not and's I think" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:52:45.577", "Id": "410140", "Score": "0", "body": "@dmikester1 `if..else` could essentially be considered an OR gate. The code could be re-written many different ways. For example, conditional operator could be substituted for `if` and `if..else`. One issue with the code at the question was not using bracket notation to get a specific element in the returned collection, resulting in false positive results. Is `quantity` expected to be an integer or a string?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:59:41.497", "Id": "410144", "Score": "0", "body": "`quantity` should be an integer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T22:02:39.327", "Id": "410145", "Score": "0", "body": "@dmikester1 The string returned by `.value` of a `DOM` element can be converted to an integer using the `+` operator. Alternatively you can use `.valueAsNumber`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T22:03:35.373", "Id": "410146", "Score": "0", "body": "so both those inner if and else if checks will handle null and undefined values for `itemTemplateQty` and `itemTemplateQty.value` and `itemTemplateIDQty` and `itemTemplateIDQty.value` ?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T22:06:02.253", "Id": "410149", "Score": "0", "body": "Basically if all 4 of those variables/objects are any combination of null and/or undefined, `quantity` will drop through and remain 1?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T22:06:45.590", "Id": "410150", "Score": "0", "body": "@dmikester1 Given that the code at the question uses `.getElementsByClassName()`, `document.getElementsByClassName('itemTemplateQty')[0]` returns `undefined` if the element is not in the `document`. If an element does not have a `.value` an empty string `\"\"` is returned, which evaluates \"falsey\". Why would `\"null\"` be the `.value` of the element?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T22:20:07.200", "Id": "410152", "Score": "0", "body": "Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/88706/discussion-between-dmikester1-and-guest271314)." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:42:30.010", "Id": "212103", "ParentId": "212099", "Score": "2" } }, { "body": "<p>Without the HTML it is hard to workout what is wanted. </p>\n\n<h1>General point</h1>\n\n<ul>\n<li>Use <code>const</code> for variables that do not change.</li>\n<li>Use functions to do common tasks, they simplify the code by reducing its size.</li>\n<li>Don't test more that you need to. If a is true then you know its not false, you don't then test if its not false.</li>\n<li>The statement <code>if (!isDynamicRecommendation) {</code> is always true and not needed. (A reminder that at codeReview code must not be example code, we assume this is production code)</li>\n<li>Use <code>querySelector</code> if you are after just the first instance of an element. It returns <code>null</code> if nothing is found.</li>\n<li>The code given should be as a function.</li>\n<li><p>Names ar poor and too verbose. We read words by their shape especially when they are more than half a dozen characters long. Long names means it's hard to spot errors. This is especially bad in JS as it does not care if you use an undefined variable names.</p>\n\n<ul>\n<li><p><code>itemTemplateQty</code> and <code>itemTemplateIDQty</code> if you have a single line with these variables repeated 7 times. Can you spot the error in the following? <code>itemTemplateQty, itemTemplateQty, itemTemplateQty, itemTemplateIDQty, itemTemplateIDQty, itemTemplate1DQty, itemTemplateIDQty</code></p>\n\n<p>You know its an <code>item</code>. the <code>template</code> part is irrelevant, the only important part is to differentiate the ID (BTW <code>Id</code> should have a lowercase <code>d</code>), <code>qty</code> and <code>qtyId</code> would be better. </p>\n\n<p>Now spot the same error <code>qty, qty, qty, qtyId, qtyId, qty1d, qtyId</code></p></li>\n<li><p><code>itemId</code>??? Have no idea what this actually is?</p></li>\n</ul></li>\n</ul>\n\n<h2>Example</h2>\n\n<p>By using two functions we can greatly reduce the complexity of the code. Removing the overly verbose names also make things easier on the eyes, and helps prevent brain fry.</p>\n\n<pre><code>function getQuantity() {\n const query = id =&gt; document.querySelector(\".itemTemplateQty\" + id);\n const valid = item =&gt; item &amp;&amp; !isNaN(item.value) &amp;&amp; Number(item.value) &gt; 0.5;\n const qty = query(\"\"), qtyId = query(\"5\");\n return Math.round(valid(qty) ? \n (!valid(qtyId) ? qty.value : 1) : \n ( valid(qtyId) ? qtyId.value : 1));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:53:14.093", "Id": "410248", "Score": "0", "body": "Thank you. These tips help a ton. I set `itemId` and `isDynamicRecommendation` arbitrarily just to get a working example like was asked. They are actually passed in variables from the calling function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:59:23.113", "Id": "410250", "Score": "0", "body": "Can you explain the return statement in detail? That looks very complicated to me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:31:04.807", "Id": "410262", "Score": "0", "body": "@dmikester1 It a ternary expression. Same as the following statement `if (valid(qty)) { if (! valid(qtyId)) { return Math.round(qty.value) } else if (valid(qtyId)) { return Math.round(qtyId.value) } return 1;` For more on ternaries https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T01:20:36.093", "Id": "212110", "ParentId": "212099", "Score": "1" } } ]
{ "AcceptedAnswerId": "212103", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T20:33:36.827", "Id": "212099", "Score": "0", "Tags": [ "javascript" ], "Title": "javascript - consolidate multiple null/undefined checks" }
212099
<p>Probably many people had to work with multithreaded applications with C++ and can understand how messy can be fine-grained locking of objects.</p> <p>So once in a while I came to idea of implementing some proxy objects using a so-called "drill down" property of <code>operator-&gt;</code> and RAII in mind.</p> <p>Yes. There is <em>some</em> implementations that do something like that but I didn't find something that fully satisfy me or at least something battle tested but not bloated.</p> <p>Here I want to show and discuss working prototype for shared locking of objects that works as simple as that:</p> <pre class="lang-cpp prettyprint-override"><code>&lt;...&gt; class dummy { public: dummy(std::string p) : p_(p) { } std::string to_string() const { return p_; } void set_string(std::string str) { p_ = str; } private: std::string p_; }; &lt;...&gt; // there it is shared_lock_wrap&lt;dummy&gt; data("hello"); { auto p = data.get(); // p-&gt;set_string("hello, world"); // will cause an error std::cout &lt;&lt; "ro access: " &lt;&lt; p-&gt;to_string() &lt;&lt; std::endl; } auto p = data.get_mutable(); p-&gt;set_string("hello, stackexchange"); std::cout &lt;&lt; "rw access: " &lt;&lt; p-&gt;to_string() &lt;&lt; std::endl; &lt;...&gt; </code></pre> <p>If you're still interested there is implementation of <code>shared_lock_wrap</code> that was used earlier. This should work with any decent C++14 compiler (I used GCC 8.2):</p> <pre class="lang-cpp prettyprint-override"><code>template&lt; typename T, typename _TMtx, template&lt;typename&gt; class _TLock, template&lt;typename&gt; class _TMutLock &gt; class lock_wrap_impl { template&lt;typename W&gt; using mimic_unique = typename std::conditional&lt; std::is_move_constructible&lt;W&gt;::value, W, std::unique_ptr&lt;W&gt; &gt;::type; using mutex_type = std::unique_ptr&lt;_TMtx&gt;; using lock_type = mimic_unique&lt;_TLock&lt;_TMtx&gt; &gt;; using mutable_lock_type = mimic_unique&lt;_TMutLock&lt;_TMtx&gt; &gt;; template&lt;bool M, typename W&gt; using mimic_const = typename std::conditional&lt;M, W, const W&gt;::type; template&lt;typename L&gt; using is_mutable = typename std::is_same&lt;L, mutable_lock_type&gt;; template&lt;bool M=true&gt; using ptr_type = const std::shared_ptr&lt;mimic_const&lt;M, T&gt; &gt;; public: template&lt;typename L&gt; class proxy { public: ptr_type&lt;is_mutable&lt;L&gt;::value &gt; operator-&gt;() { return obj_; } proxy(proxy&lt;L&gt;&amp;&amp; other) : obj_(other.obj_), lock_(std::move(other.lock_)) {} private: friend lock_wrap_impl&lt;T, _TMtx, _TLock, _TMutLock&gt;; proxy(ptr_type&lt;&gt; obj, L&amp;&amp; lock) : obj_(obj), lock_(std::move(lock)) {} ptr_type&lt;&gt; obj_; L lock_; }; lock_wrap_impl(T&amp;&amp; obj) : obj_(&amp;obj), mtx_(mutex_type(new _TMtx)) {} template&lt;typename ...Args&gt; lock_wrap_impl(Args&amp;&amp; ...args) : obj_(new T(std::forward&lt;Args&gt;(args)...)), mtx_(mutex_type(new _TMtx)) {} lock_wrap_impl(lock_wrap_impl&lt;T, _TMtx, _TLock, _TMutLock&gt;&amp;&amp; other) : obj_(std::move(other.obj_)), mtx_(std::move(other.mtx_)) {} /** * For types that ARE move constructible * e.g std::shared_lock */ template&lt;typename Q = _TLock&lt;_TMtx&gt; &gt; proxy&lt;lock_type&gt; get(typename std::enable_if&lt;std::is_move_constructible&lt;Q&gt;::value&gt;::type* = 0) { return proxy&lt;lock_type&gt;(obj_, lock_type(*mtx_)); } template&lt;typename Q = _TMutLock&lt;_TMtx&gt; &gt; proxy&lt;mutable_lock_type&gt; get_mutable(typename std::enable_if&lt;std::is_move_constructible&lt;Q&gt;::value&gt;::type* = 0) { return proxy&lt;mutable_lock_type&gt;(obj_, mutable_lock_type(mtx_)); } /** * For types that aren't move constructible */ template&lt;typename Q = _TLock&lt;_TMtx&gt; &gt; proxy&lt;lock_type&gt; get(typename std::enable_if&lt;!std::is_move_constructible&lt;Q&gt;::value&gt;::type* = 0) { return proxy&lt;lock_type&gt;(obj_, lock_type(new Q(*mtx_))); } template&lt;typename Q = _TMutLock&lt;_TMtx&gt; &gt; proxy&lt;mutable_lock_type&gt; get_mutable(typename std::enable_if&lt;!std::is_move_constructible&lt;Q&gt;::value&gt;::type* = 0) { return proxy&lt;mutable_lock_type&gt;(obj_, mutable_lock_type(new Q(*mtx_))); } private: ptr_type&lt;&gt; obj_; mutex_type mtx_; }; template&lt;typename T&gt; using shared_lock_wrap = lock_wrap_impl&lt;T, std::shared_timed_mutex, std::shared_lock, std::unique_lock&gt;; </code></pre> <p>Worth to note that I'm aware that there's some drawbacks: I prefer to use shared locks (e.g <code>std::shared_mutex</code>/<code>shared_timed_mutex</code> or <code>boost</code> alternatives) but kept in mind that there are mutexes/lockers types that are "exclusively lockable" (like <code>std::lock_guard</code> with <code>std::mutex</code> or <code>boost::scoped_lock</code>) <em>but</em> latter doesn't work with this exact implementation due to equality of <code>_TLock</code> and <code>_TMutLock</code>. Though it works fine with shared locks so maybe it will be fixed at some point but that is not what I personally needed.</p> <p>So what do you guys think about it? About idea or code structure in general or basically anything that you think. Maybe you have some thoughts about how it can be optimized.</p> <p>Personally I'm mostly prefer <code>golang</code> for developing but due to job or some embedded applications I also work with C++ or (occasionally plain C).</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T07:41:40.863", "Id": "410194", "Score": "0", "body": "> but latter (like std::lock_guard) doesn't work due to equality of _TLock and _TMutLock..\n\nCodereview is about reviewing working code, not fixing broken / incomplete code. Your comments mention `std::lock_guard` ( `/* For types that aren't move constructible e.g. std::lock_guard*/`) as a feature, and then you say it isn't working in your text. You should edit your code to retain only what's working (edit it before you get an answer)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T07:48:38.467", "Id": "410195", "Score": "0", "body": "Well, I'm aware about that and did mention that main purpose was to provide interface for separate locking so it works as expected if you take it into consideration. Otherwise it may be frustrating if I just remove that comment and that note." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T08:18:52.590", "Id": "410199", "Score": "0", "body": "@papagaga is it ok now? I changed description a little so it shouldn't be inappropriate anymore. Though I don't want to remove parts of the code (lock_guard still can be used as `_TMutLock` but just not with std::mutex)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T08:26:14.917", "Id": "410202", "Score": "0", "body": "It looks fine! It might very well have been fine since the beginning, but the wording was misleading." } ]
[ { "body": "<p>I don't want to debate the usefulness of this utility class. I can provide some feedback which I think should allow you to make the code objectively more readable. Use C++14's additions to <code>type_traits</code>. That is you should e.g. use: <code>std::enable_if_t&lt;whatever&gt;</code> instead of <code>typename std::enable_if&lt;whatever&gt;::type</code>.<br>\nA question: is there any use case for explicitly specifying template parameter to <code>get</code> or <code>get_mutable</code>? If not, then you can omit adding the template parameter \nAnother minor suggestion (that is my personal preference) is to use <code>std::enable_if</code> in template parameters specification, in my opinion this makes easier to quickly take note of the function signature. Furthermore, you could do something like:</p>\n\n<pre><code> template&lt;typename Q&gt;\n using move_constructible = std::enable_if_t&lt;std::is_move_constructible_v&lt;Q&gt;&gt;;\n\n template&lt;typename = move_constructible&lt;_TLock&lt;_TMtx&gt;&gt;&gt;\n proxy&lt;lock_type&gt; get() {\n return proxy&lt;lock_type&gt;(obj_, lock_type(*mtx_));\n }\n\n template&lt;typename = move_constructible&lt;_TMutLock&lt;_TMtx&gt;&gt;&gt;\n proxy&lt;mutable_lock_type&gt; get_mutable() {\n return proxy&lt;mutable_lock_type&gt;(obj_, mutable_lock_type(mtx_));\n }\n</code></pre>\n\n<p>Of course if you don't feel like using C++17's <code>std::is_move_constructible_v</code> you can use C++11's <code>std::is_move_constructible&lt;&gt;::value</code>. If you want to preserve the ability for the caller to specify template arguments for those methods you can do this easily as well:</p>\n\n<pre><code> template&lt;typename Q = _TLock&lt;_TMtx&gt;, typename = move_constructible&lt;Q&gt;&gt;\n proxy&lt;lock_type&gt; get() {\n return proxy&lt;lock_type&gt;(obj_, lock_type(*mtx_));\n } \n</code></pre>\n\n<p>Same can be done for types that are not move constructible.<br>\nOne more: most probably you should not use names starting with underscore followed by uppercase letter, see <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:47:49.947", "Id": "212219", "ParentId": "212101", "Score": "1" } }, { "body": "<pre><code>template&lt;\n typename T,\n typename _TMtx,\n</code></pre>\n\n<p>Get off the standard library's lawn! <code>_Ugly</code> names are reserved to the implementation.</p>\n\n<pre><code> template&lt;typename&gt; class _TLock,\n template&lt;typename&gt; class _TMutLock\n&gt;\nclass lock_wrap_impl {\n\n template&lt;typename W&gt;\n using mimic_unique = typename std::conditional&lt;\n std::is_move_constructible&lt;W&gt;::value,\n W,\n std::unique_ptr&lt;W&gt;\n &gt;::type;\n</code></pre>\n\n<p>You tagged C++14, so <code>std::conditional_t</code>.</p>\n\n<pre><code> using mutex_type = std::unique_ptr&lt;_TMtx&gt;;\n using lock_type = mimic_unique&lt;_TLock&lt;_TMtx&gt; &gt;;\n using mutable_lock_type = mimic_unique&lt;_TMutLock&lt;_TMtx&gt; &gt;;\n\n\n template&lt;bool M, typename W&gt;\n using mimic_const = typename std::conditional&lt;M, W, const W&gt;::type;\n\n template&lt;typename L&gt;\n using is_mutable = typename std::is_same&lt;L, mutable_lock_type&gt;;\n</code></pre>\n\n<p>This is a pointless <code>typename</code>.</p>\n\n<pre><code> template&lt;bool M=true&gt;\n using ptr_type = const std::shared_ptr&lt;mimic_const&lt;M, T&gt; &gt;;\n</code></pre>\n\n<p>A more descriptive name for <code>M</code> may be a good idea. There's no reason to make this top-level <code>const</code> either.</p>\n\n<pre><code> public:\n template&lt;typename L&gt;\n class proxy {\n public:\n ptr_type&lt;is_mutable&lt;L&gt;::value &gt; operator-&gt;() { return obj_; }\n</code></pre>\n\n<p>This should be a <code>const</code> member.</p>\n\n<pre><code> proxy(proxy&lt;L&gt;&amp;&amp; other) :\n obj_(other.obj_),\n lock_(std::move(other.lock_))\n {}\n</code></pre>\n\n<p>This does nothing beyond what a defaulted move constructor does. Just default it. Also, use the injected-class-name: <code>proxy(proxy&amp;&amp;) = default;</code></p>\n\n<pre><code> private:\n friend lock_wrap_impl&lt;T, _TMtx, _TLock, _TMutLock&gt;;\n\n proxy(ptr_type&lt;&gt; obj, L&amp;&amp; lock) :\n obj_(obj),\n lock_(std::move(lock))\n {}\n\n ptr_type&lt;&gt; obj_;\n L lock_;\n };\n\n lock_wrap_impl(T&amp;&amp; obj) :\n obj_(&amp;obj),\n mtx_(mutex_type(new _TMtx))\n {}\n</code></pre>\n\n<p><code>obj_(&amp;obj)</code> is badly wrong. You are making a <code>shared_ptr</code> to some random rvalue.</p>\n\n<pre><code> template&lt;typename ...Args&gt;\n lock_wrap_impl(Args&amp;&amp; ...args) :\n obj_(new T(std::forward&lt;Args&gt;(args)...)),\n mtx_(mutex_type(new _TMtx))\n {}\n</code></pre>\n\n<p>This needs to be constrained. Also can use <code>make_shared</code>.</p>\n\n<pre><code> lock_wrap_impl(lock_wrap_impl&lt;T, _TMtx, _TLock, _TMutLock&gt;&amp;&amp; other) :\n obj_(std::move(other.obj_)),\n mtx_(std::move(other.mtx_))\n {}\n</code></pre>\n\n<p>This again is just a defaulted move constructor. Additionally, since you made <code>obj_</code> const, the first <code>move</code> is just a copy. Again, there's no need to make it <code>const</code>.</p>\n\n<pre><code> /**\n * For types that ARE move constructible\n * e.g std::shared_lock\n */\n\n template&lt;typename Q = _TLock&lt;_TMtx&gt; &gt;\n proxy&lt;lock_type&gt; get(typename std::enable_if&lt;std::is_move_constructible&lt;Q&gt;::value&gt;::type* = 0) {\n return proxy&lt;lock_type&gt;(obj_, lock_type(*mtx_));\n }\n\n template&lt;typename Q = _TMutLock&lt;_TMtx&gt; &gt;\n proxy&lt;mutable_lock_type&gt; get_mutable(typename std::enable_if&lt;std::is_move_constructible&lt;Q&gt;::value&gt;::type* = 0) {\n return proxy&lt;mutable_lock_type&gt;(obj_, mutable_lock_type(mtx_));\n }\n\n\n /**\n * For types that aren't move constructible\n */\n\n template&lt;typename Q = _TLock&lt;_TMtx&gt; &gt;\n proxy&lt;lock_type&gt; get(typename std::enable_if&lt;!std::is_move_constructible&lt;Q&gt;::value&gt;::type* = 0) {\n return proxy&lt;lock_type&gt;(obj_, lock_type(new Q(*mtx_)));\n }\n\n template&lt;typename Q = _TMutLock&lt;_TMtx&gt; &gt;\n proxy&lt;mutable_lock_type&gt; get_mutable(typename std::enable_if&lt;!std::is_move_constructible&lt;Q&gt;::value&gt;::type* = 0) {\n return proxy&lt;mutable_lock_type&gt;(obj_, mutable_lock_type(new Q(*mtx_)));\n }\n</code></pre>\n\n<p>This whole business of wrapping immovable locks in <code>unique_ptr</code> is excessively costly and not useful in practice. If someone chose to use <code>lock_guard</code>, it's because they don't want to pay the difference between <code>unique_lock</code> and <code>lock_guard</code>, which is a stored <code>bool</code> and a branch in the destructor. That's far, far less than the cost of a trip to the heap.</p>\n\n<pre><code> private:\n ptr_type&lt;&gt; obj_;\n mutex_type mtx_;\n};\n</code></pre>\n\n<p>There does not appear to be any reason why this class need to be movable, and your move constructor leaves it in an unusable \"emptier-than-empty\" state.</p>\n\n<hr>\n\n<p>Additional comments:</p>\n\n<ul>\n<li>Detecting mutable locks by <em>type</em> presupposes that the shared and mutable locks are not the same. There's no need to have that limitation, since your <code>proxy</code> can just be templated directly on something like <code>bool Mutable</code> instead.</li>\n<li>There's no reason to construct a lock and then move it into the proxy. Just pass the mutex and have the proxy's constructor construct the lock directly. You save a temporary, and it also plays well with C++17 by giving you support for immovable locks for free.</li>\n<li>There's also no reason to use a <code>shared_ptr</code> at all. The pointer obtained from <code>-&gt;</code> cannot safely outlive the proxy (because you'd be accessing the object while not holding the lock) and the proxy cannot safely outlive the wrapper object (or you'd be destroying a locked mutex and then unlocking a destroyed mutex; both are UB). Just store the object directly.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:24:17.113", "Id": "212224", "ParentId": "212101", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-23T21:13:48.197", "Id": "212101", "Score": "5", "Tags": [ "c++", "c++14", "concurrency", "wrapper", "raii" ], "Title": "Automatic RAII wrapper for concurrent access" }
212101
<p>I'm prepping for a tech interview coming up and trying to have a better understanding of what I should look out for in writing code. Also, feel free to correct the terminology that I use as I want to be able to talk about my code clearly and succinctly.</p> <p>One of the specifications for the tech interview process is that I use <em>idiomatic JavaScript</em>, according to the recruiter. I'm not familiar with that term and would appreciate any feedback on how to best write to that standard. Is there a specific standard that I should adhere to? Is that related to proper <em>naming conventions</em>?</p> <p>Is there a better way for me to optimize time and space in my code?</p> <p>When I assign values to variables within loops, are there rules that I should be aware of for when I shouldn't? For example, the current element being iterated over assigned to <code>currentH1</code> variable, in my mind, makes it more readable in understanding what's happening as opposed to <code>half1[h1Index]</code>, and I reuse it more than once. Plus, I believe this might make it more <em>idiomatic</em> but I'm not sure? Am I losing out on <em>space complexity</em> in any way? Or is there something that I may not be aware of by checking <code>current</code> against <code>undefined</code> instead of checking the current index against the size of the array?</p> <p>When I assign values to variables outside of loops but within the function, are there space complexities that I should pay attention to or does <em>garbage collection</em> take care of this? Is this <span class="math-container">\$O(1)\$</span> space complexity as I'm just keeping track of the indices? Feel free to breakdown <em>space complexity</em> as I truly do want to have a more solid understanding of memory management.</p> <p>I believe I've accounted for the <em>edge cases</em> that I can think of, but are there more that I should be aware of?</p> <p>I placed the if condition for checking lengths at the top even before the index definitions because I figured that if they aren't even the same size, why bother with doing anything else. Is that weird?</p> <pre><code>function isMergedArray(half1, half2, mergedArray) { if ((half1.length + half2.length) != mergedArray.length ) { return false; } let h1Index = half1.length - 1; let h2Index = half2.length - 1; let maIndex = mergedArray.length - 1; while (maIndex &gt;= 0) { const currentH1 = half1[h1Index]; const currentH2 = half2[h2Index]; const currentMa = mergedArray[maIndex]; if (currentH1 != undefined &amp;&amp; currentH1 === currentMa) { h1Index--; } else if (currentH2 != undefined &amp;&amp; currentH2 === currentMa) { h2Index--; } else { return false; } maIndex--; } return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T05:48:32.593", "Id": "410180", "Score": "0", "body": "(Welcome to Code Review!) 2¢: comment your code; automate tests." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:24:35.243", "Id": "410260", "Score": "0", "body": "Could you clarify what you mean by merging the arrays? The most obvious way to understand it would be that both sub-arrays are sorted and merged into a single larger sorted array but I don't usually like assuming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T17:38:01.043", "Id": "410275", "Score": "0", "body": "Assuming that merging arrays follows this: https://www.geeksforgeeks.org/number-ways-merge-two-arrays-retaining-order/ Then your first check is wrong, because `([1,2], [2,3], [1,2,3])` should return `true`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T04:11:58.487", "Id": "410329", "Score": "0", "body": "@greybeard thank you for the welcome and your 2¢. I removed comments from my code because I thought it looked to messy but I'll put them back in again to make them more clear. I did have tests for them on my github (https://github.com/ThuyNT13/algorithm-practice/blob/thuy-solution/tests/spec/isMergedArraySpec.js) but realize that I need to also add an edge case..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T04:16:29.943", "Id": "410330", "Score": "0", "body": "@konjin I did not test for number uniqueness and will try and update code as soon as possible. Thank you for that!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T04:30:29.883", "Id": "410332", "Score": "0", "body": "@MarcRohloff it would appear I need to do a better job of explaining my code. The larger array should maintain the order of the sub arrays. Thank you for asking for clarifications. If there's anything else that seems muddled, please feel free to nudge me in the right direction :)" } ]
[ { "body": "<blockquote>\n <p>I placed the if condition for checking lengths at the top even before the index definitions because I figured that if they aren't even the same size, why bother with doing anything else. Is that weird?</p>\n</blockquote>\n\n<p>No I don't think that is weird. I would consider it a good optimization.</p>\n\n<p>Personally I think the code is mostly fine, a good starting point would be to Google some examples on how to merge sub-arrays since that is fairly similar.</p>\n\n<p>My one question would be why you started at the end of the array and merged them in descending order. That is kind of strange to me. I would do it in ascending order. I would also use a <code>for</code> loop instead of a <code>while</code> loop. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T04:37:31.207", "Id": "410333", "Score": "0", "body": "Mostly because I was lead to believe that JavaScript descending `while` loops are faster than for-loops because of two questions on StackOverflow: [Javascript Performance: While vs For Loops](https://stackoverflow.com/questions/18640032/javascript-performance-while-vs-for-loops) and [JavaScript loop performance - Why is to decrement the iterator toward 0 faster than incrementing](https://stackoverflow.com/questions/3520688/javascript-loop-performance-why-is-to-decrement-the-iterator-toward-0-faster-t)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T04:45:27.877", "Id": "410334", "Score": "0", "body": "But I think also, in my mind at the time, I was thinking of the arrays more as stacks, as the original problem was a stack of cards. An earlier solution was to keep track of elements by popping them off the stack, so iterating through in descending order made more sense, to my mind." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:28:07.277", "Id": "212145", "ParentId": "212112", "Score": "0" } }, { "body": "<p><em>Is there a specific standard that I should adhere to?</em></p>\n\n<p>Pick one, and stick to it. I use this one: <a href=\"https://github.com/airbnb/javascript\" rel=\"nofollow noreferrer\">https://github.com/airbnb/javascript</a></p>\n\n<p><em>One of the specifications for the tech interview process is that I use idiomatic JavaScript</em></p>\n\n<p>I understand that as follow the community conventions for writing code. Using a common standard helps.</p>\n\n<p><em>Is there a better way for me to optimize time and space in my code?</em></p>\n\n<p>I does not get much better than this, though you could drop the use of <code>currentH1</code>, <code>currentH2</code>, and <code>currentMa</code>.</p>\n\n<p><em>When I assign values to variables within loops, are there rules that I should be aware of for when I shouldn't?</em></p>\n\n<p>In my mind, if you are going to use the assigned value only once, then it does not make sense to assign it.</p>\n\n<p><em>Is there something that I may not be aware of by checking current against undefined instead of checking the current index against the size of the array?</em></p>\n\n<p>Absolutely, your code breaks in a test case where the array contains <code>undefined</code> as a value</p>\n\n<p><em>When I assign values to variables outside of loops but within the function, are there space complexities that I should pay attention to or does garbage collection take care of this?</em></p>\n\n<p>Nah</p>\n\n<p><em>Is this O(1) space complexity as I'm just keeping track of the indices?</em></p>\n\n<p>That is my understanding</p>\n\n<p><em>I believe I've accounted for the edge cases that I can think of, but are there more that I should be aware of?</em></p>\n\n<p>As I mentioned, dupe values across the two halfs. It changes the paradigm of the routine completely. Also, as mentioned before, an array with <code>undefined</code> as a value.</p>\n\n<p><code>I placed the if condition for checking lengths at the top even before the index definitions because I figured that if they aren't even the same size, why bother with doing anything else. Is that weird?</code></p>\n\n<p>Not at all, however I only do this in functions that are very frequently called. </p>\n\n<p>Other than, I tried to write this 'the proper way' by checking from the first value to the last, and it looked worse.</p>\n\n<p>From a naming convention, <code>mergedArray</code> is a bit of misnomer, you don't whether it is a merged array.</p>\n\n<p>It annoys me personally that you assign a value to <code>currentH1</code> in a loop, but then declare it as <code>const</code>. It is not wrong technically, but it reads wrong to me.</p>\n\n<p>I rewrote the code a bit with my comments in mind:</p>\n\n<pre><code>function isMergedArray(half1, half2, list) {\n if ((half1.length + half2.length) != list.length ) {\n return false;\n }\n\n let i = list.length - 1,\n h1 = half1.length - 1,\n h2 = half2.length - 1;\n\n while (i &gt;= 0) {\n\n let currentElement = list[i];\n\n if (h1 != -1 &amp;&amp; half1[h1] === currentElement) {\n h1--;\n } else if (h2 != -1 &amp;&amp; half2[h2] === currentElement) {\n h2--;\n } else {\n return false;\n }\n i--;\n }\n\n return true;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T02:03:59.187", "Id": "410892", "Score": "0", "body": "Thank you for the breakdown @konjin! Just to clarify, is it better to use `let` i/o `const` inside the loop because it's an item that changes - granted within that block scope, it doesn't - so from the matter of semantics, it's not good to use `const`. Or is it because, a `const` is a weird thing to have inside a loop?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T02:05:10.310", "Id": "410893", "Score": "0", "body": "also, as far as naming conventions, is it assumed that whenever I use `i` and `j`, that those refer to indices?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T14:10:41.167", "Id": "410980", "Score": "0", "body": "1. It's just a weird to have a changing value in a loop 2. indices or generic integers" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T18:39:01.663", "Id": "212335", "ParentId": "212112", "Score": "0" } } ]
{ "AcceptedAnswerId": "212335", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T02:01:11.077", "Id": "212112", "Score": "1", "Tags": [ "javascript", "performance", "algorithm", "memory-optimization" ], "Title": "Check whether an array can be the result of merging two smaller arrays, maintaining order" }
212112
<p>I'm trying to solve <a href="https://projecteuler.net/problem=86" rel="nofollow noreferrer">problem 86</a> in Project Euler. After some tinkering, I managed to unroll the DP solution into a loop. But still the solution takes >150s to complete. What can I do to improve the performance of this algorithm?</p> <pre><code>(defn- square [n] (* n n)) (defn- is-perfect-square? [n] (let [sq (int (Math/sqrt n))] (= n (* sq sq)))) ;; See: https://math.stackexchange.com/a/1189884/7078 (Second case) ;; So lengths = [sqrt(l^2 + b^2 + h^2 + 2bh), sqrt(l^2 + b^2 + h^2 + 2lb), sqrt(l^2 + b^2 + h^2 + 2lh)] ;; Shortest length is the smallest of the above. == sqrt(l^2 + b^2 + h^2 + min(2bh, 2lb, 2lh)) (defn- shortest-cuboid-dist-has-int-length? ([a b c] (-&gt;&gt; (min (* a b) (* b c) (* c a)) (* 2) (+ (square a) (square b) (square c)) (is-perfect-square?))) ([[a b c]] (shortest-cuboid-dist-has-int-length? a b c))) ;; if F(n) denotes number of integer shortest lengths for cuboids with dimensions equal to or less than (n,n,n), ;; F(i+1) = F(i) + int_lengths(cuboids with at least one side dimension of i+1) (defn- get-int-dist-above [lim] (loop [dim 0 c 0 i 1 j 1] (cond (&gt; c lim) dim (= i (inc dim)) (recur (inc dim) c 1 1) (= j (inc i)) (recur dim c (inc i) 1) :else (recur dim (if (shortest-cuboid-dist-has-int-length? dim i j) (inc c) c) i (inc j))))) (defn problem-86 [] (get-int-dist-above 1000000)) (time (problem-86)) ;; Takes 150s </code></pre>
[]
[ { "body": "<p>Given: 1 ≤ a ≤ b ≤ c = M, </p>\n\n<p>then, <code>min(a*b, b*c, a*c) == a*b</code></p>\n\n<p>This means, you can remove 2 multiplications and the <code>min</code> operation from <code>shortest-cuboid-dist-has-int-length?</code> as long as you pass your room’s length, width, and height in the proper order.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T09:21:08.760", "Id": "410209", "Score": "1", "body": "In practical terms, replace `(min (* a b) (* b c) (* c a))` with `(* b c)`. In my timing tests with `lim 70000` this reduces the time from about 8 seconds to about 4 secs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:42:23.430", "Id": "410243", "Score": "0", "body": "@PeterTaylor Ah! `b` & `c` are the shorter dimensions; `a` is the longest. I couldn’t grok the clojure syntax enough to figure out what was happening in that loop. Thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:45:39.120", "Id": "410245", "Score": "0", "body": "@PeterTaylor “about 8 seconds to about 4 secs” sounds like about double the performance. Not bad for a “micro-optimization” :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:59:38.247", "Id": "410251", "Score": "0", "body": "Not bad at all, especially given how counterintuitive micro-optimising Clojure seems to be. I thought it would be better to continue by combining `(* b c)(* 2)` into `(* b c 2)`, but the runtime jumped up to about 5.5 secs. I suspect that there's an optimiser which is turning `(* 2)` into a bit-shift, but I'm not certain." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T05:10:53.557", "Id": "212119", "ParentId": "212114", "Score": "2" } }, { "body": "<h3>Micro-optimisation</h3>\n\n<p>AJNeufeld's answer removes two multiplications and a <code>min</code> from <code>shortest-cuboid-dist-has-int-length?</code>. The next step, which is a much bigger rewrite, is to remove the remaining multiplications.</p>\n\n<p>Suppose you have cached the value of <span class=\"math-container\">\\${len}^2(dim, i, j) = {dim}^2 + i^2 + j^2 + 2ij\\$</span>. Now you increment <span class=\"math-container\">\\$j\\$</span>: <span class=\"math-container\">\\$j' = j + 1\\$</span>. Then <span class=\"math-container\">$$\\begin{eqnarray}{len}^2(dim, i, j') &amp;=&amp; {dim}^2 + i^2 + j'^2 + 2ij' \\\\\n&amp;=&amp; {len}^2({dim}, i, j) + 2(i + j) + 1 \\\\\n&amp;=&amp; {len}^2({dim}, i, j) + 2(i + j') - 1\\end{eqnarray}$$</span>\nSo instead of five multiplications you only need one.</p>\n\n<p>Similar caching of <span class=\"math-container\">\\${len}^2(dim, i, 1)\\$</span> allows you to optimise the calculation of <span class=\"math-container\">\\${len}^2(dim, i+1, 1)\\$</span>, and caching <span class=\"math-container\">\\${len}^2(dim, 1, 1)\\$</span> allows you to optimise the calculation of <span class=\"math-container\">\\${len}^2(dim+1, 1, 1)\\$</span>.</p>\n\n<hr>\n\n<h3>Algorithmic optimisation</h3>\n\n<p>I don't want to go into too much detail here because I'm conscious of the ethos of Project Euler, but I think there are some things I can reasonably propose.</p>\n\n<p>Rewrite as <span class=\"math-container\">\\${len}^2 = {dim}^2 + (i+j)^2\\$</span> where <span class=\"math-container\">\\$2 \\le i+j \\le 2{dim}\\$</span>. You could use a double loop rather than a triple one, and if you find a value <span class=\"math-container\">\\$2 \\le s \\le 2{dim}\\$</span> for which <span class=\"math-container\">\\${dim}^2 + s^2\\$</span> is a perfect square then increment the count of solutions by the number of integer values of <span class=\"math-container\">\\$i\\$</span> for which <span class=\"math-container\">\\$1 \\le i \\le s - i \\le dim\\$</span>.</p>\n\n<p>Then instead of looping over <span class=\"math-container\">\\${dim}\\$</span> and <span class=\"math-container\">\\$s\\$</span> and testing whether they're the shorter legs of a Pythagorean triple, you could look for a way to generate Pythagorean triples and test whether their shorter legs meet the constraints. With a good generation process this is probably the fastest option.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:36:45.537", "Id": "410264", "Score": "0", "body": "I actually went in the way of using a previous solution which required generating Pythagorean triples, but gave up halfway because I couldn't figure out how to vary `dim`. Perhaps I can give a try again. Thank you for all the suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T09:32:05.537", "Id": "212129", "ParentId": "212114", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T03:00:13.353", "Id": "212114", "Score": "2", "Tags": [ "performance", "programming-challenge", "clojure" ], "Title": "Project Euler problem 86 taking a long time" }
212114
<h2>Introduction</h2> <p>If you know what FDF files are, you can skip this section.</p> <p>PDF files sometimes includes form fields. These fields can be represented as FDF in plain text form, extracted using certain utilities. Important things to note about this file are:</p> <p>A field is represented by</p> <pre><code>/V () /T (Field) </code></pre> <p>where "Field" is the field name and whatever is written within the parenthesis next to /V will become the input for the utility that will fill the form.</p> <p>It is possible for there to be nested fields of arbitrary depth. A basic example is</p> <pre><code>/Kids [ &lt;&lt; /V () /T (node1) &gt;&gt; &lt;&lt; /V () /T (node2) &gt;&gt;] /T (root) </code></pre> <p>Here there are two fields <code>node1</code> and <code>node2</code> both nested under root. When fields are nested, names that are seen by a user are the components of the hierarchy, separated by <code>.</code>s. For instance name of <code>node1</code> is <code>root.node1</code>.</p> <h2>The code</h2> <p>The big picture goal of this is to identify the lines that need to be modified when a user provides a bunch of field names (eg. <code>Field</code>, <code>root.node1</code>)</p> <p>This code reads the FDF file and marks the lines that should be modified to fill a field of a given name. The way I do it involves iterating every line to detect the tree roots and append the name of the roots to every child. Since this will end up in CRAN I want to make sure the approach isn't overly convoluted.</p> <pre class="lang-r prettyprint-override"><code>fdfAnnotate = function(fdfLines){ fields = vector(length = length(fdfLines),mode= 'character') nests = 0 # iterate over every line for (i in seq_along(fdfLines)){ if(grepl('/T \\(',fdfLines[i])){ # /T represents a field or a root name # take the name name = stringr::str_extract(fdfLines[i],'(?&lt;=\\().*?(?=\\))') if(grepl('/V',fdfLines[i-1])){ # if the line before the naming line starts with /V # there is no hierarhcy, just name the line fields[i-1] = name } else if(grepl('&gt;&gt;\\]',fdfLines[i-1])){ # if the line above the name is &gt;&gt;] the name represents a root # start reading from the line above z = i-2 # this keeps track of the nest levels. # we will be reading the file backwards trying to # reach to the end of this root nest = 1 while(nest!=0){ if(grepl('/V',fdfLines[z])){ # if a field is found, append the name of the root to the left # separated by a "." fields[z] = paste0(name,'.',fields[z]) } else if(grepl('&gt;&gt;\\]',fdfLines[z])){ # if another nest stops, that means we are inside another root nest = nest + 1 } else if(grepl('/Kids \\[',fdfLines[z])){ # every time a root closes reduce the nest. if you reach 0 # it means its over nest = nest - 1 } # go back one line in the file. z = z - 1 } } } } data.frame(fdfLines,fields,stringsAsFactors = FALSE) } </code></pre> <h2>Usage</h2> <p>You can use it by doing</p> <pre class="lang-r prettyprint-override"><code>fdfLines = readLines([pathToFDFfile]) fdfAnnotate(fdfLines) </code></pre> <p>Below is the FDF file I use for my tests. It includes single and double layered hierarchies as well as a bunch of normal fields.</p> <pre><code>%FDF-1.2 %âãÏÓ 1 0 obj &lt;&lt; /FDF &lt;&lt; /Fields [ &lt;&lt; /V () /T (node1) &gt;&gt; &lt;&lt; /Kids [ &lt;&lt; /Kids [ &lt;&lt; /V () /T (node1) &gt;&gt; &lt;&lt; /V () /T (node3) &gt;&gt; &lt;&lt; /V () /T (node2) &gt;&gt;] /T (child) &gt;&gt; &lt;&lt; /Kids [ &lt;&lt; /V () /T (node1) &gt;&gt; &lt;&lt; /V () /T (node2) &gt;&gt;] /T (child2) &gt;&gt;] /T (hierarchy2) &gt;&gt; &lt;&lt; /V () /T (TextField1) &gt;&gt; &lt;&lt; /V () /T (TextField2) &gt;&gt; &lt;&lt; /V () /T (TextFieldPage2) &gt;&gt; &lt;&lt; /V () /T (List Box) &gt;&gt; &lt;&lt; /V () /T (TextFieldPage3) &gt;&gt; &lt;&lt; /Kids [ &lt;&lt; /V () /T (node1) &gt;&gt; &lt;&lt; /V () /T (node4) &gt;&gt; &lt;&lt; /V () /T (node3) &gt;&gt; &lt;&lt; /V () /T (node2) &gt;&gt;] /T (hierarchy) &gt;&gt; &lt;&lt; /V () /T (betweenHierarch) &gt;&gt; &lt;&lt; /V /Off /T (RadioGroup) &gt;&gt; &lt;&lt; /V /Off /T (checkBox) &gt;&gt;] &gt;&gt; &gt;&gt; endobj trailer &lt;&lt; /Root 1 0 R &gt;&gt; %%EOF </code></pre> <p>This file represents the form fields in <a href="https://www.dropbox.com/s/9xz6xkcutj2jhre/testForm.pdf?dl=0" rel="nofollow noreferrer">this</a> pdf file. </p> <p>Using my function, the output is:</p> <pre><code> fdfLines fields 1 %FDF-1.2 2 %âãÏÓ 3 1 0 obj 4 &lt;&lt; 5 /FDF 6 &lt;&lt; 7 /Fields [ 8 &lt;&lt; 9 /V () node1 10 /T (node1) 11 &gt;&gt; 12 &lt;&lt; 13 /Kids [ 14 &lt;&lt; 15 /Kids [ 16 &lt;&lt; 17 /V () hierarchy2.child.node1 18 /T (node1) 19 &gt;&gt; 20 &lt;&lt; 21 /V () hierarchy2.child.node3 22 /T (node3) 23 &gt;&gt; 24 &lt;&lt; 25 /V () hierarchy2.child.node2 26 /T (node2) 27 &gt;&gt;] 28 /T (child) 29 &gt;&gt; 30 &lt;&lt; 31 /Kids [ 32 &lt;&lt; 33 /V () hierarchy2.child2.node1 34 /T (node1) 35 &gt;&gt; 36 &lt;&lt; 37 /V () hierarchy2.child2.node2 38 /T (node2) 39 &gt;&gt;] 40 /T (child2) 41 &gt;&gt;] 42 /T (hierarchy2) 43 &gt;&gt; 44 &lt;&lt; 45 /V () TextField1 46 /T (TextField1) 47 &gt;&gt; 48 &lt;&lt; 49 /V () TextField2 50 /T (TextField2) 51 &gt;&gt; 52 &lt;&lt; 53 /V () TextFieldPage2 54 /T (TextFieldPage2) 55 &gt;&gt; 56 &lt;&lt; 57 /V () List Box 58 /T (List Box) 59 &gt;&gt; 60 &lt;&lt; 61 /V () TextFieldPage3 62 /T (TextFieldPage3) 63 &gt;&gt; 64 &lt;&lt; 65 /Kids [ 66 &lt;&lt; 67 /V () hierarchy.node1 68 /T (node1) 69 &gt;&gt; 70 &lt;&lt; 71 /V () hierarchy.node4 72 /T (node4) 73 &gt;&gt; 74 &lt;&lt; 75 /V () hierarchy.node3 76 /T (node3) 77 &gt;&gt; 78 &lt;&lt; 79 /V () hierarchy.node2 80 /T (node2) 81 &gt;&gt;] 82 /T (hierarchy) 83 &gt;&gt; 84 &lt;&lt; 85 /V () betweenHierarch 86 /T (betweenHierarch) 87 &gt;&gt; 88 &lt;&lt; 89 /V /Off RadioGroup 90 /T (RadioGroup) 91 &gt;&gt; 92 &lt;&lt; 93 /V /Off checkBox 94 /T (checkBox) 95 &gt;&gt;] 96 &gt;&gt; 97 &gt;&gt; 98 endobj 99 trailer 100 101 &lt;&lt; 102 /Root 1 0 R 103 &gt;&gt; 104 %%EOF </code></pre>
[]
[ { "body": "<p>I tried to wrap my head around this file format (what a weird one?!) and came to the realization that it is a lot easier to build the tree structure if you read the file from the bottom-up, would you agree? Based on that, I came up with this much simpler implementation where I only maintain a stack (last in, first out) of field names. The output is the same for your example data and I hope I did not miss anything.</p>\n\n<pre><code>fdfAnnotate &lt;- function(fdfLines) {\n fields &lt;- vector(length = length(fdfLines), mode = \"character\")\n store &lt;- NULL\n for (i in rev(seq_along(fdfLines))) {\n line &lt;- fdfLines[i]\n if (grepl(\"/V\", line)) {\n fields[i] &lt;- paste(store, collapse = \".\")\n store &lt;- head(store, -1)\n } else if (grepl(\"/T [(]\", line)) {\n name &lt;- sub(\".*[(](.*)[)].*\", \"\\\\1\", line)\n store &lt;- c(store, name)\n } else if (grepl(\"/Kids \\\\[\", line)) {\n store &lt;- head(store, -1)\n }\n }\n data.frame(fdfLines, fields, stringsAsFactors = FALSE)\n}\n</code></pre>\n\n<p>Some general comments or other recommendations</p>\n\n<ol>\n<li>Considering this will go on CRAN, I would try to limit package dependencies as much as possible. Here I replaced <code>stringr::str_extract</code> with a call to the base <code>sub</code></li>\n<li>You are not using the commonly accepted syntax, to list a few: use <code>&lt;-</code> for assignments; use double quotes instead of single quotes; use a space after a comma, between binary operators, after <code>if</code>, before <code>{</code></li>\n<li>The code is making a lot of assumptions about the input, essentially that the input comes from a valid fdf file. Maybe some of these assumptions ought to be tested</li>\n<li>Are the regex patterns strong enough? For example, should you be using <code>^</code> and <code>$</code> where appropriate?</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T04:27:43.283", "Id": "410331", "Score": "0", "body": "Huh never used the `head` with a negative integer before. It is a little late for not having `stringr` as a dependency as I originally used it to solve an encoding issue that I couldn't solve using base R but using `sub` seems to make the function 30% faster. Initially I assumed your's would run faster since it doesn't have that `while` loop that traces back but it is actually slower (15%) on the example data, at least after replacing the `str_replace` with sub. Can't quite tell why. Maybe it's the growing `store`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T04:50:16.477", "Id": "410336", "Score": "0", "body": "Also thanks for pointing out the assumptions. It failed horribly when the field names include paranthesis" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T03:34:23.330", "Id": "212187", "ParentId": "212118", "Score": "1" } } ]
{ "AcceptedAnswerId": "212187", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T03:34:39.993", "Id": "212118", "Score": "2", "Tags": [ "parsing", "r" ], "Title": "A faux parser for fdf files" }
212118
<p>This is a helper class that helps fill models with data obtained from the database.</p> <pre class="lang-java prettyprint-override"><code>public class Util { public static &lt;M&gt; ArrayList&lt;M&gt; createModel(M model, Cursor cursor) throws IOException { try { final Class&lt;?&gt; cls = model.getClass(); final ArrayList&lt;M&gt; result = new ArrayList&lt;&gt;(); while (cursor.next()) { final Class&lt;?&gt; item = Class.forName(cls.getName()); final M obj = (M) item.newInstance(); final Field[] fields = item.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); final Class&lt;?&gt; type = field.getType(); switch (type.toString()) { case "int": { final int value = cursor.getInt(getFieldName(field), 0); field.setInt(obj, value); break; } default: //throw new IOException(); continue; } } result.add(obj); } return result; } catch (IllegalAccessException | InstantiationException | ClassNotFoundException e) { e.printStackTrace(); throw new IOException(); } } private static String getFieldName(Field field) { final fieldName annotation = field.getDeclaredAnnotation(fieldName.class); return annotation == null ? field.getName() : annotation.name(); } } </code></pre> <p><a href="https://pastebin.com/5LgqeeSb" rel="nofollow noreferrer">All code here(pastebin.com)</a></p> <p>I think my version is very bad, so I want to improve it, but I haven’t yet figured out how to do it.</p> <p>Usage example:</p> <pre class="lang-java prettyprint-override"><code>String query = "SELECT * FROM table_name WHERE;"; Cursor cursor = helper.query(query); List&lt;Test&gt; test = Util.createModel(new Test(), cursor); </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:38:26.983", "Id": "410241", "Score": "2", "body": "Your PasteBin isn't that long; you should just include all of the code directly in the question itself, so that the question makes sense." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T15:41:04.287", "Id": "410255", "Score": "0", "body": "Can you provide an example of how you would use this? I find it more likely that you would want a specialised \"collector\" or \"adapter\" class for each specific table in database that actually uses the column names to transform a table row into an instance of a specific class." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T02:28:54.127", "Id": "410321", "Score": "0", "body": "@200_success, I could not insert all the code here, as the system did not allow to create a question. And asked to write more text." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T02:32:31.210", "Id": "410322", "Score": "0", "body": "@Imus, Example of use added to the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T02:36:44.643", "Id": "410323", "Score": "0", "body": "The length limit is 64 kiB, which is definitely long enough for all of your code to fit. If it's complaining about your text being too short, then you should [tell us more about your code](https://codereview.meta.stackexchange.com/q/7364/9357)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T02:41:44.687", "Id": "410324", "Score": "0", "body": "@200-success, But after all, I posted the most necessary code here, and delete the duplicates. Even if I delete the link it will not change anything." } ]
[ { "body": "<p>Why do you think that your version in \"very bad\" ?</p>\n\n<p>There are of course some little improvements that you can do. Like declaring <code>List&lt;M&gt;</code> instead of <code>ArrayList&lt;M&gt;</code> as the return type. Also you can pass <code>Class&lt;M&gt; cls</code> instead of an empty instance of your model.</p>\n\n<p>Another think to improve the readability of your code is to split your main method into many little methods. Like one for the mapping of a class. </p>\n\n<p>Many dislike the <code>switch</code> and specially for a long one like that. If you want you can replace it with a <code>Map&lt;String, BiConsumer&lt;Cursor, Field&gt;&gt;</code> that associate a type and a consumer to set the value to a field. It is usually a wrong parctive to silently ignore an edge case. You may consider to throw an exception or at least log something instead of continuing in the <code>default</code> case.</p>\n\n<p>Instead of testing the name of the type, you can compare the types and add the support for the wrapper types.</p>\n\n<p>Finally for the exception. I am not sure that <code>IOException</code> is the best type, you can also use a logger instead of <code>e.printStackTrace()</code> because this one will pollute your output without any means to control it.</p>\n\n<pre><code>if ( Integer.class.equals(type) || Integer.TYPE.equals(type) ) {\n // ...\n} else if ( .. ) {\n // ... \n} else {\n throw new UnsupportedTypeException(\"Type \"+type.getName()+\" cannot be mapped.\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T03:01:41.120", "Id": "410327", "Score": "0", "body": "Thank you, made changes to your suggestions." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T08:10:15.573", "Id": "410352", "Score": "0", "body": "Regarding your usage example you can also create a method that execute the query and map the result because this pattern (Create query, Execute query, Map cursor) will occurs a lot of time. You can create a decorator over your `helper` to expose this method `new SimpleOrm(helper).<M>selectAs(String query, Class<M> type):List<M>`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-10-22T06:40:55.777", "Id": "450538", "Score": "0", "body": "`int.class == type` is fine." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T20:16:50.660", "Id": "212160", "ParentId": "212121", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T07:32:42.850", "Id": "212121", "Score": "2", "Tags": [ "java", "reflection" ], "Title": "Class to fill model objects with data from the database" }
212121
<p>I have a thread which periodically executes a task. Something like the following:</p> <pre><code>std::thread thr; std::atomic&lt;bool&gt; keepWorking; void stopThread() { keepWorking = false; thr.join(); } void threadLoop() { while(keepWorking) { std::this_thread::sleep_for(std::chrono::seconds(15)); // Do Work. } } </code></pre> <p>The problem with this code is that <code>stopThread</code> can take up to 15 seconds. I need a mechanism to wake up the thread. </p> <p>After a fast search it became clear to me that I have to use <code>std::condition_variable::wait_for</code>.</p> <p>The code I currently have looks like this:</p> <pre><code>std::thread thr; bool keepWorking; std::mutex mtx; std::condition_variable cv; void stopThread() { { std::unique_lock&lt;std::mutex&gt; l(mtx); keepWorking = false; } cv.notify_one(); thr.join(); } void threadLoop() { auto endTime = std::chrono::system_clock::now(); while (true) { endTime += std::chrono::seconds(15); { std::unique_lock&lt;std::mutex&gt; l(mtx); while (true) { if (keepWorking == false) return; auto now = std::chrono::system_clock::now(); if (now &gt; endTime) break; auto toSleep = endTime - now; cv.wait_for(l, toSleep); } } // Do Work. } } </code></pre> <p>With the second <code>while(true)</code> loop my intention is to protect myself against <code>spurious wake-up calls</code>.</p> <p>What are the possible problems with the above code?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:41:09.027", "Id": "410222", "Score": "1", "body": "It looks like `// Do Work.` is a placeholder for code you've omitted. You'll need to include that for Code Review - or (better) make your code more general so that the user can supply the work to be done (e.g. as a \"task\" object, or by allowing subclassing). Then it might be complete enough for review." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T12:12:38.810", "Id": "410226", "Score": "0", "body": "@toby-speight _Then it might be complete enough for review._ I think the code is complete as it is, since `// Do Work.` is a placeholder for any code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T12:56:57.207", "Id": "410230", "Score": "0", "body": "[help/on-topic] says, \"*In order to give good advice, we need to see real, concrete code, and understand the context in which the code is used. Generic code (such as code containing placeholders like `foo`, `MyClass`, or `doSomething()`) leaves too much to the imagination.*\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:06:52.870", "Id": "410235", "Score": "0", "body": "@toby-speight That is the point, leave place to the imagination. `// Do Work.` is not relevant to the question. How about `// Do Work.` being `std::cout << \"@toby-speight is not helpful.\" << std::endl;`? is that enough?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:11:16.540", "Id": "410238", "Score": "0", "body": "Is that what your real code contains? If so, please edit so that what you've posted accurately reflects that. As I said, it might be better for the function to accept a user-passed function there." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:30:11.543", "Id": "410239", "Score": "0", "body": "No, my real code does not contain that. I understand your suggestion about accepting a user-passed function and I think it is a good suggestion, but it is not relevant to my question. If I update the code sample to accept a user-passed function, it will become bulkier and it will not focus on the problem itself, which is having a thread which periodically executes a task and can be terminated without blocking. I am not asking how to improve my code(meaning how to make it more modular or reusable)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T14:39:43.320", "Id": "410242", "Score": "1", "body": "You seem to have an unclosed brace in your `ThreadLoop`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T15:12:49.047", "Id": "410253", "Score": "0", "body": "@VisualMelon true, I`ve updated the code. Thanks." } ]
[ { "body": "<h1>Missing headers</h1>\n\n<p>The code as presented won't compile, because many of the required definitions are missing:</p>\n\n<pre><code>#include &lt;chrono&gt;\n#include &lt;condition_variable&gt;\n#include &lt;mutex&gt;\n#include &lt;thread&gt;\n</code></pre>\n\n<h1>Global variables</h1>\n\n<p>I think it would be better to take those global variables and package them into an object, so that it's possible to have more than one interruptible worker in your program. Then it would look something more like:</p>\n\n<pre><code>class worker\n{\n std::thread thr;\n bool keepWorking;\n std::mutex mtx;\n std::condition_variable cv;\n\npublic:\n worker()\n : thr{&amp;worker::threadLoop, this},\n keepWorking{true},\n mtx{},\n cv{}\n {}\n\n void stopThread();\n\nprivate:\n\n static void threadLoop(worker *w);\n};\n</code></pre>\n\n<h1>Unfinished code</h1>\n\n<p>This comment suggests that the code isn't yet finished (and therefore not ready for review).</p>\n\n<blockquote>\n<pre><code> // Do Work.\n</code></pre>\n</blockquote>\n\n<p>Moreover, it suggests that the loop will only ever execute a single, fixed block of code, which makes it very inflexible. Instead, we should allow the caller to provide the work to be done:</p>\n\n<pre><code>template&lt;typename Func&gt;\nclass worker\n{\n std::thread thr;\n bool keepWorking;\n std::mutex mtx;\n std::condition_variable cv;\n Func f;\n\npublic:\n worker(Func f)\n : thr{&amp;worker::threadLoop, this},\n keepWorking{true},\n mtx{},\n cv{},\n f{std::move(f)}\n {}\n</code></pre>\n\n<p>Then the comment becomes useful:</p>\n\n<pre><code> // Do some work\n w-&gt;f();\n</code></pre>\n\n<h1>Choice of names</h1>\n\n<p><code>l</code> is a very poor choice of names. I'd prefer <code>lock</code>, or anything that doesn't look like a number.</p>\n\n<h1>Excess complexity</h1>\n\n<p>Instead of computing <code>toSleep</code>, why not use <code>wait_until()</code> instead of <code>wait_for()</code>? We can keep the mutex locked outside the loop, allowing the interrupting thread access only during the condition-variable wait; that will cause it to block whilst work is running, but it was already waiting in that case (in <code>thr.join()</code>). That makes the code much simpler:</p>\n\n<pre><code>static void threadLoop(worker *w)\n {\n auto endTime = std::chrono::system_clock::now();\n\n std::unique_lock lock{w-&gt;mtx};\n while (!w-&gt;cv.wait_until(lock, endTime += w-&gt;duration,\n [w]{ return !w-&gt;keepWorking; }))\n {\n // Do some work\n w-&gt;f();\n }\n }\n</code></pre>\n\n<h1>Tests</h1>\n\n<p>There isn't even a simple <code>main()</code> to show how usable this is, or to demonstrate it working at all.</p>\n\n<hr>\n\n<p>Modified code</p>\n\n<pre><code>#include &lt;chrono&gt;\n#include &lt;condition_variable&gt;\n#include &lt;atomic&gt;\n#include &lt;thread&gt;\n\n// Func should be a function of no arguments\ntemplate&lt;typename Func&gt;\nclass worker\n{\n std::thread thr;\n bool keepWorking;\n std::mutex mutex;\n std::condition_variable cv;\n Func f;\n const std::chrono::system_clock::duration duration;\n\npublic:\n worker(Func f, std::chrono::system_clock::duration duration = std::chrono::seconds{15})\n : thr{&amp;worker::threadLoop, this},\n keepWorking{true},\n mutex{},\n cv{},\n f{std::move(f)},\n duration{duration}\n {}\n\n void stopThread()\n {\n std::unique_lock lock{mutex};\n keepWorking = false;\n lock.unlock();\n\n cv.notify_one();\n thr.join();\n }\n\nprivate:\n\n static void threadLoop(worker *const w)\n {\n auto endTime = std::chrono::system_clock::now();\n\n std::unique_lock lock{w-&gt;mutex};\n while (!w-&gt;cv.wait_until(lock, endTime += w-&gt;duration,\n [w]{ return !w-&gt;keepWorking; }))\n {\n // Do some work\n w-&gt;f();\n }\n }\n};\n</code></pre>\n\n\n\n<pre><code>// Simple test program\n#include &lt;iostream&gt;\n\nint main()\n{\n using namespace std::literals::chrono_literals;\n using clock = std::chrono::system_clock;\n\n auto task = []{\n std::cout &lt;&lt; \"working...\" &lt;&lt; std::endl;\n std::this_thread::sleep_for(700ms);\n };\n auto w = worker{task, 1s};\n\n std::this_thread::sleep_for(2400ms);\n auto const start_time = clock::now();\n w.stopThread();\n auto const time_taken = clock::now() - start_time;\n\n auto const millis =\n std::chrono::duration_cast&lt;std::chrono::milliseconds&gt;(time_taken);\n std::cout &lt;&lt; \"Thread stop took \" &lt;&lt; millis.count() &lt;&lt; \" ms\\n\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:57:45.467", "Id": "410270", "Score": "0", "body": "Thanks, but the only useful point of this response is the *Excess complexity*. In summary: use `wait_until` and make sure to use the overload that accepts the `pred` argument, which solves the problem with `spurious wake-up calls` in a neat way." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T09:31:20.950", "Id": "410727", "Score": "0", "body": "Don't overlook the importance of keeping the condition variable locked while you're working, so that you don't have to deal with possible race after calling the work function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T09:32:23.420", "Id": "410728", "Score": "0", "body": "And if you don't find *make a general utility* to be useful, then I'm sorry for wasting your time." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T16:04:31.777", "Id": "212143", "ParentId": "212131", "Score": "3" } } ]
{ "AcceptedAnswerId": "212143", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:11:24.970", "Id": "212131", "Score": "-1", "Tags": [ "c++", "multithreading" ], "Title": "Waking up a thread while sleeping" }
212131
<h1>Intro</h1> <p>We have some old(in my eyes) software at the place I work at the moment,</p> <p>Some stuff needs to be done manually, for instance we need to insert a XML file into a Oracle table, which will trigger... <em>stuff</em></p> <p>I got annoyed by having to do this manually all the time,</p> <p>So I decided to automate the process a bit with <a href="/questions/tagged/powershell" class="post-tag" title="show questions tagged &#39;powershell&#39;" rel="tag">powershell</a> and Oracle's sqlldr</p> <p>My knowledge of Oracle is limited hence the asking for a review,</p> <p><strong>What I did</strong></p> <ol> <li>I have created a separate table, to which I am inserting my file.</li> <li>That table has a trigger, to get the specified information, and insert it into the correct table (which is not up for review)</li> <li>Created a powershell script to be able to load files in bulk into the table</li> </ol> <h1>Code</h1> <p><em>The sql script for creating the table</em></p> <pre><code>CREATE TABLE mckdev.ogd_xml_table ( id NUMBER(10), xml XMLTYPE, &quot;IN_CON_LOG&quot; NUMBER(1,0), &quot;ZIS_EVENT&quot; VARCHAR2(35 BYTE), ); ALTER TABLE mckdev.ogd_xml_table ADD ( CONSTRAINT ogd_xml_table_pk PRIMARY KEY (id) ); CREATE SEQUENCE mckdev.ogd_xml_table_seq; </code></pre> <p><em>The load_data.ctl</em></p> <pre><code>load data infile '' append into table ogd_xml_table fields ( filename FILLER CHAR(100), xml lobfile( filename) terminated by eof ) </code></pre> <p><em>The bulkloader.ps1</em></p> <pre><code>$dataFiles = @( &quot;filelist21.dat&quot; &quot;filelist22.dat&quot;, &quot;filelist23.dat&quot;, &quot;filelist25.dat&quot;, &quot;filelist121a.dat&quot;, &quot;filelist121b.dat&quot;, &quot;filelist122a.dat&quot;, &quot;filelist122b.dat&quot; ) $ctlFile = &quot;$PSScriptRoot\load_data.ctl&quot; foreach ($f in $dataFiles) { (Get-Content $ctlFile) -Replace &quot;infile '[^']*'&quot;, &quot;infile '$($PSScriptRoot)\$($f)'&quot; | Out-File $ctlFile -Encoding ASCII sqlldr mckdev@$SecretDatabase/$SecretPassword control=$ctlFile } </code></pre> <p>An example <code>filelist.dat</code> only holds a reference to another XML file.</p> <h1>Questions</h1> <ul> <li><p>Currently I need to have multiple <code>.dat</code> file to be able to load them in bulk.</p> <p>One for each XML file I want to load into the table. Is there any way around this?</p> </li> <li><p>Is this a correct approach or would you have done things differently?</p> </li> </ul>
[]
[ { "body": "<p>As the ctl file can't be parameterized you'll have to create them for each infile.</p>\n\n<p>As it is quite small, I'd create it on the fly from a here string with the format operator.</p>\n\n<p>This sample script just echoes to screen, the commands to write/execute sqlldr are commented out.</p>\n\n<pre><code>## Q:\\Test\\2019\\01\\24\\CR_212133.ps1\n$dataFiles = @(\n \"filelist21.dat\"\n \"filelist22.dat\",\n \"filelist23.dat\",\n \"filelist25.dat\",\n \"filelist121a.dat\",\n \"filelist121b.dat\",\n \"filelist122a.dat\",\n \"filelist122b.dat\"\n)\n\n$ctlFile = \"$PSScriptRoot\\load_data.ctl\"\n\nforeach ($dataFile in $dataFiles) {\n@'\nload data\ninfile '{0}'\nappend\ninto table ogd_xml_table\nfields\n(\n filename FILLER CHAR(100),\n xml lobfile( filename) terminated by eof\n)\n'@ -f $dataFile #| Out-File $ctlFile -Encoding ASCII\n #sqlldr mckdev@$SecretDatabase/$SecretPassword control=$ctlFile\n}\n</code></pre>\n\n<hr>\n\n<pre><code>&gt; Q:\\Test\\2019\\01\\24\\CR_212133.ps1\nload data\ninfile 'filelist21.dat'\nappend\ninto table ogd_xml_table\nfields\n(\n filename FILLER CHAR(100),\n xml lobfile( filename) terminated by eof\n)\n----------------------------------------------------------------------\nload data\ninfile 'filelist22.dat'\nappend\ninto table ogd_xml_table\nfields\n(\n filename FILLER CHAR(100),\n xml lobfile( filename) terminated by eof\n)\n----------------------------------------------------------------------\n%&lt;...snip...&gt;%\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T15:35:13.997", "Id": "212142", "ParentId": "212133", "Score": "1" } }, { "body": "<p>After looking back at it again, I realized I didn't need all those different <code>dataFiles</code>,\nas all those <code>dataFiles</code> hold only a single reference with the full path to the XML file.</p>\n\n<p>Instead I could get the path for each XML file and overwrite the single dataFile with the correct file path I want to execute.</p>\n\n<ul>\n<li>This makes adding another XML file to load, as easy as adding it to the directory I read the files from</li>\n<li>And removes the need for multiple <code>dataFiles</code></li>\n</ul>\n\n<hr>\n\n<pre><code>$xmlDirectories = @(\n \"directory1\",\n \"directory2\"\n)\n$dataFile = \"$PSScriptRoot\\filelist.dat\"\n$ctlFile = \"$PSScriptRoot\\load_data.ctl\"\n\nforeach ($dir in $xmlDirectories) {\n foreach ($f in Get-ChildItem -Path \"$PSScriptRoot\\$dir\") {\n $f.FullName | Out-File $dataFile -Encoding ASCII\n sqlldr mckdev@$SecretDatabase/$SecretPassword control=$ctlFile\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T09:22:38.563", "Id": "212199", "ParentId": "212133", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:45:43.743", "Id": "212133", "Score": "0", "Tags": [ "sql", "powershell", "oracle" ], "Title": "Bulkloading xml's into Oracle table" }
212133
<p>I made an authentication system for my software (no browser is used) that works like this:</p> <ul> <li>User receives a Key on it's mail after buying the software</li> <li>User registers account using that key and inputs username, mail, password.</li> <li><strong>registration.php</strong> checks if the format is correct then sends an email with a confirmation code using a template and inserts the values into DB (verify table).</li> <li>The HTML template contains username (from user input), 2 images from the same directory as the registration.php and the <strong>template2.html</strong> and a button with a get like this: <em>www.mysite.com/activate.php?id=$serial&amp;conf=$confirmation_code</em>.</li> <li><strong>activate.php</strong> checks if everything is valid and then inserts the verify table's row into accounts table. (after it is inserted into accounts table, it becomes a valid account).</li> </ul> <p>Everything works as expected (I'm still making the login.php).</p> <h1>Why I'm posting this here:</h1> <p>As a beginner (this is the first php, mysql and html thing I do) I know there is a lot of things that can be improved. My goal is to make it as secure as possible, I followed OWASP as much as I could and at the same time I read a lot on Stack Overflow and Security.Stackexchange.</p> <h1>Here is my code:</h1> <h3>registration.php</h3> <pre><code>&lt;?php $CurrentVersionHash="asd123"; $CurrentVersion="alpha1"; $CurrentHash="asd123"; $serial_length="10"; $memory_cost="31250"; $time_cost="10"; $threads="1"; require 'mail.php'; if ( ! empty( $_POST ) ) // Check if Post is not empty { $hash = $_POST['exe']; $pw = $_POST['pass']; $user = $_POST['name']; $version = $_POST['ver']; $email = $_POST['mail']; $confirm = $_POST['pass2']; $serial = $_POST['key']; if ( empty($hash) or empty($version)) return; if ( $hash&lt;&gt;$CurrentHash) // Check if file Hash is valid { if ( $version&lt;&gt;$CurrentVersionHash ) // Check if it's because it's outdated { echo "Old exe"; } else { echo "Exe not valid"; } return; } // Checking if there is any problem in the format if ( (empty( $user )) or ( strlen( $user ) &lt; 6 ) or ( strlen( $user ) &gt; 254 ) or ( ! ctype_alnum ( $user )) ) { echo "Error"; return; } if ( (empty( $pw)) or (strlen($pw) &lt; 10) or (strlen($pw) &gt; 254) or (! preg_match("#[0-9]+#", $pw)) or ( !preg_match("#[a-z]+#", $pw )) or ( !preg_match("#[A-Z]+#", $pw )) ) { echo "Error"; return; } if ( $pw != $confirm or empty( $confirm ) ) { echo "Error"; return; } if (( empty( $email )) or ( ! filter_var($email, FILTER_VALIDATE_EMAIL)) or (strlen($email) &gt; 254) ) { echo "Error"; return; } if ( ( empty( $serial ) ) or ( strlen( $serial ) &lt;&gt; $serial_length ) ) { echo "Error"; return; } // Check if Serial exists and is not already taken $con = new mysqli($host, $username, $password, $database); $stmt = $con-&gt;prepare("SELECT * FROM acc WHERE serial=?"); $stmt-&gt;bind_param('s', $serial); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $num_of_rows = $result-&gt;num_rows; $result = $result-&gt;fetch_array(); // If Serial doesn't exist or is already taken if ( ($num_of_rows==0) or ( ! empty( $result['username'] )) ) { echo "Invalid Serial"; $error=1; } $stmt = $con-&gt;prepare("SELECT * FROM verify WHERE serial=?"); $stmt-&gt;bind_param('s', $serial); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $num_of_rows = $result-&gt;num_rows; $result = $result-&gt;fetch_array(); // If Serial is on verify DB (means that someone already registered using it) if ( ($num_of_rows&lt;&gt;0) and ($error&lt;&gt;1) ) { echo "Invalid Serial"; $error=1; } if ($error&lt;&gt;1) { // Check if Username or E-mail is not already taken $stmt = $con-&gt;prepare("SELECT * FROM acc WHERE username= ? OR email= ? LIMIT 1"); $stmt-&gt;bind_param('ss', $user, $email); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $num_of_rows = $result-&gt;num_rows; $result = $result-&gt;fetch_array(); $stmt = $con-&gt;prepare("SELECT * FROM verify WHERE username= ? OR email= ? LIMIT 1"); $stmt-&gt;bind_param('ss', $user, $email); $stmt-&gt;execute(); $result2 = $stmt-&gt;get_result(); $num_of_rows2 = $result2-&gt;num_rows; $result2 = $result2-&gt;fetch_array(); if ( ($num_of_rows) or ($num_of_rows2) ) // If user or email already exists on verify and acc DB { if ( (strcasecmp($result['username'], $user) == 0) or (strcasecmp($result2['username'], $user) == 0) ) // If user already exists { echo "Username in use"; } else if ( (strcasecmp($result['email'], $email) == 0) or (strcasecmp($result2['email'], $email) == 0) )// If e-mail is already taken { echo "Email in use"; } } else { // Do registration $password = password_hash( $pw, PASSWORD_ARGON2ID, [ 'memory_cost' =&gt; $memory_cost, 'time_cost' =&gt; $time_cost, 'threads' =&gt; $threads, ]); $rand_id = random_int(-10000, 10000); $rand_secret = random_str(32); $stmt = $con-&gt;prepare("INSERT INTO verify (username, password, email, serial, rand_id, rand_secret) VALUES (?,?,?,?,?,?)"); $stmt-&gt;bind_param('ssssss', $user, $password, $email, $serial, $rand_id, $rand_secret); $stmt-&gt;execute(); $confirmation_code = hash_hmac('sha256', $rand_id, $rand_secret); $variables = array(); $variables['User'] = $user; $variables['Serial'] = $serial; $variables['Code'] = $confirmation_code; $template = file_get_contents("template2.html"); foreach($variables as $key =&gt; $value) { $template = str_replace('{{ '.$key.' }}', $value, $template); } $mail-&gt;addAddress($email, $user); $mail-&gt;msgHTML($template, __DIR__); $mail-&gt;AltBody = "You can activate your account here: www.mysite.com/activate.php?id=$serial&amp;conf=$confirmation_code"; if (!$mail-&gt;send()) { echo 'error, mail not delivered'; } else { echo "Registration OK! mail sent"; } } } $stmt-&gt;close(); $con-&gt;close(); return; } function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') { $pieces = []; $max = mb_strlen($keyspace, '8bit') - 1; for ($i = 0; $i &lt; $length; ++$i) { $pieces []= $keyspace[random_int(0, $max)]; } return implode('', $pieces); } ?&gt; </code></pre> <h3>activate.php</h3> <pre><code>&lt;?php if ( ! empty( $_GET ) ) { if ( isset($_GET['id']) and isset($_GET['conf']) ) { $key=$_GET['id']; $code=$_GET['conf']; $con = new mysqli($host, $username, $password, $database); $stmt = $con-&gt;prepare("SELECT * FROM verify WHERE serial=?"); $stmt-&gt;bind_param('s', $key); $stmt-&gt;execute(); $result = $stmt-&gt;get_result(); $num_of_rows = $result-&gt;num_rows; $result = $result-&gt;fetch_array(); // If Serial doesn't exist or is already taken if ( ($num_of_rows==0) or ( empty( $result['username'] )) or ( empty( $result['rand_id'] )) or ( empty( $result['rand_secret'] )) ) { $error=1; echo "Invalid code"; } if ( $error&lt;&gt;1 ) { $rand_id = $result['rand_id']; $rand_secret = $result['rand_secret']; $confirmation_code = hash_hmac('sha256', $rand_id, $rand_secret); if ($confirmation_code == $code) { $user=$result['username']; $password=$result['password']; $email=$result['email']; $stmt = $con-&gt;prepare("UPDATE accounts SET username = ?, password = ?, email = ? WHERE Serial = ?"); $stmt-&gt;bind_param('ssss', $user, $password, $email, $key); $stmt-&gt;execute(); $stmt = $con-&gt;prepare("DELETE from verify WHERE serial = ?"); $stmt-&gt;bind_param('s', $key); $stmt-&gt;execute(); echo "Account activated"; } else { $error=1; echo "Invalid code"; } } $stmt-&gt;close(); $con-&gt;close(); return; } } function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') { $pieces = []; $max = mb_strlen($keyspace, '8bit') - 1; for ($i = 0; $i &lt; $length; ++$i) { $pieces []= $keyspace[random_int(0, $max)]; } return implode('', $pieces); } ?&gt; </code></pre> <p>mail.php</p> <pre><code>&lt;?php use PHPMailer\PHPMailer\PHPMailer; require 'vendor/autoload.php'; $mail = new PHPMailer; $mail-&gt;isSMTP(); $mail-&gt;Host = 'smtphost'; $mail-&gt;Port = port; $mail-&gt;SMTPAuth = true; $mail-&gt;Username = 'mymail'; $mail-&gt;Password = 'mypassword'; $mail-&gt;setFrom('mymail', 'myname'); $mail-&gt;addReplyTo('mysupportmail', 'myname'); $mail-&gt;AddEmbeddedImage('img/logo.png', 'mylogo'); $mail-&gt;AddEmbeddedImage('img/gif.gif', 'mygif'); $mail-&gt;Subject = "Activation for account"; ?&gt; </code></pre> <p>Thanks in advance.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T09:27:48.470", "Id": "410358", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T09:29:24.300", "Id": "410359", "Score": "0", "body": "Oh I'm very sorry, I will read that page. Thanks for changing it back to normal" } ]
[ { "body": "<p>Overall this is a lot of procedural code to process. That is fine to use but I would suggest you look into an MVC structure, or at least OOP - abstracting bits of code into controller methods and other functions or static methods that can be called by these pages, as well as tested by unit tests. I know that might be a lot to expect from a beginner but it is worth learning about and utilizing. </p>\n\n<p>The code already uses <a href=\"http://php.net/require\" rel=\"nofollow noreferrer\"><code>require</code></a> for <code>mail.php</code>. I would suggest abstracting the repeated function <code>random_str()</code> into a single file, along with any other common functions, and then using <code>require</code> to include it wherever necessary, which would be inline with the <a href=\"https://deviq.com/don-t-repeat-yourself/\" rel=\"nofollow noreferrer\"><em><strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself</em> principle</a>. That way any updates to the function can be done in one spot instead of multiple. If you use OOP/MVC techniques as recommended above, that function could be static method of a class - e.g. <code>Authentication</code>, <code>AuthenticationController</code>, <code>Registration</code>, <code>RegistrationController</code>, etc.</p>\n\n<p>Also, those variables listed at the top of <em>registration.php</em> which do not change can be stored as constants - either with <a href=\"http://php.net/define\" rel=\"nofollow noreferrer\"><code>define()</code></a> or the <a href=\"http://php.net/const\" rel=\"nofollow noreferrer\"><code>const</code></a> keyword - especially the latter if there is an appropriate class created to associate those with. And a common convention for constants is for them to be named using all capitalized letters. While this is not a requirement, many believe it helps when reading the code to distinguish constants from other values.</p>\n\n<p>The sequential queries in <em>registration.php</em> i.e. <code>\"SELECT * FROM acc WHERE serial=?\"</code> and <code>\"SELECT verify FROM acc WHERE serial=?\"</code> make me wonder if <code>serial</code> is a primary/foreign key of one or both of those tables, and if those two queries could be combined into a single query where the tables are <code>JOIN</code>ed one those fields.</p>\n\n<p>It would be a good habit to use the <a href=\"http://php.net/manual/en/language.operators.comparison.php\" rel=\"nofollow noreferrer\">Identical comparison operator</a> (i.e. <code>===</code>) where appropriate instead of the Equal comparison operator (i.e. <code>==</code>) unless you are sure that type-juggling is fine for your use case. And the same is true for the Not Identical Operator (i.e. <code>!==</code>) vs Not equal (i.e. <code>!=</code> or <code>&lt;&gt;</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T08:43:32.107", "Id": "410355", "Score": "0", "body": "Thanks for this answer, I will update the code with what you wrote after the first paragraph. About MVC structure, that's something new for me, I will start reading about it and will do my best to adapt my code to it. From what I read (only 1 page) it is Model View and Controllers structure where everything is separated. How would I achieve this, using different files or something else? Thanks in advance." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T09:19:20.497", "Id": "410357", "Score": "0", "body": "About the Serial thing being checked on both tables it's because when a user tries to register with a serial, I want to check if there is any valid account with that serial or any non-activated account with that serial. I still have to add something to clear the row in verify table if the user doesn't confirm his/her account in X amount of time (like 1 week or something)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T09:32:52.313", "Id": "410360", "Score": "0", "body": "I can't edit my comments so, about editing the post. Thanks to Ludisposed for telling me that it goes against Code Review. I already applied those changes in my code and everything is working fine. I'm still learning about OOP.\nStill I'm worried about the security, I already used prepared statements for almost everything, but I'm worried about the mail thing. Username and email are used and I don't know what to do with those." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T00:18:27.517", "Id": "212177", "ParentId": "212134", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:49:51.507", "Id": "212134", "Score": "3", "Tags": [ "beginner", "php", "html", "mysql", "mysqli" ], "Title": "Authentication system (no browser) with mail verification" }
212134
<p>I have attempted to implement the advice from the <a href="https://codereview.stackexchange.com/questions/212024/long-cache-refresh-with-guaranteed-response">original post</a> and debugged the original concept.</p> <p>Certain changes in the logic have necessitated other changes, including breaking into the library class and the test console app.</p> <p>Test console:</p> <pre><code>using System; namespace LongCacheTest { public class Program { public static void Main(string[] args) { var cacher = new Cacher.Cacher&lt;string&gt;(); cacher.Add("first", SimulateSlowLoadingContentRetrieval); cacher.Add("second", SimulateSlowLoadingContentRetrieval); Console.ReadLine(); } private static string SimulateSlowLoadingContentRetrieval(string key) { var end = DateTime.Now.AddSeconds(10); while (DateTime.Now &lt; end) ; return $"content:{key}"; } } } </code></pre> <p>Library class:</p> <pre><code>using System; using System.Runtime.Caching; using System.Threading.Tasks; namespace Cacher { public class Cacher&lt;T&gt; { public delegate T CacheEntryGet(string key); private MemoryCache Cache { get; set; } = new MemoryCache("long"); private CacheItemPolicy ImmediatePolicy =&gt; new CacheItemPolicy { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(3)), Priority = CacheItemPriority.Default, RemovedCallback = DidRemove }; private CacheItemPolicy RegularPolicy =&gt; new CacheItemPolicy { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(20)), Priority = CacheItemPriority.Default, RemovedCallback = DidRemove }; private CacheItemPolicy NoRemovePolicy =&gt; new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable }; private async Task GetFreshContent(CacheEntryRemovedArguments args) { await Task.Run(() =&gt; { Cache.Set(args.CacheItem, NoRemovePolicy); var item = args.CacheItem.Value as Cacheable&lt;T&gt;; item.Obj = item.Getter(args.CacheItem.Key); var policy = RegularPolicy; Cache.Set(args.CacheItem, policy); }); } private void DidRemove(CacheEntryRemovedArguments args) { GetFreshContent(args); } public void Add(string key, CacheEntryGet getter) { var item = new Cacheable&lt;T&gt; { Getter = getter }; Cache.Set(key, item, ImmediatePolicy); } public T Get(string key) =&gt; (Cache[key] as Cacheable&lt;T&gt;).Obj; } } </code></pre> <p>Supporting library class:</p> <pre><code>namespace Cacher { internal class Cacheable&lt;T&gt; { public T Obj { get; set; } public Cacher&lt;T&gt;.CacheEntryGet Getter { get; set; } } } </code></pre> <p>Answers to questions:</p> <p>Q: <em>In what context is this class meant to be used?</em><br> A: From start up of a ASP.NET web site, throughout the running life cycle. The aim is to provide a cache of data which can be refreshed, using the expiration mechanism to fire the refresh process.</p> <p>Q: <em>Why does <code>Add</code> only invoke the given getter after 3 seconds, and why does it not accept an initial value?</em><br> A: Essentially, for testing, right now. In practice, because I found that a lower value actually causes the getter to be called after a much longer wait. This is relevant to a <a href="https://stackoverflow.com/questions/54330879/how-to-make-memorycache-callback-on-time">SO question</a>.</p> <p>Q: <em>Why switch to a 20-second expiration time after the initial 3 seconds?</em><br> A: The initial expiration is attempting to force the firing of the getter for the first time. Subsequent firings will be to refresh the data after much longer time periods, but testing is for 20 second bouts. Ideally, it would be 0 seconds and 1 hour.</p> <p>Q <em>Why are entries perpetually being refreshed every 20 seconds?</em><br> A: See above answer - this would, in practice, be an hour or so. It is simulating the lifetime of the cached object, but in a short-lived console for PoC testing.</p> <p>Q: <em>Why is there no eviction policy?</em><br> A: An item expires and thus needs refreshing. While an entry is being refreshed I add it back in without an expiry to give the long-running getter time to work. The new item then replaces the non-expiring item.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T12:11:06.043", "Id": "410225", "Score": "1", "body": "It looks like you forgot to include `Cacheable<T>`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T12:42:31.027", "Id": "410228", "Score": "1", "body": "In what context is this class meant to be used? Why does `Add` only invoke the given getter after 3 seconds, and why does it not accept an initial value? Why switch to a 20-second expiration time after the initial 3 seconds? Why are entries perpetually being refreshed every 20 seconds? Why is there no eviction policy?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T13:06:06.533", "Id": "410232", "Score": "1", "body": "For internal timings, you should use `DateTime.UtcNow` instead of `DateTime.Now`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T13:15:08.067", "Id": "410234", "Score": "0", "body": "@pieter-witvoet I have added answers to your questions in the post." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:55:12.297", "Id": "212135", "Score": "3", "Tags": [ "c#", "cache" ], "Title": "Iteration of self-refreshing MemoryCache encapsulation" }
212135
<p>I'm new to web programming, and writing some web apis to enable users to sync their data between devices.</p> <p>Is it okay to use singleton pattern <strong>to prevent reconnecting the MySQL database on every api call</strong>?</p> <pre><code>&lt;?php final class MySQLiConnection { private static $connection = null; private function __construct() {} public static function getInstance() : MySQLiConnection { if ($connection == null || !$connection-&gt;ping()) { $connection = new mysqli("localhost", "id", "password", "database"); } return $connection; } public function execute(string $sql, iterable $params) : void { if ($statement = $connection-&gt;prepare($sql)) { foreach ($params in $param) { if (is_int($param)) { $statement-&gt;bind_param("i", $param); } else if (is_double($param)) { $statement-&gt;bind_param("d", $param); } else if (is_string($param)) { $statement-&gt;bind_param("s", $param); } } $statement-&gt;execute(); $statement-&gt;close(); } } public function getResult(string $sql, iterable $params) : mysqli_result { if ($statement = $connection-&gt;prepare($sql)) { foreach ($params in $param) { if (is_int($param)) { $statement-&gt;bind_param("i", $param); } else if (is_double($param)) { $statement-&gt;bind_param("d", $param); } else if (is_string($param)) { $statement-&gt;bind_param("s", $param); } } $statement-&gt;execute(); $result = $statement-&gt;get_result(); $statement-&gt;close(); return $result; } } } // example MySQLiConnection::getInstance()-&gt;execute("SELECT * FROM users WHERE forename = ? AND surname = ?", "ben", "dover"); ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T05:12:52.733", "Id": "410346", "Score": "0", "body": "There are some rather important issues in your second code, I encourage you to post another question with the renewed code. It is completely allowed by the site rules and will let me to review the new version" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:10:17.973", "Id": "410377", "Score": "0", "body": "@YourCommonSense Thanks =) https://codereview.stackexchange.com/questions/212212/simple-wrapper-for-php-mysqli-connection" } ]
[ { "body": "<p>First, on your premises.</p>\n\n<ul>\n<li>First of all, <strong>no pattern</strong> would prevent PHP from making a connection to MySQL database on every web api call. Because PHP will die between different API calls, along with all its singletons, connections and any other stuff. So all you can prevent is reconnecting the MySQL database on every call to a database connection class.</li>\n<li>No, it is frowned upon using singleton pattern to prevent reconnecting the MySQL database on every call to a database connection class. A more accepted approach is Dependency Injection. </li>\n<li>Funny enough, due to a typo, this class <strong>would not</strong> prevent reconnecting the mysql. Had you <code>error_reporting</code> set to <code>E_ALL</code>, PHP would have signaled that you are trying to use a non-existent variable <code>$connection</code> every time <code>getInstance()</code> is called. Surely you wanted to call it as <code>$this-&gt;connection</code> instead.</li>\n</ul>\n\n<p>Now to the code. </p>\n\n<p>The intention is very good, especially I like <code>getResult()</code> and <code>execute()</code> methods that allow you to avoid that bind param hassle. However, there is evidently a duplicated code. Why not to make execute to return $statement? It will let you make <code>getResult()</code> as simple as</p>\n\n<pre><code>public function getResult(string $sql, iterable $params) : mysqli_result\n{\n return $this-&gt;execute($sql, $params)-&gt;get_result();\n}\n</code></pre>\n\n<p>And finally. I just noticed, halfway the review process, that your code is off topic, as it simply doesn't work. Mysqli is not PDO, you cannot bind your parameters in a loop. So you need to rework it. In order to help, here are two my articles:</p>\n\n<ul>\n<li><a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"nofollow noreferrer\">How to properly connect to Mysql database using mysqli</a> that will show you important options missed in your connection code</li>\n<li><a href=\"https://phpdelusions.net/mysqli/simple\" rel=\"nofollow noreferrer\">Mysqli made simple</a> to show you how to bind parameters for mysqli dynamically </li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T12:24:26.630", "Id": "212137", "ParentId": "212136", "Score": "2" } } ]
{ "AcceptedAnswerId": "212137", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T11:58:44.097", "Id": "212136", "Score": "3", "Tags": [ "php", "mysqli" ], "Title": "Using singleton pattern for a MySQL connection" }
212136
<p>I want to filter directories and files by what they start with.</p> <pre><code>var result = DirectoryList(arguments.path, false, "query", arguments.filter &amp; "*|" &amp; arguments.filter &amp; "*.*"); </code></pre> <p>I am thinking this covers all scenarios because file sometimes don't have extensions and directories sometimes do. I don't think it can be simplier</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-03T02:47:57.680", "Id": "415037", "Score": "0", "body": "**Please** remember to add the [tag:cfml] tag to your questions. You seem to forget it almost every time." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-04-18T08:38:00.767", "Id": "421166", "Score": "1", "body": "You could probably remove the second filter, since `arguments.filter & \"*.*\"` is already covered by `arguments.filter & \"*\"`" } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T17:34:40.840", "Id": "212148", "Score": "0", "Tags": [ "file-system", "coldfusion", "cfml" ], "Title": "Filtering files and directories" }
212148
<p>Some of you might remember my previous implementations of this idea in C++. The threads can be found <a href="https://codereview.stackexchange.com/questions/191032/console-based-table-structure">here</a> and <a href="https://codereview.stackexchange.com/questions/192453/console-based-table-structure-revisited">here</a>. I tried to implemented the same idea, but this time in python. </p> <p>A summary of the concept again: The idea is to organize data nicely in a table structure that is fully console-based but still highly customizable so that it allows to insert, edit, sort and delete data in a convenient manner.</p> <p>For example input data like this:</p> <pre><code>["Germany", "Berlin", "82800000"] ["South Korea", "Seoul", "51446201"] ["China", "Beijing", "1403500365"] ["France", "Paris", "67201000"] ["Australia", "Canberra", "24877800"] ["Netherlands", "Amsterdam", "17200671"] ["Iceland", "Reykjavik", "348580"] </code></pre> <p>would be structured like this using the DataTable class:</p> <pre><code>+---------------+-------------+--------------+ | Country | Capital | Population | +---------------+-------------+--------------+ | Germany | Berlin | 82800000 | | South Korea | Seoul | 51446201 | | China | Beijing | 1403500365 | | France | Paris | 67201000 | | Australia | Canberra | 24877800 | | Netherlands | Amsterdam | 17200671 | | Iceland | Reykjavik | 348580 | +---------------+-------------+--------------+ </code></pre> <p><strong>DataTable.py</strong></p> <pre><code>class DataTable: """ Defines the padding between the text and each cell in the table """ padding = 2 """ Holds the width of the widest entry of each column in the table """ column_widths = [] """ Holds the description for each column header """ table_headers = [] """ Holds all the rows and their information """ table_data = [] def __init__(self, table_headers, cell_padding): """ Creates a new data table of a given size. :param table_headers: Array of table headers :param cell_padding: The padding between the cell text and the cell border """ self.table_headers.append(table_headers) self.calculate_widths() self.padding = cell_padding def calculate_widths(self): """ Calculate the correct width to the row and cell borders based on the content length in the data table. :return: None """ # If no headers exist it is not possible to calculate the table widths if len(self.table_headers) == 0: raise Exception("Header required to calculate widths") # If no column widths were set initialize them using the header text width if len(self.column_widths) == 0: for i in range(0, len(self.table_headers[0])): self.column_widths.append(len(self.table_headers[0][i])) # If the table has no rows the header defines the widths for i in range(0, len(self.table_headers[0])): self.column_widths[i] = len(self.table_headers[0][i]) # check if [0] is right thing to use here # If the table has rows check all for larger widths then the current one for i in range(0, len(self.table_data)): for j in range(0, len(self.table_data[i])): if len(self.table_data[i][j]) &gt; self.column_widths[j]: self.column_widths[j] = len(self.table_data[i][j]) def add_row(self, values): """ Adds a row to the data table. :param values: Array of row values, count must be equal to data table widths :return: None """ # Ensure correct amount of values is provided to fill exactly one table row if len(values) != len(self.table_headers[0]): raise Exception("Value count doesn't match table dimensions") self.table_data.append(values) self.calculate_widths() def insert_row(self, index, values): """ Insert a row into the data table at a specific position :param index: The index in the table where the row gets inserted :param values: Array of row values, count must be equal to data table widths :return: None """ # Ensure correct amount of values is provided to fill exactly one table row if len(values) != len(self.table_headers[0]): raise Exception("Value count doesn't match table dimensions") self.table_data.insert(index, values) self.calculate_widths() def edit_row(self, row_index, column_index, value): """ Edit a field in a row in the data table :param row_index: The index of the row that should be edited :param column_index: The position of the cell in the selected row that should be edited :param value: The new value the cell will be updated with :return: None """ # Ensure row_index is valid if row_index &lt; 0 or row_index &gt; len(self.table_data): raise Exception("Row index out of range") # Ensure column index is valid if column_index &lt; 0 or column_index &gt; len(self.table_data[0]): raise Exception("Column index out of range") self.table_data[row_index][column_index] = value self.calculate_widths() def delete_row(self, row_index): """ Removes a row from the data table :param row_index: The index of the row that should be deleted :return: None """ if row_index &lt; 0 or row_index &gt; len(self.table_data): raise Exception("Row index out of range") del self.table_data[row_index] self.calculate_widths() def edit_header(self, column_index, value): """ Edit one of the header columns of the data table :param column_index: The index of the column that should be edited :param value: The new value that should be written in the selected header field :return: None """ self.table_headers[0][column_index] = value if len(self.table_headers[0][column_index]) &gt; self.column_widths[column_index]: self.column_widths[column_index] = len(self.table_headers[0][column_index]) self.calculate_widths() def print_separator(self): """ Generates a separator line that fits the table width :return: The separator line """ output = "+" for i in range(0, len(self.column_widths)): output += ("-" * self.column_widths[i]) + ("-" * 2 * self.padding) + "+" return output def sort_table(self, column_index, descending): """ Sorts the data table based on a column specified by the column index :param column_index: The index of the column that should be used for sorting :param descending: If true the table will be sorted in descending order, otherwise in ascending order :return: None """ self.table_data.sort(key=lambda x: x[column_index], reverse=descending) def print_header(self): """ Generates the table header of the data table formatted for printing :return: """ output = "" for i in range(0, len(self.table_headers[0])): text = self.table_headers[0][i] diff = self.column_widths[i] - len(self.table_headers[0][i]) output += ("|" + " " * self.padding + text + diff * " " + " " * self.padding) return output + "|" def print_rows(self): """ Prints all rows and the intersecting separators of the data table :return: None """ output = "" for j in range(0, len(self.table_data)): for i in range(0, len(self.table_data[j])): text = self.table_data[j][i] diff = self.column_widths[i] - len(self.table_data[j][i]) output += ("|" + " " * self.padding + text + diff * " " + " " * self.padding) if j != len(self.table_data) - 1: output += "|\n" else: output += "|" return output def display(self): """ Displays the formatted data table in text form :return: None """ print(self.print_separator()) print(self.print_header()) print(self.print_separator()) print(self.print_rows()) print(self.print_separator()) </code></pre> <p><strong>Usage example:</strong></p> <pre><code>from datatable import DataTable table = DataTable(["Country", "Capital", "Population"], 2) table.add_row(["Germany", "Berlin", "82800000"]) table.add_row(["South Korea", "Seoul", "51446201"]) table.add_row(["China", "Beijing", "1403500365"]) table.add_row(["France", "Paris", "67201000"]) table.add_row(["Australia", "Canberra", "24877800"]) table.add_row(["Netherlands", "Amsterdam", "17200671"]) table.add_row(["Iceland", "Reykjavik", "348580"]) # Delete a row table.delete_row(3) # Update cell with a new value table.edit_row(1, 1, "SEOUL!!") # Edit header table.edit_header(2, "PEOPLE!!") # Sort table alphabetically by capital table.sort_table(1, False) # Show the table table.display() </code></pre> <p>Any bad practices or things that I could improve to make it more convenient to use? Also I am open for more functionality/features that could be added to this class.</p>
[]
[ { "body": "<p>I think the best designs come from usage. And your usage could be far simpler:</p>\n\n<pre><code>from datatable import DataTable\n\npadding = 2\nheader = [\"Country\", \"Capital\", \"Population\"]\n\ntable = [\n [\"Germany\", \"Berlin\", \"82800000\"],\n [\"South Korea\", \"Seoul\", \"51446201\"],\n [\"China\", \"Beijing\", \"1403500365\"],\n [\"France\", \"Paris\", \"67201000\"],\n [\"Australia\", \"Canberra\", \"24877800\"],\n [\"Netherlands\", \"Amsterdam\", \"17200671\"],\n [\"Iceland\", \"Reykjavik\", \"348580\"]\n]\n\n# Delete a row\ndel table[3]\n\n# Update cell with a new value\ntable[1][1] = \"SEOUL!!\"\n\n# Edit header\nheader[2] = \"PEOPLE!!\"\n\n# Sort table alphabetically by capital\ntable = sorted(table, key=lambda r: r[1])\n\n# Show the table\nt = DataTable(header, padding)\nfor row in table:\n t.add_row(row)\nt.display()\n</code></pre>\n\n<p>This shows the most complicated aspect is interfacing with your code. And it shows that the majority of your code is not needed. To simplify the \"show the table\" section you can make your code a function. And so the following is all the code we need to know, so that we can create the function.</p>\n\n<blockquote>\n<pre><code>class DataTable:\n\n \"\"\"\n Defines the padding between the text and each cell in the table\n \"\"\"\n padding = 2\n\n \"\"\"\n Holds the width of the widest entry of each column in the table\n \"\"\"\n column_widths = []\n\n \"\"\"\n Holds the description for each column header\n \"\"\"\n table_headers = []\n\n \"\"\"\n Holds all the rows and their information\n \"\"\"\n table_data = []\n\n def __init__(self, table_headers, cell_padding):\n \"\"\"\n Creates a new data table of a given size.\n :param table_headers: Array of table headers\n :param cell_padding: The padding between the cell text and the cell border\n \"\"\"\n self.table_headers.append(table_headers)\n self.calculate_widths()\n self.padding = cell_padding\n\n def calculate_widths(self):\n \"\"\"\n Calculate the correct width to the row and cell borders based on the content length in the data table.\n :return: None\n \"\"\"\n # If no headers exist it is not possible to calculate the table widths\n if len(self.table_headers) == 0:\n raise Exception(\"Header required to calculate widths\")\n\n # If no column widths were set initialize them using the header text width\n if len(self.column_widths) == 0:\n for i in range(0, len(self.table_headers[0])):\n self.column_widths.append(len(self.table_headers[0][i]))\n\n # If the table has no rows the header defines the widths\n for i in range(0, len(self.table_headers[0])):\n self.column_widths[i] = len(self.table_headers[0][i]) # check if [0] is right thing to use here\n\n # If the table has rows check all for larger widths then the current one\n for i in range(0, len(self.table_data)):\n for j in range(0, len(self.table_data[i])):\n if len(self.table_data[i][j]) &gt; self.column_widths[j]:\n self.column_widths[j] = len(self.table_data[i][j])\n\n def print_separator(self):\n \"\"\"\n Generates a separator line that fits the table width\n :return: The separator line\n \"\"\"\n output = \"+\"\n for i in range(0, len(self.column_widths)):\n output += (\"-\" * self.column_widths[i]) + (\"-\" * 2 * self.padding) + \"+\"\n return output\n\n def print_header(self):\n \"\"\"\n Generates the table header of the data table formatted for printing\n :return:\n \"\"\"\n output = \"\"\n for i in range(0, len(self.table_headers[0])):\n text = self.table_headers[0][i]\n diff = self.column_widths[i] - len(self.table_headers[0][i])\n output += (\"|\" + \" \" * self.padding + text + diff * \" \" + \" \" * self.padding)\n return output + \"|\"\n\n def print_rows(self):\n \"\"\"\n Prints all rows and the intersecting separators of the data table\n :return: None\n \"\"\"\n output = \"\"\n for j in range(0, len(self.table_data)):\n for i in range(0, len(self.table_data[j])):\n text = self.table_data[j][i]\n diff = self.column_widths[i] - len(self.table_data[j][i])\n output += (\"|\" + \" \" * self.padding + text + diff * \" \" + \" \" * self.padding)\n if j != len(self.table_data) - 1:\n output += \"|\\n\"\n else:\n output += \"|\"\n return output\n\n def display(self):\n \"\"\"\n Displays the formatted data table in text form\n :return: None\n \"\"\"\n print(self.print_separator())\n print(self.print_header())\n print(self.print_separator())\n print(self.print_rows())\n print(self.print_separator())\n</code></pre>\n</blockquote>\n\n<ol>\n<li><p><code>calculate_widths</code> can be simplified by:</p>\n\n<ol>\n<li>Join the headers to the rows for the following calculations.</li>\n<li>Rotate the table by using <code>zip</code>.</li>\n<li>Change all the values to their length.</li>\n<li>Find the longest via <code>max</code>.</li>\n</ol>\n\n<p>This will result in a 1d list of the maximum, and doesn't require any headers.</p></li>\n<li><p><code>print_separator</code> can be simplified by:</p>\n\n<ol>\n<li>Using a list comprehension and <code>str.join</code>.</li>\n<li>Calculating the amount of \"-\" characters together.</li>\n</ol></li>\n<li><p><code>print_header</code> and <code>print_rows</code> can use the same underlying function, differentiated by the input you give it. And so I'm ignoring <code>print_header</code>.</p></li>\n<li><code>print_rows</code> can be simplified by:\n\n<ol>\n<li>Performing the separation of each row with a newline outside the function. And make the function <code>yield</code> each row.</li>\n<li>Looping Pythonically through data via <code>for row in self.table_data</code>, rather than through a range and indexing the data.</li>\n<li>You can use <code>str.format</code> to pad text to a width.</li>\n</ol></li>\n</ol>\n\n<p>To make the changes I made to each function very apparent below is what they look like after the changes, but before making everything a single function.</p>\n\n<pre><code>class DataTable:\n padding = 2\n column_widths = []\n table_headers = []\n table_data = []\n\n def __init__(self, table_headers, cell_padding):\n self.table_headers.append(table_headers)\n self.padding = cell_padding\n\n def calculate_widths(self):\n table = []\n if self.table_headers:\n table += [self.table_headers]\n table += self.table_data\n table = zip(*table)\n self.column_widths = [max(len(t) for t in row) for row in table]\n\n\n def print_separator(self):\n row = [\"-\" * (width + 2 * self.padding) for width in self.column_widths]\n return \"+{}+\".format(\"+\".join(row))\n\n def print_rows(self, data):\n for row in data:\n row = [\n \"|{p}{text: &lt;{width}}{p}|\".format(\n text=text,\n width=width,\n p=\" \" * self.padding\n )\n for text, width in zip(row, self.column_widths)\n ]\n yield \"|{}|\".format(\"|\".join(row))\n\n def display(self):\n self.calculate_widths()\n print(self.print_separator())\n print(next(self.print_rows([self.table_headers])))\n print(self.print_separator())\n print(\"\\n\".join(self.print_rows(self.table_data)))\n print(self.print_separator())\n</code></pre>\n\n<p>After this I'd change the code to a couple of functions:</p>\n\n<pre><code>def _calculate_widths(data, header):\n table = []\n if header:\n table += [header]\n table += data\n table = zip(*table)\n return [max(len(t) for t in row) for row in table]\n\n\ndef _pretty_rows(data, padding, widths):\n for row in data:\n yield \"|\".join(\n ['']\n + [\n \"|{p}{text: &lt;{width}}{p}|\".format(\n text=text,\n width=width,\n p=\" \" * padding\n )\n for text, width in zip(row, widths)\n ]\n + ['']\n )\n\n\ndef _pretty_table(data, padding, header):\n widths = _calculate_widths(data, header)\n seperator = \"+\".join(\n [\"\"]\n + [\"-\" * (width + 2 * padding) for width in widths]\n + [\"\"]\n )\n if header:\n yield seperator\n yield from _pretty_rows([header], padding, widths)\n yield separator\n yield from _pretty_rows(rows, padding, widths)\n yield seperator\n\n\ndef pretty_table(data, *, padding=2, header=None):\n return '\\n'.join(_pretty_table(\n data=data,\n padding=padding,\n header=header\n ))\n</code></pre>\n\n\n\n<pre><code># Show the table\nprint(pretty_table(table, header=header, padding=padding))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:54:32.653", "Id": "212156", "ParentId": "212150", "Score": "2" } } ]
{ "AcceptedAnswerId": "212156", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T18:29:21.527", "Id": "212150", "Score": "2", "Tags": [ "python", "python-3.x", "data-visualization" ], "Title": "Console-based table structure - A python implementation" }
212150
<p>I would like constructive criticism of a networking plugin I've written for Unity 3D. The use-case of the code is for people in "creative coding," where simple TCP and UDP messages are used for communication with lighting controllers, micro-controllers, and other devices, in addition to other computers. The requirement was to make it totally non-blocking, even in the event of a delayed or failed TCP message, so that it would be suitable for use in live performances or guest-experiences in theme parks. It does not support persistent TCP. </p> <p>A design choice was to separate sending and receiving into different classes, in a similar pattern to the graphical language Max. Each of these classes is wrapped by a Unity class (<code>MonoBehaviour</code> derived), messages and errors being passed back and forth from the main Unity thread with <code>ConcurrentQueue</code>.</p> <p><strong>TCP Sending</strong></p> <pre><code>public class TcpThreadedClient { // For returning error messages to main private ConcurrentQueue&lt;string&gt; errorQueue = new ConcurrentQueue&lt;string&gt;(); public void Send(string address, int port, string message) { var sendTask = new Task(() =&gt; SendTask(address, port, message)); sendTask.Start(); } public void SendTask(string address, int port, string message) { using (TcpClient client = new TcpClient()) { try { // Connect to endpoint. Task connect = client.ConnectAsync(address, port); connect.Wait(); // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(message); // Get the NetworkStream and send, // with NoDelay (disable caching). client.NoDelay = true; NetworkStream stream = client.GetStream(); stream.Write(byteData, 0, message.Length); } catch (SocketException se) { PrintError("SocketException connecting to " + address + ":" + port + ": " + se.ToString()); } catch (Exception e) { PrintError("Unexpected exception connecting to " + address + ":" + port + ": " + e.ToString()); } } } private void PrintError(string e) { errorQueue.Enqueue(e); } // Wrapperr uses this function to // get error messages. public bool GetError(out string outError) { // Out promises initialization return errorQueue.TryDequeue(out outError); } </code></pre> <p><strong>TCP Receiving</strong></p> <pre><code>// State object for reading client data asynchronously public class TcpStateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 1024; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } public class TcpThreadedServer { // Queue for sharing messages with Unity main thread. private ConcurrentQueue&lt;NetworkMessage&gt; messageQueue = new ConcurrentQueue&lt;NetworkMessage&gt;(); // For returning error messages to main Unity thread private ConcurrentQueue&lt;string&gt; errorQueue = new ConcurrentQueue&lt;string&gt;(); // Thread signal. public static ManualResetEvent allDone = new ManualResetEvent(false); // For reading new messages from Queue // without exposing Queue to other classes. public bool GetMessage(out NetworkMessage message) { if(messageQueue.TryDequeue(out message)) { return true; } return false; } // Start the network listening thread. public void StartListening(int port) { // uses Task, but with LongRunning option it will create // new thread, not use one from ThreadPool. var listenTask = new Task(() =&gt; ListenTask(port), TaskCreationOptions.LongRunning); listenTask.Start(); } private void ListenTask(int port) { // Establish the local endpoint for the socket. IPAddress ipAddress = IPAddress.Any; IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp); // Bind the socket to the local endpoint and listen for incoming connections. try { listener.Bind(localEndPoint); listener.Listen(100); while (true) { // Set the event to nonsignaled state. allDone.Reset(); // Start an asynchronous socket to listen for connections. listener.BeginAccept( new AsyncCallback(AcceptCallback), listener); // Wait until a connection is made before continuing. allDone.WaitOne(); } } catch (Exception e) { PrintError("Error opening TCP socket: " + e.ToString()); } } private void AcceptCallback(IAsyncResult ar) { // Signal the main thread to continue. allDone.Set(); // Get the socket that handles the client request. Socket listener = (Socket)ar.AsyncState; Socket handler = listener.EndAccept(ar); // Create the state object. TcpStateObject state = new TcpStateObject(); state.workSocket = handler; handler.BeginReceive(state.buffer, 0, TcpStateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } private void ReadCallback(IAsyncResult ar) { string content = string.Empty; // Retrieve the state object and the handler socket // from the asynchronous state object. TcpStateObject state = (TcpStateObject)ar.AsyncState; Socket handler = state.workSocket; // Read data from the client socket. int bytesRead = handler.EndReceive(ar); if (bytesRead &gt; 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString( state.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = state.sb.ToString(); int pos = content.IndexOf("&lt;EOF&gt;"); if (pos &gt; -1) { // All the data has been read from the // client. Place message into Queue for // Unity to retrieve. NetworkMessage message = new NetworkMessage(); message.content = content.Remove(pos); message.clientAddress = ((IPEndPoint)handler.RemoteEndPoint).Address; message.clientPort = ((IPEndPoint)handler.RemoteEndPoint).Port; messageQueue.Enqueue(message); } else { // Not all data received. Get more. handler.BeginReceive(state.buffer, 0, TcpStateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); } } } private void PrintError(string e) { errorQueue.Enqueue(e); } // For container to check for networking errors. public bool GetError(out string outError) { // Out promises initialization return errorQueue.TryDequeue(out outError); } } </code></pre> <p><strong>UDP Sending</strong></p> <pre><code>public class UdpThreadedClient { // For returning error messages to main Unity thread private ConcurrentQueue&lt;string&gt; errorQueue = new ConcurrentQueue&lt;string&gt;(); public void Send(string address, int port, string message) { var sendTask = new Task(() =&gt; SendTask(address, port, message)); sendTask.Start(); } // Even though UDP sends immediately, taking very little time, // it is technically blocking. There are very rare situations // in which the call will take longer than usual, so sending // takes place on a separate thread. public void SendTask(string address, int port, string message) { using (UdpClient client = new UdpClient()) { try { // String address to IPAddress IPAddress ip; IPAddress.TryParse(address, out ip); // Convert message to byte array byte[] buffer = Encoding.ASCII.GetBytes(message); // Creatte IPEndPoint from the given address and port IPEndPoint endPoint = new IPEndPoint(ip, port); // Send the contents of buffer client.Send(buffer, buffer.Length, endPoint); } catch (SocketException se) { PrintError("SocketException sending to " + address + ":" + port + ": " + se.ToString()); } catch (Exception e) { PrintError("Unexpected exception sending to " + address + ":" + port + ": " + e.ToString()); } } } private void PrintError(string e) { errorQueue.Enqueue(e); } // For container to check for networking errors. public bool GetError(out string outError) { // Out promises initialization return errorQueue.TryDequeue(out outError); } } </code></pre> <p><strong>UDP Receiving</strong></p> <pre><code>public class UdpThreadedServer { // Queue for sharing messages with Unity thread. private ConcurrentQueue&lt;NetworkMessage&gt; messageQueue = new ConcurrentQueue&lt;NetworkMessage&gt;(); // For returning error messages to main Unity thread private ConcurrentQueue&lt;string&gt; errorQueue = new ConcurrentQueue&lt;string&gt;(); // For reading new messages from Queue // without exposing Queue to other classes. public bool GetMessage(out NetworkMessage message) { if (messageQueue.TryDequeue(out message)) { return true; } return false; } // Start the network listening thread. public void StartListening(int port) { // Uses Task, but with LongRunning option it will create // new thread, not use one from ThreadPool. var listenTask = new Task(() =&gt; ListenTask(port), TaskCreationOptions.LongRunning); listenTask.Start(); } private void ListenTask(int port) { // Bind the socket to the local endpoint and listen for incoming connections. try { UdpClient udpClient = new UdpClient(port); IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); while (true) { Byte[] buffer = udpClient.Receive(ref remoteEndPoint); string content = Encoding.ASCII.GetString(buffer); NetworkMessage message = new NetworkMessage(); message.content = content; message.clientAddress = remoteEndPoint.Address; message.clientPort = remoteEndPoint.Port; messageQueue.Enqueue(message); } } catch (Exception e) { PrintError("Error opening UDP socket: " + e.ToString()); } } private void PrintError(string e) { errorQueue.Enqueue(e); } // For container to check for networking errors. public bool GetError(out string outError) { // Out promises initialization return errorQueue.TryDequeue(out outError); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:45:49.103", "Id": "410386", "Score": "1", "body": "_Each of these classes is wrapped by a Unity class_ - where exactly? None of these classes here has any other class as its base. And could you clarify which unity you mean? The Unity DI or the Unit3D framework? These are not the same but you seem to use these interchangeably which is very confusing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T18:54:05.250", "Id": "410415", "Score": "0", "body": "Maybe wrapped has a formal meaning I wasn't aware of. What I mean is that, in order to use these, a corresponding MonoBehaviour derived class has one of these as a member, passing in messages to send and polling the Queues for messages received. This is in Unity 3D, the game engine. Sorry for the confusion, where does it look like I'm referring to Unity DI?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T18:58:16.690", "Id": "410421", "Score": "1", "body": "Well, I understand the quoted part as if you had a decorator for it or another base class, that you might have removed. Also when you write just _Unity_ I sounds as if you were referring to the DI package... or e.g. this part _networking plugin I've written for Unity_ - this could also be some module for networking components." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:01:49.473", "Id": "410422", "Score": "0", "body": "I see, edited for clarity." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T06:27:04.173", "Id": "410464", "Score": "0", "body": "@t3chb0t In all fairness, the correct [tag:unity3d] tag was used." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T07:31:37.953", "Id": "410471", "Score": "0", "body": "@Mast well, since OP didn't know about the difference, one couldn't tell what was actually correct. The question or the tag. And there was also absolutely no evidence of using unity3d before the edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T08:53:36.360", "Id": "410482", "Score": "0", "body": "\"And there was also absolutely no evidence of using unity3d before the edit.\" Except for exactly the right tag being used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T23:35:13.023", "Id": "411363", "Score": "0", "body": "I rolled back your last edit. After getting an answer you are not allowed to change your code anymore. This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information. *Protip*: you likely gain more reputation if you post an updated question with the update." } ]
[ { "body": "<h2>General</h2>\n\n<p>From the code that you posted it looks like you are creating a client for every message that you are sending, this isn't very common behavior. Unless there is a specific reason i would expect the connection to be reused multiple times. I.e. at start set up the client and then use the existing connection to write as often as needed. </p>\n\n<p>Creating asynchronous flows is not easy and neither is network programming in general. I am not that versed in .NET network programming, but you are already using the socket with some of its callbacks on the server side. I would probably choose a similar approach on the clients side. Using <code>BeginSend()</code> on the clients socket rather than <code>stream.write()</code> will make the writing asynchrounos without having to create a separate task for it, and also without having to start a new connection for every message written. </p>\n\n<p>Why not use the <code>ReadCallback()</code> in the UDP Server code ? You use in in the TCP server code. But the UDP code uses the blocking <code>Read()</code> method. </p>\n\n<h2>Calls that may fail</h2>\n\n<p>You have <code>GetError()</code> and <code>GetMessage()</code> that indicate success or failure with a boolean. A good convention is to prefix these with <code>Try</code> (as the queue does) to indicate not only a function that may fail but also to remind the user of your API that they should check the return value of these functions. </p>\n\n<h2>Errors as strings</h2>\n\n<p>Your mileage may vary but having errors only as strings may make discerning what the error was from software a bit harder than necessary, using an <code>enum</code> for the specific error types might make it easier for the client software to actually deal with errors. Pairing this enum with a string explanation might give you the best of both worlds. </p>\n\n<h2><code>PrintError()</code></h2>\n\n<p>I did a double take, and was wondering why just print out the errors, and then I realized you actually are queuing up the errors, in this case i'd probably just get rid of the function and call enqueue directly when needed. </p>\n\n<h2>Superclass</h2>\n\n<p>To make it a little bit more convenient for the users you could introduce interfaces that can be used independent of whether the actual Server or Client is UPD or TCP. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:27:44.113", "Id": "410427", "Score": "0", "body": "I super appreciate the suggestions. Can you help me with one? I used Task to avoid blocking or waiting when I connectd. Thinking about your answer I may have had a realization - ALL the code after the Asynchronous connection request can go into the callback, which is called on another thread, which avoids blocking? [The MSDN example](https://docs.microsoft.com/en-us/dotnet/api/system.net.sockets.tcpclient.beginconnect?view=netframework-4.7.2) has the code waiting for the Async request to finish, but that is probably an illustration and I just realized - I don't need to do that, do I?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T19:01:31.883", "Id": "411013", "Score": "0", "body": "@Yosemite Looking at the documentation yes, there are various callbacks for each of the events that might happen. Looking at the examples on that page yes I would think that the waits in there are just for the purpose of the example." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T21:21:37.787", "Id": "212165", "ParentId": "212151", "Score": "4" } } ]
{ "AcceptedAnswerId": "212165", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:13:32.063", "Id": "212151", "Score": "7", "Tags": [ "c#", "networking", "unity3d", "tcp", "udp" ], "Title": "Non-blocking TCP and UDP in Unity3D Game Engine" }
212151
<p>My code tries to solve the wooden snake chain puzzle:</p> <p><a href="https://i.stack.imgur.com/SknqG.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SknqG.gif" alt="enter image description here"></a></p> <p>I do so by generating all possible link configurations which are then tested. I was hoping that laziness would take care of the very many configurations. But it seems that I was wrong. While the program runs for smaller chains (cf. <code>lengths'</code> which gives the lengths of the individual segments), it won't complete for the full chain (<code>lengths</code>). I have used profile runs to make some modifications but I don't have many ideas left besides starting over. I have also attached the result of a profile run.</p> <p><em>What can I do (besides starting over) to optimize the program such that it can solve the complete chain (ie. <code>lengths</code> instead of <code>lengths'</code>)?</em></p> <p>Source with <a href="https://pastebin.com/raw/ET1ta9BB" rel="nofollow noreferrer">pastebin link</a></p> <pre><code>import Data.Array (Array, array, bounds, range, (//), (!)) import Data.List (intercalate) import Data.Maybe (catMaybes) import Prelude {- - There is a puzzle whit the objectiv of folding a chain of wooden segments - into a 3x3x3 cube. This program attempts to solve this puzzle by testing - all the different possible configurations of the links between the segments. - - Example: Chain with segment lengths: `[3, 3, 3]` - - [X][ ][X] - [ ] - [X][ ][X] - - and a possible placement (in the z=0 plane) - - 1 1 1 - 0 0 2 - 3 3 2 - - * The segments are labeled with ids: 1, 2, 3. - * The link between segments can be in configuration 1, 2, 3, 4. - * The orientation of the segments: X, X', Y, Y', Z, Z'. - -} lengths = [3, 3, 3, 3, 2, 2, 2, 3, 3, 2, 2, 3, 2, 3, 2, 2, 3] :: [Int] lengths'= [3, 3, 3, 3, 2, 2, 2, 3, 3, 2] :: [Int] main = printSolution lengths' type Grid = Array (Int, Int, Int) Int data Orientation = X | X' | Y | Y' | Z | Z' deriving (Show) data Segment = Seg { id :: Int, len :: Int, orientation :: Orientation } deriving Show show1D grid y z = intercalate " " $ map (\i -&gt; show $ grid!(i,y,z)) [0..2] show2D grid z = let hdr = "z=" ++ show z body = intercalate "\n" $ map (\i -&gt; show1D grid i z) [0..2] in hdr ++ "\n" ++ body show3D grid = intercalate "\n\n" $ map (\i -&gt; show2D grid i) [0..2] show3D' grid = putStrLn $ show3D grid -- Place a segment within the grid. If the placement is possible, return -- `Just (grid, endPos)` where `endPos` is the position of the last cube in -- the segment. placeSeg grid pos seg@(Seg id _ _) = let destPositions = placeSeg' pos seg -- The first and last cube overlap. This function chooses the second -- variant (see picture below). Therefore the first cube is handled -- specially. -- -- 1 1 2 1 1 1 -- 0 0 2 versus 2 -- 0 0 2 2 -- curFirstId = grid!pos newFirstId = if curFirstId == 0 then id else curFirstId values = (pos, newFirstId) : (map (\p -&gt; (p, id)) (tail destPositions)) grid' = grid // values in -- We must not check the first destination, it is already taken. if all isValidPos (tail destPositions) then Just (grid', last destPositions) else Nothing where -- Returns the list of positions when placing a segment of a given length -- and orientation. -- eg: placeSeg' (0,0,0) (Seg _ 3 Y) = [(0,0,0), (0, 1, 0), (0, 2, 0)] placeSeg' _ seg@(Seg _ 0 _) = [] placeSeg' pos (Seg _ len orient) = pos : placeSeg' (nextPos pos orient) seg { len = len-1 } isValidPos pos = (isInRange (bounds grid) pos) &amp;&amp; (grid ! pos == 0) isInRange ((xmin, ymin, zmin), (xmax, ymax, zmax)) (x,y,z) = isInRange' xmin xmax x &amp;&amp; isInRange' ymin ymax y &amp;&amp; isInRange' zmin zmax z where isInRange' a b x = a &lt;= x &amp;&amp; x &lt;= b nextPos (x,y,z) X = (x+1,y,z) nextPos (x,y,z) X' = (x-1,y,z) nextPos (x,y,z) Y = (x,y+1,z) nextPos (x,y,z) Y' = (x,y-1,z) nextPos (x,y,z) Z = (x,y,z+1) nextPos (x,y,z) Z' = (x,y,z-1) placeChain :: Grid -&gt; [Segment] -&gt; Maybe Grid placeChain grid segments = let start = Just (grid, (0,0,0)) placement = foldl f start segments in placement &gt;&gt;= (\(grid', _) -&gt; Just grid') where f (Just (grid', pos')) seg = placeSeg grid' pos' seg f Nothing _ = Nothing -- Convert the (local) link configuration (1, 2, 3, 4) to the (global) -- orientation. linkConfToOrientation :: Orientation -&gt; Int -&gt; Orientation -- There are many different assignments possible. This is just a possible one. linkConfToOrientation X 1 = Y linkConfToOrientation X 2 = Z linkConfToOrientation Y 1 = Z linkConfToOrientation Y 2 = X linkConfToOrientation Z 1 = X linkConfToOrientation Z 2 = Y -- The assignment for the "negative" orientations is also arbitrary. linkConfToOrientation X' 1 = Y linkConfToOrientation X' 2 = Z' linkConfToOrientation Y' 1 = Z linkConfToOrientation Y' 2 = X' linkConfToOrientation Z' 1 = X linkConfToOrientation Z' 2 = Y' linkConfToOrientation orient conf = reflect $ linkConfToOrientation orient (conf - 2) reflect :: Orientation -&gt; Orientation reflect X = X' reflect X' = X reflect Y = Y' reflect Y' = Y reflect Z = Z' reflect Z' = Z chainFromConf :: Orientation -&gt; [Int] -&gt; [Int] -&gt; [Segment] chainFromConf startOrientation lengths conf = let orientations = scanl linkConfToOrientation startOrientation conf in zipWith3 Seg [1..(length lengths)] lengths orientations -- Note: The values of `(tail lengths)` are not used, only its size. allLinkConfigs lengths = mapM (const [1..4]) (tail lengths) placements lengths = let chains = map (chainFromConf X lengths) (allLinkConfigs lengths) bounds = ((0,0,0), (2,2,2)) grid = array bounds [(pos, 0) | pos &lt;- range bounds] placements' = catMaybes $ map (placeChain grid) chains in map show3D placements' printSolution lengths = putStrLn $ intercalate "\n\n" (placements lengths) </code></pre> <p>Profiler run with <a href="https://pastebin.com/raw/qCm1uY5U" rel="nofollow noreferrer">pastbin link</a>:</p> <pre><code> Thu Jan 24 19:45 2019 Time and Allocation Profiling Report (Final) woodenCube +RTS -p -RTS total time = 2.21 secs (2214 ticks @ 1000 us, 1 processor) total alloc = 4,112,689,072 bytes (excludes profiling overheads) COST CENTRE MODULE SRC %time %alloc placeSeg.grid' Main woodenCube.hs:70:5-26 20.7 12.6 placeSeg.isValidPos Main woodenCube.hs:(86,5)-(87,41) 16.0 10.4 placeSeg.isInRange.isInRange' Main woodenCube.hs:94:9-43 14.5 7.0 placeSeg Main woodenCube.hs:(54,1)-(101,34) 11.6 18.5 placeSeg.placeSeg' Main woodenCube.hs:(82,5)-(84,62) 7.2 9.8 chainFromConf Main woodenCube.hs:(142,1)-(146,59) 6.4 13.9 placeSeg.nextPos Main woodenCube.hs:(96,5)-(101,34) 5.5 3.7 placeSeg.isInRange Main woodenCube.hs:(89,5)-(94,43) 3.5 6.8 chainFromConf.orientations Main woodenCube.hs:144:5-68 3.1 6.4 placeChain.placement Main woodenCube.hs:107:5-38 2.9 2.7 placeChain.f Main woodenCube.hs:(111,5)-(112,25) 2.2 0.9 placeSeg.values Main woodenCube.hs:68:5-75 1.7 3.2 placeChain Main woodenCube.hs:(104,1)-(112,25) 1.3 0.9 linkConfToOrientation Main woodenCube.hs:(118,1)-(131,85) 1.0 0.4 allLinkConfigs Main woodenCube.hs:149:1-59 0.6 1.0 individual inherited COST CENTRE MODULE SRC no. entries %time %alloc %time %alloc MAIN MAIN &lt;built-in&gt; 40 0 0.0 0.0 100.0 100.0 CAF GHC.IO.Encoding.CodePage &lt;entire-module&gt; 68 0 0.0 0.0 0.0 0.0 CAF GHC.IO.Handle.Text &lt;entire-module&gt; 65 0 0.0 0.0 0.0 0.0 CAF GHC.IO.Encoding &lt;entire-module&gt; 63 0 0.0 0.0 0.0 0.0 CAF GHC.IO.Handle.FD &lt;entire-module&gt; 57 0 0.0 0.0 0.0 0.0 CAF Main &lt;entire-module&gt; 47 0 0.0 0.0 99.7 100.0 lengths' Main woodenCube.hs:30:1-49 88 1 0.0 0.0 0.0 0.0 main Main woodenCube.hs:161:1-29 80 1 0.0 0.0 99.7 100.0 printSolution Main woodenCube.hs:159:1-74 81 1 0.0 0.0 99.7 100.0 placements Main woodenCube.hs:(150,1)-(157,26) 84 1 0.0 0.0 99.7 100.0 show3D Main woodenCube.hs:48:1-67 113 12 0.0 0.0 0.0 0.0 show3D.\ Main woodenCube.hs:48:47-59 114 36 0.0 0.0 0.0 0.0 show2D Main woodenCube.hs:(45,1)-(47,38) 115 36 0.0 0.0 0.0 0.0 show2D.body Main woodenCube.hs:46:21-80 117 36 0.0 0.0 0.0 0.0 show2D.body.\ Main woodenCube.hs:46:58-72 118 108 0.0 0.0 0.0 0.0 show1D Main woodenCube.hs:44:1-74 119 108 0.0 0.0 0.0 0.0 show1D.\ Main woodenCube.hs:44:48-66 120 324 0.0 0.0 0.0 0.0 show2D.hdr Main woodenCube.hs:45:21-40 116 36 0.0 0.0 0.0 0.0 placements.bounds Main woodenCube.hs:153:5-31 102 1 0.0 0.0 0.0 0.0 placements.chains Main woodenCube.hs:152:5-67 86 1 0.3 0.6 11.6 22.3 chainFromConf Main woodenCube.hs:(142,1)-(146,59) 91 262144 6.4 13.9 10.7 20.7 chainFromConf.orientations Main woodenCube.hs:144:5-68 92 262144 3.1 6.4 4.2 6.8 linkConfToOrientation Main woodenCube.hs:(118,1)-(131,85) 108 758436 1.0 0.4 1.2 0.4 reflect Main woodenCube.hs:(134,1)-(139,14) 109 252812 0.1 0.0 0.1 0.0 allLinkConfigs Main woodenCube.hs:149:1-59 87 1 0.6 1.0 0.6 1.0 placements.grid Main woodenCube.hs:154:5-56 101 1 0.0 0.0 0.0 0.0 placements.placements' Main woodenCube.hs:155:5-58 85 1 0.3 0.6 88.1 77.7 placeChain Main woodenCube.hs:(104,1)-(112,25) 89 262144 1.3 0.9 87.8 77.1 placeChain.placement Main woodenCube.hs:107:5-38 90 262144 2.9 2.7 86.5 76.2 placeChain.f Main woodenCube.hs:(111,5)-(112,25) 93 2621440 2.2 0.9 83.6 73.5 placeSeg Main woodenCube.hs:(54,1)-(101,34) 95 767768 11.6 18.5 81.4 72.7 placeSeg.isValidPos Main woodenCube.hs:(86,5)-(87,41) 98 1262072 16.0 10.4 34.1 24.1 placeSeg.isInRange Main woodenCube.hs:(89,5)-(94,43) 99 1262072 3.5 6.8 18.1 13.7 placeSeg.isInRange.isInRange' Main woodenCube.hs:94:9-43 104 3587318 14.5 7.0 14.5 7.0 placeSeg.bnds Main woodenCube.hs:72:5-22 100 767768 0.5 0.4 0.5 0.4 placeSeg.destPositions Main woodenCube.hs:56:5-37 96 767768 0.2 0.3 12.9 13.8 placeSeg.placeSeg' Main woodenCube.hs:(82,5)-(84,62) 97 2535476 7.2 9.8 12.7 13.5 placeSeg.nextPos Main woodenCube.hs:(96,5)-(101,34) 103 1262072 5.5 3.7 5.5 3.7 placeSeg.grid' Main woodenCube.hs:70:5-26 105 505636 20.7 12.6 20.7 12.6 placeSeg.values Main woodenCube.hs:68:5-75 106 505636 1.7 3.2 1.7 3.2 placeSeg.values.\ Main woodenCube.hs:68:46-52 107 989244 0.0 0.0 0.0 0.0 placeSeg.curFirstId Main woodenCube.hs:66:5-25 111 8798 0.1 0.1 0.1 0.1 placeSeg.newFirstId Main woodenCube.hs:67:5-59 110 8798 0.0 0.0 0.0 0.0 placeChain.start Main woodenCube.hs:106:5-32 94 262144 0.0 0.0 0.0 0.0 placeChain.\ Main woodenCube.hs:109:35-44 112 12 0.0 0.0 0.0 0.0 main Main woodenCube.hs:161:1-29 82 0 0.0 0.0 0.3 0.0 printSolution Main woodenCube.hs:159:1-74 83 0 0.3 0.0 0.3 0.0 </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:45:38.143", "Id": "410290", "Score": "0", "body": "I [changed the title](https://codereview.stackexchange.com/posts/212152/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:36:34.650", "Id": "212152", "Score": "2", "Tags": [ "performance", "haskell", "time-limit-exceeded" ], "Title": "Solving the wooden snake chain puzzle" }
212152
<p>Here is an initial attempt at unit test of user input in C. The thing that feels unusual is the use of freopen to send the test data to stdin. Are there better ways to implement this kind of test?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;assert.h&gt; static size_t get_num(size_t tmpnum) { if (scanf("%zu", &amp;tmpnum) != 1) { fprintf(stderr, "ERROR: system error: failed to read input, exiting.\n"); exit(1); } return tmpnum; } int main(void) { int return_status = 0; /* Test 1 */ if (freopen("test-data.txt", "r", stdin) != NULL) { size_t tmpnum = 0; tmpnum = get_num(tmpnum); assert(tmpnum &gt;= 1 &amp;&amp; tmpnum &lt;= 20); printf("ok: tmpnum == %ld\n", tmpnum); freopen("/dev/stdin", "r", stdin); } else { printf("ERROR: failed to open test-data.txt\n"); return_status = EXIT_FAILURE; } return return_status; } </code></pre>
[]
[ { "body": "<blockquote>\n<p>The thing that feels unusual is the use of freopen to send the test data to stdin.</p>\n<p>Are there better ways to implement this kind of test?</p>\n</blockquote>\n<p>C has a <code>freopen()</code> footnote</p>\n<blockquote>\n<p>The primary use of the <code>freopen</code> function is to change the file associated with a standard text stream (<code>stderr</code>, <code>stdin</code>, or <code>stdout</code>), as those identifiers need not be modifiable lvalues to which the value returned by the <code>fopen</code> function may be assigned.</p>\n</blockquote>\n<p>This looks like a good direct way to test code, although I'd expect <code>stdout</code>, <code>strderr</code> being re-opened to capture output.</p>\n<hr />\n<blockquote>\n<p>Are there better ways</p>\n</blockquote>\n<p>Enable all compiler warnings - save time.</p>\n<p>The mismatch of specifier and type implies code is not efficiently using the 1st round of code improvement: Compiler warnings.</p>\n<pre><code>// printf(&quot;ok: tmpnum == %ld\\n&quot;, tmpnum);\nprintf(&quot;ok: tmpnum == %zu\\n&quot;, tmpnum);\n</code></pre>\n<hr />\n<p>Code is strange in that it passes in <code>tmpnum</code> for no good reason.</p>\n<pre><code>//static size_t get_num(size_t tmpnum) {\n// if (scanf(&quot;%zu&quot;, &amp;tmpnum) != 1) {\n\nstatic size_t get_num(void) {\n size_t tmpnum;\n if (scanf(&quot;%zu&quot;, &amp;tmpnum) != 1) {\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:53:49.720", "Id": "410438", "Score": "0", "body": "1. Not sure what you mean about stdout and stderr. The code doesn't change them, should it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T20:05:55.303", "Id": "410440", "Score": "0", "body": "2. There weren't any compiler warnings for the specifier missmatch. I used this compiler command: clang -Wall -Wextra -Weverything -pedantic code_review.c -o code_review.o. I corrected the specifier anyways as you suggested." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T20:08:12.197", "Id": "410441", "Score": "0", "body": "3. @chux Thanks for pointing out the that tmpnum didn't need to be passed to get_num(). I've removed it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T00:01:08.163", "Id": "410451", "Score": "0", "body": "@RunwayBlues The idea of re-opening `stderr`, `stdout` would allow the test code a step towards automatically testing if `get_num()` performed as expected. It appears that `atexit()` would also be needed to catch the `fprintf(stderr, \"ERROR: system error: failed to read input, exiting.\\n\");\n exit(1);`. It simply comes down to how much do you want to wrap around the testing of `get_num()` to provide/catch all its input/output." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T02:27:46.547", "Id": "212184", "ParentId": "212155", "Score": "1" } } ]
{ "AcceptedAnswerId": "212184", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:54:27.327", "Id": "212155", "Score": "1", "Tags": [ "c", "unit-testing", "io" ], "Title": "Simple unit test in C of input using freopen" }
212155
<p>Any problems with this D wrapper around <code>libcomcom_run_command()</code> C function from C library <a href="https://github.com/vporton/libcomcom" rel="nofollow noreferrer">libcomcom</a>?</p> <p>Does it work as expected? Is it idiomatic? Is it the right way to do this?</p> <pre><code>module libcomcom_wrapper; import std.string; import std.algorithm.iteration : map; import std.array : array; import std.exception : ErrnoException; import libcomcom; string runCommand(string file, string[] argv, string[] envp, string input, int timeout = -1) { const(char*) output; size_t output_len; const char*[] childArgv = map!(s =&gt; s.toStringz)(argv).array; const char*[] childEnvp = map!(s =&gt; s.toStringz)(envp).array; immutable int res = libcomcom_run_command(input.ptr, input.length, &amp;output, &amp;output_len, file.toStringz, childArgv.ptr, childEnvp.ptr, timeout); if (res != 0) { throw new ErrnoException("Run command"); // TODO: Localization } import core.stdc.stdlib : free; scope(exit) free(cast(void*) output); return output[0..output_len].idup; } </code></pre> <p>The code was taken <a href="https://github.com/D-Programming-Deimos/libcomcom/blob/3cd76a25e2e4195b26bb1e642a3e4a7f1ede460d/deimos/libcomcom_wrapper.d" rel="nofollow noreferrer">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T20:35:35.220", "Id": "410298", "Score": "0", "body": "I've discovered that I can use just `toStringz` instead of `s => s.toStringz`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T18:33:13.263", "Id": "410526", "Score": "0", "body": "Need to add `~ null` after every `.array` (as otherwise there is no array terminator and it is undefined behavior probably)" } ]
[ { "body": "<p>Nitpick: <code>map!(s =&gt; s.toStringz)(argv)</code> would be more idiomatic as <code>argv.map!toStringz</code>. Apart from that, your code looks very much correct. It should work as expected, and is indeed the way to do this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T07:27:10.530", "Id": "212195", "ParentId": "212157", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:55:52.500", "Id": "212157", "Score": "0", "Tags": [ "wrapper", "child-process", "d" ], "Title": "A D wrapper around a C function" }
212157
<p>I want to find the fastest method of getting the range object which contains all values in a worksheet, while only containing 1 area. Traditionally one might think this is what <code>UsedRange</code> does, however <code>UsedRange</code> often selects cells outside of the value range.</p> <p><a href="https://i.stack.imgur.com/pQEvT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pQEvT.png" alt="screenshot of selection in workbook"></a></p> <p>I believe there is no existing VBA range which will suffice to this criteria alone then so I set out to build my own. I tested 2 versions. The first exploits the <code>SpecialCells()</code> function:</p> <pre><code>Function ValueBoundingBox(sht As Worksheet) As Range 'Get used range Dim ur As Range Set ur = sht.UsedRange 'If used range is 1x1 then result is 1x1 If ur.Rows.Count = 1 And ur.Columns.Count = 1 Then Set ValueBoundingBox = ur Exit Function End If 'Find all non-empty cells Dim x As Range Set x = Application.Union( _ ur.SpecialCells(xlCellTypeConstants), _ ur.SpecialCells(xlCellTypeFormulas) _ ) 'Loop over all areas Dim area As Range, colMin, colMax, rowMin, rowMax, colArea, colAreaMax, rowArea, rowAreaMax As Long 'Set Initial (Large) values for colMin and rowMin rowMin = 1048576 colMin = 16384 'Loop over all areas selected by special cells. For Each area In x.Areas With area 'Calculate min and max rows/cols of area colArea = .Column colAreaMax = .Column + .Columns.Count rowArea = .row rowAreaMax = .row + .Rows.Count 'Calculate min/max of range based on these values If rowAreaMax &gt; rowMax Then rowMax = rowAreaMax If rowArea &lt; rowMin Then rowMin = rowArea If colAreaMax &gt; colMax Then colMax = colAreaMax If colArea &lt; colMin Then colMin = colArea End With Next 'Return bounding box Set ValueBoundingBox = Range(sht.Cells(rowMin, colMin), sht.Cells(rowMax, colMax)) End Function </code></pre> <p>The next uses the array of values extracted from a range to determine the minimum and maximum rows:</p> <pre><code>Function ValueBoundingBox2(sht As Worksheet) As Range 'Get used range Dim ur As Range Set ur = sht.UsedRange 'If used range is 1x1 then result is 1x1 If ur.Rows.Count = 1 And ur.Columns.Count = 1 Then Set ValueBoundingBox2 = ur Exit Function End If 'Find via array 'Get array of all values: Dim v As Variant v = ur.Value 'Define required values Dim colMin, colMax, rowMin, rowMax, row, col As Long 'Find min row: For row = LBound(v, 1) To UBound(v, 1) For col = LBound(v, 2) To UBound(v, 2) If Not IsEmpty(v(row, col)) Then rowMin = row GoTo NextNum End If Next Next NextNum: 'Find max row For row = UBound(v, 1) To LBound(v, 1) Step -1 For col = LBound(v, 2) To UBound(v, 2) If Not IsEmpty(v(row, col)) Then rowMax = row GoTo NextNum2 End If Next Next NextNum2: 'Find min col: For col = LBound(v, 2) To UBound(v, 2) For row = LBound(v, 1) To UBound(v, 1) If Not IsEmpty(v(row, col)) Then colMin = col GoTo NextNum3 End If Next Next NextNum3: 'Find max col For col = UBound(v, 2) To LBound(v, 2) Step -1 For row = LBound(v, 1) To UBound(v, 1) If Not IsEmpty(v(row, col)) Then colMax = col GoTo NextNum4 End If Next Next NextNum4: Set ValueBoundingBox2 = Range(sht.Cells(rowMin, colMin), sht.Cells(rowMax, colMax)) End Function </code></pre> <p>Testing the above functions for performance results in the following results:</p> <pre><code>| Proc name | Time taken | |-------------------|------------| | ValueBoundingBox | 52s | | ValueBoundingBox2 | 1s | </code></pre> <p>Clearly the 2nd version I made is far superior than the version which exploits <code>SpecialCells()</code> however I was wondering whether anyone else had any other ideas to speed up the algorithm further?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T21:08:23.113", "Id": "410301", "Score": "0", "body": "Given the example data in your image, you're expecting the function to return a range including only `A1:A2` (the first contiguous data range) or `A1:D7` (the bounding box containing all available data)? Also, what dataset are you testing the code to get the shown execution times?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T21:09:21.780", "Id": "410302", "Score": "0", "body": "Additionally, your `ValueBoundingBox` function fails for me on the line `Set x = Application.Union` when using the dataset in your image." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T11:53:08.537", "Id": "410368", "Score": "0", "body": "Hi @PeterT sorry about the confusion. Yes \"the bounding box containing all available data\" is what I wanted i.e. `A1:D7`. Also you are correct, I didn't actually test the first function on that dataset in the image. That's just an example I found online :P I guess the alternative would be checking whether the range has values before hand, however it doesn't matter massively given the fact it's super slow :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T02:37:50.250", "Id": "410896", "Score": "0", "body": "@Sancam Good catch. My logic for my loops was just bad. `STD_Performance` is missing from your past bin. Can you add it or better yet provide download link fr the test workbook? I thought of a simpler solution but don't want to post it without a speed comparison." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:40:46.200", "Id": "410920", "Score": "0", "body": "@TinMan Good spot. I though I had removed the dependency but apparrently not. Here you go: https://pastebin.com/zPWKkYtM" } ]
[ { "body": "<p>This should work. It's pretty simple method. I cannot test with your sheet as mine is not nearly that large, but you can try it.</p>\n\n<p>IMPORTANT NOTE: This MUST be called as a Sub if it is a function that is called from a cell then, it will not work. (because excel uses the active range to perform the start of the SpecialCells I believe).</p>\n\n<p>I have tested this code with your picture of cells and it works well.</p>\n\n<p>It also works with other versions of cell combinations and locations that I have tested.</p>\n\n<p>The reason to use the following code is because it is simple and can save valuable programming time. The SpecialCells Method is reliable if used correctly just like any other programming language and function. It is worth a try and also worth timing with your larger data. </p>\n\n<p>In addition, the OP also uses SpecialCells in his code, just not the same way that I have.</p>\n\n<p>I hope this helps.</p>\n\n<pre><code> Option Explicit\n\n Sub RunIT()\n 'Input range must be the first cell of where the data starts\n GetAllCells Range(\"A1\")\n End Sub\n\n Public Sub GetAllCells(rngInStartingRange As Range)\n Dim strTemp As String\n\n strTemp = Range(rngInStartingRange, rngInStartingRange.SpecialCells(xlLastCell, xlTextValues)).Address\n End Sub\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:39:12.433", "Id": "410400", "Score": "0", "body": "Thanks, I'll have a look to see whether using special cells in this way is any faster :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T07:32:24.873", "Id": "410472", "Score": "0", "body": "after looking at @vbasic2008 's post I would use his. It is what you see is what you get as opposed to .specialcells (only Microsoft can see the logic)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T11:27:21.760", "Id": "410492", "Score": "0", "body": "It is 5 times slower than this method and 100 times slower than the 2nd code I posted... xD I'm going to post the results today :) Also the \"Important note\" you mentioned isn't actually true from my testing... I'll post the test cases I used also :)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:00:08.523", "Id": "410515", "Score": "0", "body": "Unfortunately this fails when cells are formatted external to the cells which contain values." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T20:24:58.580", "Id": "212163", "ParentId": "212162", "Score": "1" } }, { "body": "<p>In terms of speeding up your 2nd option. The following code changes should work.\nNOTICE that I put in a decrement counter in each loop. this should half the loops' run time.</p>\n\n<p>You can then do this for each of your NextNum sections (NextNum, NextNum2, NextNum3, and NextNum4)</p>\n\n<pre><code> Dim intK as integer\n Dim intUB1 as integer\n Dim intL as integer\n Dim intUB2 as integer\n\n 'Find min row:\n intUB1 = UBOUND(v,1)\n intK = intUB1\n intUB2 = UBound(v,2)\n For row = LBound(v, 1) To intUB1\n intL = intUB2\n For col = LBound(v, 2) To intUB2\n If Not IsEmpty(v(row, col)) Then\n rowMin = row\n GoTo NextNum\n End If\n If Not IsEmpty(v(row, intL)) Then\n rowMin = row\n GoTo NextNum\n End If\n\n if intL &lt;= row then Exit For\n intL = intL - 1\n Next\n For col = LBound(v, 2) To intUB2\n If Not IsEmpty(v(intK, col)) Then\n rowMin = intK\n GoTo NextNum\n End If\n If Not IsEmpty(v(intK, intL)) Then\n rowMin = intK\n GoTo NextNum\n End If\n\n if intL &lt;= row then Exit For\n intL = intL - 1\n Next\n\n if intK &lt;= row then exit for\n intK = intK - 1\n Next\n NextNum:\n\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:35:07.610", "Id": "410396", "Score": "0", "body": "That is quite ingenious! I will definitely test to see whether this is faster! Also, I forgot that storing `UBound` is faster than calculating it at the end of the loop arg. Thanks for the input!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:38:00.963", "Id": "410399", "Score": "0", "body": "You are welcome. Glad I could help." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T01:21:57.863", "Id": "212181", "ParentId": "212162", "Score": "1" } }, { "body": "<h1>The Real Used Range (not UsedRange)</h1>\n\n<h2>Using the Find Method</h2>\n\n<p>I've recently written this function:</p>\n\n<pre><code>'*******************************************************************************\n' Purpose: Returns the used range of a worksheet.\n' Returns: Range Object.\n'*******************************************************************************\nFunction URng(Optional NotActiveSheet As Worksheet) As Range\n Dim objWs As Worksheet\n If Not NotActiveSheet Is Nothing Then\n Set objWs = NotActiveSheet\n Else: Set objWs = ActiveSheet: End If\n If Not objWs Is Nothing Then\n With objWs\n If Not .Cells.Find(\"*\", .Cells(.Rows.count, .Columns.count), -4123, , 1) _\n Is Nothing Then Set URng = .Range(.Cells(.Cells.Find(\"*\", _\n .Cells(.Rows.count, .Columns.count)).Row, .Cells.Find(\"*\", _\n .Cells(.Rows.count, .Columns.count), , , 2).Column), .Cells(.Cells _\n .Find(\"*\", , , , 1, 2).Row, .Cells.Find(\"*\", , , , 2, 2).Column))\n End With\n Set objWs = Nothing\n End If\nEnd Function\n'*******************************************************************************\n' Remarks: To remove any confusion about the search, consider a worksheet *\n' containing only 3 rows and 3 columns. Then the search order *\n' would be: *\n' ------------------------------------------------------------------\n' | Type | Start | Search Order |\n' |----------------------------------------------------------------|\n' | First Used Row | C3 | A1,B1,C1,A2,B2,C2,A3,B3,C3. |\n' | First Used Column | C3 | A1,A2,A3,B1,B2,B3,C1,C2,C3. |\n' | Last Used Row | A1 | C3,B3,A3,C2,B2,A2,C1,B1,A1. |\n' | Last Used Column | A1 | C3,C2,C1,B3,B2,B1,A3,A2,A1. |\n'*******************************************************************************\n</code></pre>\n\n<p>where you might find the following part to your interest:</p>\n\n<pre><code>With objWs\n If Not .Cells.Find(\"*\", .Cells(.Rows.count, .Columns.count), -4123, , 1) _\n Is Nothing Then Set URng = .Range(.Cells(.Cells.Find(\"*\", _\n .Cells(.Rows.count, .Columns.count)).Row, .Cells.Find(\"*\", _\n .Cells(.Rows.count, .Columns.count), , , 2).Column), .Cells(.Cells _\n .Find(\"*\", , , , 1, 2).Row, .Cells.Find(\"*\", , , , 2, 2).Column))\nEnd With\n</code></pre>\n\n<p>or in a Sub</p>\n\n<pre><code>Sub RealUsedRange()\n\n Const cSheet As Variant = \"Sheet1\" ' Worksheet Name/Index\n\n Dim URng As Range ' Real Used Range\n\n With ThisWorkbook.Worksheets(cSheet)\n If Not .Cells.Find(\"*\", .Cells(.Rows.Count, .Columns.Count), -4123, , _\n 1) Is Nothing Then Set URng = .Range(.Cells(.Cells.Find(\"*\", _\n .Cells(.Rows.Count, .Columns.Count)).Row, .Cells.Find(\"*\", _\n .Cells(.Rows.Count, .Columns.Count), , , 2).Column), _\n .Cells(.Cells.Find(\"*\", , , , 1, 2).Row, .Cells _\n .Find(\"*\", , , , 2, 2).Column))\n End With\n\n If Not URng Is Nothing Then\n Debug.Print \"The Real Used Range address is [\" &amp; URng.Address &amp; \"]\"\n Else\n MsgBox \"Worksheet '\" &amp; cSheet &amp; \"' is empty.\"\n End If\n\nEnd Sub\n</code></pre>\n\n<p><a href=\"https://stackoverflow.com/questions/53727142/how-to-find-the-first-and-last-populated-cell-in-a-range-with-whitespace/53733361#53733361\">Other 'fractions' of the Real Used Range using the Find Method.</a></p>\n\n<p>By the way, as the UsedRange property has failed you so will the SpecialCells method rather sooner than later since they are somehow connected. See <a href=\"https://stackoverflow.com/questions/53078262/how-to-select-a-cell-after-a-block-of-non-contiguous-data/53079722#53079722\">example</a>.</p>\n\n<h2>The Find Method's 6(9) Arguments</h2>\n\n<p><a href=\"https://docs.microsoft.com/en-us/office/vba/api/excel.range.find\" rel=\"nofollow noreferrer\">Microsoft</a> (VBA Help)</p>\n\n<p><strong>Syntax</strong>: <em>expression</em>. <strong>Find</strong>(<em>What</em>, <strong><em>After</em></strong>, <strong><em>LookIn</em></strong>, <strong><em>LookAt</em></strong>, <strong><em>SearchOrder</em></strong>, <strong><em>SearchDirection</em></strong>, <em>MatchCase</em>, <em>MatchByte</em>, <em>SearchFormat</em>)</p>\n\n<p>Expression is a range object, in our case it will be <code>.Cells</code> which refers to all cells in the worksheet.</p>\n\n<p>The Find method has 9 arguments:</p>\n\n<ol>\n<li>What</li>\n</ol>\n\n<blockquote>\n <ol start=\"2\">\n <li>After</li>\n <li>LookIn</li>\n <li>LookAt</li>\n <li>SearchOrder</li>\n <li>SearchDirection</li>\n </ol>\n</blockquote>\n\n<ol start=\"7\">\n<li>MatchCase</li>\n<li>MatchByte</li>\n<li>SearchFormat</li>\n</ol>\n\n<p>You can use them in <code>Argument:Parameter</code> style or enter them by adding their parameters in the exact order (separated by commas) which will be used here.</p>\n\n<p>The <strong>What</strong> argument is understandable by itself: search for anything \"*\". The <strong>MatchCase</strong> argument is by <em>default</em> <code>False</code> (Caution: it is <strong>not</strong> by <em>default</em> <code>False</code> for the <code>Replace</code> method though). The arguments <strong>MatchByte</strong> and <strong>SearchFormat</strong> are beyond the scope of this case and will not be further investigated, which leaves us with arguments number <strong>2</strong> to <strong>6</strong>.</p>\n\n<p><strong>2. After</strong> has to be a one-cell range contained in <em>expression</em> (Initial Search Range). Note that this cell will be searched last, so if you use <code>.Cells(1, 1)</code> or <code>.Cells(1)</code> the search will start with the next cell e.g. <code>.Cells(1, 2)</code>, <code>.Cells(2, 1)</code>... or <code>.Cells(2)</code>, or the previous cell e.g. <code>.Cells(1,.Columns.Count)</code>, <code>.Cells(.Rows.Count,1)</code> or <code>.Cells(.Cells.Count)</code> depending on the <code>SearchOrder</code> and <code>SearchDirection</code> parameters. The <em>default</em> value is <code>.Cells(1, 1)</code> or <code>.Cells(1)</code>, which can be omitted when used. </p>\n\n<p>To calculate the <strong>Last Used Row</strong>, <strong>Last Used Column</strong> or <strong>Last Used Cell</strong> this parameter will be omitted (<code>.Cells(1)</code>) because we want to start searching from the last cell going <strong>up</strong> or to the <strong>left</strong>.<br>\nTo calculate the <strong>First Used Row</strong>, <strong>First Used Column</strong> or <strong>First Used Cell</strong> this parameter will be <code>.Cells(.Rows.Count, .Columns.Count)</code> or <code>.Cells(.Cells.Count)</code> because we want to start searching from the first cell going <strong>down</strong> or to the <strong>right</strong>.</p>\n\n<p><strong>3. LookIn</strong> can be one of the following <code>XLLookIn</code> constants:<br>\n - <code>xlValues</code> or <code>-4163</code> will find any cell with a value except a cell containing a formula that evaluates to <strong>\"\"</strong>.<br>\n - <code>xlFormulas</code> or <code>-4123</code> will find any cells with a value including cells containing a formula that evalutates to <strong>\"\"</strong>. This parameter will be used because we cannot ignore cells containing a formula that evaluates to <strong>\"\"</strong>.<br>\n - <code>xlComments</code> or <code>-4144</code> will find any cell containing a comment (not used in this case).</p>\n\n<p><strong>4. LookAt</strong> can be one of the following <code>XLLookAt</code> constants: </p>\n\n<ul>\n<li><p><code>xlWhole</code> or <code>1</code> searches for whole strings only i.e. to find a cell\ncontaining e.g. <strong>Word</strong>, it will find a cell containing <strong>Word</strong>, but will <strong>not</strong> find a cell containing <strong>WordId</strong>.</p></li>\n<li><p><code>xlPart</code> or <code>2</code> searches for parts of the string i.e. to find a cell\ncontaining e.g. <strong>Word</strong> it will find cells containing <strong>both</strong>, <strong>Word</strong> or <strong>WordId</strong>.</p></li>\n</ul>\n\n<p>From everything I've read it is unclear using which parameter would make our search faster so it will be omitted in our case. Should be further investigated.</p>\n\n<p><strong>5. SearchOrder</strong> can be one of the following <code>XLSearchOrder</code> constants: </p>\n\n<ul>\n<li><p><code>xlByRows</code> or <code>1</code> will perform the search by rows e.g. in a <code>Next</code>\nsearch from the last cell it will search in <strong><code>A1, B1, C1...A2, B2, C2...(.Rows.Count, .Columns.Count)</code></strong>.</p></li>\n<li><p><code>xlByColumns</code> or <code>2</code> will perform the search by columns e.g. in a\n<code>Next</code> search from the last cell it will search in <strong><code>A1, A2, A3...B1, B2, B3...(.Rows.Count, .Columns.Count)</code></strong>.</p></li>\n</ul>\n\n<p><strong>6. SearchDirection</strong> can be one of the following <code>XLSearchDirection</code> constants: </p>\n\n<ul>\n<li><p><code>xlNext</code> or <code>1</code> (<em>Default</em>) in a 'by columns' search (<code>xlByColumns</code>) with <code>After:=\"A5\"</code> will search in <code>A6, A7, A8...</code></p></li>\n<li><p><code>xlPrevious</code> or <code>2</code> in a 'by columns' search (<code>xlByColumns</code>) with <code>After:=\"A5\"</code> will search in <code>A4, A3, A2...</code></p></li>\n</ul>\n\n<hr>\n\n<p><strong>VBA Remarks</strong></p>\n\n<blockquote>\n <p>The settings for <strong>LookIn</strong>, <strong>LookAt</strong>, <strong>SearchOrder</strong>, and\n MatchByte are saved each time you use this method. If you don’t\n specify values for these arguments the next time you call the method,\n the saved values are used. Setting these arguments changes the\n settings in the Find dialog box, and changing the settings in the Find\n dialog box changes the saved values that are used if you omit the\n arguments. To avoid problems, set these arguments explicitly each time\n you use this method.</p>\n</blockquote>\n\n<p><strong>Note</strong></p>\n\n<p>There is the <strong>What</strong> argument, there are 2 arguments (<strong>After, SearchDirection</strong>) with possible default values and 3 arguments (<strong>LookIn, LookAt, SearchOrder</strong>) that are saved each time.</p>\n\n<h2>Dissecting the Real Used Range Expression</h2>\n\n<pre><code>If Not .Cells.Find(\"*\", .Cells(.Rows.Count, .Columns.Count), -4123, , _\n 1) Is Nothing Then Set URng = .Range(.Cells(.Cells.Find(\"*\", _\n .Cells(.Rows.Count, .Columns.Count)).Row, .Cells.Find(\"*\", _\n .Cells(.Rows.Count, .Columns.Count), , , 2).Column), _\n .Cells(.Cells.Find(\"*\", , , , 1, 2).Row, .Cells _\n .Find(\"*\", , , , 2, 2).Column))\n</code></pre>\n\n<p>to be continued... </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T13:49:59.223", "Id": "410374", "Score": "1", "body": "Adding an explanation of the improvements in your code would improve your answer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:48:44.240", "Id": "410381", "Score": "0", "body": "While I was able to run your code just fine, I have to admit it made my brain hurt to read. I found the commented-out portion of your linked answer on SO much clearer for what was going on." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:37:38.303", "Id": "410398", "Score": "0", "body": "Wow. I tried for a long time to get the used range from `Find(\"*\")` directly. Will add this to the test suite and report results tonight :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:04:14.873", "Id": "410516", "Score": "0", "body": "Unfortunately using `find` like this isn't the fastest, but it is the \"simplest\" (even if it does look very complicated lol!) Perhaps a slightly refactored version wouldn't lose too much speed yet still be fast but easier to understand :)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:32:28.443", "Id": "410520", "Score": "0", "body": "Refactored and sped up in my answer :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T02:07:04.627", "Id": "212182", "ParentId": "212162", "Score": "1" } }, { "body": "<p>I've tested all of the responses. And these are the results</p>\n\n<pre><code>FUNCTION | Valid? | Performance |\n-----------------------------------------|--------|-------------|\nModule1.RealUsedRange_Sancarn1 | YES | 76906.5109 |\nModule1.RealUsedRange_Sancarn2 | YES | 6570.8505 |\nModule1.RealUsedRange_VBasic2008 | YES | 44600.0445 |\nModule1.RealUsedRange_IAmNerd2000_1 | NO | 21472.0677 |\nModule1.RealUsedRange_Sancarn3 | YES | 5371.9298 |\nModule1.RealUsedRange_IAmNerd2000_2 | YES | 8423.5989 |\nModule1.RealUsedRange_VBasic2008_refac | YES | 35906.7597 |\nModule1.RealUsedRange_Tinman | NO | 6489.7732 |\nModule1.ValueRange | YES | 4930.6771 |\n</code></pre>\n\n<p>I had to modify the code I originally posted as it didn't work in some conditions. All test cases are tested with the code below. I've tried to make it easy for you to set up your own test cases by providing a <code>CreateTestRange</code> function. You can test all functions by calling <code>testAllFuncs</code>. You can also add your own functions here also!:</p>\n\n<p><a href=\"https://pastebin.com/zPWKkYtM\" rel=\"nofollow noreferrer\">https://pastebin.com/zPWKkYtM</a></p>\n\n<p>The fastest method so far is listed as <code>ValueRange</code> and is a modification of which came from being inspired by code posted by IAmNerd2000.</p>\n\n<p>In this post I'd like to cover the 2 best solutions discussed.</p>\n\n<hr>\n\n<h1>The simple solution</h1>\n\n<p>The simplest solution appears to be VBasic2008's version. This is solution is short and easy to understand. If code readability is more important to you than speed use this! <strong>Edit: I've refactored this code slightly which not only makes it faster but also makes it easier to understand</strong>:</p>\n\n<pre><code>Function RealUsedRange_VBasic2008_refac(sht As Worksheet) As Range\n Dim firstCell, lastCell1, lastCell2 As Range\n With sht\n 'Start at first cell in sheet, go forward and find next cell (i.e. first cell of RealUsedRange)\n Set firstCell = .Cells.Find(\"*\", .Cells(1, 1), Excel.XlFindLookIn.xlValues, , XlSearchOrder.xlByRows)\n If Not firstCell Is Nothing Then\n 'Start at last cell in sheet, go back and find previous cell (i.e. last cell of RealUsedRange)\n Set lastCell1 = .Cells.Find(\"*\", .Cells(1, 1), XlFindLookIn.xlValues, , XlSearchOrder.xlByColumns, xlPrevious)\n Set lastCell2 = .Cells.Find(\"*\", .Cells(1, 1), XlFindLookIn.xlValues, , XlSearchOrder.xlByRows, xlPrevious)\n 'Find combined range between first and last cell\n Set RealUsedRange_VBasic2008_refac = Range(firstCell, Range(lastCell1, lastCell2))\n End If\n End With\nEnd Function\n</code></pre>\n\n<h1>The optimal solution</h1>\n\n<p>If you are more concerned with performance than clean code use this. It restricts the number of calls to slow COM objects property accessors. This is the main reason why this solution is faster than the above simple method:</p>\n\n<pre><code>'Changes:\n'V2 - Initial version using arrays by Sancarn.\n'V3 - IAmNerd2000: Store ubound, lbound to prevent recalculation after compilation.\n'V3 - MacroMark: Added fallback to VBasic2008's version for large ranges\n'V4 - Tinman: Changed Dim a,b,c as x to Dim a as x, b as x, c as x\n'V4 - Tinman: Changed use ur.countLarge instead of .rows.count and .columns.count for 1x1 check\n'V4 - Tinman: Use Value2 instead of Value\nFunction ValueRange(sht As Worksheet) As Range\n 'Get used range\n Dim ur As Range\n Set ur = sht.UsedRange\n\n 'If used range is 1x1 then result is 1x1\n If ur.CountLarge = 1 Then\n Set ValueRange = ur\n Exit Function\n End If\n\n 'Find via array\n 'Get array of all values:\n On Error GoTo URValueError\n Dim v As Variant\n v = ur.Value2\n On Error GoTo 0\n\n 'Offsets if they exist\n Dim offR As Long, offC As Long\n With ur\n offR = .row - 1\n offC = .Column - 1\n End With\n\n 'Define required values\n Dim colMin As Long, colMax As Long, rowMin As Long, rowMax As Long, row As Long, col As Long\n\n 'Find min row:\n Dim ubndR As Long, ubndC As Long, lbndR As Long, lbndC As Long\n lbndR = 1 'should always be 1\n lbndC = 1 'should always be 1\n ubndR = UBound(v, 1)\n ubndC = UBound(v, 2)\n\n For row = lbndR To ubndR\n For col = lbndC To ubndC\n If Not IsEmpty(v(row, col)) Then\n rowMin = row\n GoTo NextNum\n End If\n Next\n Next\nNextNum:\n 'Find max row\n For row = ubndR To lbndR Step -1\n For col = lbndC To ubndC\n If Not IsEmpty(v(row, col)) Then\n rowMax = row\n GoTo NextNum2\n End If\n Next\n Next\nNextNum2:\n 'Find min col:\n For col = lbndC To ubndC\n For row = lbndR To ubndR\n If Not IsEmpty(v(row, col)) Then\n colMin = col\n GoTo NextNum3\n End If\n Next\n Next\nNextNum3:\n 'Find max col\n For col = ubndC To lbndC Step -1\n For row = lbndR To ubndR\n If Not IsEmpty(v(row, col)) Then\n colMax = col\n GoTo NextNum4\n End If\n Next\n Next\nNextNum4:\n Set ValueRange = Range(sht.Cells(offR + rowMin, offC + colMin), sht.Cells(offR + rowMax, offC + colMax))\n Exit Function\nURValueError:\n If Err.Number = 7 Then 'Out of memory error:\n 'If out of memory, fall back on VBasic2000's version. It's not optimal but it doesn't have memory issues!\n Dim firstCell As Range, lastCell1 As Range, lastCell2 As Range\n With sht\n Set firstCell = .Cells.Find(\"*\", .Cells(1, 1), XlFindLookIn.xlFormulas, , XlSearchOrder.xlByRows)\n If Not firstCell Is Nothing Then\n Set lastCell1 = .Cells.Find(\"*\", .Cells(1, 1), XlFindLookIn.xlFormulas, , XlSearchOrder.xlByColumns, xlPrevious)\n Set lastCell2 = .Cells.Find(\"*\", .Cells(1, 1), XlFindLookIn.xlFormulas, , XlSearchOrder.xlByRows, xlPrevious)\n Set ValueRange = .Range(firstCell, Range(lastCell1, lastCell2))\n End If\n End With\n Else\n 'Raise unhandled error\n Err.Raise Err.Number, Err.Source, Err.Description, Err.HelpFile, Err.HelpContext\n End If\nEnd Function\n</code></pre>\n\n<hr>\n\n<p>Edit: <code>IAmNerd2000</code>'s original approach fails when formatting lies outside the \"RealUsedRange\". Thus it was removed from this post. </p>\n\n<hr>\n\n<p>Edit: As <code>MacroMarc</code> pointed out, very large used ranges will cause the optimal code to crash due to an <code>Out of memory</code> error. As a current work around I resort to <code>VBasic2008</code>'s code if the error occurs. So at worse it will be as slow as <code>VBasic2008</code>'s code, but at best it will be 10x faster.</p>\n\n<hr>\n\n<p>Edit: <code>RealUsedRange_VBasic2008_refac</code> didn't work in some situations. The solution has now been changed to reflect this.</p>\n\n<hr>\n\n<p>Edit: Changes based on Tinman's post. Main changes were removing variant references, using <code>CountLarge</code> instead of <code>.Rows.Count=1 and .Columns.Count=1</code> and <code>Value2</code> instead of <code>Value</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T00:42:39.783", "Id": "410568", "Score": "0", "body": "This fails outright when clowns put some format (or even a value) in ZZ400000. This stuff happens with all sorts of jokers in the workforce, and is a real fail point. You will have to plan for breaking into chunks if you want to use arrays." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T01:19:06.983", "Id": "410570", "Score": "0", "body": "@MacroMarc yes, everything pretty much fails at that point. But to be fair it depends what you mean by \"fails\". Or rather, it depends on what your use case is. In my case for example, it's detecting if a sheet is \"valid\" or tampered. In which case if some clown did add a cell into ZZ400000 then it would raise as tampered, which would be entirely correct." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T01:23:38.660", "Id": "410571", "Score": "0", "body": "I copied the code exactly and it failed as expected on line `v = ur.Value`. The code is not robust enough to deal with large UsedRanges." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T02:08:54.050", "Id": "410576", "Score": "0", "body": "@MacroMarc right! Out of memory, I see. Will refactor to use VBasic2008's version if ur.value errors. I doubt it'd be easy to do anything else. Not totally sure how to get around the out of memory issue without introducing huge amounts of complications/slow downs." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:07:41.680", "Id": "212273", "ParentId": "212162", "Score": "1" } } ]
{ "AcceptedAnswerId": "212273", "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T19:08:05.693", "Id": "212162", "Score": "3", "Tags": [ "excel", "vba" ], "Title": "Fastest method of getting the bounding box containing all value ranges" }
212162
<p>This is considered as my second python project, I made the password generator where user has to input length of password minimum 5.</p> <p>I made the code that it will guarantee at least one lowers case, one upper case and one special character is included in the password. please review and comment.</p> <pre><code>import random def letters(): return list('abcdefghijklmnopqrstuvwxyz') def upper_case(): uppercase = [] for x in letters(): uppercase.append(x.upper()) return uppercase def special_char(): return list('!@#$%^&amp;*()\'\"') def all_char(): return letters() + upper_case() + special_char() def create_password(password, n): for x in range(n): password += random.choice(all_char()) return password def check_password(password): nletter, nupper, nspecial = [0]*3 for x in password: if x in letters(): nletter += 1 if x in upper_case(): nupper += 1 if x in special_char(): nspecial += 1 if nletter &gt; 0 and nupper &gt; 0 and nspecial &gt; 0: return True else: return False def main(): n = 0 while n &lt; 5: n = int(input('Enter your password length (minimum 5): ')) password = '' while not check_password(password): password = '' password = create_password(password, n) check_password(password) print('Generated password : {}'.format(password)) while True: main() </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T21:02:36.697", "Id": "410300", "Score": "1", "body": "You could error check the user input, you can never trust people do what you ask. If I enter a letter it crashes. Good to get into the habit of writing comments as you write the code. It works, and that's the important thing" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:51:51.413", "Id": "410437", "Score": "0", "body": "I added the following try statement ~\n\n while n < 5:\n try:\n n = abs(int(input('Enter your password length (minimum 5): ')))\n except ValueError:\n print('Enter a valid number')" } ]
[ { "body": "<h3>Lots of lists</h3>\n\n<p>Every time you call <code>letters</code>, <code>upper_case</code>, <code>special_char</code> or <code>all_char</code>, you are creating a new list which will be no different from the other lists that were previously created. You can make these variables that are assigned once and used everywhere.</p>\n\n<h3>Repeated checks</h3>\n\n<p>For every password you generate, you are checking its validity twice: once at the end of the loop, and the other on the <code>while</code> line. The former serves no purpose, and should be removed.</p>\n\n<h3>Unused assignment</h3>\n\n<p>The assignment to <code>password = ''</code> inside your <code>while</code> loop is unused, and can be removed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T22:10:44.867", "Id": "410450", "Score": "0", "body": "You're welcome. Please don't forget to mark this as best answer if it worked for you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T21:34:25.070", "Id": "212167", "ParentId": "212164", "Score": "1" } }, { "body": "<p>To build on what else has been posted, validating your inputs is necessary and you have a lot of functions and loops that can be removed. </p>\n\n<h3>String module</h3>\n\n<p>First, I would like to introduce you to the <a href=\"https://docs.python.org/3/library/string.html#string-constants\" rel=\"nofollow noreferrer\"><code>string</code></a> module that is part of the python standard library. This module has string constants that you can import and use:</p>\n\n<pre><code>&gt;&gt;&gt; import string\n&gt;&gt;&gt; string.ascii_lowercase\n'abcdefghijklmnopqrstuvwxyz'\n&gt;&gt;&gt; string.ascii_uppercase\n'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n&gt;&gt;&gt; string.ascii_letters\n'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n&gt;&gt;&gt; string.punctuation\n'!\"#$%&amp;\\'()*+,-./:;&lt;=&gt;?@[\\\\]^_`{|}~'\n</code></pre>\n\n<p>Using these would allow you to get rid of your first three functions (<code>letter</code>, <code>upper_case</code>, and <code>special_char</code>). Similarly to what Joe said, it would be better to make your character space a variable to avoid creating extra objects, and remove the <code>all_char</code> function at the same time.</p>\n\n<h3><code>create_password</code> function</h3>\n\n<p>This function is clear and works okay, but can also be improved. As you are doing the same operation in each iteration of the loop (<code>random.choice</code>) this is and ideal scenario to use a <a href=\"https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions\" rel=\"nofollow noreferrer\">list comprehension</a>.</p>\n\n<pre><code># Before\ndef create_password(password, n):\n for x in range(n):\n password += random.choice(all_char())\n return password\n\n# After\ndef create_password(n):\n return ''.join([random.choice(all_char()) for _ in range(n)])\n</code></pre>\n\n<p>This works by creating a list where a random character is selected from <code>all_char()</code> and then joining them all together. The underscore is a 'throwaway' variable here, see <a href=\"https://stackoverflow.com/a/5893946/3279716\">here</a>.</p>\n\n<p>Alternatively, as we are already using the <code>random</code> module we could use <a href=\"https://docs.python.org/3/library/random.html#random.choices\" rel=\"nofollow noreferrer\"><code>random.choices</code></a> (but only in python3.6 and above) as this will return a list of <code>k</code> size:</p>\n\n<pre><code>def create_password(n):\n return ''.join(random.choices(all_char(), k=n))\n</code></pre>\n\n<h3><code>check_password</code> function</h3>\n\n<p>In general, simple statements are better than complex statements. Therefore, I would change the first line of this function to be:</p>\n\n<pre><code>nletter, nupper, nspecial = 0, 0, 0\n</code></pre>\n\n<p>As this is clearer.</p>\n\n<p>The for loop works, and could be improved by using the <code>string</code> module constants, though they would need to be made into lists.</p>\n\n<pre><code>for x in password:\n if x in list(string.ascii_lowercase):\n nletter += 1\n if x in list(string.ascii_uppercase):\n nupper += 1\n if x in list(string.punctuation):\n nspecial += 1\n</code></pre>\n\n<p>Another way to test if two strings overlap is to use <a href=\"https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset\" rel=\"nofollow noreferrer\"><code>sets</code></a>; but this is getting more complex.</p>\n\n<hr>\n\n<h3>Altogether</h3>\n\n<pre><code>import random\nimport string\n\ndef create_password(n, chars):\n return ''.join(random.choices(chars, k=n)) \n\ndef check_password(password):\n nletter, nupper, nspecial = 0, 0, 0\n for x in password:\n if x in list(string.ascii_lowercase):\n nletter += 1\n if x in list(string.ascii_uppercase):\n nupper += 1\n if x in list(string.punctuation):\n nspecial += 1\n if nletter &gt; 0 and nupper &gt; 0 and nspecial &gt; 0:\n return True\n else:\n return False\n\ndef main():\n characters = string.ascii_letters + string.punctuation\n n = 0\n while n &lt; 5:\n try:\n n = int(input('Enter your password length (minimum 5): '))\n except ValueError:\n print('Not a number')\n\n password = ''\n while not check_password(password):\n password = create_password(n, characters)\n\n print('Generated password : {}'.format(password))\n\nrun = True\nwhile run:\n try:\n main()\n except KeyboardInterrupt:\n run = False\n print('Ctrl+c caught exiting')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T18:51:56.263", "Id": "410528", "Score": "0", "body": "Thanks a lot man! a lot of new subjects to go through and learn I will be looking more into using list comprehension, Can you explain more about KeyboardInterrupt exception" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T12:38:19.193", "Id": "410603", "Score": "0", "body": "Because the `main()` function is running perpetually (`while True:...`) you exit your script by pressing `Ctrl`+`c`, which raises `KeyboardInterrupt`. By using `try:...except KeyboardInterrupt:...` we can handle the programme exiting more gracefully. There are other ways to handle this, such as the module [signal](https://docs.python.org/3/library/signal.html), but catching the KeyboardInterrupt works nicely in cases like yours." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T01:08:54.387", "Id": "212246", "ParentId": "212164", "Score": "2" } } ]
{ "AcceptedAnswerId": "212246", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T20:43:55.237", "Id": "212164", "Score": "1", "Tags": [ "python", "beginner", "strings", "random" ], "Title": "Python password generator" }
212164
<p>I'm (very) new to writing unit tests and I'm wondering how I should approach testing a static method that constructs our API endpoints based on what the properties are set to in our <code>environment.ts</code> file.</p> <p>The <code>environment.ts</code> file changes with the environment, so I'm curious how I would accommodate for that in my test.</p> <p>Does my method need to be refactored to make this easier to test? For example, instead of implicitly referencing environment.endpoint, instead pass-in environment as a argument? Would I mock the environment.ts file?</p> <p>Any suggestions would be helpful.</p> <pre><code>import {environment} from '../../environments/environment'; export class Utilities { public static constructAPIEndpoint(): string { const hostname: string = environment.endpoint; const protocol: string = environment.local ? 'http:' : 'https:'; return `${protocol}//${hostname}/`; } } </code></pre> <p>environments.ts</p> <pre><code>export const environment = { production: false, local: false, hostname: 'localhost', showLogs: true, endpoint: 'foo-dev-graphapp.com', appInsights: { instrumentationKey: '123' } }; </code></pre> <p>jasmine test:</p> <pre><code> import {environment} from '../../environments/environment'; it('constructAPIEndpoint() it should construct an endpoint based on environment.ts', () =&gt; { const endpoint: string = Utilities.constructAPIEndpoint(); /// THIS DOESN'T SEEM - having to recreate logic inside constructAPIEndpoint() const protocol: string = environment.local ? 'http:' : 'https'; expect(endpoint).toEqual(`${protocol}//${environment.endpoint}`); }); </code></pre>
[]
[ { "body": "<p>If you really want to unit test that logic, you should fake its data. In order to do that, you need a way to inject that dependency instead of getting it straight from it.</p>\n\n<p>You have 3 options:</p>\n\n<ol>\n<li>Installing a framework to mock the import (as detailed in <a href=\"https://medium.com/@emandm/import-mocking-with-typescript-3224804bb614\" rel=\"nofollow noreferrer\">https://medium.com/@emandm/import-mocking-with-typescript-3224804bb614</a>)</li>\n<li>Have a constructor that is autocalled for its usage statically.</li>\n<li>Similar to number 2: have a method with environment as parameter (so you can test it), and the current one calls the new one with the imported environment as parameter. </li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-21T21:24:57.033", "Id": "220677", "ParentId": "212166", "Score": "3" } } ]
{ "AcceptedAnswerId": "220677", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T21:34:04.450", "Id": "212166", "Score": "1", "Tags": [ "unit-testing", "typescript", "angular-2+", "jasmine" ], "Title": "Unit testing static method that imports environment file" }
212166
<p>When you only want a couple styles from a workbook but not all of them it's easier to merge styles then remove those you don't want. </p> <p>How can I improve the form or the backing code?</p> <hr> <p>Userform with styles listed.</p> <p><a href="https://i.stack.imgur.com/nH82F.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nH82F.png" alt="Userform"></a></p> <pre><code>'CustomStyleRemoverForm Private Sub UserForm_Initialize() ListStyles End Sub Private Sub ListStyles() CustomStylesListBox.Clear Dim listStyle As Style For Each listStyle In ActiveWorkbook.Styles If Not listStyle.BuiltIn Then CustomStylesListBox.AddItem listStyle.Name End If Next End Sub Private Sub SelectAllButton_Click() CheckAllBoxes True End Sub Private Sub UnselectAllButton_Click() CheckAllBoxes False End Sub Private Sub InvertSelectionButton_Click() Dim counter As Long For counter = 0 To CustomStylesListBox.ListCount - 1 CustomStylesListBox.Selected(counter) = Not CustomStylesListBox.Selected(counter) Next End Sub Private Sub CheckAllBoxes(ByVal updateValue As Boolean) Dim counter As Long For counter = 0 To CustomStylesListBox.ListCount - 1 CustomStylesListBox.Selected(counter) = updateValue Next End Sub Private Sub RemoveSelectedButton_Click() Dim counter As Long For counter = 0 To CustomStylesListBox.ListCount - 1 If CustomStylesListBox.Selected(counter) Then ActiveWorkbook.Styles(CustomStylesListBox.List(counter)).Delete End If Next ListStyles End Sub </code></pre>
[]
[ { "body": "<p>There is not much to review, your code is clean. There are some things that you can do to improve User Experience (UX).</p>\n\n<ul>\n<li>Replace the label, SelectAllButton and UnselectAllButton with a checkbox. </li>\n<li>Place a Frame around the Controls</li>\n<li>Add a ComboBox to change target workbooks</li>\n<li>Add buttons to copy and paste styles between workbooks</li>\n</ul>\n\n<p><a href=\"https://i.stack.imgur.com/ZJ62C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZJ62C.png\" alt=\"enter image description here\"></a></p>\n\n<p>And if you want to go buckwild you could add a Preview Button</p>\n\n<p><a href=\"https://i.stack.imgur.com/U1QEw.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/U1QEw.png\" alt=\"enter image description here\"></a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T20:59:18.363", "Id": "411210", "Score": "0", "body": "For your styles preview did you use a `ListBox`? I can't figure out how to change the BackColor and ForeColor text for each element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T22:58:02.610", "Id": "411219", "Score": "0", "body": "@IvenBach I used a WebBrowser control using the `CellStyleCSS` class from [Using Excel Cell StyleElements to Style HTML Document](https://codereview.stackexchange.com/questions/179439/using-excel-cell-styleelements-to-style-html-document)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T07:35:54.693", "Id": "212308", "ParentId": "212169", "Score": "1" } } ]
{ "AcceptedAnswerId": "212308", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T21:48:56.393", "Id": "212169", "Score": "1", "Tags": [ "vba", "excel" ], "Title": "Excel custom cell style remover" }
212169
<p><a href="https://web.archive.org/web/20180612111858/http://www.projectwonderful.com/" rel="nofollow noreferrer">Project Wonderful</a> is no more. ☹ As a little project, I've been trying to (slowly) re-implement the service. Here's my implementation of the Infinite Auction. The main function is <code>run_auction</code>; you feed it <code>Bid</code>s and it'll tell you when you need to change what ad is showing and how much to deduct from the account.</p> <pre><code>"""An implementation of Project Wonderful's Infinite Auction.""" # This implementation is unaffiliated with Project Wonderful and is not # guaranteed to behave identically to Project Wonderful's implementation. # For a friendly description of the algorithm, see: # https://web.archive.org/web/20180612112237/ # https://www.projectwonderful.com/abouttheinfiniteauction.php from collections import deque NANOSECONDS_PER_DAY = 86400000000000 Nanotime = int Currency = int Tokens = int class Bid: __slots__ = 'bid', 'expense_limit', 'expiry', 'id' def __init__(self, bid: Currency, expense_limit: Tokens, expiry: Nanotime, id=None): self.bid = bid self.expense_limit = expense_limit self.expiry = expiry self.id = id def winning_bid(bids, increment: Currency) -&gt; (Bid, Currency): """Get the highest bid. In the event of a tie, goes with the first.""" try: return next(winning_bids(bids, increment)) except StopIteration: return None, 0 def winning_bids(bids, increment: Currency) -&gt; [(Bid, Currency)]: bids = sorted(enumerate(bids), key=lambda a: (a[1].bid, -a[0])) output = deque() to_beat = 0 for i, bid in bids: bid_amount = bid.bid output.appendleft((bid, min(bid_amount, to_beat))) to_beat = bid_amount + increment yield from output def valid_bids(bids: [Bid], now: Nanotime=0) -&gt; [Bid]: """Filter bids for valid ones. It's best to do this in SQL or something; don't use this function please. """ for bid in bids: if bid.bid &gt; 0 and bid.expense_limit &gt; 0 and bid.expiry &gt; now: yield bid def find_end(amount: Currency, limit: Tokens, expiry: Nanotime, now: Nanotime) -&gt; (Nanotime, Tokens): """Find the end point of a bid, so a timer can be set. WARNING: Assumes that this is the only bid; ensure that expiry is the minimum of the expiry date of the bid and the amount's validity. A naïve use would be to take the minimum of all bids' expiry dates, but this is suboptimal. """ if expiry &lt;= now: raise ValueError("Expiry date in the past! Bid invalid.") if amount == 0: return expiry, 0 broke = (limit // amount) + now if broke &gt; expiry: return expiry, ((expiry - now) * amount) return broke, limit - (limit % amount) def run_auction(bids: [Bid], increment: Currency, now: Nanotime) -&gt; [(Bid, Nanotime, Tokens)]: """Run an auction and yield (current bid, when it ends, tokens spent).""" bids = list(bids) expense_limits = [bid.expense_limit for bid in bids] while bids: candidates = winning_bids(bids, increment) while True: try: candidate, candidate_amount_c = next(candidates) except StopIteration as e: return # No more candidates index = bids.index(candidate) if candidate_amount_c &lt;= expense_limits[index]: # It has a chance of being able to pay bid = candidate bid_amount_c = candidate_amount_c break candidate_index = None while True: try: candidate, candidate_amount_c = next(candidates) except StopIteration as e: expiry = bid.expiry break candidate_index = bids.index(candidate) if candidate_amount_c &lt;= expense_limits[candidate_index]: expiry = min(candidate.expiry, bid.expiry) break del candidate, candidate_amount_c, candidate_index now, spent_t = find_end(bid_amount_c, expense_limits[index], expiry, now) assert bid_amount_c == 0 or spent_t &gt; 0, "Stuck in an infinite loop!" expense_limits[index] -= spent_t yield bid, now, spent_t i = 0 while i &lt; len(bids): if bids[i].expiry &lt;= now: del bids[i] del expense_limits[i] else: i += 1 </code></pre> <p>You can find the tests <a href="https://github.com/wizzwizz4/project-brilliant/blob/master/infinite_auction/test.py" rel="nofollow noreferrer">here</a>. I've tried to make the program clear, but it's really a bit of a mess. How can I improve it?</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T21:51:26.510", "Id": "212170", "Score": "1", "Tags": [ "python", "python-3.x", "generator" ], "Title": "An implementation of Project Wonderful's Infinite Auction" }
212170
<p>I'm new learning python and image processing with python. For this reason, I took a project called "Classification of breast cancer images with deep learning".</p> <p>I applied the following techniques: 1)Threshold, 2)K-Means</p> <pre><code>import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread('n001.tif', 0) _, blackAndWhite = cv2.threshold(img, 100, 255, cv2.THRESH_BINARY_INV) nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(blackAndWhite, None, None, None, 8, cv2.CV_32S) sizes = stats[1:, -1] #get CC_STAT_AREA component img2 = np.zeros((labels.shape), np.uint8) for i in range(0, nlabels - 1): if sizes[i] &gt;= 100: #filter small dotted regions img2[labels == i + 1] = 255 res = cv2.bitwise_not(img2) cv2.imwrite('n001New.tif', res) ######################################################################## img = cv2.cvtColor(res, cv2.COLOR_BGR2RGB) Z = img.reshape((-1,3)) Z = np.float32(Z) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 250 , 1.0) K=2 ret, label, center= cv2.kmeans(Z, K, None, criteria, 250, cv2.KMEANS_RANDOM_CENTERS) center = np.uint8(center) res = center[label.flatten()] output = res.reshape((img.shape)) plt.imshow(output) plt.show() </code></pre> <p>Data set consists of tif extension image: benign, inSitu, invasive and normal <a href="https://i.stack.imgur.com/9KPIg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9KPIg.png" alt="Input images"></a></p> <p>Output images:<a href="https://i.stack.imgur.com/Nl64f.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nl64f.png" alt="Output images"></a></p> <p>I have a few questions:</p> <ol> <li>Are my methods correct?</li> <li>Are the outputs correct? Do I find the right areas?</li> <li>Did I use the K-Means algorithm correctly?</li> </ol> <p>I would appreciate it if you could answer the questions above.</p>
[]
[ { "body": "<blockquote>\n <p>Are my methods correct?</p>\n</blockquote>\n\n<p>That depends on what you want to accomplish. Since you are \"learning python and image processing with python\", it seems you picked some related methods to explore, which is good. But since your project is called \"Classification of breast cancer images with deep learning\", and you're not using deep learning, maybe you didn't pick the right methods...</p>\n\n<p>See below for some more concepts.</p>\n\n<blockquote>\n <p>Are the outputs correct? Do I find the right areas?</p>\n</blockquote>\n\n<p>Again, that depends on what your goal is. Do you know what these images represent? If no, then you need to start there. Understand what the image represents, what is relevant in it, and understand what the output of your algorithms will be used for. Then you will be able to answer your question yourself.</p>\n\n<p>It looks like you found mostly the nuclei, the results are quite OK if that is what you're after.</p>\n\n<blockquote>\n <p>Did I use the K-Means algorithm correctly?</p>\n</blockquote>\n\n<p>You've copy-pasted this from the OpenCV tutorial, so it's correct. But it also is a bit redundant, since the values of <code>center</code> are not useful to you in this case. The output <code>label</code> is an image with values 0 and 1, representing background and foreground. You should be able to directly display that (maybe multiply by 255 first).</p>\n\n<p>Also the line where you convert BGR to RGB is redundant, the k-means result will be the same regardless, and you don't need the colors after that.</p>\n\n<hr>\n\n<p>When dealing with brightfield microscopy, as you are, you might want to consider separating the stains instead of directly using the RGB values. These images are all H&amp;E stain (Hematoxylin and Eosin). These are purple and pink, respectively. Because we're dealing with transmitted light, and the dyes absorb light of specific wavelengths, we see darker pixels of specific colors. The absorption is characterized by the <a href=\"https://en.wikipedia.org/wiki/Beer%E2%80%93Lambert_law\" rel=\"nofollow noreferrer\">Beer-Lambert law</a>. This law states that the amount of light transmitted (and thus seen by the camera) is given by <span class=\"math-container\">\\$10^{-A}\\$</span>, with <span class=\"math-container\">\\$A\\$</span> proportional to the amount of dye. Thus, given a pixel value <span class=\"math-container\">\\$v\\$</span> and the illumination intensity <span class=\"math-container\">\\$v_\\text{max}\\$</span> (the whitest area in the image), you can compute <span class=\"math-container\">\\$-log(v/v_\\text{max})\\$</span>, which is proportional to the amount of dye. You can do this separately for each of the channels R, G and B. Each dye has a different absorption coefficient for each channel. If you know these (you can compute them from the image data), you can now do a linear unmixing (solve a linear set of equations) to derive, for each pixel, the relative amount of Hematoxylin and the relative amount of Eosin at that location on the slide. These two values is what you should be working with.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T23:31:07.497", "Id": "412308", "Score": "0", "body": "thank you for your answer. My goal is I will increase the accuracy of like CNN algorithms by dealing with pictures. But you are right. I don't know what image represent. What I need to find from picture with image processing. Which area should I deal with? I'm researching, but I don't quite understand. For example, when I classify pictures according to which features?color?nuclei position?size?.... My English not good I hope my problem is clear. @CrisLuengo" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T23:45:08.707", "Id": "412309", "Score": "0", "body": "@dogac: What you need to find depends very much on the application. \"CNN algorithm dealing with pictures\" is not the application, it's the tool. Nuclei size can certainly be important, but it depends on the application and on the context. I cannot advise you like this. --- But I can strongly suggest you learn about Beer-Lambert and stain unmixing, and use that. Most people using CNNs in digital pathology don't, because they don't know digital pathology, they just apply CNNs blindly. I'm sure CNNs would work significantly better if given the right input." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T23:54:31.980", "Id": "412310", "Score": "0", "body": "yes, what should be the right inputs? I will research. Thank you again and good luck. @cris" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-08T20:59:48.720", "Id": "213118", "ParentId": "212171", "Score": "1" } } ]
{ "AcceptedAnswerId": "213118", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T22:49:01.827", "Id": "212171", "Score": "3", "Tags": [ "python", "python-3.x", "image", "numpy", "opencv" ], "Title": "Image pre-processing and segmentation" }
212171
<p>I am writing this class to eventually create a playing card game (Spades) and also to utilize the object oriented paradigm. This was my attempt to model a card as an object. Each card has a suit and a rank that have each been given a specific weight that can be modified to fit the needs of the game. I have had several thoughts on how to implement this code differently, I thought about collapsing the weight system I had into a 1 - to 52 type system, or defining a dictionary where all cards assigned a value etc. However I decided to keep what I currently have as I feel this may yield greater flexibility to be expanded across several games. Last note, I decided to employ the Joker identity as a catch for cards that fall outside the expected input.</p> <pre><code>class Card(object): """Models a playing card, each Card object will have a suit, rank, and weight associated with each. possible_suits -- List of possible suits a card object can have possible_ranks -- List of possible ranks a card object can have Suit and rank weights are initialized by position in list. If card parameters are outside of expected values, card becomes joker with zero weight """ possible_suits = ["Clubs", "Hearts", "Diamonds", "Spades"] possible_ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"] def __init__(self, suit, rank): if suit in Card.possible_suits and rank in Card.possible_ranks: self.suit = suit self.rank = rank self.suit_weight = Card.possible_suits.index(suit) self.rank_weight = Card.possible_ranks.index(rank) else: self.suit = "Joker" self.rank = "J" self.suit_weight = 0 self.rank_weight = 0 def __str__(self): """Returns abbreviated name of card Example: str(Card('Spades', 'A') outputs 'AS' """ return str(self.rank) + self.suit[0] def __eq__(self, other): """Return True if cards are equal by suit and rank weight""" return self.suit_weight == other.suit_weight and self.rank_weight == other.rank_weight def __gt__(self, other): """Returns true if first card is greater than second card by weight""" if self.suit_weight &gt; other.suit_weight: return True if self.suit_weight == other.suit_weight: if self.rank_weight &gt; other.rank_weight: return True return False def modify_weight(self, new_suit_weight = None, new_rank_weight = None): """Modifies weight of card object""" if new_suit_weight: self.suit_weight = new_suit_weight if new_rank_weight: self.rank_weight = new_rank_weight def get_suit(self): return self.suit def get_rank(self): return self.rank def get_suit_weight(self): return self.suit_weight def get_rank_weight(self): return self.rank_weight </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T22:52:04.790", "Id": "212172", "Score": "3", "Tags": [ "python", "object-oriented", "playing-cards" ], "Title": "Playing card object" }
212172
<p>So my code works as intended, but suffers major performance issues every time I add a new object to the screen. The speed of my objects basically gets cut in half.</p> <p>All you have to do to observe this is run the code and hit spacebar to create a new object. it is suppose to represent a production line. the product is the red square and the workstation is the green square.</p> <p>The first station should take 5 seconds, The second station should take 8, and the third should be 3.</p> <p>I'm guessing there is something fundamentally wrong with the way I am creating objects into the system that is leading to a slow run speed. Thoughts?</p> <pre><code>import pygame import time pygame.init() screenx = 1200 screeny = 600 win = pygame.display.set_mode((screenx, screeny)) pygame.display.set_caption("simulation testing") clock = pygame.time.Clock() class Product(object): def __init__(self, x, y, width, height): self.x = x self.y = y self.width = width self.height = height self.vel = 5 self.color = (255, 0, 0) self.count = 0 def draw(self, win): pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0) def move(self): self.x += self.vel def wait(self): self.vel = 0 def count_and_finish(self): global count count += 1 class Workstation(object): def __init__(self, name, x, y, width, height, cycletime): self.name = name self.x = x self.y = y self.width = width self.height = height self.cycletime = cycletime self.color = (0, 255, 0) self.complete = False def draw(self, win): pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0) def do_work(self): global seconds if seconds &lt;= self.cycletime: seconds += .1 time.sleep(.1) else: self.complete = True seconds = 0 def redraw_screen(): win.fill((0, 0, 0)) pygame.draw.line(win, (255, 0, 0), (0, screeny // 2 + 155), (screenx, screeny // 2 + 155), 5) pygame.draw.line(win, (255, 0, 0), (0, screeny // 2 - 155), (screenx, screeny // 2 - 155), 5) ws1.draw(win) ws2.draw(win) ws3.draw(win) for product in products: product.draw(win) pygame.display.update() seconds = 0 count = 0 products = [] ws1 = Workstation("ws1", 200, 165, 160, 165, 5) ws2 = Workstation("ws2", 500, 165, 160, 165, 8) ws3 = Workstation("ws3", 800, 165, 160, 165, 3) run = True while run: clock.tick(30) for event in pygame.event.get(): if event.type == pygame.QUIT: run = False keys = pygame.key.get_pressed() if keys[pygame.K_SPACE]: time.sleep(.25) products.append(Product(0, round(screeny // 2 - 75), 150, 150)) for product in products: if product.x &gt;= 0 and product.x + product.width + 15 &lt;= screenx: if products.index(product) != 0: if product.x &gt;= products[products.index(product) - 1].x - product.width - 10: product.wait() elif product.x == ws1.x + 5: product.wait() ws1.do_work() if ws1.complete: product.vel = 5 ws1.complete = False product.move() elif product.x == ws2.x + 5: product.wait() ws2.do_work() if ws2.complete: product.vel = 5 ws2.complete = False product.move() elif product.x == ws3.x + 5: product.wait() ws3.do_work() if ws3.complete: product.vel = 5 ws3.complete = False product.move() else: product.vel = 5 product.move() else: if product.x == ws1.x + 5: product.wait() ws1.do_work() if ws1.complete: product.vel = 5 ws1.complete = False product.move() elif product.x == ws2.x + 5: product.wait() ws2.do_work() if ws2.complete: product.vel = 5 ws2.complete = False product.move() elif product.x == ws3.x + 5: product.wait() ws3.do_work() if ws3.complete: product.vel = 5 ws3.complete = False product.move() else: product.vel = 5 product.move() else: products.pop(products.index(product)) product.count_and_finish() print(str(count)) redraw_screen() pygame.quit() </code></pre>
[]
[ { "body": "<p>Your <code>Workstation</code> objects are calling <code>time.sleep(.1)</code> when any object is being processed. This will delay the main loop. If more than one <code>Workstation</code> is active, the game will slow down twice as much.</p>\n\n<p>If you want to sleep for 0.1 seconds, it should be done <strong>only</strong> by the main loop itself, after updating all of the items. It should never be done by the objects in the simulation.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T23:11:00.683", "Id": "212241", "ParentId": "212175", "Score": "1" } }, { "body": "<p>AJ was right and I've been able to fix my code so that it performs as intended. I made the timer in the do_work() function part of the class instead. I was able to get the milliseconds per frame from the</p>\n\n<pre><code>clock = pygame.time.Clock() # creates a clock object\nself.seconds = clock.get_time() # use the get time method that returns milliseconds per frame\n\nself.seconds_total += seconds\nif cycletime * 1000 &lt;= seconds_total: # Keeps track of the cycle time of the workstation to see if the product has been there long enough.\n</code></pre>\n\n<p>'</p>\n\n<p>full code so people can see.</p>\n\n<pre><code>import pygame\nimport time\n\n\npygame.init()\n\nscreenx = 1200\nscreeny = 600\n\nwin = pygame.display.set_mode((screenx, screeny))\n\npygame.display.set_caption(\"simulation testing\")\n\nclock = pygame.time.Clock()\n\n\nclass Product(object):\n def __init__(self, x, y, width, height):\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.vel = 5\n self.color = (255, 0, 0)\n self.count = 0\n\n def draw(self, win):\n pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)\n\n def move(self):\n self.x += self.vel\n\n def wait(self):\n self.vel = 0\n\n def count_and_finish(self):\n global count\n count += 1\n\n\nclass Workstation(object):\n def __init__(self, name, x, y, width, height, cycletime):\n self.name = name\n self.x = x\n self.y = y\n self.width = width\n self.height = height\n self.cycletime = cycletime\n self.color = (0, 255, 0)\n self.complete = False\n self.seconds = 0\n self.secondstotal = 0\n\n def draw(self, win):\n pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 0)\n\n def do_work(self):\n self.seconds = clock.get_time() / 1000\n self.secondstotal += self.seconds\n if self.secondstotal &gt;= self.cycletime:\n self.complete = True\n self.seconds = 0\n self.secondstotal = 0\n\n\ndef redraw_screen():\n win.fill((0, 0, 0))\n pygame.draw.line(win, (255, 0, 0), (0, screeny // 2 + 155), (screenx, screeny // 2 + 155), 5)\n pygame.draw.line(win, (255, 0, 0), (0, screeny // 2 - 155), (screenx, screeny // 2 - 155), 5)\n ws1.draw(win)\n ws2.draw(win)\n ws3.draw(win)\n for product in products:\n product.draw(win)\n win.blit(pygame.font.SysFont('None', 50).render('ws1 ' + str(round(ws1.cycletime - ws1.secondstotal, 2)), 0, (255, 255, 255)), (ws1.x, ws1.y - 55))\n win.blit(pygame.font.SysFont('None', 50).render('ws2 ' + str(round(ws2.cycletime - ws2.secondstotal, 2)), 0, (255, 255, 255)), (ws2.x, ws2.y - 55))\n win.blit(pygame.font.SysFont('None', 50).render('ws3 ' + str(round(ws3.cycletime - ws3.secondstotal, 2)), 0, (255, 255, 255)), (ws3.x, ws3.y - 55))\n win.blit(pygame.font.SysFont('None', 50).render('count ' + str(count), 0, (255, 255, 255)), (5, 5))\n pygame.display.update()\n\n\ncount = 0\nproducts = []\nws1 = Workstation(\"ws1\", 200, 165, 160, 165, 5)\nws2 = Workstation(\"ws2\", 500, 165, 160, 165, 8)\nws3 = Workstation(\"ws3\", 800, 165, 160, 165, 3)\n\nrun = True\nwhile run:\n clock.tick(30)\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n\n keys = pygame.key.get_pressed()\n\n if keys[pygame.K_SPACE]:\n time.sleep(.25)\n products.append(Product(0, round(screeny // 2 - 75), 150, 150))\n\n for product in products:\n if product.x &gt;= 0 and product.x + product.width + 15 &lt;= screenx:\n if products.index(product) != 0:\n if product.x &gt;= products[products.index(product) - 1].x - product.width - 10:\n product.wait()\n elif product.x == ws1.x + 5:\n product.wait()\n ws1.do_work()\n if ws1.complete:\n product.vel = 5\n ws1.complete = False\n product.move()\n elif product.x == ws2.x + 5:\n product.wait()\n ws2.do_work()\n if ws2.complete:\n product.vel = 5\n ws2.complete = False\n product.move()\n elif product.x == ws3.x + 5:\n product.wait()\n ws3.do_work()\n if ws3.complete:\n product.vel = 5\n ws3.complete = False\n product.move()\n else:\n product.vel = 5\n product.move()\n else:\n if product.x == ws1.x + 5:\n product.wait()\n ws1.do_work()\n if ws1.complete:\n product.vel = 5\n ws1.complete = False\n product.move()\n elif product.x == ws2.x + 5:\n product.wait()\n ws2.do_work()\n if ws2.complete:\n product.vel = 5\n ws2.complete = False\n product.move()\n elif product.x == ws3.x + 5:\n product.wait()\n ws3.do_work()\n if ws3.complete:\n product.vel = 5\n ws3.complete = False\n product.move()\n else:\n product.vel = 5\n product.move()\n else:\n products.pop(products.index(product))\n product.count_and_finish()\n\n print(str(count))\n\n redraw_screen()\n\npygame.quit()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T02:39:52.727", "Id": "212357", "ParentId": "212175", "Score": "1" } } ]
{ "AcceptedAnswerId": "212241", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-24T23:56:40.910", "Id": "212175", "Score": "2", "Tags": [ "python", "performance", "simulation", "pygame" ], "Title": "Pygame simulation of a production line" }
212175
<p>Today I started learning C++ and at the end of the day have made a simple generic matrix class. I'm looking for feedback on techniques and features. It's still not complete, though. But everything works!</p> <p>I put some functions outside the class and inside a namespace because I was trouble defining template member functions with partial specialization.</p> <p><strong>Matrix.hpp</strong></p> <pre><code>#pragma once #include &lt;iostream&gt; template &lt;typename T, int m, int n = m&gt; class mat { template &lt;typename, int, int&gt; friend class mat; private: T * data; public: mat(const std::initializer_list&lt;T&gt; &amp; ini) { std::copy(ini.begin(), ini.end(), data); } mat() : data(new T[m * n]) { } mat(T * values) : data(values) { } mat(const mat &amp; mat2) : mat(){ for (int i = 0; i &lt; m; ++i) for (int j = 0; j &lt; n; ++j) data[i * n + j] = mat2(i, j); } ~mat() { delete data; } void fill(T val) { for (int i = 0; i &lt; m; ++i) for (int j = 0; j &lt; n; ++j) data[i * n + j] = val; } void print() { for (int i = 0; i &lt; m; ++i) { for (int j = 0; j &lt; n; ++j) std::cout &lt;&lt; data[i * n + j] &lt;&lt; " "; std::cout &lt;&lt; std::endl; } } mat&lt;T, m, 1&gt; col(int j) const { mat&lt;T, m, 1&gt; col; for (int i = 0; i &lt; m; ++i) col.data[i] = data[i * n + j]; return col; } mat&lt;T, 1, n&gt; row(int i) const { mat&lt;T, 1, n&gt; row; std::copy_n(data + i * n, n, row.data); return row; } T operator () (int row, int col) const { return data[row * n + col]; } T &amp; operator () (int row, int col) { return data[row * n + col]; } mat&lt;T, n, m&gt; transpose() const { mat&lt;T, n, m&gt; res; for (int i = 0; i &lt; m; ++i) for (int j = 0; j &lt; n; ++j) res(j, i) = this-&gt;data[i * n + j]; return res; } template &lt;int p&gt; mat&lt;T, m, p&gt; operator * (const mat&lt;T, n, p&gt; &amp; other) const { mat&lt;T, m, p&gt; res; for (int i = 0; i &lt; m; ++i) for (int j = 0; j &lt; p; ++j) { T sum = 0; for (int k = 0; k &lt; n; ++k) sum += this-&gt;data[i * n + k] * other.data[k * n + j]; res(i, j) = sum; } return res; } mat&lt;T, m, n&gt; &amp; operator *= (T val) { for (int i = 0; i &lt; m; ++i) for (int j = 0; j &lt; n; ++j) data[i * n + j] *= val; return *this; } mat&lt;T, m, n&gt; &amp; operator /= (T val) { return this *= 1 / val; } mat&lt;T, m, n&gt; &amp; operator += (const mat &amp; other) { for (int i = 0; i &lt; m; ++i) for (int j = 0; j &lt; n; ++j) data[i * n + j] += other(i, j); return *this; } mat&lt;T, m, n&gt; &amp; operator -= (const mat &amp; other) { for (int i = 0; i &lt; m; ++i) for (int j = 0; j &lt; n; ++j) data[i * n + j] -= other(i, j); return *this; } mat&lt;T, m, n&gt; operator * (T val) const { auto res(*this); res *= val; return res; } mat&lt;T, m, n&gt; operator / (T val) const { return (*this) * (1 / val); } mat&lt;T, m, n&gt; operator + (const mat &amp; other) const { auto res(*this); res += other; return res; } mat&lt;T, m, n&gt; operator - (const mat &amp; other) const { auto res(*this); res -= other; return res; } mat&lt;T, m - 1, n - 1&gt; cut(int row, int col) const { mat&lt;T, m - 1, n - 1&gt; res; int index = 0; for (int i = 0; i &lt; m; ++i) for (int j = 0; j &lt; n; ++j) { if (i == row || j == col) continue; res.data[index++] = data[i * n + j]; } return res; } }; namespace matrix { template &lt;typename T&gt; T det(const mat&lt;T, 1, 1&gt; &amp; arg) { return arg(0, 0); } template &lt;typename T&gt; T det(const mat&lt;T, 2, 2&gt; &amp; arg) { return arg(0, 0) * arg(1, 1) - arg(1, 0) * arg(0, 1); } template &lt;typename T, int n&gt; T det(const mat&lt;T, n, n&gt; &amp; arg) { T res = 0, coef = 1; for (int i = 0; i &lt; n; ++i, coef *= -1) { res += coef * arg(0, i) * matrix::det(arg.cut(0, i)); } return res; } template &lt;typename T&gt; mat&lt;T, 2, 2&gt; inv(const mat&lt;T, 2, 2&gt; &amp; arg) { mat&lt;T, 2, 2&gt; helper; helper(1, 1) = arg(0, 0); helper(0, 0) = arg(1, 1); helper(0, 1) = -arg(0, 1); helper(1, 0) = -arg(1, 0); return helper / det(arg); } template &lt;typename T, int m&gt; mat&lt;T, m, m&gt; id() { mat&lt;T, m, m&gt; res; for (int i = 0; i &lt; m; ++i) res(i, i) = 1; return res; } }; </code></pre> <p><strong>Main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;exception&gt; #include "Matrix.hpp" using namespace std; int main() { constexpr int size = 4; long * data = new long[size * size]{ 0 }; for (int i = 0; i &lt; size; ++i) data[size * i + i] = 2; mat&lt;long, size&gt; big(data); cout &lt;&lt; matrix::det(big) &lt;&lt; endl; return 0; } </code></pre>
[]
[ { "body": "<h1>mat (const std::initializer_list &amp; ini)</h1>\n\n<p>You forgot to allocate any memory.</p>\n\n<h1>Rule of 0/5</h1>\n\n<p>Your class should follow the rule of 5 which states you should define copy-constructor, copy-assignment operator, move-constructor, move-assignment operator and destructor if you define one of them. You are missing copy-assignment operator, move-constructor, and move-assignment operator. You code cannot be efficiently moved. Implicitly defined copy-assignment operator is incorrect because you are dealing with memory ownership and the default copy-assignment operator can leads to double freeing the memory. </p>\n\n<p>You could also follow the rule of zero and delegate the responsibility of memory management to something like std::unique_ptr.</p>\n\n<p>Since the size of your matrix are template parameters you could just allocate the data as part of your class rather then dynamically allocating the data. </p>\n\n<pre><code>T data[n][m];\n</code></pre>\n\n<h1>mat (T * values) : data (values)</h1>\n\n<p>In this constructor you are stealing the ownership of the allocated memory. This is bad style because you could accidentally free the memory from outside of the class or pass the same memory to multiple mat object, each will free the same memory. </p>\n\n<p>You should allocate new memory and copy the values over.</p>\n\n<h1>mat (const mat &amp; mat2)</h1>\n\n<p>Could call fixed version of mat (T * values) instead to reduce code duplication.\nCould also be done using <a href=\"https://en.cppreference.com/w/cpp/algorithm/copy_n\" rel=\"nofollow noreferrer\">std::copy_n</a></p>\n\n<h1>~mat ()</h1>\n\n<p>Should be delete[] data; since you are using new[].</p>\n\n<h1>void fill (T val)</h1>\n\n<p>Can be done using <a href=\"https://en.cppreference.com/w/cpp/algorithm/fill_n\" rel=\"nofollow noreferrer\">std::fill_n</a></p>\n\n<h1>Row and column iterator</h1>\n\n<p>You could provide row and column iterators and implement some of your functions using those iterator. That would make your code easier to understand and easier to spot error.</p>\n\n<h1>operator *=, operator * (T val)</h1>\n\n<p>Can be done using <a href=\"https://en.cppreference.com/w/cpp/algorithm/for_each_n\" rel=\"nofollow noreferrer\">std::for_each_n</a></p>\n\n<h1>operator += (const mat &amp; other), operator -= (const mat &amp; other)</h1>\n\n<p>Can be done using <a href=\"https://en.cppreference.com/w/cpp/algorithm/transform\" rel=\"nofollow noreferrer\">std::transform</a></p>\n\n<h1>operator += (T value)</h1>\n\n<p>You are missing the version that add constant to matrix. Also what about matrix multiplication?</p>\n\n<h1>print()</h1>\n\n<p>Print should take in <a href=\"https://en.cppreference.com/w/cpp/io/basic_ostream\" rel=\"nofollow noreferrer\">std::ostream &amp;</a> that way you can print to files as well as std::cout.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T08:13:31.037", "Id": "410353", "Score": "0", "body": "`T data[n][m];`: generally I'd use `std::array` over built-in arrays. In this case I'd contemplate my options between `std::array<std::array<T, m>, n>` which is a bit ugly, or better `std::array<T, m*n>` with a custom subscript operator (btw +1 for `algorithm`s)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:36:49.300", "Id": "410383", "Score": "0", "body": "There is matrix multiplication `operator * (const mat<...>& other)`. However the `*=` for matrixes did not make much sense because matrixes change size after multiplication and therefore the type changes." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:47:33.327", "Id": "410411", "Score": "0", "body": "@wooooooooosh How would you define \"the version that add constant to matrix\"?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T04:48:31.110", "Id": "212190", "ParentId": "212178", "Score": "5" } }, { "body": "<p>The C++ side seems covered, so in this answer I take more of a linear algebra angle.</p>\n\n<p>The algorithms used for the determinant is not practical for matrixes that are not small. Cofactor expansion works fine with small matrixes and it is a useful mathematical definition, but its computational expense scales as the factorial of the matrix size, which quickly grows to unreasonable levels.</p>\n\n<p>There are some other options. You could implement triangular factorization (eg LUP), after which the determinant can be found by multiplying the diagonal elements. The cost of this approach scales only as the cube of the matrix size, though it involves divisions which makes it not so efficient for small matrixes where such overhead still dominates. The divisions also mean that it only works with <code>T</code> being <code>float</code> or <code>double</code>, there are some techniques that do work for integers but they are probably out of scope for a <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged &#39;beginner&#39;\" rel=\"tag\">beginner</a> question. To counter these disadvantages you could keep cofactor expansion as well, and apply the best algorithm for the case depending on <code>T</code> and the matrix dimensions (this seems like a nice place to apply some template magic).</p>\n\n<p>Triangular factorization can also be used to efficiently solve equations of the form Ax=b, and therefore also to find the explicit inverse of A by solving for all the basis vectors, though most commonly this wouldn't be needed since the purpose of the inverse would typically be to solve such equations in the first place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:19:28.233", "Id": "212226", "ParentId": "212178", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T00:49:44.110", "Id": "212178", "Score": "5", "Tags": [ "c++", "beginner", "matrix" ], "Title": "Simple matrix library in C++" }
212178
<p>I have created a basic web page that contains a panel which displays some details about an object, and a panel which contains some <em>tiles</em> that are used to choose which object to view. The idea is straight-forward, and with plenty of C# experience, the learning curve was small. However, since I am relatively new to JavaScript, I'd like a brief code review of my JavaScript to determine if there are any <em>gotchas</em> or perhaps alternatives that are more graceful.</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>// The available titles and their associated data. var titles = ["Pong", "Tetris", "Pac-Man", "Snake", "Super Mario", "Pokemon", "Match 3", "Blossom Blast", "Driven", "Terrible Zombies"]; var data = [ ["Pong is the equivalent of Hello World in the game development industry.", "Vectors, Rendering", "Directions", "Adding obstacles.", "Add effects."] ["Tetris is an iconic title. Though I am unable to provide the greatest theme music of all time, I hope you thoroughly enjoy the remake!", "Multi-Dimensional Arrays", "Arrays of Arrays", "Creating new pieces.", "Add effects."] ["Pac-Man is an iconic title providing a lot of fun and some great concepts.", "Collision Detection", "Building the walls.", "Object pooling.", "Add more ghosts and effects."] ["Dialing it back down, Snake is another iconic title with great concepts but simple implementation.", "Collision Detection", "None", "Linked Lists", "None"] ["Another iconic title, Super Mario is known around the world.", "Parallaxing Backgrounds", "None", "None", "None"] ["Pokemon is a favorite of multiple generations, this remake is simple and for demonstrations only.", "None", "None", "None", "None"] ["This is a simple demonstration of the match three game logic.", "None", "None", "None", "None"] ["The beautiful game Blossom Blast was my inspiration to go mobile.", "None", "None", "None", "None"] ["Driven is a basic 3D driving game.", "None", "None", "None", "None"] ["Terrible zombies is just as the name states, a terrible zombie game.", "None", "None", "None", "None"] ]; function swapGame(domElement, title) { // The tile collection. var tileCollection = document.getElementsByClassName('tiles'); var tiles = tileCollection[0].getElementsByTagName('li'); // The labels for display. var lblTitle = document.getElementById('dTitle'); var lblDescription = document.getElementById('dDescription'); var lblConcepts = document.getElementById('dConcepts'); var lblChallenges = document.getElementById('dChallenges'); var lblAdvanced = document.getElementById('dAdvanced'); var lblHomework = document.getElementById('dHomework'); for (var i = 0; i &lt; tiles.length; i++) tiles[i].className = ''; domElement.classList.toggle('active'); lblTitle.innerHTML = title; var id = titles.indexOf(title); lblDescription.innerHTML = data[id][0]; lblConcepts.innerHTML = 'Concepts: ' + data[id][1]; lblChallenges.innerHTML = 'Challenges: ' + data[id][2]; lblAdvanced.innerHTML = 'Advanced: ' + data[id][3]; lblAdvanced.innerHTML = 'Homework: ' + data[id][4]; }</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>.tile-container { width: 100%; height: 100%; display: flex; } .view-panel { width: 30%; box-shadow: 0px 5px 15px #111; background-color: #fff; color: #333; padding: 5px; } .launch-button { background-color: #fc0; border-radius: 5px; height: 50px; width: 95%; margin: auto; cursor: wait; transition: 0.5s all; } .launch-button:hover { background-color: #da0; } .launch-button a { text-decoration: none; color: #333; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; } .tiles { width: 70%; display: flex; align-items: flex-start; justify-content: flex-start; } .tile-view { list-style: none; width: 100%; display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: center; padding: 0; } .tile-view li { display: flex; flex-direction: column; align-items: center; justify-content: center; will-change: all; width: 150px; height: 150px; cursor: pointer; transition: 0.5s background-color; margin-left: 5px; margin: 5px; background-color: #222; color: #eee; box-shadow: 2px 2px 5px #111; } .tile-view li&gt;a { color: #eee; text-decoration: none; } .tile-view li:hover { background-color: #fc0; box-shadow: 5px 5px 15px #111; } .tile-view li.active { background-color: #fc0; } .tile-view li.active, .tile-view li.active&gt;a, .tile-view li:hover, .tile-view li:hover&gt;a { color: #333; } @media screen and (max-width: 750px) { .view-panel { display: none; } .tiles { width: 100%; } .tile-view li { width: 300px; } }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div class="tile-container"&gt; &lt;div class="view-panel"&gt; &lt;h1 id="dTitle"&gt;Pong&lt;/h1&gt; &lt;p id="dDescription"&gt;Pong is the equivalent of Hello World in the game development industry.&lt;/p&gt; &lt;ul&gt; &lt;li&gt;&lt;span id="dConcepts"&gt;Concepts: Vectors, Rendering&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span id="dChallenges"&gt;Challenges: Directions&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span id="dAdvanced"&gt;Advanced: Adding obstacles.&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;span id="dHomework"&gt;Homework: Add effects.&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="launch-button"&gt;&lt;a href="#"&gt;Launch&lt;/a&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="tiles"&gt; &lt;ul class="tile-view"&gt; &lt;li onclick="swapGame(this, 'Pong')" class="active"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Pong&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Tetris')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Tetris&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Pac-Man')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Pac-Man&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Snake')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Snake&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Super Mario')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Super Mario&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Pokemon')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Pokemon&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Match 3')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Match 3&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Blossom Blast')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Blossom Blast&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Driven')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Driven&lt;/a&gt; &lt;/li&gt; &lt;li onclick="swapGame(this, 'Terrible Zombies')"&gt; &lt;i class="fas fa-gamepad" aria-hidden="true"&gt;&lt;/i&gt; &lt;a href="#"&gt;Terrible Zombies&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T02:50:23.447", "Id": "410325", "Score": "0", "body": "Is there a reason why you want the text to be partly stored in the JavaScript code and partly in the HTML, rather than all in JavaScript or all in HTML?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T03:00:05.963", "Id": "410326", "Score": "0", "body": "@200_success Not really, I prefer consolidation but I haven't made it to the point of calling the `setGame` function once the DOM has loaded." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T03:59:06.147", "Id": "410328", "Score": "0", "body": "`data` is missing commas between arrays. Is `.view-panel` element and child nodes expected to not be displayed in the `document`?" } ]
[ { "body": "<p>It could go either way, but for this small example, I would suggest moving all the content in the HTML. You could even skip the JS and use <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/:target\" rel=\"nofollow noreferrer\"><code>:target</code></a> to show and hide stuff in conjunction with hashed link hrefs.</p>\n\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-css lang-css prettyprint-override\"><code>.panel {\n display: none\n}\n\n.panel:target {\n display: block\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;div class=\"app\"&gt;\n &lt;div class=\"panels\"&gt;\n &lt;div class=\"panel\" id=\"pong\"&gt;\n &lt;h1&gt;Pong&lt;/h1&gt;\n &lt;p&gt;Lorem ipsum sit dolor amet...&lt;/p&gt;\n &lt;/div&gt;\n &lt;div class=\"panel\" id=\"pokemon\"&gt;\n &lt;h1&gt;Pokemon&lt;/h1&gt;\n &lt;p&gt;Lorem ipsum sit dolor amet...&lt;/p&gt;\n &lt;/div&gt;\n &lt;div class=\"panel\" id=\"donkey-kong\"&gt;\n &lt;h1&gt;Donkey Kong&lt;/h1&gt;\n &lt;p&gt;Lorem ipsum sit dolor amet...&lt;/p&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;nav class=\"menu\"&gt;\n &lt;ul&gt;\n &lt;li&gt;&lt;a href=\"#pong\"&gt;Pong&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#pokemon\"&gt;Pokemon&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#donkey-kong\"&gt;Donkey Kong&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/nav&gt;\n&lt;/div&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Now onto your code...</p>\n\n<p>I recommend using <code>const</code> over <code>var</code>. Nothing wrong with <code>var</code>, but <code>const</code> guarantees the value referenced by the variable never changes (i.e. you cannot reassign it). This ensures that whatever you set to it is the same thing later in code. It's also block-scoped, so if you're in <code>if</code>s or <code>for</code>s, it scopes it in the block.</p>\n\n<p>In JS, there's <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector\" rel=\"nofollow noreferrer\"><code>document.querySelector</code></a> and <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll\" rel=\"nofollow noreferrer\"><code>document.querySelectorAll</code></a>. These allow you to fetch DOM elements using CSS selectors. You target DOM elements in the same way you target them when writing CSS. This way, you can be more expressive instead of being limited to <code>getElementById</code>, <code>getElementsByTagName</code>, <code>getElementsByClassName</code>.</p>\n\n<p><code>element.innerHTML</code> is fine. But if you're just updating text, consider using <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent\" rel=\"nofollow noreferrer\"><code>element.textContent</code></a> instead.</p>\n\n<p>Instead of <code>onclick</code> on the HTML, use <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener\" rel=\"nofollow noreferrer\"><code>element.addEventListener</code></a> in JavaScript instead. Inline scripts, while legit, are discouraged due to separation of concerns. Also, in inline scripts, the function is a global. Globals are to be avoided in JS to avoid clobbering stuff in the global namespace.</p>\n\n<p>Avoid targetting HTML elements in your CSS selectors. For instance <code>.tile-view li</code> targets all <em>descendant</em> <code>li</code> elements under <code>.tile-view</code>. This is fine for small apps, but this is a bad habit to have when working on larger apps. On larger apps, where components are composed of smaller independent components, you never know what's in them. You may be hitting an <code>li</code> you did not originally anticipate to be under there.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:33:17.000", "Id": "212214", "ParentId": "212183", "Score": "2" } } ]
{ "AcceptedAnswerId": "212214", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T02:07:22.543", "Id": "212183", "Score": "1", "Tags": [ "javascript", "dom" ], "Title": "Changing the text of a few elements when a tile is clicked" }
212183
<p>I have an exercise that ask to plot the prior and posterior distribution in the Poisson-Gamma model. I did it (I think it's correct) inspired in the answer of this question <a href="https://stats.stackexchange.com/questions/70661/how-does-the-beta-prior-affect-the-posterior-under-a-binomial-likelihood">https://stats.stackexchange.com/questions/70661/how-does-the-beta-prior-affect-the-posterior-under-a-binomial-likelihood</a></p> <p>Is there anything that can improve the code?</p> <pre><code>colors = c("red","blue","green","orange","purple") n = 10 lambda = .2 x = rpois(n,lambda) grid = seq(0,7,.01) alpha = c(.5,5,1,2,2) beta = c(.5,1,3,2,5) plot(grid,grid,type="n",xlim=c(0,5),ylim=c(0,4),xlab="",ylab="Prior Density", main="Prior Distributions", las=1) for(i in 1:length(alpha)){ prior = dgamma(grid,shape=alpha[i],rate=1/beta[i]) lines(grid,prior,col=colors[i],lwd=2) } legend("topleft", legend=c("Gamma(0.5,0.5)", "Gamma(5,1)", "Gamma(1,3)", "Gamma(2,2)", "Gamma(2,5)"), lwd=rep(2,5), col=colors, bty="n", ncol=3) for(i in 1:length(alpha)){ dev.new() plot(grid,grid,type="n",xlim=c(0,5),ylim=c(0,10),xlab="",ylab="Density",xaxs="i",yaxs="i", main="Prior and Posterior Distribution") alpha.star = alpha[i] + sum(x) beta.star = beta[i] + n prior = dgamma(grid,shape=alpha[i],rate=1/beta[i]) post = dgamma(grid,shape=alpha.star,rate=beta.star) lines(grid,post,lwd=2) lines(grid,prior,col=colors[i],lwd=2) legend("topright",c("Prior","Posterior"),col=c(colors[i],"black"),lwd=2) } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T10:26:19.050", "Id": "410363", "Score": "0", "body": "Could I ask why you use 1/`beta[i]` in the first set of priors and `beta[i]` in the second set of priors.The first thing I'd do if refactoring your code would be to write a function that does the code that you've written inside the for-loops; then I'd split the data-generation from the data-plotting or plot-appending logic into different functions. If I was rethinking how you present your plots, I'd consider plotting several prior/posterior figures side-by-side, eg, using `par(mfrow = c(1, 5))` and add a meaningful x-label" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T10:32:23.607", "Id": "410364", "Score": "0", "body": "I'd also expand the range of the x-axis in your first plot: < 20% of the density is covered for all but the Gamma(0.5, 0.5) distibution" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T11:10:03.447", "Id": "410365", "Score": "1", "body": "I have another query: your choices of alpha and beta jump around quite a bit. The mean of the gamma-dist defined by your alpha/beta pairs varies between 0.3 and 5, and the variance from 0.08 to 5. It might be more illustrative to pick three prior means and two prior variances (say); and then choose alpha/beta pairs that are consistent with the 6 possible combinations of mean/variance" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:21:33.093", "Id": "410423", "Score": "0", "body": "@RussHyde ooh, it's a typo, should be `1/beta[i]`. With this `prior/posterior figures side-by-side` you mean one prior in one plane and the posterior in a different plane but next to the prior?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:22:30.030", "Id": "410424", "Score": "0", "body": "@RussHyde I've change to `xlim=c(0,2)` now looks complete" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:27:33.480", "Id": "410426", "Score": "0", "body": "Hi, I'm working on your code at the moment. The alpha/beta vs shape/rate/scale thing is a bit confusing: if you explicitly put `dgamma(x, shape = my_shape, rate = my_rate)` it's a bit clearer" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:33:49.527", "Id": "410428", "Score": "0", "body": "@RussHyde ok oh I'll edit" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:38:19.937", "Id": "410431", "Score": "0", "body": "@RussHyde actually I think should be `scale` instead of `rate`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:39:04.500", "Id": "410432", "Score": "0", "body": "Your `beta` values are _definitely_ rates" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:45:40.053", "Id": "410435", "Score": "0", "body": "@RussHyde Ok I was a little confused because of the `help` section provided in R" } ]
[ { "body": "<p>There was a couple of errors in the code as originally posted. The code was OK as far as base R goes.</p>\n\n<p>First thing I did was run <code>styler</code> and then <code>lintr</code> on your code; these two things help clean up the coding style in your scripts.</p>\n\n<p>That does things like this:</p>\n\n<pre><code>colors = c(\"red\",\"blue\",\"green\",\"orange\",\"purple\")\n\n# changed to (spaces / idiomatic assignment):\ncolors &lt;- c(\"red\", \"blue\", \"green\", \"orange\", \"purple\")\n\n</code></pre>\n\n<p>Then I changed your <code>1:length(alphas)</code> to <code>seq_along(alphas)</code>. The latter is a bit safer since the former can fail with empty input.</p>\n\n<p>Then I replaced your 5-separate prior/posterior plots with a single plot that contains 5 panels. This makes it easier to compare the appropriateness of the different priors. To do this, I removed your <code>dev.new()</code>s, added a call to <code>par(mfrow = c(number_of_rows, number_of_columns))</code> and obviously, tidied this up afterwards (returning to a 1x1 grid)</p>\n\n<pre><code>par(mfrow = c(2, ceiling(length(alpha) / 2)))\n\nfor (i in seq_along(alpha)) {\n # removed dev.new()\n ... plotting code ...\n )\n }\n\npar(mfrow = c(1, 1))\n</code></pre>\n\n<p>Then I cleaned up your experimental data and your prior-parameters / plotting parameters; they were all winding around each other. I also renamed your alpha / beta vectors - in R, these correspond to the shape and rate parameters that are passed into <code>dgamma</code>:</p>\n\n<pre><code># ---- experimental data\n\nnum_observations &lt;- 10\n\nlambda &lt;- .2\n\nx &lt;- rpois(num_observations, lambda)\n\n# ---- prior parameters\n\n# assumed 'beta' was a rate parameter\n# - this, since there was confusion in the parameterisation of dgamma():\n# - early section used rate = 1 / beta[i];\n# - later section used rate = beta[i]; and\n# - definition of beta_star = beta[i] + n; implied beta was definitely a rate\n\nshape &lt;- c(.5, 5, 1, 2, 2)\nrate &lt;- c(.5, 1, 3, 2, 5)\n\n# ---- plotting parameters\n\ncolors &lt;- c(\"red\", \"blue\", \"green\", \"orange\", \"purple\")\n\n# ---- search parameters\n\ngrid &lt;- seq(0, 2, .01)\n\n</code></pre>\n\n<p>Then I made a function to do your prior-comparison stuff (the first set of plots). Any parameters that were to be passed through to <code>plot</code> were passed in using the <code>...</code> argument.</p>\n\n<pre><code># ---- comparison of the prior distributions\n\nplot_priors &lt;- function(grid, shapes, rates, colors,\n legend_text, lwd = 2, ...) {\n plot(grid, grid, type = \"n\", ...)\n\n for (i in seq_along(shape)) {\n prior &lt;- dgamma(grid, shape = shape[i], rate = rate[i])\n lines(grid, prior, col = colors[i], lwd = lwd)\n }\n\n legend(\n \"topleft\",\n legend = legend_text, lwd = lwd, col = colors, bty = \"n\", ncol = 2\n )\n}\n\n</code></pre>\n\n<p>This can be called like:</p>\n\n<pre><code>plot_priors(\n grid, shape, rate, colors,\n legend_text = paste0(\"Gamma(\", c(\"0.5,0.5\", \"5,1\", \"1,3\", \"2,2\", \"2,5\"), \")\"),\n xlim = c(0, 1), ylim = c(0, 4), xlab = \"\", ylab = \"Prior Density\",\n main = \"Prior Distributions\", las = 1\n)\n</code></pre>\n\n<p>It's useful to split your computations away from your plotting code - so I extracted the code you used to compute the posterior params:</p>\n\n<pre><code>compute_posterior_parameters &lt;- function(observations,\n prior_shape,\n prior_rate) {\n list(\n shape = prior_shape + sum(observations),\n rate = prior_rate + length(observations)\n )\n}\n</code></pre>\n\n<p>Then I pulled the plotting code for your prior/posterior comparisons into a function (similarly to the above)</p>\n\n<pre><code>plot_prior_post_comparison &lt;- function(\n observations,\n grid, shapes, rates, colors,\n lwd = 2,\n ...) {\n # make a grid for plotting\n par(mfrow = c(2, ceiling(length(shapes) / 2)))\n\n for (i in seq_along(shapes)) {\n # details of the prior and post distributions\n posterior_params &lt;- compute_posterior_parameters(\n observations,\n prior_shape = shapes[i], prior_rate = rates[i]\n )\n prior &lt;- dgamma(\n grid,\n shape = shapes[i],\n rate = rates[i]\n )\n post &lt;- dgamma(\n grid,\n shape = posterior_params$shape,\n rate = posterior_params$rate\n )\n\n # plotting code\n plot(grid, grid, type = \"n\", ...)\n lines(grid, post, lwd = lwd)\n lines(grid, prior, col = colors[i], lwd = lwd)\n legend(\"topright\",\n c(\"Prior\", \"Posterior\"),\n col = c(colors[i], \"black\"), lwd = lwd\n )\n }\n\n # revert the plotting grid back to 1x1\n par(mfrow = c(1, 1))\n}\n\n</code></pre>\n\n<p>note that the <code>par</code> calls, which change the plotting grid are all nested inside the function, so any subsequent plots should be unaffected.</p>\n\n<p>Then I called that function:</p>\n\n<pre><code># ---- prior/posterior comparison\n\nplot_prior_post_comparison(\n observations = x,\n grid = grid, shapes = shape, rates = rate, colors = colors,\n xlim = c(0, 1), ylim = c(0, 10), xlab = \"\", ylab = \"Density\",\n xaxs = \"i\", yaxs = \"i\",\n main = \"Prior and Posterior Distribution\"\n)\n\n</code></pre>\n\n<hr>\n\n<p>Then I put all the functions at the start and all the calls at the end of a script:</p>\n\n<h1>The full code:</h1>\n\n<pre><code># ---- comparison of the prior distributions\n\nplot_priors &lt;- function(grid, shapes, rates, colors,\n legend_text, lwd = 2, ...) {\n plot(grid, grid, type = \"n\", ...)\n\n for (i in seq_along(shape)) {\n prior &lt;- dgamma(grid, shape = shape[i], rate = rate[i])\n lines(grid, prior, col = colors[i], lwd = lwd)\n }\n\n legend(\n \"topleft\",\n legend = legend_text, lwd = lwd, col = colors, bty = \"n\", ncol = 2\n )\n}\n\n# ---- prior:posterior analysis\n\ncompute_posterior_parameters &lt;- function(observations,\n prior_shape,\n prior_rate) {\n list(\n shape = prior_shape + sum(observations),\n rate = prior_rate + length(observations)\n )\n}\n\nplot_prior_post_comparison &lt;- function(\n observations,\n grid, shapes, rates, colors,\n lwd = 2,\n ...) {\n # make a grid for plotting\n par(mfrow = c(2, ceiling(length(shapes) / 2)))\n\n for (i in seq_along(shapes)) {\n # details of the prior and post distributions\n posterior_params &lt;- compute_posterior_parameters(\n observations,\n prior_shape = shapes[i], prior_rate = rates[i]\n )\n prior &lt;- dgamma(\n grid,\n shape = shapes[i],\n rate = rates[i]\n )\n post &lt;- dgamma(\n grid,\n shape = posterior_params$shape,\n rate = posterior_params$rate\n )\n\n # plotting code\n plot(grid, grid, type = \"n\", ...)\n lines(grid, post, lwd = lwd)\n lines(grid, prior, col = colors[i], lwd = lwd)\n legend(\"topright\",\n c(\"Prior\", \"Posterior\"),\n col = c(colors[i], \"black\"), lwd = lwd\n )\n }\n\n # revert the plotting grid back to 1x1\n par(mfrow = c(1, 1))\n}\n\n\n# ----\n\n# ---- experimental data\n\nnum_observations &lt;- 10\n\nlambda &lt;- .2\n\nx &lt;- rpois(num_observations, lambda)\n\n# ---- prior parameters\n\n# assumed 'beta' was a rate parameter\n# - this, since there was confusion in the parameterisation of dgamma():\n# - early section used rate = 1 / beta[i];\n# - later section used rate = beta[i]; and\n# - definition of beta_star = beta[i] + n; implied beta was definitely a rate\n\nshape &lt;- c(.5, 5, 1, 2, 2)\nrate &lt;- c(.5, 1, 3, 2, 5)\n\n# ---- plotting parameters\n\ncolors &lt;- c(\"red\", \"blue\", \"green\", \"orange\", \"purple\")\n\n# ---- search parameters\n\ngrid &lt;- seq(0, 2, .01)\n\n# ---- comparison of priors\n\nplot_priors(\n grid, shape, rate, colors,\n legend_text = paste0(\"Gamma(\", c(\"0.5,0.5\", \"5,1\", \"1,3\", \"2,2\", \"2,5\"), \")\"),\n xlim = c(0, 1), ylim = c(0, 4), xlab = \"\", ylab = \"Prior Density\",\n main = \"Prior Distributions\", las = 1\n)\n\n# ---- prior/posterior comparison\n\nplot_prior_post_comparison(\n observations = x,\n grid = grid, shapes = shape, rates = rate, colors = colors,\n xlim = c(0, 1), ylim = c(0, 10), xlab = \"\", ylab = \"Density\",\n xaxs = \"i\", yaxs = \"i\",\n main = \"Prior and Posterior Distribution\"\n)\n\n</code></pre>\n\n<p>I don't thnk its perfect - the plotting and calculation steps are still pretty tied together - but it should be more easy to add extra pairs of rate/shape values into your prior distributions, for example.</p>\n\n<p>One place the code coould be further improved is by passing in a data.frame where each row contains the shape/rate/colour values and any annotations for a given prior. The functions contain too many arguments at the moment, and this would fix that (and guarantee that there is a shape for each rate).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T20:46:39.663", "Id": "410443", "Score": "0", "body": "Thank you so much Russ Hyde. I've tested the full code and the output looks really nice :) . I'll read in detail your full answer later to understand the code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T18:42:19.063", "Id": "410527", "Score": "0", "body": "With this: the plotting and calculation steps are still pretty tied together, you meant the code could be improved? Or you meant the output of the code could be improved ? Or both?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T11:57:12.183", "Id": "410601", "Score": "0", "body": "More the code than the output. It's important to think about what bits of the code you would need to change if you wanted to do X. X could be any number of things: i) you might want to sample from a different class of prior; ii) you might want to add an extra example plot or change the parameters for your current examples; iii) you might want to plot using ggplot2 instead of base etc. At present, to do any of these things you'd have to change a few different places in the code, so there's still improvements that could be made" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T19:11:38.270", "Id": "410654", "Score": "0", "body": "I see. For example, What new parameters would be a good idea to use?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T10:19:19.480", "Id": "410732", "Score": "0", "body": "Haha, that's for you to decide. I was just giving an example of how the code might evolve..." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T20:23:36.857", "Id": "212236", "ParentId": "212189", "Score": "3" } } ]
{ "AcceptedAnswerId": "212236", "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T03:44:41.630", "Id": "212189", "Score": "3", "Tags": [ "beginner", "statistics", "r", "data-visualization" ], "Title": "Plots of prior and posterior distributions for a model" }
212189
<p>I am using a panda's dataframe and I am doing filtering and some calculations per column and per row. </p> <p>The dataframe looks this:</p> <pre><code> 100 200 300 400 0 1 1 0 1 1 1 1 1 0 </code></pre> <p>Each header of the dataframe represents a company ID (x) and the rows represent specific users (y). If the user has accessed that firm, then the in the cell <strong>x*y</strong> the value is equal with 1 or 0 otherwise. What I want to do is see how searched are 2 firms are in comparison with the other firms. If it is necessary I can go into more detail about the general formula.</p> <pre><code>for base in list_of_companies: counter = 0 for peer in list2_of_companies: counter += 1 if base == peer: "do nothing" else: # Calculate first the denominator since we slice the big matrix # In dataframes that only have accessed the base firm denominator_df = df_matrix.loc[(df_matrix[base] == 1)] denominator = denominator_df.sum(axis=1).values.tolist() denominator = sum(denominator)-len(denominator) # Calculate the numerator. This is done later because # We slice up more the dataframe above by # Filtering records which have been accessed by both the base and the peer firm numerator_df = denominator_df.loc[(denominator_df[base] == 1) &amp; (denominator_df[peer] == 1)] numerator = len(numerator_df.index) annual_search_fraction = numerator/denominator print("Base: {} and Peer: {} ==&gt; {}".format(base, peer, annual_search_fraction)) </code></pre> <p>In total I have data for 13 years. I have a ryzen 2700x and it only managed to do 2 days in about 12 hours.</p> <p><strong>Edit 1 (added example input):</strong></p> <p>The metric is the following: </p> <p><a href="https://i.stack.imgur.com/NCnQu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NCnQu.png" alt="enter image description here"></a></p> <p>1) The metric that I am trying to calculate is going to tell me how many times 2 companies are searched together in comparison with all the other searches. </p> <p>2) The code is first selecting all the users which have accessed the base firm (<code>denominator_df = df_matrix.loc[(df_matrix[base] == 1)]</code>)line. Then it calculates the denominator which counts how many unique combinations between the base firm and any other searched firm by the user are there and since I can count the number of firms accessed (by the user), I can subtract 1 to get the number of unique links between the base firm and the other firms.</p> <p>3) Next, the code filters the previous <code>denominator_df</code> to select only the rows which accessed the base and the peer firm. Since I need to count the number of users which accessed the base and the peer firm, I use the command: <code>numerator = len(numerator_df.index)</code> to count the number of rows and that will give me the numerator. </p> <p>The expected output from the dataframe at the top is the following: </p> <pre><code>Base: 100 and Peer: 200 ==&gt; 0.5 Base: 100 and Peer: 300 ==&gt; 0.25 Base: 100 and Peer: 400 ==&gt; 0.25 Base: 200 and Peer: 100 ==&gt; 0.5 Base: 200 and Peer: 300 ==&gt; 0.25 Base: 200 and Peer: 400 ==&gt; 0.25 Base: 300 and Peer: 100 ==&gt; 0.5 Base: 300 and Peer: 200 ==&gt; 0.5 Base: 300 and Peer: 400 ==&gt; 0.0 Base: 400 and Peer: 100 ==&gt; 0.5 Base: 400 and Peer: 200 ==&gt; 0.5 Base: 400 and Peer: 300 ==&gt; 0.0 </code></pre> <p>4) The sanity check to see if the code gives the correct solution: all the metrics between 1 base firm and all the other peer firms have to sum up to 1 (all the metrics between base 100 and peer[200,300,400] summed together give 1.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T10:55:03.170", "Id": "410489", "Score": "1", "body": "Please add a short example input, i.e. a valid `df_matrix`, `list_of_companies` and `list2_of_companies`, so reviewers can test if their approach also works and performs better than yours." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T10:23:03.283", "Id": "410733", "Score": "0", "body": "`if base == peer: \"do nothing\"` Is that valid Python?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T10:45:08.127", "Id": "410735", "Score": "0", "body": "@Mast what do you mean by valid Python? I use the quotes there so no code is executed.. there is no need to put there \"do nothing\". I put that syntax there so it reminds me that it should not be doing anything there" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:42:39.357", "Id": "410740", "Score": "0", "body": "Ok, is there a reason you didn't go for a [pass statement](https://docs.python.org/3/tutorial/controlflow.html#pass-statements) there?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:44:12.360", "Id": "410741", "Score": "1", "body": "@Mast ah, didn't know you can do that. Thanks for the tip" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:49:20.333", "Id": "410742", "Score": "1", "body": "Do you always want all combinations or can `list_of_companies` and `list2_of_companies` be 1) different from each other 2) be different from `df.columns`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:52:37.930", "Id": "410743", "Score": "1", "body": "I always want all the combinations. The`list_of_companies` and `list2_of_companies` are exactly the same and they are not different from `df.columns`, meaning that if you were to extract the list of column names and compare it to the `list_of_companies` there would be no difference." } ]
[ { "body": "<p>I'm not sure about the issue, but what I can gather so far from your code is, that your Ryzen will not be able to parralellize due to your 2 loops. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:36:54.217", "Id": "410379", "Score": "1", "body": "Hi Philip, I'd recommend expanding a little bit about your point. Otherwise it doesn't help the OP much :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T10:17:26.577", "Id": "212202", "ParentId": "212197", "Score": "0" } }, { "body": "<p>One quick and obvious improvement is possible in these two lines:</p>\n\n<pre><code>denominator = denominator_df.sum(axis=1).values.tolist()\ndenominator = sum(denominator)-len(denominator)\n</code></pre>\n\n<p>This is equivalent to:</p>\n\n<pre><code>denominator = denominator_df.sum(axis=1)\ndenominator = denominator.sum() - len(denominator)\n</code></pre>\n\n<p>which should be a lot faster since converting to a temporary list will be quite slow, as is summing using the Python built-in instead of using the <code>pandas</code> vectorized method.</p>\n\n<p>Since you only care for the count in the numerator case, just use <code>sum</code>:</p>\n\n<pre><code>numerator = (denominator_df[peer] == 1).sum()\n</code></pre>\n\n<p>Note that checking for <code>denominator_df[base] == 1</code> is unnecessary since that was already done in the construction of <code>denominator_df</code>.</p>\n\n<hr>\n\n<p>But the real speed gains are probably in eliminating the double <code>for</code> loop altogether and writing this using vectorized methods. With some example input that might be possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T09:57:22.973", "Id": "410730", "Score": "0", "body": "I implemented the differences in the code as you suggested and I did see some speed improvements. \nRegarding the example input, I will update the question now" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T11:00:41.650", "Id": "212263", "ParentId": "212197", "Score": "1" } } ]
{ "AcceptedAnswerId": "212263", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T08:18:51.263", "Id": "212197", "Score": "2", "Tags": [ "python", "python-3.x", "matrix", "pandas" ], "Title": "Pandas calculations per columns and per rows for very big datasets" }
212197
<p>I have several (12) WCF services which are structured like this:</p> <p>I have inherited a very large 10-year-old project, I've introduced some inheritance so that I can have 1 echo method where I can control the timeout and not have duplicate code everywhere.</p> <p>The <code>PostalAddressFinderServiceService</code> (Shittly named I appreciate) is the autogenerated WCF class locally, this <code>GetWebRequest</code> method is overridden in all the WVF service that I have - the AddressFinderService is a smaller service so I want to analyse that, all the other service follow the exact same pattern but I will omit them for brevity.</p> <pre><code>public class LocalAddressFinderServerService : PostalAddressFinderServiceService, IWrapAutoGenService { /// &lt;summary&gt; /// Get the web request /// &lt;/summary&gt; /// &lt;remarks&gt; /// In some cases the first call to the web service works just fine, /// but if in the following few minutes no new call to the web service is made, /// the next call would throw the exception shown above. /// This problem could be solved by altering the generated proxy class; /// in the GetWebRequest function the KeepAlive property must be set to false /// see http://weblogs.asp.net/jan/archive/2004/01/28/63771.aspx /// &lt;/remarks&gt; /// &lt;param name="uri"&gt;The uri&lt;/param&gt; /// &lt;returns&gt;The web request&lt;/returns&gt; protected override WebRequest GetWebRequest(Uri uri) { var webRequest = (HttpWebRequest) base.GetWebRequest(uri); webRequest.KeepAlive = false; if (Globals.CompressResponse == true) { webRequest.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } return webRequest; } } </code></pre> <p>This local service is consumed by the generic wrapper that pulls in the abstract <code>ServiceWrapper</code> class.</p> <pre><code>/// &lt;summary&gt; /// A class to represent the service for the address finder /// &lt;/summary&gt; public class AddressServiceWrapper : ServiceWrapper&lt;LocalAddressFinderServerService&gt; { /// &lt;summary&gt; /// The single instance of the address service /// &lt;/summary&gt; public static readonly AddressServiceWrapper Service = new AddressServiceWrapper(); /// &lt;summary&gt; /// Prevents a default instance of the &lt;see cref="AddressServiceWrapper" /&gt; class from being created /// &lt;/summary&gt; private AddressServiceWrapper() { } protected override LocalAddressFinderServerService AppWebService { get { if (_webService == null) { _webService = base.AppWebService; _webService.findAddressCompleted += PAFFindAddressCompleted; } return _webService; } } /// &lt;summary&gt; /// Gets the display name for the web service /// &lt;/summary&gt; public override string DisplayName =&gt; "Address Finder Service"; /// &lt;summary&gt; /// Gets the service reference string this is used within /// the &lt;see cref="ServiceURLs" /&gt; settings file /// &lt;/summary&gt; public override string RefString =&gt; "Address_Finder"; /// &lt;summary&gt; /// The find address completed event /// &lt;/summary&gt; public event findAddressCompletedEventHandler FindAddressCompleted; /// &lt;summary&gt; /// Attempt an address search /// &lt;/summary&gt; /// &lt;param name="request"&gt;The request parameters&lt;/param&gt; /// &lt;param name="user"&gt;The logged in user&lt;/param&gt; public void BeginSearch(FindAddressRequest request, User user) { try { AppWebService.findAddressAsync(user.ToServiceType(), request.ToServiceType()); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } } /// &lt;summary&gt; /// Format a single address into name value pairs /// &lt;/summary&gt; /// &lt;param name="request"&gt;The format address request&lt;/param&gt; /// &lt;param name="user"&gt;The logged in user&lt;/param&gt; /// &lt;returns&gt;The format address response&lt;/returns&gt; public FormatAddressRes FormatAddress(FormatAddressReq request, ServiceClient.askPAF.User user) { try { return AppWebService.formatAddress(user, request); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } } /// &lt;summary&gt; /// Get a list of selection criteria and filters /// &lt;/summary&gt; /// &lt;param name="user"&gt;The logged in user&lt;/param&gt; /// &lt;param name="findType"&gt;The name of the selection choices being populated&lt;/param&gt; /// &lt;returns&gt;The selection criteria&lt;/returns&gt; public FindResponse GetFind(User user, string findType) { try { return new FindResponse(AppWebService.getFind(user.ToServiceType(), findType)); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } } /// &lt;summary&gt; /// Login to the postal address finder service /// &lt;/summary&gt; /// &lt;param name="request"&gt;The login request&lt;/param&gt; /// &lt;returns&gt;The login response&lt;/returns&gt; public LoginResponse Login(LoginRequest request) { return new LoginResponse(CallServiceSafely(AppWebService.login, request.ToServiceType())); } /// &lt;summary&gt; /// Handle the find address completed event /// &lt;/summary&gt; /// &lt;param name="sender"&gt;The sender of the event&lt;/param&gt; /// &lt;param name="e"&gt;The event arguments&lt;/param&gt; private void PAFFindAddressCompleted(object sender, findAddressCompletedEventArgs e) { if (!e.Cancelled &amp;&amp; FindAddressCompleted != null) { FindAddressCompleted(sender, e); } } } </code></pre> <p>As you can see there is a TON of duplicate try catch code. This makes the classes quite bloated and this is the smallest one. The largest one is north of 15,000 lines of repeated try, method pass through and catch. I've applied the refactoring to the Login method of the previous class to show the reduction in code.</p> <p>This is the abstract, generic class I have inserted so I have somewhere to introduce common logic. I've put in the <code>CallServiceSafely</code> methods that take "Funcs" and "Actions". </p> <pre><code>public abstract class ServiceWrapper&lt;S&gt; : IService where S : IWrapAutoGenService, new() { /// &lt;summary&gt; /// The local web service /// &lt;/summary&gt; protected static S _webService; /// &lt;summary&gt; /// Gets the reference to the web service /// &lt;/summary&gt; protected virtual S AppWebService { get { if (_webService == null) { _webService = new S {Timeout = 100000}; if (URL != null) { _webService.Url = URL; } } return _webService; } } /// &lt;summary&gt; /// Gets the display name for the web service /// &lt;/summary&gt; public abstract string DisplayName { get; } /// &lt;summary&gt; /// Send an echo request to the server to test /// the availability of the service /// &lt;/summary&gt; /// &lt;param name="echo"&gt;The text to send&lt;/param&gt; /// &lt;returns&gt;The text returned by the service&lt;/returns&gt; public virtual string Echo(string echo) { var originalTimeOut = AppWebService.Timeout; AppWebService.Timeout = 5000; var result = CallServiceSafely(AppWebService.echo, echo); AppWebService.Timeout = originalTimeOut; return result; } protected void CallServiceSafely(Action serviceMethod) { try { serviceMethod.Invoke(); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected void CallServiceSafely&lt;T&gt;(Action&lt;T&gt; serviceMethod,T firstParam) { try { serviceMethod.Invoke(firstParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected void CallServiceSafely&lt;T, TU&gt;(Action&lt;T, TU&gt; serviceMethod,T firstParam, TU secondParam) { try { serviceMethod.Invoke(firstParam, secondParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected void CallServiceSafely&lt;T, TU, TV&gt;(Action&lt;T, TU, TV&gt; serviceMethod,T firstParam, TU secondParam, TV thirdParam) { try { serviceMethod.Invoke(firstParam, secondParam, thirdParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected void CallServiceSafely&lt;T, TU, TV, TX&gt;(Action&lt;T, TU, TV, TX&gt; serviceMethod,T firstParam, TU secondParam, TV thirdParam, TX fourthParam) { try { serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected TR CallServiceSafely&lt;TU, TR&gt;(Func&lt;TU, TR&gt; serviceMethod, TU firstParam) { try { return serviceMethod.Invoke(firstParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected TR CallServiceSafely&lt;TU, TA, TR&gt;(Func&lt;TU, TA, TR&gt; serviceMethod, TU firstParam, TA secondParam) { try { return serviceMethod.Invoke(firstParam, secondParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected TR CallServiceSafely&lt;TU, TA, TV, TR&gt;(Func&lt;TU, TA, TV, TR&gt; serviceMethod, TU firstParam, TA secondParam, TV thirdParam) { try { return serviceMethod.Invoke(firstParam, secondParam, thirdParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected TR CallServiceSafely&lt;TU, TA, TV,TX, TR&gt;(Func&lt;TU, TA, TV, TX, TR&gt; serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam) { try { return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } protected TR CallServiceSafely&lt;TU, TA, TV,TX,TY, TR&gt;(Func&lt;TU, TA, TV, TX, TY, TR&gt; serviceMethod, TU firstParam, TA secondParam, TV thirdParam, TX fourthParam, TY fifthParam) { try { return serviceMethod.Invoke(firstParam, secondParam, thirdParam, fourthParam, fifthParam); } catch (SoapException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (WebException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (ApplicationException ex) { throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex)); } catch (FaultException ex) { throw new ServiceException(CreateErrorDescriptionInstance(ex)); } } /// &lt;summary&gt; /// Create an error description from the WCF FaultException /// It may need further fixed after more implementations of WCF as is only currently used for the document printing /// &lt;/summary&gt; /// &lt;param name="ex"&gt;&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; private static ErrorDescription CreateErrorDescriptionInstance(FaultException ex) { if (ex.Reason.ToString().IndexOf((char)255) != -1) { string[] elements = ex.Reason.ToString().Split((char)255); ErrorDescription errorDescription = new ErrorDescription(elements[3], elements[1], elements[2], elements[0]); return errorDescription; } string severity = ex.Reason.ToString(); string reason = ex.Reason.ToString(); string message = ex.Message; object details = ex.StackTrace; ErrorDescription errorDesc = new ErrorDescription(severity, reason, message, details); return errorDesc; } /// &lt;summary&gt; /// Gets or sets a value indicating whether the service is /// available /// &lt;/summary&gt; public bool ServiceAvailable { get; set; } /// &lt;summary&gt; /// Gets or sets the url of the service /// &lt;/summary&gt; public string URL { get; set; } public abstract string RefString { get; } /// &lt;summary&gt; /// Clear data cached in the service /// &lt;/summary&gt; public virtual void ClearCachedData() { } } public interface IService { string DisplayName { get; } bool ServiceAvailable { get; set; } string URL { get; set; } string RefString { get; } //Uid for the Iservice, used in Esprit as the name of the setting that contains the url for the service string Echo(string @string); //Used to clear the cached user on logoff //this is done within EspritServiceStateController for each module void ClearCachedData(); } </code></pre> <p>The <code>ServiceWrapper</code> class now contains many <code>CallServiceSafely</code> methods. Is there a way I can have one block of try catch code or will I have to maintain all the blocks as I have now?</p> <p>Final interface for completeness.</p> <pre><code>/// &lt;summary&gt; /// Provides access to autogenerated WSDL services that allow you to "Echo" them to check for their /// prescence /// &lt;/summary&gt; public interface IWrapAutoGenService { int Timeout { get; set; } string Url { get; set; } //It needs to be lower case as that is what the wsdl presents to us. // ReSharper disable once InconsistentNaming string echo(string echo); } </code></pre>
[]
[ { "body": "<p>If I understand your question right your main concern is how to refactor all the <code>CallServiceSafely(...)</code> methods, so you don't have to maintain a lot of repetitive code. A way to go could be to have an <code>ExecuteMethod()</code> method like:</p>\n\n<pre><code>private void ExecuteMethod(Action action)\n{\n try\n {\n action();\n }\n catch (Exception ex)\n {\n switch (ex)\n {\n case FaultException fe:\n throw new ServiceException(CreateErrorDescriptionInstance(fe));\n // TODO: Other specialized exception cases\n default:\n throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));\n }\n }\n}\n</code></pre>\n\n<p>and then call it from the <code>CallServiceSafely</code> methods like:</p>\n\n<pre><code>protected void CallServiceSafely&lt;T, TU, TV&gt;(Action&lt;T, TU, TV&gt; serviceMethod, T firstParam, TU secondParam, TV thirdParam)\n{\n ExecuteMethod(() =&gt; serviceMethod(firstParam, secondParam, thirdParam));\n //serviceMethod.Invoke(firstParam, secondParam, thirdParam);\n}\n</code></pre>\n\n<hr>\n\n<p>You could also do:</p>\n\n<pre><code>private void ExecuteMethod(Action action)\n{\n try\n {\n action();\n }\n catch (FaultException fe)\n {\n throw new ServiceException(CreateErrorDescriptionInstance(fe));\n }\n catch (Exception ex)\n {\n throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));\n }\n}\n</code></pre>\n\n<hr>\n\n<pre><code> private T ExecuteFunc&lt;T&gt;(Func&lt;T&gt; function)\n {\n try\n {\n return function();\n }\n catch (SoapException ex)\n {\n throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));\n }\n catch (WebException ex)\n {\n throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));\n }\n catch (ApplicationException ex)\n {\n throw new ServiceException(ToolKit.ErrorDescriptionFactory.CreateInstance(ex));\n }\n catch (FaultException ex)\n {\n throw new ServiceException(CreateErrorDescriptionInstance(ex));\n }\n }\n</code></pre>\n\n<p>Which is maybe more \"catchy\" correct.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T11:10:57.080", "Id": "212204", "ParentId": "212203", "Score": "2" } } ]
{ "AcceptedAnswerId": "212204", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T10:19:38.303", "Id": "212203", "Score": "3", "Tags": [ "c#", "wcf" ], "Title": "Multiple WCF Service with boilerplate error handling" }
212203
<p>I have an alternative solution for family tree that have been posted some time ago and please forgive the similarity of the task but when i tried to post alternative solution in someone else's post and asked for review I got deleted.</p> <p>Model the family tree such that:</p> <pre><code>Input: Person=Alex Relation=Brothers Expected Output should be Brothers=John,Joe Input: Husband=Bern Wife=Julia Expected Output should be Welcome to the family, Julia </code></pre> <p>List of supported relations:</p> <pre><code>Father Mother Brother(s) Sister(s) Son(s) Daughter(s) Sibling </code></pre> <p>Assumption:</p> <ul> <li>Names are unique. Any new member added will also have a unique name.</li> </ul> <h3>TreeApp</h3> <pre><code>import java.util.Scanner; public class TreeApp { public static Scanner sc= new Scanner(System.in); public static RelationshipFactory rl = new RelationshipFactory(); public static void main(String[] args) { Boolean quit = false; printMenu(); try{ while(!quit){ System.out.println("Enter option:"); int operation = sc.nextInt(); sc.nextLine(); switch(operation){ case 1: System.out.println("Menu:"); printMenu(); break; case 2: rl.printFamilyMap(); break; case 3: System.out.println("Enter query"); proceedWithQuerry(); break; case 4: System.out.println("Fill with test data"); rl.populateFamilyTree(); break; default: System.out.println("QUIT"); quit = true; break; } } } catch(Exception e){ System.out.println("Error while getting option - quit"); } } private static void proceedWithQuerry() { String query = sc.nextLine(); QueryParser qp = new QueryParser(); qp = qp.parse(query); if (qp.com.equals(Command.ADD)){ rl.addRelation(qp.p1,qp.rel2,qp.p2,qp.rel1,0); } else if (qp.com.equals(Command.RETRIEVE)){ rl.getSiblings(qp); } else{ System.out.println("Process terminated"); } } private static void printMenu() { System.out.println("1 - Print menu," + "\n2 - Print familyTree," + "\n3 - Enter query," + "\n4 - Inject test data."); } } </code></pre> <h3>RelationshipFactory</h3> <pre><code>import java.util.HashMap; import java.util.Map; public class RelationshipFactory { private static Map&lt;String,HashMap&lt;String,Relation&gt;&gt; familyMap = new HashMap&lt;&gt;(); public RelationshipFactory() { } public void addRelation(String p1, Relation rel1, String p2, Relation rel2, int mode){ HashMap&lt;String, Relation&gt; personalMap = new HashMap&lt;&gt;(); if (familyMap.get(p1) == null){ personalMap.put(p2, rel1); familyMap.put(p1, personalMap); System.out.println("Welcome to the family, " + p1 ); } else { personalMap = familyMap.get(p1); if (personalMap.get(p2) == null){ personalMap.put(p2, rel1); } } if (mode == 0){ addRelation(p2, rel2, p1, rel1, 1); } } public void printFamilyMap(){ System.out.println("Family Tree:\n"); for (Map.Entry&lt;String,HashMap&lt;String,Relation&gt;&gt; entry : familyMap.entrySet()){ System.out.println("Person: " + entry.getKey() + ":"); entry.getValue().forEach((p,role) -&gt; { System.out.println("\t\t\t" + p + " - " + role.toString());}); } } public void getSiblings(QueryParser qp) { Boolean foundMember = false; if (familyMap.get(qp.p1) == null) System.out.println("Unregonised member of the family."); else { System.out.println(qp.rel2 + ": "); for (Map.Entry&lt;String,Relation&gt; entry : familyMap.get(qp.p1).entrySet()){ if (entry.getValue().equals(qp.rel2)){ System.out.println("\t\t\t" + entry.getKey()); foundMember = true; } } if (!foundMember) System.out.println("\tnot found." ); } } public void populateFamilyTree() { addRelation("Bern", Relation.WIFE, "Julia", Relation.HUSBAND, 0); addRelation("Bern", Relation.SON, "Boris", Relation.FATHER, 0); addRelation("Bern", Relation.SON, "Adam", Relation.FATHER, 0); addRelation("Bern", Relation.DAUGHTER, "Zoe", Relation.FATHER, 0); addRelation("Julia", Relation.SON, "Adam", Relation.MOTHER, 0); addRelation("Julia", Relation.SON, "Boris", Relation.MOTHER, 0); addRelation("Julia", Relation.DAUGHTER, "Zoe", Relation.MOTHER, 0); addRelation("Julia", Relation.SISTER, "Alicia", Relation.SISTER, 0); addRelation("Bern", Relation.SIBLING, "Alicia", Relation.SIBLING, 0); } } </code></pre> <h3>QueryParser</h3> <pre><code>import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; enum Command {ADD, RETRIEVE, ERROR} enum Relation {MOTHER, FATHER, SON, DAUGHTER, BROTHER, SISTER, WIFE, HUSBAND, SIBLING}; public class QueryParser { /* Person=Bern Relation=Wife Mother=Julia Son=Boris */ Command com; String p1; String p2; Relation rel1; Relation rel2; public QueryParser() { } public QueryParser(Command com, String p1, String p2, Relation rel1, Relation rel2) { this.com = com; this.p1 = p1; this.p2 = p2; this.rel1 = rel1; this.rel2 = rel2; } public QueryParser parse(String query) { List&lt;String&gt; list = Stream.of(query.split("[ =]+")).map(elem -&gt; new String(elem)).collect(Collectors.toList()); if (list.size()!=4) { System.out.println("Error while parsing to list"); com = Command.ERROR; } else if (list.get(0).equals("Person")){ com = Command.RETRIEVE; p1 = list.get(1); rel2 = adjustRelation(list.get(3)); } else { com = Command.ADD; p1 = list.get(1); p2 = list.get(3); rel1 = adjustRelation(list.get(0)); rel2 = adjustRelation(list.get(2)); } return new QueryParser(com,p1,p2,rel1,rel2); } private Relation adjustRelation(String rel){ switch(rel){ case "Mother": return Relation.MOTHER; case "Father": return Relation.FATHER; case "Husband": return Relation.HUSBAND; case "Wife": return Relation.WIFE; case "Son": return Relation.SON; case "Sons": return Relation.SON; case "Daughters": return Relation.DAUGHTER; case "Daughter": return Relation.DAUGHTER; case "Sisters": return Relation.SISTER; case "Sister": return Relation.SISTER; case "Brother": return Relation.BROTHER; case "Brothers": return Relation.BROTHER; default: return Relation.SIBLING; } } } </code></pre>
[]
[ { "body": "<h3>QueryParser</h3>\n<p>Right now your query parser has two responsibilities. It parses the query (hence its name), but it also contains the result of the parse, which is kind of unintuitive and violates the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>.</p>\n<p>I'd create a <code>Query</code> class that would contain the members <code>com, p1, p2, rel1, rel2</code>.</p>\n<p>If you're not already confortable with polymorphism, I'd try using it to create <code>ErrorCommand</code>, <code>RetrieveCommand</code> and <code>AddCommand</code> instead of just a <code>Query</code> class. You could use the <code>Command</code> pattern to separate the responsibilities instead of using the <code>if/else if/else</code> from the <code>proceedWithQuerry</code> method.</p>\n<h3>RelationshipFactory</h3>\n<p>This class isn't really a <a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"nofollow noreferrer\">Factory Pattern</a>. In this situation I think you should try to rename it to something else. The only method in the class that kind of fits a <code>Factory</code> is the <code>populateFamilyTree</code> method. You could check out the <a href=\"https://en.wikipedia.org/wiki/Builder_pattern\" rel=\"nofollow noreferrer\">Builder</a> pattern to help build your family tree. It could be an interesting exercise though some people might argue that it's overkill. But as you tagged your question as <code>beginner</code>, I feel like you could learn something from trying to implement this :)</p>\n<p>The <code>int mode</code> parameter to <code>addRelation</code> isn't intuitive. I think that it is used to &quot;mirror&quot; the relationship (so that <code>Sibling(Harry,Emma)</code> would also add <code>Sibling(Emma,Harry)</code>), this should be made clearer.</p>\n<h3>TreeApp</h3>\n<p>If I'm using your application, how can I know what I'm supposed to enter when this is prompted : <code>System.out.println(&quot;Enter option:&quot;);</code>. You should print the options with what they do so that users can use your application.</p>\n<h3>General</h3>\n<p>The variable names should be more explicit. Looking at this : <code>String p1;</code>, how can I know what it will contain? Naming it <code>firstPerson</code> or something of the like would be good. Short variable names bring nothing of value, especially with IDEs.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:15:54.617", "Id": "212216", "ParentId": "212205", "Score": "2" } } ]
{ "AcceptedAnswerId": "212216", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T11:11:50.357", "Id": "212205", "Score": "1", "Tags": [ "java", "beginner" ], "Title": "Developer Assignment - Family Tree" }
212205
<p>I have two processes. First (main) one is "dealing" with user stuff. Second one is doing some internal stuff and should update its internal state according to user actions. So I've created two pipes. By one I send actions to subprocess, from another I get messages that emits this subprocess.</p> <p>I wonder about two things:</p> <ol> <li>Is this architecture clean enough?</li> <li>Is my usage of python's typing is good? </li> </ol> <hr> <pre><code>import time from multiprocessing import Pipe from multiprocessing import Process from multiprocessing import Queue from typing import Any from typing import Dict from typing import List class Counter(object): _i: int def __init__(self): super().__init__() self._i = 0 def drop(self): self._i = 0 def inc(self): self._i += 1 @property def i(self) -&gt; int: return self._i class Action(object): _data: Dict[str, Any] _label: str def __init__(self, label: str, data: Dict[str, Any]): super().__init__() self._data = data self._label = label @property def data(self) -&gt; Dict[str, Any]: return self._data @property def label(self) -&gt; str: return self._label class CounterProcess(Process): _counters: Dict[str, Counter] _in_queue: Queue _out_queue: Queue def __init__(self, in_queue: Queue, out_queue: Queue): super().__init__() self._in_queue = in_queue self._out_queue = out_queue self._counters = {} self._counters["a"] = Counter() self._counters["b"] = Counter() def run(self): for i in range(15): time.sleep(0.5) self._process_actions() self._update() self._emit() def _dispatch_action(self, action: Action): if action.label != "drop": return if "label" not in action.data: return self._drop_counter(action.data["label"]) def _drop_counter(self, label: str): if label in self._counters: self._counters[label].drop() def _emit(self): msg = {} for c in self._counters: msg[c] = self._counters[c].i self._out_queue.put(msg) def _get_actions(self) -&gt; List[Action]: actions = [] while not self._in_queue.empty(): actions.append(self._in_queue.get(False)) return actions def _process_actions(self): for action in self._get_actions(): self._dispatch_action(action) def _update(self): for c in self._counters.values(): c.inc() def print_output(queue: Queue, to_receive: int, dt: float): while to_receive &gt; 0: if not queue.empty(): print(queue.get(False)) to_receive -= 1 time.sleep(dt) if __name__ == '__main__': oq = Queue() iq = Queue() proc = CounterProcess(iq, oq) proc.start() print_output(oq, 5, 0.1) iq.put(Action(label="drop", data=dict(label="a"))) # Try to send incorrect actions iq.put(Action(label="notdrop", data=dict(lbl="b"))) iq.put(Action(label="drop", data=dict())) print() print_output(oq, 5, 0.1) iq.put(Action(label="drop", data=dict(label="b"))) print() print_output(oq, 5, 0.1) proc.join() </code></pre>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T13:16:42.323", "Id": "212208", "Score": "1", "Tags": [ "python", "python-3.x", "multiprocessing" ], "Title": "Python process-subprocess communication" }
212208
<p>I have a function which does the following:</p> <ol> <li>When new Post Entity is added some fields in Category table are updated.</li> <li>When new Thread Entity is added the same fields in Category table are updated.</li> </ol> <p>Because of this, some lines are completely the same.</p> <pre><code>public function postPersist(LifecycleEventArgs $args) { $entity = $args-&gt;getObject(); $entityManager = $args-&gt;getObjectManager(); if ($entity instanceof Post) { $post = $entity; $thread = $post-&gt;getThread(); $category = $thread-&gt;getCategory(); $category-&gt;setLastPostThreadTitle($thread-&gt;getTitle()); $category-&gt;setLastPostThreadSlug($thread-&gt;getSlug()); $category-&gt;setLastPostBody($post-&gt;getBody()); $category-&gt;setLastPosterUsername($post-&gt;getUser()-&gt;getUsername()); $category-&gt;setLastPostCreatedAt($post-&gt;getCreatedAt()); $category-&gt;setIsLastPostOp(false); $category-&gt;setPosts($category-&gt;getPosts() + 1); $entityManager-&gt;merge($category); $entityManager-&gt;flush(); } if ($entity instanceof Thread) { $thread = $entity; $category = $thread-&gt;getCategory(); $category-&gt;setLastPostThreadTitle($thread-&gt;getTitle()); $category-&gt;setLastPostThreadSlug($thread-&gt;getSlug()); $category-&gt;setLastPostBody($thread-&gt;getBody()); $category-&gt;setLastPosterUsername($thread-&gt;getUser()-&gt;getUsername()); $category-&gt;setLastPostCreatedAt($thread-&gt;getCreatedAt()); $category-&gt;setIsLastPostOp(true); $entityManager-&gt;merge($category); $entityManager-&gt;flush(); } } </code></pre> <p>How would be possible to refactor this code to avoid WET?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T13:41:34.607", "Id": "410372", "Score": "0", "body": "Errr.... Move the common code above if?" } ]
[ { "body": "<p>How about something like this there is some checking that needs to be done because I inverse the <code>$isPost</code> bool and that could be buggy</p>\n\n<pre><code>public function postPersist(LifecycleEventArgs $args)\n{\n $entity = $args-&gt;getObject();\n $entityManager = $args-&gt;getObjectManager();\n\n $isPost = $entity instanceof Post;\n\n $thread = $isPost ? $post-&gt;getThread() : $entity;\n\n $details = $isPost ? $entity : $thread;\n\n $category = $thread-&gt;getCategory(); \n $category-&gt;setLastPostThreadTitle($thread-&gt;getTitle()); \n $category-&gt;setLastPostThreadSlug($thread-&gt;getSlug()); \n $category-&gt;setLastPostBody($details-&gt;getBody());\n $category-&gt;setLastPosterUsername($details-&gt;getUser()-&gt;getUsername());\n $category-&gt;setLastPostCreatedAt($details-&gt;getCreatedAt());\n\n //NOTE the inversion of the isPost bool\n //TODO Test this\n $category-&gt;setIsLastPostOp(!$isPost);\n\n if($isPost){ \n $category-&gt;setPosts($category-&gt;getPosts() + 1);\n }\n\n $entityManager-&gt;merge($category); \n $entityManager-&gt;flush();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:31:00.670", "Id": "410378", "Score": "0", "body": "It works:). Just had to change $post->getThread() to $entity->getThread(), because $post is undefined on line 8" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T13:47:16.463", "Id": "212211", "ParentId": "212210", "Score": "1" } } ]
{ "AcceptedAnswerId": "212211", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T13:33:55.150", "Id": "212210", "Score": "3", "Tags": [ "php", "doctrine" ], "Title": "Forum system implementation" }
212210
<p>I'm creating some web apis to sync some data between desktop/mobile apps.<br/> Working on it, I wrote a simple wrapper for <code>mysqli</code> connection to simplify querying like:<br/></p> <pre><code>// examples $connection = new MySQLiConnection(); $connection-&gt;execute("INSERT INTO songs VALUES ('God\'s Plan', 'Drake')"); $connection-&gt;execute('INSERT INTO songs VALUES (?, ?)', 'Perfect', 'Ed Sheeran'); $result = $connection-&gt;getResult('SELECT * FROM songs'); var_dump($result); $result = $connection-&gt;getResult('SELECT * FROM songs WHERE artist = ?', 'Ed Sheeran'); var_dump($result); </code></pre> <p><br/> Code of the wrapper:</p> <pre><code>&lt;?php final class MySQLiConnection { private $connection; public function __construct() { $this-&gt;connection = new mysqli('localhost', 'id', 'password', 'database'); if ($this-&gt;connection-&gt;connect_errno) { throw new mysqli_sql_exception('Failed to open mysqli connection: ' . $this-&gt;connection-&gt;connect_error); } if (!$this-&gt;connection-&gt;set_charset('utf8')) { throw new mysqli_sql_exception('Failed to set utf8 character set: ' . $this-&gt;connection-&gt;error); } } public function __destruct() { if (!$this-&gt;connection-&gt;close()) { throw new mysqli_sql_exception('Failed to close mysqli connection: ' . $this-&gt;connection-&gt;error); } } private function buildStatement(string $sql, ...$params) : mysqli_stmt { if ($statement = $this-&gt;connection-&gt;prepare($sql)) { if (!empty($params)) { $types = ''; foreach ($params as $param) { if (is_int($param)) { $types .= 'i'; } elseif (is_float($param)) { $types .= 'd'; } elseif (is_string($param)) { $types .= 's'; } else { $types .= 'b'; } } $statement-&gt;bind_param($types, ...$params); } return $statement; } throw new mysqli_sql_exception('Failed to prepare mysqli_stmt: ' . $this-&gt;connection-&gt;error); } public function execute(string $sql, ...$params) : void { $statement = $this-&gt;buildStatement($sql, ...$params); $success = $statement-&gt;execute(); $statement-&gt;close(); if (!$success) { throw new mysqli_sql_exception('Failed to execute mysqli_stmt: ' . $this-&gt;connection-&gt;error); } } public function getResult(string $sql, ...$params) : mysqli_result { $statement = $this-&gt;buildStatement($sql, ...$params); $success = $statement-&gt;execute(); if ($success) { $result = $statement-&gt;get_result(); $statement-&gt;close(); return $result; } $statement-&gt;close(); throw new mysqli_sql_exception('Failed to execute mysqli_stmt: ' . $this-&gt;connection-&gt;error); } } ?&gt; </code></pre>
[]
[ { "body": "<h2>PSR 2</h2>\n\n<p>Psr2 is a code standard for php use it, most ides have good integration to auto-reformat your code <a href=\"https://www.php-fig.org/psr/psr-2/\" rel=\"nofollow noreferrer\">read about it here</a></p>\n\n<h2>Generally</h2>\n\n<p>Wrapping libraries for databases is a bad idea, how do I start a transaction in your class ? </p>\n\n<p>@Yourcommonsense will im sure provide a link for his website demonstrating why this is a bad idea.</p>\n\n<h2>Return early &amp;&amp; Use Constants</h2>\n\n<p>There is no point having long statements that cause the indentation level to be excessive, </p>\n\n<p>Use constants for random strings because they mean nothing to anybody but you, with a good name (my names probably aren't good because I dont know that mean) it can speak a million words,</p>\n\n<p>For example </p>\n\n<pre><code>private const INT_PARAM_STRING = \"i\";\nprivate const FLOAT_PARAM_STRING = \"d\";\nprivate const STRING_PARAM_STRING = \"s\";\nprivate const DEFAULT_PARAM_STRING = \"b\";\n\nprivate function buildStatement(string $sql, ...$params) : mysqli_stmt\n{\n if (empty($params)) {\n throw new \\Exception(\"Empty params\", 1);\n }\n\n $statement = $this-&gt;connection-&gt;prepare($sql);\n\n if ($statement == false) {\n throw new mysqli_sql_exception('Failed to prepare mysqli_stmt: ' . $this-&gt;connection-&gt;error);\n }\n\n $types = '';\n\n foreach ($params as $param) {\n $types .= $this-&gt;getParamType($param);\n }\n\n $statement-&gt;bind_param($types, ...$params);\n\n return $statement;\n}\n\nprivate function getParamType($param) :string\n{\n if (is_int($param)) {\n return MySQLiConnection::INT_PARAM_STRING;\n } elseif (is_float($param)) {\n return MySQLiConnection::FLOAT_PARAM_STRING;\n } elseif (is_string($param)) {\n return MySQLiConnection::STRING_PARAM_STRING;\n }\n\n return DEFAULT_PARAM_STRING;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:05:52.257", "Id": "410390", "Score": "0", "body": "A little correction, it is not an error when params are empty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:54:26.353", "Id": "410402", "Score": "0", "body": "Thank you.\n\nI do agree with you that wrapping a library is generally considered bad, but my intention was just to avoid the code being lengthy.\nWithout any wrapper, it would take several lines just to create and execute a prepared statement in mysqli.\n\nAnd as you asked about the transaction, I should've created a getter of the `$connection`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:28:36.160", "Id": "212217", "ParentId": "212212", "Score": "0" } }, { "body": "<h3>Error reporting</h3>\n<p>This is much better than your initial attempt, but somehow it become <em>more verbose</em> and I'll tell you why: you are, so to say, abused the error reporting. <code>mysqli_sql_exception</code> is not intended to be thrown manually. Like it's said in the article I gave you link to, mysqli <a href=\"https://phpdelusions.net/mysqli/mysqli_connect#functions\" rel=\"nofollow noreferrer\">can throw exceptions by itself</a> - so just let mysqli to do it. And therefore there is no reason to check for errors manually, and it will <strong>greatly reduce</strong> the amount of repeated code.</p>\n<h3>Automatic binding</h3>\n<p>Your automated binding function is rather confusing. Apparently you didn't have any clear idea what this code is intended to do:</p>\n<pre><code> else\n {\n $types .= 'b';\n }\n</code></pre>\n<p>And I'll tell you - there is no good scenario for it.<br />\nDon't write a code just in case, when you just don't know what to write. In such circumstances just <strong>don't write any code at all.</strong></p>\n<p>Besides, I am scared by functions like this that sniff a type off a variable automatically. If you will have a query that will compare a string stored in a database to a number, the consequences would be fatal. And PHP is known for converting strings to numbers on its own will. So, although quite small, but there is still a possibility that your binding function will ruin your database.</p>\n<p>That's why I prefer either a manual explicit type setting or just blunt setting a string type for all variables. At least it won't harm anyone.</p>\n<p>In practice it means that I recommend to use string type for all parameters by default, with a possibility of a fallback with manual type setting. So, taken from ny other article, the <a href=\"https://phpdelusions.net/mysqli/simple#code\" rel=\"nofollow noreferrer\">mysqli binding function</a> would be like</p>\n<pre><code>public function execute(string $sql, $params = [], $types = '') : mysqli_stmt\n{\n if (!$params) {\n return $this-&gt;connection-&gt;query($sql);\n }\n $types = $types ?: str_repeat(&quot;s&quot;, count($params));\n $statement = $this-&gt;connection-&gt;prepare($sql);\n $statement-&gt;bind_param($types, ...$params);\n $stmt-&gt;execute();\n return $stmt;\n}\n</code></pre>\n<p>this function does a lot of good stuff:</p>\n<ul>\n<li><p>it lets you to run a query that doesn't support prepared statements</p>\n</li>\n<li><p>it does no harm automatically sniffing the variable's type</p>\n</li>\n<li><p>at the same time it lets you to provide a type string manually, like</p>\n<pre><code> $conn-&gt;execute('INSERT INTO songs VALUES (?, ?, ?)', ['foo', 'bar', 1], &quot;ssi&quot;);\n</code></pre>\n</li>\n</ul>\n<p>I also removed an argument unpacking operator from the function definition as it makes no sense. Trust me, it takes <strong>no effort</strong> to add two square brackets around parameters, but it makes your code WAY cleaner and more maintainable.</p>\n<h3>Closing statements</h3>\n<p>PHP is incredibly programmer-friendly. Resources don't have to be closed manually, they will be closed automatically when no longer needed.</p>\n<h3>The code</h3>\n<pre><code>&lt;?php\n\nfinal class MySQLiConnection\n{\n public $connection;\n\n public function __construct($config)\n {\n mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\n try {\n $this-&gt;connection = new mysqli('localhost', 'id', 'password', 'database');\n $this-&gt;connection-&gt;set_charset('utf8');\n } catch (\\mysqli_sql_exception $e) {\n throw new \\mysqli_sql_exception($e-&gt;getMessage(), $e-&gt;getCode());\n }\n }\n\n public function execute(string $sql, $params = [], $types = '') : mysqli_stmt\n {\n if (!$params) {\n return $this-&gt;connection-&gt;query($sql);\n }\n $types = $types ?: str_repeat(&quot;s&quot;, count($params));\n $statement = $this-&gt;connection-&gt;prepare($sql);\n $statement-&gt;bind_param($types, ...$params);\n $statement-&gt;execute();\n return $statement;\n }\n\n public function getResult(string $sql, $params = [], $types = '') : mysqli_result\n {\n return $this-&gt;execute($sql, $params, $types)-&gt;get_result();\n }\n}\n</code></pre>\n<p>As you can see, the final code is much more concise, thanks to code reuse and proper error reporting.</p>\n<p>I also made $connection variable public, as there is no more getConnection() function but you will need to access it from outside for sure.</p>\n<p>An exception is caught in the constructor because of security concerns. A stack trace for the exception thrown in case of a connection error would contain the database credentials that will end up either in the server logs or - the worst case - displayed on the screen. Once re-thrown this way, credentials are no more exposed. So although as a rule you don't catch an Exception right in place, here it's a special case to take care of.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:11:44.343", "Id": "410406", "Score": "0", "body": "Thanks a lot for the nice code. If the error reporting is enabled as you suggested, do `mysqli` always throw an exception instead of just returning `FALSE` so that manual handling is never required? And may I ask why do you re-`throw` the `mysqli_sql_exception`, are they ignored or do they cause a problem if not caught immediately?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:45:50.677", "Id": "410409", "Score": "0", "body": "1.yes. 2. I am doing it for connection only. A stack trace for the exception thrown from connect would contain the database credentials. Once rethrown it would not. So it's a special case to take care of" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:57:16.877", "Id": "212221", "ParentId": "212212", "Score": "1" } } ]
{ "AcceptedAnswerId": "212221", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:06:12.010", "Id": "212212", "Score": "1", "Tags": [ "php", "mysql", "mysqli" ], "Title": "Simple wrapper for PHP mysqli connection" }
212212
<p>The following program takes 3 integer inputs(noOfThreadToBeCreate,fromNo,toNo) and print the Consecutive numbers based on the range using different threads e.g (Thread 1 - Print 1, Thread 2 - print 2, and so on ). </p> <p>I am new to the multi threading and implement this program as per my basic understanding without taking any online help. </p> <p>One of my senior colleague reviewed this and told its incorrect. </p> <p>It would be great help if somebody review the code and provide comments, what wrong in this.</p> <pre><code> package multithreading.programs; public class PrintConsecutiveNumberByThreads { int whoseThreadTurnToRun = 1; int fromNumber; int toNumber; int threadSize; public PrintConsecutiveNumberByThreads(int threadSize, int fromNumber, int toNumber){ this.fromNumber = fromNumber; this.toNumber = toNumber; this.threadSize = threadSize; } public static void main(String[] args) { PrintConsecutiveNumberByThreads obj = new PrintConsecutiveNumberByThreads(4,1,100); Runnable task = obj.createRunnableTask(); obj.createAndExecuteThread(task); } private void createAndExecuteThread(Runnable task){ for(int i = 0; i &lt; threadSize; i++){ new Thread(task,String.valueOf(i+1)).start(); } } private Runnable createRunnableTask() { Runnable task = () -&gt; { synchronized (this) { while (fromNumber &lt;= toNumber) { if (whoseThreadTurnToRun != Integer.parseInt(Thread.currentThread().getName())) { this.notifyAll(); } else { System.out.println("Thread "+Thread.currentThread().getName() + " :: " + fromNumber++); whoseThreadTurnToRun = whoseThreadTurnToRun % threadSize + 1; this.notifyAll(); } try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } } }; return task; } } Output : Thread 1 :: 1 Thread 2 :: 2 Thread 3 :: 3 Thread 4 :: 4 Thread 1 :: 5 Thread 2 :: 6 Thread 3 :: 7 Thread 4 :: 8 Thread 1 :: 9 Thread 2 :: 10 Thread 3 :: 11 Thread 4 :: 12 So on.... </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:48:08.483", "Id": "410380", "Score": "1", "body": "Hi, did your senior colleague say what's wrong with it? Maybe you should seek more details about it so you can fix it before posting here. In your case, it's hard to tell if the question is on topic as you're not sure if the code works as intended." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:28:31.920", "Id": "410382", "Score": "2", "body": "What are the requirements you're trying to meet? As written, this code more obtuse and less efficient than using a single thread." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:48:41.880", "Id": "410387", "Score": "0", "body": "My colleague commented as this code has problem of data inconsistency and 'guarded block'." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:51:41.320", "Id": "410389", "Score": "0", "body": "The requirements is to establish inter thread communication. So that each thread prints number in consecutive order. Its similar to print even and odd number using 2 threads. I implemented the same for n threads." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:21:35.727", "Id": "212213", "Score": "1", "Tags": [ "java", "multithreading" ], "Title": "Inter Thread communication between n thread" }
212213
<p>I have a spreadsheet with five sheets all of which run the same VBA code; everything was good when it was on just the one sheet, but now it's running on all five sheets Excel is extremely slow to load and the items take a while to update.</p> <p>I have a drop down menu in one column and if a user selects an item from this list it updates the next two cells with their username and date and time stamps it. I have 12 sections on each sheet for each month of the year.</p> <p>I'm a VBA newbie but I adapted this code from another website with a little trial and error. Is there a way I can speed things up?</p> <pre><code>Private Sub Worksheet_Change(ByVal Target As Excel.Range) If Target.Column = 1 Or Target.Column = 2 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("D" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("C" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("C:D").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 5 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("G" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("F" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("F:G").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 8 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("J" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("I" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("I:J").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 11 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("M" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("L" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("L:M").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 14 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("P" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("O" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("O:P").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 17 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("S" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("R" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("R:S").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 20 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("V" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("U" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("U:V").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 23 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("Y" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("X" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("X:Y").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 26 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("AB" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("AA" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("AA:AB").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 29 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("AE" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("AD" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("AD:AE").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 32 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("AH" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("AG" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("AG:AH").EntireColumn.AutoFit End If If Target.Column = 1 Or Target.Column = 35 Then ThisRow = Target.Row If (ThisRow = 1) Then Exit Sub ' time stamp corresponding to cell's last update Range("AK" &amp; ThisRow).Value = Now ' Windows level UserName | Application level UserName Range("AJ" &amp; ThisRow).Value = Environ("username") &amp; "|" &amp; Application.UserName Range("AK:AJ").EntireColumn.AutoFit End If End Sub </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:48:57.703", "Id": "410412", "Score": "0", "body": "In general, Worksheet_Change is NOT performance friendly" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T16:15:28.943", "Id": "411673", "Score": "0", "body": "Biggest **speed** issue, is the fact that this code will run **3 times**...once when the user changes a cell, once when you write the date and once when you write the username...more to follow" } ]
[ { "body": "<p>This is untested but is this any faster ?</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)\n column = Target.Column\n ThisRow = Target.Row\n\n If (column &lt;&gt; 1 Or ThisRow = 1) Then Exit Sub\n\n startColumn = Col_Letter(Target.Column + 1)\n endColumn = Col_Letter(Target.Column + 2) \n\n ' time stamp corresponding to cell's last update\n Range(endColumn &amp; ThisRow).Value = Now\n ' Windows level UserName | Application level UserName\n Range(startColumn &amp; ThisRow).Value = Environ(\"username\") &amp; \"|\" &amp; Application.UserName\n Range(startColumn &amp; \":\" &amp; endColumn).EntireColumn.AutoFit\nEnd Sub\n\n' taken from https://stackoverflow.com/questions/12796973/function-to-convert-column-number-to-letter\nFunction Col_Letter(lngCol As Long) As String\n Dim vArr\n vArr = Split(Cells(1, lngCol).Address(True, False), \"$\")\n Col_Letter = vArr(0)\nEnd Function\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:49:21.480", "Id": "212220", "ParentId": "212215", "Score": "0" } }, { "body": "<p>The first two points I want to make in this review are general ones that are good discipline to aid in any maintenance.</p>\n\n<ul>\n<li>Always use <code>Option Explicit</code>. <strong><em>Always</em></strong>. At the very least, it\nwill encourage strong type checking and help avoid any nuisance\nerrors caused by spelling errors.</li>\n<li>Always indent your code properly. This will help any reader identify\nlogical blocks.</li>\n</ul>\n\n<p>I can see from your above code that you have done neither. This makes the code harder to read, thus harder to review.</p>\n\n<p>The next point is also a common one - <strong>D</strong>on't <strong>R</strong>epeat <strong>Y</strong>ourself (DRY). In your code you have a repetitive theme:</p>\n\n<pre><code>Range(\"D\" &amp; ThisRow).Value = Now\n' Windows level UserName | Application level UserName\nRange(\"C\" &amp; ThisRow).Value = Environ(\"username\") &amp; \"|\" &amp; Application.UserName\nRange(\"C:D\").EntireColumn.AutoFit\n</code></pre>\n\n<p>Repeated blocks identify two methods for improvement - either a stand-alone routine or a loop. Because your code logic is based on the conditional location of the change, I advocate for a stand-alone routine here (in this case, a <code>Sub</code>, not a <code>Function</code>):</p>\n\n<pre><code>Sub MakeMyAmendments(rangeToAmend as Range) `** See notes below\n rangeToAmend(1).Value = Environ(\"username\") &amp; \"|\" &amp; Application.UserName\n rangeToAmend(2).Value = Now()\n rangeToAmend.EntireColumn.Autofit\nEnd Sub\n</code></pre>\n\n<p>Notes:</p>\n\n<ol>\n<li>Name this sub something sensible, something that fits in with your\nlogic flow</li>\n<li>I could have approached this a number of ways - such as passing in\nthe address rather than the range, passing in the row number,\npassing in any other factors.</li>\n<li>For me the easiest and simplest way was simply to let the logic in\nthe main event handler identify what had to be changed.</li>\n</ol>\n\n<p>This reduces the main event handler to:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)\n If Target.Column = 1 Or Target.Column = 2 Then\n 'ThisRow = Target.Row\n If (ThisRow = 1) Then Exit Sub\n 'MakeMyAmendments Target.Worksheet.Range(\"C\" &amp; ThisRow &amp; \":D\" &amp; ThisRow) ' Option 1 - following closely to the original\n 'MakeMyAmendments Target.Worksheet.Range(\"C\" &amp; Target.Row &amp; \":D\" &amp; Target.Row) ' Option 2, negating need for the additional variable\n With Target.Worksheet\n MakeMyAmendments .Range(.Cells(Target.Row,3),.Cells(Target.Row,4))\n End With - preferred, fully qualified and makes the next logic leap easier to see.\n End If\n If Target.Column = 1 Or Target.Column = 5 Then\n ThisRow = Target.Row\n If (ThisRow = 1) Then Exit Sub\n With Target.Worksheet\n MakeMyAmendments .Range(.Cells(Target.Row,6),.Cells(Target.Row,7))\n End With\n End If\n If Target.Column = 1 Or Target.Column = 8 Then\n ThisRow = Target.Row\n If (ThisRow = 1) Then Exit Sub\n With Target.Worksheet\n MakeMyAmendments .Range(.Cells(Target.Row,9),.Cells(Target.Row,10))\n End With\n End If\n ' Repeat: 11 gives us 12 &amp; 13 ' Yeah, I am getting bored with this.\n ' Repeat: 14 gives us 15 &amp; 16\n ' Repeat: 17 gives us 18 &amp; 19\n ' Repeat: 20 gives us 21 &amp; 22\n ' Repeat: 23 gives us 24 &amp; 25\n ' Repeat: 26 gives us 27 &amp; 28\n ' Repeat: 29 gives us 30 &amp; 31\n ' Repeat: 32 gives us 33 &amp; 34\n ' Repeat: 35 gives us 36 &amp; 37\nEnd Sub\n</code></pre>\n\n<p>You can see a clear pattern here. But, what happens if you want to expand to the right - just keep adding more \"If\" statements?</p>\n\n<p>And your logic is non-intuitive (a subtle trap that I missed on the first reading). If the Column = 1 then you want to amend all the other columns, but if the Column = anything other than that, then only amend the one set. So now we have to understand the full collection.</p>\n\n<p>And if my statement above is wrong - then you certainly have a problem in your code - refer to my first points about making the logic easier to see.</p>\n\n<p>How do we describe the pattern. I think one way is to set up an array. Another way is to use a formula to reflect the 3-based pattern - but I think an array is the easiest to see and maintain.</p>\n\n<p>Again, this is an example of DRY - in this case we can use a loop.</p>\n\n<pre><code>Dim iterator as Long ' always long\nFor iterator = 2 to 35 Step 3 ' this will include the first and last columns, so easy to amend if the number of data points change.\n If Target.Column = 1 Or Target.Column = Iterator Then\n With Target.Worksheet\n MakeMyAmendments .Range(.Cells(Target.Row,iterator+1),.Cells(Target.Row,iterator+2))\n End With\n End If\nNext iterator\n</code></pre>\n\n<p>Putting all this together:</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)\n Dim iterator as Long ' always long\n For iterator = 2 to 35 Step 3 ' this will include the first and last columns, so easy to amend if the number of data points change.\n If Target.Column = 1 Or Target.Column = Iterator Then\n With Target.Worksheet\n MakeMyAmendments .Range(.Cells(Target.Row,iterator+1),.Cells(Target.Row,iterator+2))\n End With\n End If\n Next iterator\nEnd Sub\n</code></pre>\n\n<p>This creates a simple and maintainable event handler. It will also be easier to add further logic for different change rules as a new logic block because you are now not dealing with lots of lines of code.</p>\n\n<p>What can we do to slightly speed this up? Calls to Excel Objects incur an overhead because the VBA has to switch from the VBA model to the Excel model (referencing and de-referencing) every time we reference the object. We can minimise those switches for those items we know that will not change:</p>\n\n<pre><code>Dim targetColumn as Long\nDim targetRow as Long\ntargetColumn = Target.Column\ntargetRow = Target.Row\n</code></pre>\n\n<p>Throwing this in adds a few lines, but will save time (not much in this case but could add up if you are looking at 100s of columns).</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Excel.Range)\n Dim targetColumn as Long\n Dim targetRow as Long\n targetColumn = Target.Column\n targetRow = Target.Row\n\n Dim iterator as Long ' always long\n For iterator = 2 to 35 Step 3 ' this will include the first and last columns, so easy to amend if the number of data points change.\n If targetColumn = 1 Or targetColumn = Iterator Then\n With Target.Worksheet\n MakeMyAmendments .Range(.Cells(targetRow ,iterator+1),.Cells(targetRow ,iterator+2))\n End With\n End If\n Next iterator\nEnd Sub\n</code></pre>\n\n<p>In this case, creating an object to represent the <code>Target.Worksheet</code> is unlikely to make any difference. But should always consider it!</p>\n\n<p>All code in this answer is untested.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T10:15:00.397", "Id": "410731", "Score": "0", "body": "Thank you for your extensive commentary. It is very useful. I have never used VBA before doing the code I adapted above; I can see VBA is going to be very useful and make my life easier, but at present I think I need to do some more reading and experimenting. Much of what you have coded above makes sense, but I'm not sure I get it all yet! :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T21:30:45.457", "Id": "410862", "Score": "0", "body": "To tag onto @AJD's note about indentation, here's a handy Smart Indenter tool that you can use for existing code, or to double-check while you're learning - http://rubberduckvba.com/Indentation" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T16:08:02.220", "Id": "411671", "Score": "0", "body": "Instead of the `iterator`, just use the `mod` function....`If targetColumn mod 3 = 2 then`" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T18:27:32.027", "Id": "411687", "Score": "0", "body": "@Profex: the loop (`iterator`) is still needed and the use of mod obscures the start and end column. While the suggestion is really good for other cases, in this case the simplicity of the statement helps the OP." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T22:31:46.267", "Id": "212240", "ParentId": "212215", "Score": "2" } }, { "body": "<p>In addition to all the great advice in the other answers, specifically about always using <code>Option Explicit</code> and the <a href=\"https://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow noreferrer\">DRY</a> principle...</p>\n\n<p>What happens when someone pastes multiple cells at once (instead of using the down down)?</p>\n\n<p>Typically I use a <code>For Each cell in Target</code> followed by a <code>Select Case Cell.Column</code>. </p>\n\n<p>It handles the pasting of multiple cells at once (where your code only deals with the first cell) and is much easier to read.</p>\n\n<p>There are also a few Application variables that you can change to speed things up. The main one, that should almost be a requirement for the <code>Worksheet_Change</code> function is:</p>\n\n<p><strong>Application.EnableEvents</strong>. </p>\n\n<p><strong><em>If you don't turn this off while you make changes to the current worksheet, you could get stuck in an endless loop</em></strong>. </p>\n\n<p>Anyway, this is the basic idea of what I end up using...</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\nDim isActiveWindow As Boolean\nDim InitialScreenUpdating As Boolean, InitialEnableEvents As Boolean, InitialCalculation As Boolean\nDim DataRange As Excel.Range, Cell As Excel.Range\n\n ' Get current State\n isActiveWindow = Not ActiveWindow Is Nothing\n ' Can't reference Application.Calculation unless a Window is active\n If isActiveWindow Then InitialCalculation = Application.Calculation\n InitialEnableEvents = Application.EnableEvents\n InitialScreenUpdating = Application.ScreenUpdating\n\n ' In case anything goes wrong, we need a safe exit...\n On Error GoTo ErrHandler\n\n ' Turn off Automatic Calculation mode...if changing a lot of values that are referenced in formulas\n If isActiveWindow Then Application.Calculation = xlCalculationManual\n ' Turn off All Events...such as Worksheet_Change.\n ' Make sure that you turn it back on (specificaly when debugging and you stop the code, no events will trigger)\n Application.EnableEvents = False\n ' Pause screen rendering, to speed up code if there are lots of changes (doesn't apply while debugging)\n Application.ScreenUpdating = False\n\n ' Limit the Target to the range that you care about...\n ' in this case anything but the first row\n Set DataRange = ActiveSheet.Range(\"2:\" &amp; ActiveSheet.Rows.Count)\n Set Target = Intersect(Target, DataRange)\n\n ' Just in case there are multiple cells changed...\n For Each Cell In Target\n Select Case Cell.Column\n Case 1\n ' Do something\n Case Else\n If Cell.Column Mod 3 = 2 Then\n ' Do something else\n End If\n End Select\n Next\n\nErrHandler:\n If Err.Number &lt;&gt; 0 Then\n MsgBox \"Error: \" &amp; Err.Number &amp; vbCr &amp; vbCr &amp; Err.Description\n End If\n\n ' Restore States to what it was at the start\n isActiveWindow = Not ActiveWindow Is Nothing\n ' Can't reference Application.Calculation unless a Window is active, hence the nested If statements\n If isActiveWindow Then _\n If Application.Calculation &lt;&gt; InitialCalculation Then _\n Application.Calculation = InitialCalculation\n If Application.EnableEvents &lt;&gt; InitialEnableEvents Then _\n Application.EnableEvents = InitialEnableEvents\n If Application.ScreenUpdating &lt;&gt; InitialScreenUpdating Then _\n Application.ScreenUpdating = InitialScreenUpdating\n ' You could just set these, but if this is added to nested functions, \n ' you wouldn't want to cause unnecessary flickering.\nEnd Sub\n</code></pre>\n\n<hr>\n\n<p>In reality, and because of DRY, you would want to create a function to clean it up so that it would look something like this...</p>\n\n<pre><code>Private Sub Worksheet_Change(ByVal Target As Range)\nDim AppState As AppStateType\n On Error GoTo ErrorHandler\n AppState = ChangeAppState(AppState, -1, True, True)\n\n ' Do stuff here\n\nErrorHandler:\n\nEndSub:\n ChangeAppState AppState, , True, True\nEnd Sub\n</code></pre>\n\n<p>Where I have a public <em>User Defined Type</em>:</p>\n\n<pre><code>Public Type AppStateType\n ScreenUpdating As Boolean\n DisplayStatusBar As Boolean\n Calculation As Integer\n EnableEvents As Boolean\nEnd Type\n</code></pre>\n\n<p>and the <em>ChangeAppState</em> Function</p>\n\n<pre><code>' Turn ScreenUpdating off for speed, while writing values to the cells.\n' Turn EnableEvents off to disable the SheetChange Events from firing while updating values.\n' Turn Calculation to xlCalculationManual for speed while updating values.\nFunction ChangeAppState(AppState As AppStateType, Optional State As Integer, _\n Optional SetScreenUpdating As Boolean, Optional SetEnableEvents As Boolean, _\n Optional SetCalculation As Boolean, Optional SetDisplayStatusBar As Boolean) As AppStateType\nDim bActiveWindow As Boolean\n' Change the Application States to False/Manual if State is -1\n' Change the Application States back to the the values in AppState if State is 0\n' Change the Application States to True/Automatic if State is 1\n bActiveWindow = Not ActiveWindow Is Nothing\n ChangeAppState.ScreenUpdating = Application.ScreenUpdating\n ChangeAppState.DisplayStatusBar = Application.DisplayStatusBar\n If bActiveWindow Then ChangeAppState.Calculation = Application.Calculation\n ChangeAppState.EnableEvents = Application.EnableEvents\n Select Case State\n Case -1\n If SetScreenUpdating And Application.ScreenUpdating &lt;&gt; False _\n Then Application.ScreenUpdating = False\n If SetEnableEvents And Application.EnableEvents &lt;&gt; False _\n Then Application.EnableEvents = False\n If bActiveWindow Then _\n If SetCalculation And Application.Calculation &lt;&gt; xlCalculationManual _\n Then Application.Calculation = xlCalculationManual\n If SetDisplayStatusBar And Application.DisplayStatusBar &lt;&gt; False _\n Then Application.DisplayStatusBar = False\n Case 0\n If SetDisplayStatusBar And Application.DisplayStatusBar &lt;&gt; AppState.DisplayStatusBar _\n Then Application.DisplayStatusBar = AppState.DisplayStatusBar\n If bActiveWindow Then _\n If SetCalculation And Application.Calculation &lt;&gt; AppState.Calculation _\n Then Application.Calculation = AppState.Calculation\n If SetEnableEvents And Application.EnableEvents &lt;&gt; AppState.EnableEvents _\n Then Application.EnableEvents = AppState.EnableEvents\n If SetScreenUpdating And Application.ScreenUpdating &lt;&gt; AppState.ScreenUpdating _\n Then Application.ScreenUpdating = AppState.ScreenUpdating\n Case 1\n If SetScreenUpdating And Application.ScreenUpdating &lt;&gt; True _\n Then Application.ScreenUpdating = True\n If SetEnableEvents And Application.EnableEvents &lt;&gt; True _\n Then Application.EnableEvents = True\n If bActiveWindow Then _\n If SetCalculation And Application.Calculation &lt;&gt; xlCalculationAutomatic _\n Then Application.Calculation = xlCalculationAutomatic\n If SetDisplayStatusBar And Application.DisplayStatusBar &lt;&gt; True _\n Then Application.DisplayStatusBar = True\n End Select\nEnd Function\n</code></pre>\n\n<h2>In addition</h2>\n\n<p>The <code>AutoFit</code> function is probably going to be one of the slowest operations that you have. The above code should help speed it up. If it doesn't, you may want/need to do the following</p>\n\n<ul>\n<li>create a new temporary sheet in the background</li>\n<li>add the same username/date values</li>\n<li><code>Autofit</code> the new sheet</li>\n</ul>\n\n<p>If those columns are larger then the ones in the original sheet, you would</p>\n\n<ul>\n<li>adjust the original sheet's columns</li>\n<li>delete the temporary sheet. </li>\n</ul>\n\n<p>Just make sure the font/size &amp; sheet zoom are the same.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T17:17:30.713", "Id": "212863", "ParentId": "212215", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T14:54:39.557", "Id": "212215", "Score": "2", "Tags": [ "beginner", "vba", "excel" ], "Title": "VBA code slowing workbook" }
212215
<p>We use a third party dll which has an object called CServer and was provided by one of our software vendors to act as an API between our applications and their applications.</p> <p>CServer has the following method: </p> <p><code>bool SynchroniseData()</code> which can be called if we want to fetch data from server which is very important for our application. This call signifies to the DLL our <strong>intention</strong> that we want to fetch the data. It does not fetch the data. Instead it returns true, if the request was successfully send to their application.</p> <p>When data are actually fetched in the <code>CServer</code> object, <code>CServer</code> fires the event <code>onDataFetched</code>. We listen to that event and process the data. The <code>CServer</code> always has the latest data, since it continuously synchronises the data with our Vendor's servers.</p> <p>However, there are many times at which the event <code>onDataSynchronisationStopped</code> is called. This signifies that the <code>CServer</code> object will stop data synchronisation with the server. This event is fired when the network is momentarily down, or if the server has some minor delays and so on.</p> <p>We always want to have that data, and thus we try to fetch them again.</p> <p>We currently do it like this:</p> <pre><code>private void OnDataFetchedHandler(object sender, EventArgs eventArgs){ try{ bool dataHaveBeenFetched; do{ dataHaveBeenFetched = TrytoFetchData((CServer) sender); Thread.Sleep(1000); } while (!dataHaveBeenFetched); } catch (Exception ex){ Log.ErrorFormat(ex.Message, ex); } } private bool TrytoFetchData(CServer sender){ sender.SynchroniseData(); ManualResetEvent manualResetEvent = new ManualResetEvent(false); EventHandler manualResetEventSethandler = (s, e) =&gt; manualResetEvent.Set(); sender.OnDataFetched += manualResetEventSethandler; bool dataHaveBeenFetched = manualResetEvent.WaitOne(new TimeSpan(0, 0, 3, 0)); sender.OnDataFetched -= manualResetEventSethandler; return dataHaveBeenFetched; } </code></pre> <p>Is there any cleaner way of doing this?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:50:27.357", "Id": "410388", "Score": "1", "body": "Why does the loop in the event handler has to wait 1 second? What for? Shouldn't the event be fired everytime data arrives? Mhmm this is a weird..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T20:40:03.347", "Id": "410664", "Score": "0", "body": "Is your intention for this code to continually execute? Each time `OnDataFetchedHandler()` calls `TrytoFetchData()`, another `CServer.OnDataFetched` is raised causing `OnDataFetchedHandler()` to fire again." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T12:36:19.613", "Id": "410748", "Score": "0", "body": "@t3chb0t, you are right, I have edited the code. The handler is the onDataSynchronisationStoppedHandler and not the onDataFetchedHandler." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T12:43:47.120", "Id": "410750", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T12:45:55.097", "Id": "410751", "Score": "0", "body": "@Mast I had a copy paste mistake which was identified by the community. That's why I pasted the correct method name, and updated the community about the edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T13:03:39.970", "Id": "410752", "Score": "0", "body": "And had you made the edit before there was an answer, that would have been absolutely fine. But we take answer invalidation quite seriously, so we can't have you changing the code after there have been remarks about it in existing answers." } ]
[ { "body": "<p>Instead of <code>do ... while</code> loop you can use <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.threading.spinwait.spinuntil?view=netframework-4.7.2#System_Threading_SpinWait_SpinUntil_System_Func_System_Boolean__System_TimeSpan_\" rel=\"nofollow noreferrer\"><code>SpinWait.SpinUntil</code></a>:</p>\n\n<pre><code>bool dataHaveBeenFetched = SpinWait.SpinUntil(() =&gt; TrytoFetchData((CServer)sender))\n</code></pre>\n\n<p>And as <a href=\"https://codereview.stackexchange.com/users/59161/t3chb0t\">@t3chb0t</a> noted it seems strange to sleep 1 second between <code>TrytoFetchData</code> calls.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T18:57:54.747", "Id": "212235", "ParentId": "212218", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T15:47:09.233", "Id": "212218", "Score": "0", "Tags": [ "c#" ], "Title": "Synchronising data in C#" }
212218
<p>I found a trick to significantly reduce the time needed to compute Huffman codes in <a href="https://codereview.stackexchange.com/questions/211912/improved-rfc-1951-deflate-compression">my implementation of RFC1951</a>. I was slightly surprised to find it slightly improves compression as well, something I had not anticipated.</p> <p>The trick is to encode the required information about a tree node in a ulong, arranged so that the ulong values can be compared directly, rather than by calling a delegate function which accessed related arrays to get the frequency and depth. This has a substantial effect on the performance.</p> <p>The symbol or tree node id goes in the bottom 16 bits, the tree depth in the next 8 bits, and the frequency ( how many times the tree node is used ) in the remaining 40 bits. The revised code is below.</p> <p>I think the reason compression is improved is that the compare now includes the symbol id, this tends to assign the same number of bits to adjacent symbols if they have the same frequency, and that in turn tends to reduce the number of bits needed to encode the lengths.</p> <p>Here's the revised code:</p> <pre><code>struct HuffmanCoding // Variable length coding. { public ushort Count; // Number of used symbols. public byte [] Bits; // Number of bits used to encode a symbol. public ushort [] Codes; // Huffman code for a symbol ( bit 0 is most significant ). public int [] Used; // Count of how many times a symbol is used in the block being encoded. private int Limit; // Maximum number of bits for a code. private ushort [] Tree; public HuffmanCoding( int limit, ushort symbols ) { Limit = limit; Count = symbols; Bits = new byte[ symbols ]; Codes = new ushort[ symbols ]; Used = new int[ symbols * 2 ]; // Second half of array is for tree nodes. Tree = new ushort[ symbols * 2] ; // First half is one branch, second half is other branch. } public int Total() { int result = 0, count = Count; for ( int i = 0; i &lt; count; i += 1 ) result += Used[i] * Bits[i]; return result; } public bool ComputeCodes() // returns true if Limit is exceeded. { ushort count = Count; UlongHeap heap = new UlongHeap( count ); for ( ushort i = 0; i &lt; Count; i += 1 ) { int used = Used[ i ]; if ( used &gt; 0 ) { // The values are encoded as 16 bits for the symbol, 8 bits for the depth, then 32 bits for the frequency. heap.Insert( ( (ulong)used &lt;&lt; 24 ) + i ); } } int maxBits = 0; if ( heap.Count == 1 ) { GetBits( (ushort) heap.Remove(), 1 ); maxBits = 1; } else if ( heap.Count &gt; 1 ) { ulong treeNode = Count; do // Keep pairing the lowest frequency TreeNodes. { ulong left = heap.Remove(); Tree[ treeNode - Count ] = (ushort) left; ulong right = heap.Remove(); Tree[ treeNode ] = (ushort) right; // Extract depth of left and right nodes ( depth is encoded as bits 16..23 ). uint dleft = (uint)left &amp; 0xff0000u, dright = (uint)right &amp; 0xff0000u; uint depth = ( dleft &gt; dright ? dleft : dright ) + 0x10000u; heap.Insert( ( ( left + right ) &amp; 0xffffffffff000000 ) | depth | treeNode ); treeNode += 1; } while ( heap.Count &gt; 1 ); uint root = ( (uint) heap.Remove() ) &amp; 0xffffff; maxBits = (int)( root &gt;&gt; 16 ); if ( maxBits &gt; Limit ) return true; GetBits( (ushort)root, 0 ); // Walk the tree to find the code lengths (Bits). } // Compute codes, code below is from RFC 1951 page 7. int [] bl_count = new int[ maxBits + 1 ]; for ( int i = 0; i &lt; count; i += 1 ) bl_count[ Bits[ i ] ] += 1; int [] next_code = new int[ maxBits + 1 ]; int code = 0; bl_count[ 0 ] = 0; for ( int i = 0; i &lt; maxBits; i += 1 ) { code = ( code + bl_count[ i ] ) &lt;&lt; 1; next_code[ i+1 ] = code; } for ( int i = 0; i &lt; count; i += 1 ) { int length = Bits[ i ]; if ( length != 0 ) { Codes[ i ] = (ushort)Reverse( next_code[ length ], length ); next_code[ length ] += 1; } } // Reduce count if there are unused symbols. while ( count &gt; 0 &amp;&amp; Bits[ count - 1 ] == 0 ) count -= 1; Count = count; // System.Console.WriteLine( "HuffEncoder.ComputeCodes" ); // for ( int i = 0; i &lt; count; i += 1 ) if ( Bits[ i ] &gt; 0 ) // System.Console.WriteLine( "i=" + i + " len=" + Bits[ i ] + " tc=" + Codes[ i ].ToString("X") + " freq=" + Used[ i ] ); return false; } private void GetBits( ushort treeNode, int length ) { if ( treeNode &lt; Count ) // treeNode is a leaf. { Bits[ treeNode ] = (byte)length; } else { length += 1; GetBits( Tree[ treeNode - Count ], length ); GetBits( Tree[ treeNode ], length ); } } private static int Reverse( int x, int bits ) // Reverse a string of bits ( ready to be output as Huffman code ). { int result = 0; for ( int i = 0; i &lt; bits; i += 1 ) { result &lt;&lt;= 1; result |= x &amp; 1; x &gt;&gt;= 1; } return result; } } // end struct HuffmanCoding // ****************************************************************************** struct UlongHeap // An array organised so the smallest element can be efficiently removed. { public int Count { get{ return _Count; } } private int _Count; private ulong [] Array; public UlongHeap ( int capacity ) { _Count = 0; Array = new ulong[ capacity ]; } public void Insert( ulong e ) { int j = _Count++; while ( j &gt; 0 ) { int p = ( j - 1 ) &gt;&gt; 1; // Index of parent. ulong pe = Array[ p ]; if ( e &gt;= pe ) break; Array[ j ] = pe; // Demote parent. j = p; } Array[ j ] = e; } public ulong Remove() // Returns the smallest element. { ulong result = Array[ 0 ]; _Count -= 1; ulong e = Array[ _Count ]; int j = 0; while ( true ) { int c = ( j + j ) + 1; if ( c &gt;= _Count ) break; ulong ce = Array[ c ]; if ( c + 1 &lt; _Count ) { ulong ce2 = Array[ c + 1 ]; if ( ce2 &lt; ce ) { c += 1; ce = ce2; } } if ( ce &gt;= e ) break; Array[ j ] = ce; j = c; } Array[ j ] = e; return result; } } // end struct Heap </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T19:50:50.820", "Id": "410436", "Score": "1", "body": "Nice trick, but there are also completely treeless approaches such as Engel coding" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T20:19:31.393", "Id": "410442", "Score": "0", "body": "Thanks. I just started looking at engel coding. Up to now, I have relied on reducing the block size if the code length limit is exceeded, but I could do with a better approach." } ]
[ { "body": "<p>I see it's not the first post from you for the last week. Here some comments for all of your pieces of code.</p>\n\n<ol>\n<li><p>Strange assignments:</p>\n\n<blockquote>\n<pre><code>public ushort Count;\n</code></pre>\n \n <p>...</p>\n\n<pre><code>public bool ComputeCodes() // returns true if Limit is exceeded.\n{\n ushort count = Count;\n</code></pre>\n</blockquote>\n\n<p>What purpose of the last line? <code>Count</code> already <code>ushort</code> and it's a field, not a property (which is a case where this assignment can has sense).</p></li>\n<li><p>A lot of spaces:</p>\n\n<blockquote>\n<pre><code>UlongHeap heap = new UlongHeap( count );\n\nfor ( ushort i = 0; i &lt; Count; i += 1 )\n</code></pre>\n</blockquote>\n\n<p>Don't use spaces after <code>(</code> and <code>[</code>, and before <code>)</code> and <code>]</code>. They add noise to the code.</p></li>\n<li><p>Don't use PascalCasing for private fields names. Many programmers use <code>_</code> prefix to indicate private field.</p></li>\n<li><p>Use <code>var</code> where it's appropriate. For example, here</p>\n\n<blockquote>\n<pre><code>UlongHeap heap = new UlongHeap( count );\n</code></pre>\n</blockquote>\n\n<p>it's obvious that <code>heap</code> will be of type <code>UlongHeap</code>. So this</p>\n\n<pre><code>var heap = new UlongHeap( count );\n</code></pre>\n\n<p>is more clear without redundant type specification.</p></li>\n<li><p>Increments can be written as <code>++</code> instead of <code>+= 1</code>.</p></li>\n<li><p>It's better to use properties instead of public fields. Also properties like this</p>\n\n<blockquote>\n<pre><code>public int Count { get{ return _Count; } }\n</code></pre>\n</blockquote>\n\n<p>can be rewritten as</p>\n\n<pre><code>public int Count =&gt; _Count;\n</code></pre></li>\n<li><p>Use full names for variables and method parameters. So instead of <code>dleft</code>, <code>dright</code> and so on use <code>depthLeft</code>, <code>depthRight</code>.</p></li>\n<li><p>Use consistent naming. You have variables <code>treeNode</code>, <code>maxBits</code>, <code>bl_count</code>, <code>next_code</code>. Use camelCasing (like <code>maxBits</code>) without underscores.</p></li>\n<li><p>Magic numbers should be defined as constants. What is <code>0xff0000u</code> or <code>0xffffffffff000000</code>?</p></li>\n<li><p>Place bodies of <code>if</code> statements on next line, like so</p>\n\n<pre><code>if (maxBits &gt; Limit)\n return true;\n</code></pre></li>\n<li><p>Check arguments of public methods. For example, here</p>\n\n<blockquote>\n<pre><code>public HuffmanCoding( int limit, ushort symbols )\n</code></pre>\n</blockquote>\n\n<p>what will happen if user pass negative number to <code>limit</code>? You can check value and throw <code>ArgumentOutOfRangeException</code> with a message describing error if a value is invalid.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T18:44:39.373", "Id": "212234", "ParentId": "212223", "Score": "4" } }, { "body": "<p>Here's a revised version. I have added <a href=\"https://en.wikipedia.org/wiki/Package-merge_algorithm\" rel=\"nofollow noreferrer\">Package Merge</a> code to handle the situation where the bit limit is exceeded ( rather than returning failure ). I have implemented many of Maxim's suggestions but not all. </p>\n\n<p>On spacing I don't agree yet, but I will think about it. I use a leading <code>_</code> for private fields only when there is a property clash. I prefer to stick to the earliest versions of C# unless there is a strong reason not to, so I don't use var or the => notation for properties. </p>\n\n<p>This is an internal struct, so although it could check arguments, I think it's not essential, this is also why there are public fields. The weird names such as <code>bl_count</code> are from <a href=\"https://www.ietf.org/rfc/rfc1951.txt\" rel=\"nofollow noreferrer\">RFC 1951</a>, I considered changing them, but I feel it makes it easier to compare my code with the standard.</p>\n\n<pre><code>struct HuffmanCoding // Variable length coding.\n{\n public ushort Count; // Number of used symbols.\n public byte [] Bits; // Number of bits used to encode a symbol ( code length ).\n public ushort [] Codes; // Huffman code for a symbol ( bit 0 is most significant ).\n public int [] Used; // Count of how many times a symbol is used in the block being encoded.\n\n private int Limit; // Limit on code length ( 15 or 7 for RFC 1951 ).\n private ushort [] Left, Right; // Tree storage.\n\n public HuffmanCoding( int limit, ushort symbols )\n {\n Limit = limit;\n Count = symbols;\n Bits = new byte[ symbols ];\n Codes = new ushort[ symbols ];\n Used = new int[ symbols ];\n Left = new ushort[ symbols ];\n Right = new ushort[ symbols ];\n }\n\n public int Total()\n {\n int result = 0;\n for ( int i = 0; i &lt; Count; i += 1 ) \n result += Used[i] * Bits[i];\n return result;\n }\n\n public void ComputeCodes()\n {\n // Tree nodes are encoded in a ulong using 16 bits for the id, 8 bits for the tree depth, 32 bits for Used.\n const int IdBits = 16, DepthBits = 8, UsedBits = 32;\n const uint IdMask = ( 1u &lt;&lt; IdBits ) - 1;\n const uint DepthOne = 1u &lt;&lt; IdBits;\n const uint DepthMask = ( ( 1u &lt;&lt; DepthBits ) - 1 ) &lt;&lt; IdBits;\n const ulong UsedMask = ( ( 1ul &lt;&lt; UsedBits ) - 1 ) &lt;&lt; ( IdBits + DepthBits );\n\n // First compute the number of bits to encode each symbol (Bits).\n UlongHeap heap = new UlongHeap( Count );\n\n for ( ushort i = 0; i &lt; Count; i += 1 )\n {\n int used = Used[ i ];\n if ( used &gt; 0 )\n heap.Insert( ( (ulong)used &lt;&lt; ( IdBits + DepthBits ) ) | i );\n }\n\n int maxBits = 0;\n\n if ( heap.Count == 1 )\n { \n GetBits( unchecked( (ushort) heap.Remove() ), 1 );\n maxBits = 1;\n }\n else if ( heap.Count &gt; 1 ) unchecked\n {\n ulong treeNode = Count;\n\n do // Keep pairing the lowest frequency TreeNodes.\n {\n ulong left = heap.Remove(); \n Left[ treeNode - Count ] = (ushort) left;\n\n ulong right = heap.Remove(); \n Right[ treeNode - Count ] = (ushort) right;\n\n // Extract depth of left and right nodes ( still shifted though ).\n uint depthLeft = (uint)left &amp; DepthMask, depthRight = (uint)right &amp; DepthMask; \n\n // New node depth is 1 + larger of depthLeft and depthRight.\n uint depth = ( depthLeft &gt; depthRight ? depthLeft : depthRight ) + DepthOne;\n\n heap.Insert( ( ( left + right ) &amp; UsedMask ) | depth | treeNode );\n\n treeNode += 1;\n } while ( heap.Count &gt; 1 );\n\n uint root = ( (uint) heap.Remove() ) &amp; ( DepthMask | IdMask );\n maxBits = (int)( root &gt;&gt; IdBits );\n if ( maxBits &lt;= Limit )\n GetBits( (ushort)root, 0 );\n else\n {\n maxBits = Limit;\n PackageMerge();\n }\n }\n\n // Computation of code lengths (Bits) is complete.\n // Now compute Codes, code below is from RFC 1951 page 7.\n\n int [] bl_count = new int[ maxBits + 1 ];\n for ( int i = 0; i &lt; Count; i += 1 ) \n bl_count[ Bits[ i ] ] += 1; \n\n int [] next_code = new int[ maxBits + 1 ];\n int code = 0; bl_count[ 0 ] = 0;\n for ( int i = 0; i &lt; maxBits; i += 1 ) \n {\n code = ( code + bl_count[ i ] ) &lt;&lt; 1;\n next_code[ i + 1 ] = code;\n }\n\n for ( int i = 0; i &lt; Count; i += 1 ) \n {\n int length = Bits[ i ];\n if ( length != 0 ) \n {\n Codes[ i ] = (ushort) Reverse( next_code[ length ], length );\n next_code[ length ] += 1;\n }\n }\n\n // Reduce Count if there are unused symbols.\n while ( Count &gt; 0 &amp;&amp; Bits[ Count - 1 ] == 0 ) Count -= 1;\n\n // System.Console.WriteLine( \"HuffmanCoding.ComputeCodes\" );\n // for ( int i = 0; i &lt; Count; i += 1 ) if ( Bits[ i ] &gt; 0 )\n // System.Console.WriteLine( \"symbol=\" + i + \" len=\" + Bits[ i ] + \" code=\" + Codes[ i ].ToString(\"X\") + \" used=\" + Used[ i ] );\n\n }\n\n private void GetBits( ushort treeNode, int length )\n {\n if ( treeNode &lt; Count ) // treeNode is a leaf.\n {\n Bits[ treeNode ] = (byte)length;\n }\n else \n {\n treeNode -= Count;\n length += 1;\n GetBits( Left[ treeNode ], length );\n GetBits( Right[ treeNode ], length );\n }\n }\n\n private static int Reverse( int x, int bits )\n // Reverse a string of bits ( ready to be output as Huffman code ).\n { \n int result = 0; \n for ( int i = 0; i &lt; bits; i += 1 ) \n {\n result &lt;&lt;= 1; \n result |= x &amp; 1; \n x &gt;&gt;= 1; \n } \n return result; \n } \n\n // PackageMerge is used if the Limit code length limit is reached.\n // The result is technically not a Huffman code in this case ( due to the imposed limit ).\n // See https://en.wikipedia.org/wiki/Package-merge_algorithm for a description of the algorithm.\n\n private void PackageMerge()\n {\n // Tree nodes are encoded in a ulong using 16 bits for the id, 32 bits for Used.\n const int IdBits = 16, UsedBits = 32;\n const ulong UsedMask = ( ( 1ul &lt;&lt; UsedBits ) - 1 ) &lt;&lt; IdBits;\n\n Left = new ushort[ Count * Limit ];\n Right = new ushort[ Count * Limit ];\n\n // Fisrt sort using Heapsort.\n UlongHeap heap = new UlongHeap( Count );\n for ( uint i = 0; i &lt; Count; i += 1 ) \n {\n if ( Used[ i ] != 0 ) \n {\n heap.Insert( (ulong)Used[ i ] &lt;&lt; IdBits | i );\n }\n }\n int n = heap.Count; \n ulong [] sorted = new ulong[ n ];\n for ( int i = 0; i &lt; n; i += 1 ) sorted[ i ] = heap.Remove();\n\n // List class is from System.Collections.Generic.\n List&lt;ulong&gt; merged = new List&lt;ulong&gt;( Count ), \n next = new List&lt;ulong&gt;( Count );\n\n uint package = (uint) Count; // Allocator for package ids.\n\n for ( int i = 0; i &lt; Limit; i += 1 ) \n {\n int j = 0, k = 0; // Indexes into the lists being merged.\n next.Clear();\n for ( int total = ( sorted.Length + merged.Count ) / 2; total &gt; 0; total -= 1 ) \n {\n ulong left, right; // The tree nodes to be packaged.\n\n if ( k &lt; merged.Count )\n {\n left = merged[ k ];\n if ( j &lt; sorted.Length )\n {\n ulong sj = sorted[ j ];\n if ( left &lt; sj ) k += 1;\n else { left = sj; j += 1; }\n }\n else k += 1;\n }\n else left = sorted[ j++ ];\n\n if ( k &lt; merged.Count )\n {\n right = merged[ k ];\n if ( j &lt; sorted.Length )\n {\n ulong sj = sorted[ j ];\n if ( right &lt; sj ) k += 1;\n else { right = sj; j += 1; }\n }\n else k += 1;\n }\n else right = sorted[ j++ ];\n\n Left[ package ] = unchecked( (ushort) left );\n Right[ package ] = unchecked( (ushort) right );\n next.Add( ( left + right ) &amp; UsedMask | package ); \n package += 1;\n }\n\n // Swap merged and next.\n List&lt;ulong&gt; tmp = merged; merged = next; next = tmp;\n }\n\n for ( int i = 0; i &lt; merged.Count; i += 1 )\n MergeGetBits( unchecked( (ushort) merged[i] ) );\n }\n\n private void MergeGetBits( ushort node )\n {\n if ( node &lt; Count )\n Bits[ node ] += 1;\n else\n {\n MergeGetBits( Left[ node ] );\n MergeGetBits( Right[ node ] );\n }\n }\n\n} // end struct HuffmanCoding\n\n\n// ******************************************************************************\n\n\nstruct UlongHeap // An array organised so the smallest element can be efficiently removed.\n{\n public int Count { get{ return _Count; } }\n private int _Count;\n private ulong [] Array;\n\n public UlongHeap ( int capacity )\n {\n _Count = 0;\n Array = new ulong[ capacity ];\n }\n\n public void Insert( ulong e )\n {\n int j = _Count++;\n while ( j &gt; 0 )\n {\n int p = ( j - 1 ) &gt;&gt; 1; // Index of parent.\n ulong pe = Array[ p ];\n if ( e &gt;= pe ) break;\n Array[ j ] = pe; // Demote parent.\n j = p;\n } \n Array[ j ] = e;\n }\n\n public ulong Remove() // Returns the smallest element.\n {\n ulong result = Array[ 0 ];\n _Count -= 1;\n ulong e = Array[ _Count ];\n int j = 0;\n while ( true )\n {\n int c = ( j + j ) + 1; if ( c &gt;= _Count ) break;\n ulong ce = Array[ c ];\n if ( c + 1 &lt; _Count )\n {\n ulong ce2 = Array[ c + 1 ];\n if ( ce2 &lt; ce ) { c += 1; ce = ce2; }\n } \n if ( ce &gt;= e ) break;\n Array[ j ] = ce; j = c; \n }\n Array[ j ] = e;\n return result;\n }\n\n} // end struct UlongHeap\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T14:06:52.363", "Id": "212266", "ParentId": "212223", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T16:14:08.910", "Id": "212223", "Score": "1", "Tags": [ "c#", "compression" ], "Title": "Optimised code to compute Huffman codes when implementing RFC 1951" }
212223
<p>Here's my solution for the Leet Code's Two Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting.</p> <p>Problem: </p> <blockquote> <p>Given an array of integers, return indices of the two numbers such that they add up to a specific target.</p> <p>You may assume that each input would have exactly one solution, and you may not use the same element twice.</p> <p>Example:</p> <p>Given nums = [2, 7, 11, 15], target = 9,</p> <p>Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].</p> </blockquote> <p>My solution: </p> <pre><code>def twoSum(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ num_lst = list(range(len(nums))) for indx, num in enumerate(num_lst): for num_other in num_lst[indx+1:]: if nums[num] + nums[num_other] == target: return [num, num_other] else: continue return None </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T14:00:50.870", "Id": "410498", "Score": "2", "body": "Would any of the lists contain negative numbers?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T18:06:39.470", "Id": "410643", "Score": "0", "body": "@MSeifert I don't know, but feel free to assume yes" } ]
[ { "body": "<pre><code>num_lst = list(range(len(nums)))\n\nfor indx, num in enumerate(num_lst):\n</code></pre>\n\n<p>I'm not sure if I'm missing something, but I think not. I ran this code</p>\n\n<pre><code>nums = [2,5,7,9]\nnum_lst = list(range(len(nums)))\nlist(enumerate(num_lst))\n\noutput : [(0, 0), (1, 1), (2, 2), (3, 3)]\n</code></pre>\n\n<p>So why do you create the list and then enumerate it? Maybe what you want to do is simply : <code>enumerate(nums)</code> then <code>enumerate(nums[index+1:])</code> on your other loop? A simpler way would be to only use the ranges, as I'll show below.</p>\n\n<p>Also, given your input, there's a possibility that a single number would be higher than the target, in this case you shouldn't make the second iteration.</p>\n\n<p>You also don't need the <code>else: continue</code> , as it's going to <code>continue</code> either way.</p>\n\n<p>I'd end up with : </p>\n\n<pre><code>def twoSum(nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n\n for i1 in range(len(nums)):\n if nums[i1] &gt; target:\n continue\n\n for i2 in range(i1 + 1, len(nums)):\n if nums[i1] + nums[i2] == target:\n return [i1, i2]\n\n return None\n</code></pre>\n\n<p>Without knowing the expected input size, it's hard to focus on performance improvements. The main goal of my review was to remove what seemed like a misunderstanding in your code and in my opinion the code is clearer now.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T15:12:51.760", "Id": "410505", "Score": "1", "body": "Your code is still `O(n**2)`, so I wouldn't say it offers any significant performance boost." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T15:16:52.357", "Id": "410506", "Score": "0", "body": "Also, your code has a few bugs. It doesn't work with negative numbers, it doesn't even work with `0` reliably (`twoSum([2,0], 2)`) and it uses the same number twice (`twoSum([1, 1], 2)`). :-/" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:46:20.843", "Id": "410513", "Score": "0", "body": "@EricDuminil The latter is fine; number != element." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:53:52.470", "Id": "410514", "Score": "1", "body": "@wizzwizz4: Thanks for the comment. You're right. I meant to write `twoSum([1], 2)`, which should return `None`, not `[0, 0]`. The bug is here, my description was incorrect." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T19:23:12.567", "Id": "411014", "Score": "0", "body": "@EricDuminil I mainly wanted to focus on some of the bloat to simplify it, went fast and introduced bugs, lol. And without the expected size of input it's hard to tell if there's a real performance value to my answer (and to any other one at that, if we always expect 4 numbers, performance isn't really an issue). I also wrongfully assumed that we dealt with positive non-zero integers." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T18:20:25.360", "Id": "212230", "ParentId": "212228", "Score": "5" } }, { "body": "<h1>Code Style</h1>\n\n<ul>\n<li><p>Your code contains a few lines that accomplish nothing and obfuscate your intent:</p>\n\n<pre><code> else: \n continue\n</code></pre>\n\n<p>If the conditional is false, you'll automatically <code>continue</code> on to the next iteration without having to tell the program to do that.</p>\n\n<pre><code> return None\n</code></pre>\n\n<p>All Python functions implicitly <code>return None</code>. While <a href=\"https://www.python.org/dev/peps/pep-0008/#programming-recommendations\" rel=\"nofollow noreferrer\">PEP 8</a> appears to endorse this practice (\"explicit is better than implicit\"), it seems noisy to me.</p></li>\n<li><p><code>num_lst = list(range(len(nums)))</code> effectively generates a list of all the indices in the <code>nums</code> input list. Then, you immediately <code>enumerate</code> this list, which produces pairs of identical indices <code>indx, num</code>. If all you're attempting to do is iterate, this is significant obfuscation; simply call <code>enumerate</code> directly on <code>nums</code> to produce index-element tuples:</p>\n\n<pre><code>def twoSum(self, nums, target):\n for i, num in enumerate(nums):\n for j in range(i + 1, len(nums)):\n if num + nums[j] == target:\n return [i, j]\n</code></pre>\n\n<p>This makes the intent much clearer: there are no duplicate variables with different names representing the same thing. It also saves unnecessary space and overhead associated with creating a list from a range.</p></li>\n<li>Following on the previous item, <code>indx, num</code> and <code>num_lst</code> are confusing variable names, especially when they're all actually indices (which are technically numbers).</li>\n</ul>\n\n<hr>\n\n<h1>Efficiency</h1>\n\n<ul>\n<li><p>This code is inefficient, running in <a href=\"https://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions\" rel=\"nofollow noreferrer\">quadratic time</a>, or <span class=\"math-container\">\\$\\mathcal{O}(n^2)\\$</span>. Leetcode is generous to let this pass (but won't be so forgiving in the future!). The reason for this is the nested loop; for every element in your list, you iterate over every other element to draw comparisons. A linear solution should finish in ~65 ms, while this takes ~4400 ms. </p>\n\n<p>Here is an efficient solution that runs in <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span> time:</p>\n\n<pre><code>hist = {}\n\nfor i, n in enumerate(nums):\n if target - n in hist:\n return [hist[target-n], i]\n hist[n] = i\n</code></pre>\n\n<p>How does this work? The magic of <a href=\"https://en.wikipedia.org/wiki/Hash_function\" rel=\"nofollow noreferrer\">hashing</a>. The dictionary <code>hist</code> offers constant <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> lookup time. Whenever we visit a new element in <code>nums</code>, we check to see if its sum complement is in the dictionary; else, we store it in the dictionary as a <code>num =&gt; index</code> pair.</p>\n\n<p>This is the classic time-space tradeoff: the quadratic solution is slow but space efficient, while this solution takes more space but gains a huge boost in speed. In almost every case, choose speed over space.</p>\n\n<p>For completeness, even if you were in a space-constrained environment, there is a fast solution that uses <span class=\"math-container\">\\$\\mathcal{O}(1)\\$</span> space and <span class=\"math-container\">\\$\\mathcal{O}(n\\log{}n)\\$</span> time. This solution is worth knowing about for the practicality of the technique and the fact that it's a common interview follow-up. The way it works is:</p>\n\n<ol>\n<li>Sort <code>nums</code>.</li>\n<li>Create two pointers representing an index at 0 and an index at <code>len(nums) - 1</code>.</li>\n<li>Sum the elements at the pointers. \n\n<ul>\n<li>If they produce the desired sum, return the pointer indices. </li>\n<li>Otherwise, if the sum is less than the target, increment the left pointer</li>\n<li>Otherwise, decrement the right pointer.</li>\n</ul></li>\n<li>Go back to step 3 unless the pointers are pointing to the same element, in which case return failure.</li>\n</ol></li>\n<li><p>Be wary of list slicing; it's often a hidden linear performance hit. Removing this slice as the nested loop code above illustrates doesn't improve the quadratic time complexity, but it does reduce overhead.</p></li>\n</ul>\n\n<p>Now you're ready to try <a href=\"https://leetcode.com/problems/3sum/\" rel=\"nofollow noreferrer\">3 Sum</a>!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T01:48:42.057", "Id": "410453", "Score": "2", "body": "As for returning `None`, see [the relevant section of PEP 8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T01:58:35.960", "Id": "410455", "Score": "0", "body": "That's true, Python does say \"explicit is better than implicit\". I can amend my recommendation to be \"at least be aware that Python statements implicitly `return None`\". Maybe Python should also put `else: continue` at the end of every loop, just to be explicit :-)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:44:13.650", "Id": "410512", "Score": "0", "body": "Python should, but _doesn't_ know not to copy the entire thing. It has no such optimisation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:20:29.047", "Id": "410518", "Score": "0", "body": "@wizzwizz4 No lazy copying? E.g. return a pointer in O(1) to the slice element and then wait for mutation to perform a copy? I'd like to update if incorrect here." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:54:08.817", "Id": "410522", "Score": "0", "body": "@ggorlen Apparently not. [Try it online!](https://tio.run/##dYw5CoAwEAB7XxFSbUAkkkIQ8hKxiBB0YXOQrIWvj4K2VtPMTL74SNG0hiGnwoIxeOSOhBWElaG4uHsYtdZKdblgZHiV4QVIWuZV9mKntDmq9iOoP98tZn3u09NUz2e20tn/R2s3 \"Python 3 – Try It Online\") Rule of thumb: Python performs **no optimisations at all**." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T18:41:10.400", "Id": "212232", "ParentId": "212228", "Score": "16" } }, { "body": "<p>You can use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations\" rel=\"nofollow noreferrer\">itertools.combinations</a> for a more readable (and likely faster) <code>for</code> loop. As long as returning a <code>list</code> isn't a requirement, I would consider it better style to return a <code>tuple</code> instead. (Especially since it allows you to convey the list length.) Also, as long as the current name isn't a requirement, <a href=\"https://www.python.org/dev/peps/pep-0008/#function-and-variable-names\" rel=\"nofollow noreferrer\">it is preferable to use <code>snake_case</code> for function and variable names</a>.</p>\n\n<pre><code>from itertools import combinations\n\n\ndef twoSum(nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[int]\n \"\"\"\n\n for (i, first), (j, second) in combinations(enumerate(nums), 2):\n if first + second == target:\n return [i, j]\n\n return None\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T09:31:00.313", "Id": "410485", "Score": "1", "body": "You don't need to create `num_list` anymore. Also, `combinations` requires (at least in Python 3.6) a second argument `r` which specifies the length of the combinations. Here, `r` should be 2." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T01:59:17.547", "Id": "212248", "ParentId": "212228", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:32:47.003", "Id": "212228", "Score": "14", "Tags": [ "python", "python-3.x", "k-sum" ], "Title": "Leetcode Two Sum code in Python" }
212228
<p>I'm trying to determine if an instance of an object exists within a collection.</p> <p>I'm using array_walk_recursive to walk and check the leaves of an array.</p> <p>I've added a small short circuit, but still all leaves will be iterated over.</p> <p>I could alternatively use something like an exception which is thrown on the first find, to break out early, but that feels kind of wrong.</p> <p>Am I missing a simple alternative?</p> <pre><code>&lt;?php class Fish {} class Mammal {} class Whale extends Mammal {} class Human extends Mammal {} class Shark extends Fish {} function anyFish(array $collection) { $found = false; array_walk_recursive($collection, function ($v) use (&amp;$found) { if(!$found &amp;&amp; $v instanceof Fish) $found = true; }); return $found; } $seas = [ 'pacific' =&gt; [new Whale, new Shark], 'atlantic' =&gt; [new Human, new Shark] ]; $pub = [new Human, new Human]; var_dump(anyFish($seas)); var_dump(anyFish($pub)); </code></pre> <p>Output:</p> <pre><code>bool(true) bool(false) </code></pre> <p>Found on Stackoverflow: <a href="https://stackoverflow.com/questions/17853113/break-array-walk-from-anonymous-function">https://stackoverflow.com/questions/17853113/break-array-walk-from-anonymous-function</a>)</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T23:22:05.843", "Id": "410555", "Score": "0", "body": "Just want to make a note for anyone investigating alternatives. http://php.net/manual/en/class.recursivearrayiterator.php#106519" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T23:26:46.243", "Id": "410558", "Score": "0", "body": "Wouldn't you rather have logic like: `!$found &&` so that you are not overwriting `true` with `true`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T18:57:16.723", "Id": "410649", "Score": "0", "body": "@mickmackusa, of course that's exactly what I meant! Logic error on my part there, thanks." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T19:04:46.973", "Id": "410652", "Score": "0", "body": "Here is an example of using an exception to break out of the lambda on the first find of an instance: https://3v4l.org/OvMMm this avoids leafing through everything. But feels dirty." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T20:32:22.923", "Id": "410663", "Score": "0", "body": "Yes, I saw that in my researching. I don't disagree about the dirtiness." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T21:53:35.637", "Id": "410672", "Score": "0", "body": "So long as you post an explanation with your snippet to explain the advantage, I reckon you should post that as an answer. That's the way I'd do it, I just didn't get around to coding it up. ...well something like that (I'd probably try to make just one function which was recursive -- to call itself)" } ]
[ { "body": "<p>Here is an example of using recursion, it stops soon after an instance is found, so doesn't iterate through the entire collection.</p>\n\n<pre><code>&lt;?php\nclass Fish {}\nclass Mammal {}\nclass Whale extends Mammal {}\nclass Human extends Mammal {}\nclass Shark extends Fish {}\n\nfunction anyFish($collection)\n{\n $found = false;\n rFish($collection, $found);\n\n return $found;\n}\nfunction rFish(array $collection, &amp;$found)\n{ \n if($found)\n return;\n foreach($collection as $item)\n {\n if(is_array($item))\n {\n rFish($item, $found);\n }\n elseif($item instanceof Fish)\n {\n $found = true;\n break;\n }\n }\n}\n$seas = [\n 'pacific' =&gt; [new Whale, new Whale, new Shark, new Whale],\n 'atlantic' =&gt; [new Human, new Shark]\n];\n\n$pub = [new Human, new Human];\n\nvar_dump(anyFish($seas));\nvar_dump(anyFish($pub));\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>bool(true)\nbool(false)\n</code></pre>\n\n<p>@mickmackusa distilled the recursive function beautifully.</p>\n\n<p>I'm adding my generalised solution here:</p>\n\n<pre><code>function hasInstance(array $collection, $class)\n{\n foreach($collection as $item)\n if(is_array($item) &amp;&amp; hasInstance($item, $class) || $item instanceof $class)\n return true;\n\n return false;\n}\n</code></pre>\n\n<p>A call would be like:</p>\n\n<pre><code>hasInstance($seas, Fish::class);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T22:00:22.203", "Id": "212348", "ParentId": "212229", "Score": "1" } }, { "body": "<p>I think good coding practices should prioritize efficiency before code brevity. It is important to not ask for unnecessary work to be done (this is part of the artistry of being a clever coder). Implementing an early exit, in my opinion is a non-negotiable factor in selecting the \"best\" code design.</p>\n\n<p>Using a function like <code>array_walk_recursive()</code> is handy for its leafnode traversal, but I agree that the syntax of making an early exit is a little unsightly. For this reason, I recommend a language construct as part of the recursive design. The conditional logic is the only part that can be condensed, so I've tried to boil it down as much as possible.</p>\n\n<p>Code: (<a href=\"https://3v4l.org/ZTMcu\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>function anyFish(array $collection)\n{\n foreach ($collection as $item)\n {\n if((is_array($item) &amp;&amp; anyFish($item)) || $item instanceof Fish)\n {\n return true;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>I don't think it is horrible to look at, but everybody loves their own babies. I'm not sure that I can make it any more readable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T22:41:49.487", "Id": "410677", "Score": "0", "body": "I see what you are saying, but I am hesitant to ditch the curly braces as a matter of personal preference. If you are looking to do some \"code golf\" go ahead, but I am in this camp: https://stackoverflow.com/a/8726411/2943403 ." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T05:00:03.927", "Id": "410693", "Score": "1", "body": "@Progrock this is not Python, PHP is C-like language. And it is not a matter of taste, there is a **standard**: https://www.php-fig.org/psr/psr-2/" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T22:13:44.590", "Id": "212349", "ParentId": "212229", "Score": "3" } } ]
{ "AcceptedAnswerId": "212349", "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T17:39:53.177", "Id": "212229", "Score": "3", "Tags": [ "php", "array" ], "Title": "Efficient method to look for an instance of an object in a collection" }
212229
<p>I know randomness in programming can be a deep topic, and searching the topic seems to result in Fisher-Yates being the best method, but I'm curious what people would say about this method.</p> <p>Basically, since I have the cards as objects, I just add a property of a random number then sort the entire array based on those random numbers.</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 suits = [ { digit: 'H', word: 'hearts' }, { digit: 'C', word: 'clubs' }, { digit: 'D', word: 'diamonds' }, { digit: 'S', word: 'spades' } ] const cardsWithoutSuits = [ { numeric: 1, word: 'ace', digit: 'A' }, { numeric: 2, word: 'two', }, { numeric: 3, word: 'three', }, { numeric: 4, word: 'four', }, { numeric: 5, word: 'five', }, { numeric: 6, word: 'six', }, { numeric: 7, word: 'seven', }, { numeric: 8, word: 'eight', }, { numeric: 9, word: 'nine', }, { numeric: 10, word: 'ten', }, { numeric: 11, word: 'jack', digit: 'J' }, { numeric: 12, word: 'queen', digit: 'Q' }, { numeric: 13, word: 'king', digit: 'K' } ] function createDeck(decks = 1){ let deck = []; for (let i = 0; i &lt; decks; i++) { suits.forEach( x =&gt; { cardsWithoutSuits.forEach( y =&gt; { deck.push({ numeric: y.numeric, word: y.word, suit: x.word, phrase: `${y.word} of ${x.word}`, abbr: `${y.hasOwnProperty('digit') ? y.digit : y.numeric}${x.digit}` }) }) }) } return deck; } function shuffle(array){ array.forEach( x =&gt;{ x.ran = Math.random(); }) array.sort( (a, b) =&gt;{ return a.ran - b.ran; }) return array; } let deck = shuffle(createDeck(2)); console.log(deck);</code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T21:38:31.810", "Id": "410449", "Score": "0", "body": "Here is a version in codepen: https://codepen.io/LouBagel/pen/WPrzjy" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T08:19:44.923", "Id": "410479", "Score": "2", "body": "The time complexity of this algorithm is `O(n*lg(n))` while Fisher-Yates and friends are linear in n. And a big problem with pseudo-random number generators as shufflers is that they have far fewer possible permutations than a deck of cards. 52 factorial is about 8e67; compare to [Chrome's Math.random()](https://v8.dev/blog/math-random) with 128 bits of internal state - about 3e38 possible states. For a given real-world deck ordering, the odds are only about 1 in a nonillion that your algorithm can produce it in a better-than-average JavaScript engine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:15:05.560", "Id": "410914", "Score": "1", "body": "@OhMyGoodness The size of the random does not limit the permutations, rather it limits the length of a sequence without a predictable repeating pattern.; Games of chance play with as little as 1 bit (coin) yet will still require a sufficiently large PRNG to ensure the game can not be exploited. With dedication, an unaided human will be hard pushed to identify pattern from a 16bit PRNG" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:37:02.853", "Id": "410918", "Score": "0", "body": "@Blindman67 2^128 seeds cannot yield more than 2^128 distinct initial sequences of 52 numbers from a deterministic algorithm. 2^128 <<< 52!, the end. Unless you're saying we don't need to use the *first* 52 numbers? Which is true, but you have to choose which 52 to use, somehow, and it has to be unpredictable, and if you can choose 52 things unpredictably, just make those things be \"cards\" instead of \"PRNG cycles\" and then you don't need the PRNG at all." } ]
[ { "body": "<p>There has already been some discussion by <a href=\"https://codereview.stackexchange.com/users/131732/oh-my-goodness\">@Oh My Goodness</a> and <a href=\"https://codereview.stackexchange.com/users/120556/blindman67\">@Blindman67</a> in the comments about the time complexity of this code vs Fisher-Yates. I don't really have much to add to that discussion but will offer some suggestions about the code on a deeper level below.</p>\n\n<p>Like I mentioned in <a href=\"https://codereview.stackexchange.com/a/194958/120114\">my answer to your post <em>Simple math game in JavaScript</em></a> some variable names could more accurately hint at the semantic meaning of the value - for example, instead of <code>x.ran = Math.random();</code>, a name like <code>sortVal</code> would hint that the value is to be used for sorting.</p>\n\n<pre><code>array.forEach( x =&gt;{\n x.sortVal = Math.random();\n})\n</code></pre>\n\n<hr>\n\n<p>The arrow function in the <code>shuffle()</code> method is quite short and thus can be simplified to a single line:</p>\n\n<pre><code>array.sort( (a, b) =&gt; a.sortVal - b.sortVal)\n</code></pre>\n\n<p>The <code>forEach</code> block above it could also be simplified:</p>\n\n<pre><code>array.forEach( x =&gt; x.sortVal = Math.random())\n</code></pre>\n\n<p>In this case, <code>x.sortVal</code> would be returned in each iteration but that doesn't make a difference.</p>\n\n<hr>\n\n<p>The Array sort method <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort\" rel=\"nofollow noreferrer\"><code>Array.prototype.sort()</code></a> returns the array so the <code>shuffle()</code> function could be simplified to have the <code>return</code> statement on the same line as the call to that method:</p>\n\n<pre><code> return array.sort( (a, b) =&gt; a.sortVal - b.sortVal)\n</code></pre>\n\n<hr>\n\n<p>Additionally, any value that doesn't get re-assigned could be declared using <code>const</code>, which would help avoid any unintentional re-assignment - e.g. <code>deck</code> within <code>shuffle()</code>, and <code>deck</code> at the end of the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-05T17:50:05.743", "Id": "212927", "ParentId": "212238", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T21:11:11.637", "Id": "212238", "Score": "2", "Tags": [ "javascript", "sorting", "ecmascript-6", "playing-cards", "shuffle" ], "Title": "Shuffle deck of cards in JavaScript" }
212238
<p>We have a little tournament in our company between coworkers and I decided to write an application for managing games, results and rankings of players and teams.</p> <p><strong>The base logic for application is quite simple:</strong></p> <ul> <li>We have players</li> <li>We have teams, which are formed from players</li> <li>We have game/s</li> <li>There are matches in a game, which could be between two teams, or two players.</li> <li>Each match have a result that specifies the winner and the loser</li> <li>The result contains rounds won, rounds lost, points (or score) taken and points lost for that single participant (team or player) in the given match and game.</li> <li>since we have several games, each game needs its own set of rules for the app to decide who wins and who loses, and of course, how to calculate the points taken and lost for that participant.</li> </ul> <p></p> <pre><code> [Fact] public void HaveA_Winner() { Player playerA = new Player(Guid.NewGuid()) { Name = "A" }; Player playerB = new Player(Guid.NewGuid()) { Name = "B" }; Game game = new Game(Guid.NewGuid(), "Mortal Kombat"); DateTime tomorrow = DateTime.Now.AddDays(1); PlayerMatch theMatch = new PlayerMatch(Guid.NewGuid(), game.Id, playerA, playerB, game, tomorrow); var mockA = new Mock&lt;IGameResultRepository&gt;(); mockA.Setup(x =&gt; x.GameScores(playerA.Id, game.Id)).Returns(ResultScoreMockPlayerA(playerA, game.Id, theMatch.Id)); var mockB = new Mock&lt;IGameResultRepository&gt;(); mockB.Setup(x =&gt; x.GameScores(playerA.Id, game.Id)).Returns(ResultScoreMockPlayerB(playerB, game.Id, theMatch.Id)); IMatchResultSpecification&lt;Player&gt; mkSpecs = new MortalKombatPlayerMatchResultSpecification( playerA.Specs(mockA.Object, game.Id, 3), playerB.Specs(mockB.Object, game.Id, 2)); var result = theMatch.Result(mkSpecs); result.Winner.Participant.Should().Be(playerA); result.Loser.Participant.Should().Be(playerB); } private List&lt;PlayerResultScore&gt; ResultScoreMockPlayerA(Player player, Guid gameId, Guid matchId) { var score1 = new PlayerResultScore(player, matchId, gameId, 3, 2); var clc = new MortalKombatPointCalculator(3, 3, 0, 0); score1.SetPointsTaken(clc); score1.SetPointsLost(clc); var score2 = new PlayerResultScore(player, matchId, gameId, 1, 3); clc = new MortalKombatPointCalculator(3, 1, 0, 5); score2.SetPointsTaken(clc); score2.SetPointsLost(clc); var score3 = new PlayerResultScore(player, matchId, gameId, 3, 1); clc = new MortalKombatPointCalculator(3, 3, 6.2, 6); score3.SetPointsTaken(clc); score3.SetPointsLost(clc); List&lt;PlayerResultScore&gt; scores = new List&lt;PlayerResultScore&gt; {score1, score2, score3}; return scores; } private List&lt;PlayerResultScore&gt; ResultScoreMockPlayerB(Player player, Guid gameId, Guid matchId) { var score1 = new PlayerResultScore(player, matchId, gameId, 2, 3); var clc = new MortalKombatPointCalculator(3, 2, 0, 0); score1.SetPointsTaken(clc); score1.SetPointsLost(clc); var score2 = new PlayerResultScore(player, matchId, gameId, 3, 1); clc = new MortalKombatPointCalculator(3, 3, 5, 0); score2.SetPointsTaken(clc); score2.SetPointsLost(clc); var score3 = new PlayerResultScore(player, matchId, gameId, 1, 3); clc = new MortalKombatPointCalculator(3, 1, 6, 6.2); score2.SetPointsTaken(clc); score2.SetPointsLost(clc); List&lt;PlayerResultScore&gt; scores = new List&lt;PlayerResultScore&gt; {score1, score2, score3}; return scores; } </code></pre> <p><a href="https://github.com/aliBordbar1992/SainaYar/blob/master/SainaYar.Matchmaking.Tests/MatchShould.cs" rel="nofollow noreferrer">Direct link to this test</a></p> <p>The core logic is in <a href="https://github.com/aliBordbar1992/SainaYar/tree/master/SainaYar.Matchmaking.Model" rel="nofollow noreferrer">this GitHub repository</a> from which you can explore the details.</p> <p><strong>The problem</strong></p> <p>For now, I just implemented a logic for the "<em>Mortal Kombat</em>" game, with it' rules of scoring and all, as you can see, it already turned into an abomination.</p> <p>Everything works fine and the test passes, but I know the design could be way better than this. I want to know the weak spots of this design and I want to refactor this to good quality code.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-05T19:46:07.953", "Id": "438094", "Score": "1", "body": "Can you provide the classes used by these test methods so we know what is going on better (i.e. for mocking purposes, if needed, etc.)." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T21:45:14.597", "Id": "212239", "Score": "2", "Tags": [ "c#", "object-oriented" ], "Title": "Game tournament service - core logic for matchmaking and results" }
212239
<p>Task: convert this array of hashes:</p> <pre><code>animals = [ {"cats" =&gt; 3}, {"dogs" =&gt; 5 } ] </code></pre> <p>to this hash:</p> <pre><code>{ "cats" =&gt; 3, "dogs" =&gt; 5 } </code></pre> <p>This is my solution, any feedback is appreciated :-)</p> <pre><code>animals.reduce({}) {|m,e| e.each{|k,v| m[k] = v}; m } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T00:08:13.633", "Id": "410452", "Score": "1", "body": "You've given an example, but can you be more specific about the requirements and constraints? For example, is guaranteed that each element of `animals` is a Hash with a single entry? Is it guaranteed that there are no duplicates or clashes?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T23:11:52.527", "Id": "410680", "Score": "0", "body": "no constraints, it just has to work with that example :-)" } ]
[ { "body": "<p>The snippet <code>e.each{|k,v| m[k] = v}</code> does the same thing as the standard library method <a href=\"https://ruby-doc.org/core-2.6/Hash.html#method-i-merge-21\" rel=\"noreferrer\">Hash#merge!</a>, so the shortest way to write your solution is probably:</p>\n\n<pre><code>animals.reduce({}, :merge!)\n</code></pre>\n\n<p>Note that with this solution, if two hashes in the source array have duplicate keys, those coming later in the array will take priority and overwrite the duplicate keys from earlier in the array:</p>\n\n<pre><code>[{\"egrets\" =&gt; 17}, {\"egrets\" =&gt; 21}].reduce({}, :merge!) # =&gt; {\"egrets\"=&gt;21}\n</code></pre>\n\n<p>Also be aware that <code>merge!</code> is destructive to the original hash, which is fine here since we don't reuse the literal input to <code>reduce</code>. There is a non-destructive version, <code>merge</code>, which is better when the input needs to be preserved.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T02:44:20.660", "Id": "212251", "ParentId": "212242", "Score": "6" } } ]
{ "AcceptedAnswerId": "212251", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-25T23:46:17.020", "Id": "212242", "Score": "0", "Tags": [ "ruby" ], "Title": "Arrays of hashes to hash" }
212242
<p>I am trying to implement a minimal symbolic algebra library (AKA C.A.S.) in C++ that allows me to utilize delayed evaluation similar to <a href="https://stackoverflow.com/questions/414243/lazy-evaluation-in-c/414260#414260">this question</a> from SO. </p> <p>My class hierarchy is getting a little complex, as it uses CRTP, abstract base classes, and smart pointers (which is where I'm running into issues). </p> <p>I'm not confident using smart pointers yet, so I'm hoping that I can get feedback on how I'm using them and whether or not there are better ways to handle this. I'm also appreciative of any feedback on how to make this work without running into any unforeseen or classic pitfalls.</p> <p>I've included background code to demonstrate a simplified version of what I have so far, and my actual question is down below. I appreciate any feedback I can get. </p> <h1>Background:</h1> <p>I have an abstract base class which looks like this:</p> <pre><code>class BaseSymbolic : public std::enable_shared_from_this&lt;BaseSymbolic&gt; { public: virtual ~BaseSymbolic() {} inline std::shared_ptr&lt;BaseSymbolic&gt; as_ptr(); virtual std::string as_str() const = 0; // For printing a symbolic. virtual size_t hash() const = 0; // For comparing two symbolics. }; inline std::shared_ptr&lt;BaseSymbolic&gt; BaseSymbolic::as_ptr() { return shared_from_this(); } </code></pre> <p>With a CRTP base class that looks like this:</p> <pre><code>template&lt;typename Derived&gt; class Symbolic : public BaseSymbolic { public: inline Derived &amp;operator~(); inline const Derived &amp;operator~() const; inline std::shared_ptr&lt;Derived&gt; as_ptr(); std::string as_str() const override; inline operator std::string() const; size_t hash() const override; }; // Using the overloaded binary 'not' operator here is just a style choice. I'm // sure this could easily be changed to 'derived' or 'const_derived', but I // like the way it looks as an operator rather than a function call. template&lt;typename Derived&gt; inline Derived &amp;Symbolic&lt;Derived&gt;::operator~() { return static_cast&lt;Derived &amp;&gt;(*this); } template&lt;typename Derived&gt; inline const Derived &amp;Symbolic&lt;Derived&gt;::operator~() const { return static_cast&lt;const Derived &amp;&gt;(*this); } // Uses static_pointer_cast to down cast the shared pointer to the derived type. template&lt;typename Derived&gt; inline std::shared_ptr&lt;Derived&gt; Symbolic&lt;Derived&gt;::as_ptr() { return std::static_pointer_cast&lt;Derived&gt;(shared_from_this()); } template&lt;typename Derived&gt; std::string Symbolic&lt;Derived&gt;::as_str() const { // I realize underscores before names can be bad style, // I just don't know what to call these vvvvvvv yet. return static_cast&lt;const Derived &amp;&gt;(*this)._as_str(); } template&lt;typename Derived&gt; inline Symbolic&lt;Derived&gt;::operator std::string() const { return static_cast&lt;const Derived &amp;&gt;(*this)._as_str(); } template&lt;typename Derived&gt; size_t Symbolic&lt;Derived&gt;::hash() const { return static_cast&lt;const Derived &amp;&gt;(*this)._hash(); } </code></pre> <p>I chose not to use the <code>Derived</code>/<code>Base</code> CRTP pattern here for simplicity. Right now, nothing inherits from the derived classes.</p> <p>I'm separating the virtual call from the CRTP call (<code>as_str()</code> vs <code>_as_str()</code>), just to minimize the amount of virtual function calls in my code. I'm pretty sure the vtable gets carried around regardless, but I think it reduces the size of the vtable.</p> <p>I'm unsure about the <code>as_ptr()</code> calls, which return a casted <code>std::shared_ptr</code>. In my tests, I occasionally get away with calling the <code>Symbolic</code> version, but mostly it defaults to the <code>BaseSymbolic</code> version.</p> <p>Now, I have a couple derived classes from <code>Symbolic</code>, such as symbolic variables, numbers, expressions, etc. that I want to be able to use in a matrix, vector, etc. (which is why the abstract base class is needed). I chose to use CRTP to manage all of these so that I could use templates to handle the types.</p> <p>An example declaration of a symbolic number:</p> <pre><code>template&lt;typename T&gt; class Number : public Symbolic&lt;Number&lt;T&gt;&gt; { private: T value_; size_t hash_; public: explicit inline Number(); // Checks to make sure T is a number internally. explicit inline Number(const T &amp;m); inline Number(const Number&lt;T&gt; &amp;m); inline Number&lt;T&gt; &amp;operator=(const T &amp;rhs); inline Number&lt;T&gt; &amp;operator=(const Number&lt;T&gt; &amp;rhs); inline std::string _as_str() const; inline size_t _hash() const; inline T value() const; }; </code></pre> <p>In order to implement delayed evaluation, I create a templated "expression" class for each operation (add, subtract, multiply, etc.) that stores a const reference to the <code>Symbolic</code> arguments and is also derived from <code>Symbolic</code>. </p> <p>An example of a delayed evaluation operation:</p> <pre><code>template&lt;typename T1, typename T2&gt; class ExprAdd : public Symbolic&lt;ExprAdd&lt;T1, T2&gt;&gt; { private: const T1 &amp;lhs_; const T2 &amp;rhs_; public: explicit inline ExprAdd(const T1 &amp;lhs, const T2 &amp;rhs); inline std::string _as_str() const; inline size_t _hash() const; }; template&lt;typename T1, typename T2&gt; inline ExprAdd&lt;T1, T2&gt;::ExprAdd(const T1 &amp;lhs, const T2 &amp;rhs) : lhs_(lhs), rhs_(rhs) {} // The trailing return type is just a style choice. Sometimes as these get // more complex, the return type can get pretty large, or I want to use // decltype(...) to keep things simple. // Also, the `const` modifier for the return type is just so that I can // store the result in the wrapper class below. template&lt;typename T1, typename T2&gt; inline auto operator+(const Symbolic&lt;T1&gt; &amp;lhs, const Symbolic&lt;T2&gt; &amp;rhs) -&gt; const ExprAdd&lt;T1, T2&gt; { return ExprAdd&lt;T1, T2&gt;(~lhs, ~rhs); } </code></pre> <p>This leads the expression <code>a + b</code>, where <code>a</code> and <code>b</code> are both variables, to return the type <code>const ExprAdd&lt;Variable, Variable&gt;</code> My goal in the end is to check whether the two are both numbers and to "collapse" the expression if they are, meaning <code>const ExprAdd&lt;Number&lt;...&gt;, Number&lt;...&gt;&gt;</code> gets replaced with <code>a.value() + b.value()</code>.</p> <p>But I also don't want to have the user keep track of the type, meaning I don't want them to use template arguments for creating variables.</p> <p>I <strong>don't</strong> want this:</p> <pre><code>Number&lt;int&gt; a = 2; Number&lt;int&gt; b = 3; ExprAdd&lt;Number&lt;int&gt;, Number&lt;int&gt;&gt; c = a + b; </code></pre> <p>I <strong>do</strong> want this:</p> <pre><code>sym a = 2; sym b = 3; sym c = a + b; </code></pre> <h1>Actual Question:</h1> <p>I created a derived class called <code>sym</code> which holds a smart pointer to a <code>BaseSymbolic</code>. I chose to use the 'rule of zero' for the class, because all it does is hold a smart pointer. Not sure if I explicitly need the copy and move functions for this. </p> <p>Note that the sample below is simplified just for integers. There will be other constructors to handle other types in real life.</p> <p>Also, the symbolic manipulations will be handled elsewhere, this is just to demonstrate one specific aspect of the code, namely the smart pointer class.</p> <pre><code>class sym : public Symbolic&lt;sym&gt; { private: // Not sure if this needs to be a 'shared_ptr'. Might be a 'unique_ptr'. std::shared_ptr&lt;BaseSymbolic&gt; ptr_; public: // Other ctors for other types. For example, there might be: // explicit inline sym(std::string name) for a named variable. inline sym(int m); // These seem wrong. I want to be able to accept 'const' expressions, // but don't mind copying. Right now, this accepts the rvalues // from the addition operator. template&lt;typename Derived&gt; inline sym(const Symbolic&lt;Derived&gt; &amp;&amp;m); template&lt;typename Derived&gt; inline sym &amp;operator=(const Symbolic&lt;Derived&gt; &amp;&amp;rhs); inline std::string _as_str() const; inline size_t _hash() const; }; // Constructor inline sym::sym(int m) : ptr_(std::make_shared&lt;Number&lt;int&gt;&gt;(m)) {} // This is most certainly wrong, but it works somehow. template&lt;typename Derived&gt; inline sym::sym(const Symbolic&lt;Derived&gt; &amp;&amp;m) : ptr_(std::make_shared&lt;Derived&gt;(std::move(~m))) {} // Assignment Operators // This is also most certainly wrong. template&lt;typename Derived&gt; inline sym &amp;sym::operator=(const Symbolic&lt;Derived&gt; &amp;&amp;m) { ptr_ = std::make_shared&lt;Derived&gt;(std::move((~m))); return *this; } // Member Functions inline std::string sym::_as_str() const { return ptr_-&gt;as_str(); } inline size_t sym::_hash() const { return ptr_-&gt;hash(); } </code></pre> <p>My question is whether or not I am implementing the smart pointer wrapper class correctly. I'm having trouble understanding how this might be used to chain expressions such as <code>c = c + a</code> while maintaining the reference to <code>c</code>. My first thought is that I'll need a temporary reference while I replace the smart pointer with a new value using <code>reset</code>.</p> <p>I would appreciate any feedback, especially about how to handle the smart pointer wrapper class. So far, my solution seems tenuous at best, and I would like to learn how to improve on it.</p> <p><a href="http://cpp.sh/5i6lh" rel="nofollow noreferrer">Here</a> is a link to some working code.</p>
[]
[ { "body": "<p><strong>Code:</strong></p>\n\n<ul>\n<li><p>The only real utility of the <code>inline</code> keyword nowadays is to allow function definitions to be placed header files. However, template functions, or functions in template classes, don't need to be marked <code>inline</code>. There's also no need to mark both the declaration and the definition as inline.</p></li>\n<li><p>Use <code>std::size_t</code>, not <code>size_t</code> (the former is the C++ version, the latter is the C version).</p></li>\n<li><p>Don't overload random operators because it looks cool! Call it <code>as_derived</code> or something.</p></li>\n<li><p>The <code>Number</code> class stores the <code>hash_</code> of the string (o.O), but the <code>hash()</code> function returns a hash of the value? Seems weird.</p></li>\n<li><p>Use the default implementations of the copy and move constructors and assignment operators where appropriate, e.g.:</p>\n\n<pre><code>Number(Number const&amp;) = default;\nNumber&amp; operator=(Number const&amp;) = default;\nNumber(Number&amp;&amp;) = default;\nNumber&amp; operator=(Number&amp;&amp;) = default;\n</code></pre></li>\n<li><p>If we allow assignment of a value to <code>Number</code>, it might be cleaner to implement const and non-const reference versions of the <code>value()</code> member function instead:</p>\n\n<pre><code>T&amp; value() { return value_; }\nT const&amp; value() const { return value_; }\n</code></pre></li>\n<li><p>Having different, non-virtual <code>as_ptr()</code> functions in <code>BaseSymbolic</code> and <code>Symbolic</code> is quite confusing. Do we actually need the <code>BaseSymbolic</code> version?</p></li>\n<li><p>The <code>operator std::string() const</code> in <code>Symbolic</code> should be made explicit. And then deleted, since it does exactly what <code>as_str()</code> does.</p></li>\n<li><p>There doesn't seem to be any reason to split off <code>_as_str()</code> from <code>as_str()</code> and <code>_hash()</code> from <code>hash()</code> in <code>Symbolic</code>. Since <code>Number</code> and <code>ExprAdd</code> are ultimately derived from <code>BaseSymbolic</code>, we can avoid just override them there, and leave them as abstract in <code>Symbolic</code>.</p></li>\n<li><p><code>operator+()</code> to make the <code>ExprAdd</code> will work fine without the <code>operator~</code>!</p></li>\n<li><p>Storing references will cause problems, e.g.: <code>sym a = sym(3) + sym(5); a.as_str();</code> will crash (or something). Both those temporaries are destroyed before <code>a.as_str()</code> is evaluated. We should probably store symbols by value and provide a way to store references when explicitly requested by the user (see below).</p>\n\n<ul>\n<li><p><code>sym a = 5; a-&gt;as_ptr();</code> will crash (or something) because the <code>sym</code> isn't created as a <code>std::shared_ptr</code>.</p></li>\n<li><p>Note that allocating symbols on the heap as shared pointers adds overhead, if we don't need to build a tree of arbitrary expressions at run-time, this is quite a steep price to pay to save some keystrokes (and seems quite contrary to trying to optimize the math expressions).</p></li>\n<li><p>We can actually replace <code>std::shared_ptr</code> in the <code>sym</code> class with <code>std::unique_ptr</code>. This further highlights that we don't actually need <code>operator~()</code> at all. The only time we need the derived type is when copying the object. So we can add a <code>virtual BaseSymbolic* clone() const</code> function instead.</p></li>\n</ul></li>\n</ul>\n\n<p>Suddenly, we don't need <code>std::enable_shared_from_this</code>, or <code>as_ptr()</code>, and we can delete a fair amount of code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;memory&gt;\n\nclass BaseSymbolic {\npublic:\n\n virtual ~BaseSymbolic() {}\n\n virtual BaseSymbolic* clone() const = 0;\n\n virtual std::string as_str() const = 0;\n virtual std::size_t hash() const = 0;\n};\n\ntemplate&lt;typename Derived&gt;\nclass Symbolic : public BaseSymbolic {\npublic:\n\n // ¯\\_(ツ)_/¯\n\n};\n\ntemplate&lt;typename T&gt;\nclass Number : public Symbolic&lt;Number&lt;T&gt;&gt; {\nprivate:\n\n T value_;\n\npublic:\n\n explicit Number(T value): value_(value) { }\n\n Number(Number const&amp;) = default;\n Number&amp; operator=(Number const&amp;) = default;\n Number(Number&amp;&amp;) = default;\n Number&amp; operator=(Number&amp;&amp;) = default;\n\n Number* clone() const override { return new Number(value_); }\n\n std::string as_str() const { return std::to_string(value_); }\n std::size_t hash() const { return std::hash&lt;T&gt;{}(value_); }\n\n T&amp; value() { return value_; }\n T const&amp; value() const { return value_; }\n};\n\ntemplate&lt;typename T1, typename T2&gt;\nclass ExprAdd : public Symbolic&lt;ExprAdd&lt;T1, T2&gt;&gt; {\nprivate:\n\n T1 lhs_;\n T2 rhs_;\n\npublic:\n\n explicit ExprAdd(const T1 &amp;lhs, const T2 &amp;rhs): lhs_(lhs), rhs_(rhs) { }\n\n ExprAdd(ExprAdd const&amp;) = default;\n ExprAdd&amp; operator=(ExprAdd const&amp;) = default;\n ExprAdd(ExprAdd&amp;&amp;) = default;\n ExprAdd&amp; operator=(ExprAdd&amp;&amp;) = default;\n\n ExprAdd* clone() const override { return new ExprAdd(lhs_, rhs_); }\n\n std::string as_str() const override { return lhs_.as_str() + \" + \" + rhs_.as_str(); }\n std::size_t hash() const override { return lhs_.hash() ^ rhs_.hash(); }\n};\n\ntemplate&lt;typename T1, typename T2&gt;\nauto operator+(const Symbolic&lt;T1&gt; &amp;lhs, const Symbolic&lt;T2&gt; &amp;rhs) -&gt; const ExprAdd&lt;T1, T2&gt; {\n return ExprAdd&lt;T1, T2&gt;(lhs, rhs);\n}\n\nclass sym : public Symbolic&lt;sym&gt; {\nprivate:\n\n std::unique_ptr&lt;BaseSymbolic&gt; ptr_;\n\npublic:\n\n sym(int m):\n ptr_(std::make_unique&lt;Number&lt;int&gt;&gt;(m)) { }\n\n template&lt;class Derived&gt;\n sym(Symbolic&lt;Derived&gt; const&amp; m):\n ptr_(m.clone()) { }\n\n sym(sym const&amp; other):\n ptr_(other.ptr_-&gt;clone()) { }\n\n sym&amp; operator=(sym const&amp; other)\n {\n sym temp(other);\n ptr_ = std::move(temp.ptr_);\n return *this;\n }\n\n sym(sym&amp;&amp;) = default;\n sym&amp; operator=(sym&amp;&amp;) = default;\n\n sym* clone() const override { return new sym(*this); }\n\n std::string as_str() const override { return ptr_-&gt;as_str(); }\n std::size_t hash() const override { return ptr_-&gt;hash(); }\n};\n\nint main() {\n\n sym a = 5;\n sym b = 10;\n sym c = a + b;\n\n std::cout &lt;&lt; c.as_str() &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>We could probably get rid of the <code>Symbolic</code> class too, but maybe there's a better way to organize things...</p>\n\n<hr>\n\n<p><strong>Design:</strong></p>\n\n<p>It's a little unclear whether you want to be able to construct an expression tree at run-time (e.g. parsing arbitrary string input from the user and calculating the result), or at compile time (e.g. improving C++ code efficiency with expression templates).</p>\n\n<p>These are two different things. The latter (which is what <a href=\"https://stackoverflow.com/questions/414243/lazy-evaluation-in-c/414260#414260\">that stackoverflow question</a> seems to be about) shouldn't require virtual functions or run-time polymorphism at all.</p>\n\n<hr>\n\n<p><strong>Compile-time:</strong></p>\n\n<p>For static lazy evaluation we don't need the base-class and inheritance hierarchy. As long as we implement the same static interface with our types, we can use them in template functions without caring what type they are.</p>\n\n<p>We can use the <code>auto</code> keyword, and some utility functions to save the user bit of typing:</p>\n\n<pre><code>#include &lt;memory&gt;\n#include &lt;string&gt;\n#include &lt;utility&gt;\n\ntemplate&lt;class T&gt;\nstruct Number\n{\n T value;\n\n std::string to_string() const { return std::to_string(value); }\n std::size_t hash() const { return std::hash&lt;T&gt;()(value); }\n};\n\ntemplate&lt;class T&gt;\nNumber&lt;T&gt; make_num(T value)\n{\n return{ value };\n}\n\ntemplate&lt;class T&gt;\nstruct Ref\n{\n T* thing;\n\n std::string to_string() const { return thing-&gt;to_string(); }\n std::size_t hash() const { return thing-&gt;hash(); }\n};\n\ntemplate&lt;class T&gt;\nRef&lt;T&gt; make_ref(T&amp; value)\n{\n return{ &amp;value };\n}\n\ntemplate&lt;class T&gt;\nRef&lt;const T&gt; make_ref(T const&amp; value)\n{\n return{ &amp;value };\n}\n\ntemplate&lt;class LeftT, class RightT&gt;\nstruct Add\n{\n LeftT left;\n RightT right;\n\n std::string to_string() const { return left.to_string() + \" + \" + right.to_string(); }\n std::size_t hash() const { return left.hash() ^ right.hash(); }\n};\n\ntemplate&lt;class LeftT, class RightT&gt;\nAdd&lt;LeftT, RightT&gt; operator+(LeftT a, RightT b) // copy\n{\n return{ std::move(a), std::move(b) }; // and move\n}\n\n#include &lt;iostream&gt;\n\nint main()\n{\n auto a = make_num(5);\n auto b = make_num(10);\n\n auto sum = a + make_ref(b);\n std::cout &lt;&lt; sum.to_string() &lt;&lt; std::endl;\n\n auto test = make_num(3) + make_num(34);\n std::cout &lt;&lt; test.to_string() &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>We could even use free-functions instead of member functions for <code>to_string()</code> and <code>hash()</code>. If we supply appropriate overloads for standard numeric types (<code>int</code>, <code>float</code>, etc.), then we don't need the <code>Number</code> class at all.</p>\n\n<p>Since the type information is immediately available, it's also simple (in an awful C++ way) to overload various operators to do particular things, e.g.</p>\n\n<pre><code>namespace impl\n{\n // \"simple\"\n\n template&lt;class A, class B&gt;\n struct AddImpl\n {\n using return_type = Add&lt;A, B&gt;;\n\n static return_type add(A a, B b) // general version\n {\n return{ std::move(a), std::move(b) };\n }\n };\n\n template&lt;class A, class B&gt;\n struct AddImpl&lt;Number&lt;A&gt;, Number&lt;B&gt;&gt;\n {\n using return_type = Number&lt;decltype(A() + B())&gt;;\n\n static return_type add(Number&lt;A&gt; const&amp; a, Number&lt;B&gt; const&amp; b) // specific version\n {\n return return_type{ a.value + b.value }; // trivial types, so just do this now...\n }\n };\n\n} // impl\n\ntemplate&lt;class LeftT, class RightT&gt;\ntypename impl::AddImpl&lt;LeftT, RightT&gt;::return_type operator+(LeftT const&amp; a, RightT const&amp; b)\n{\n return impl::AddImpl&lt;LeftT, RightT&gt;::add(a, b);\n}\n\n\n#include &lt;iostream&gt;\n\nint main()\n{\n auto a = make_num(5);\n auto b = make_num(10);\n\n auto sum = a + make_ref(b);\n std::cout &lt;&lt; sum.to_string() &lt;&lt; std::endl;\n\n auto test = make_num(3) + make_num(34);\n std::cout &lt;&lt; test.to_string() &lt;&lt; std::endl;\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Run-time:</strong></p>\n\n<p>If you do need to construct the tree at run-time, I'd suggest watching one of Sean Parent's talks, which describe an alternative approach to run-time polymorphism:</p>\n\n<ul>\n<li><a href=\"https://www.youtube.com/watch?v=2bLkxj6EVoM\" rel=\"noreferrer\">Going Native 2013 - Inheritance is the Base Class of Evil</a>.</li>\n<li><a href=\"https://www.youtube.com/watch?v=QGcVXgEVMJg\" rel=\"noreferrer\">NDC London 2017 - Better Code: Runtime Polymorphism</a>.</li>\n</ul>\n\n<p>In short, we make our expression / number types adhere to a static interface (concept) as above. Then we can use a type-hiding class to add the run-time polymorphism in a very self-contained fashion:</p>\n\n<pre><code>#include &lt;memory&gt;\n#include &lt;string&gt;\n#include &lt;utility&gt;\n\nclass Expression\n{\npublic:\n\n template&lt;class T&gt;\n explicit Expression(T e):\n model(std::make_unique&lt;Model&lt;T&gt;&gt;(std::move(e))) { }\n\n Expression(Expression const&amp; other):\n model(other.model-&gt;clone()) { }\n\n Expression&amp; operator=(Expression const&amp; other)\n {\n model.reset(other.model-&gt;clone());\n return *this;\n }\n\n Expression(Expression&amp;&amp; other):\n model(std::move(other.model)) { }\n\n Expression&amp; operator=(Expression&amp;&amp; other)\n {\n model = std::move(other.model);\n return *this;\n }\n\n std::string to_string() const { return model-&gt;to_string(); }\n std::size_t hash() const { return model-&gt;hash(); }\n\nprivate:\n\n struct Concept\n {\n virtual Concept* clone() const = 0;\n\n virtual std::string to_string() const = 0;\n virtual std::size_t hash() const = 0;\n };\n\n template&lt;class T&gt;\n class Model : public Concept\n {\n public:\n\n explicit Model(T const&amp; e):\n expression(e) { }\n\n explicit Model(T&amp;&amp; e):\n expression(e) { }\n\n virtual Model* clone() const { return new Model(expression); }\n\n virtual std::string to_string() const { return expression.to_string(); }\n virtual std::size_t hash() const { return expression.hash(); }\n\n private:\n\n T expression;\n };\n\n std::unique_ptr&lt;Concept&gt; model;\n};\n</code></pre>\n\n<p>This works fine together with compile-time code above so we can do things like this:</p>\n\n<pre><code>#include &lt;iostream&gt;\n\nint main()\n{\n auto a = Expression(make_num(5));\n auto b = make_num(10);\n\n auto sum = a + Expression(make_ref(b));\n\n std::cout &lt;&lt; sum.to_string() &lt;&lt; std::endl; // evaluate!\n}\n</code></pre>\n\n<p>It's a little wordy when creating the expressions, but if we're parsing user input to make an expression tree, that's unlikely to be a big problem.</p>\n\n<p>We could get more towards the desired syntax with a utility function, e.g.:</p>\n\n<pre><code>template&lt;class T, typename = std::enable_if_t&lt;std::is_integral&lt;T&gt;::value || std::is_floating_point&lt;T&gt;::value&gt;&gt;\nExpression make_expr(T number)\n{\n return Expression(Number&lt;T&gt;{ number });\n}\n</code></pre>\n\n<p>But note again that the main point of adding the run-time polymorphism is to allow us to construct arbitrary expression trees at run-time. We can probably make the syntax \"nice-enough\" with the compile-time version if we don't need this feature.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T19:42:30.067", "Id": "410657", "Score": "0", "body": "This is an amazing, well thought out, and comprehensive answer that addresses nearly every one of my concerns and problems. Bullets 1-3, 5, 6, 8-11 are great advice. For point 4, I'm hashing the string to avoid ambiguity in comparing the numbers and expressions. For point 7, I need the `BaseSymbolic` version in some other functions that do comparisons, etc." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T19:48:26.893", "Id": "410658", "Score": "0", "body": "The concepts are something I haven't played with yet, but I've read a few articles and seen some of the videos you linked to. I will definitely look into implementing that. The big reason for the abstract base class was to allow these to be used in a `std::vector` within a `Matrix<sym>` class that I define elsewhere. Mostly, I'm looking for compile-time expression trees, but I want to enable these to be used from a shared library, which will require some amount of run-time code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T18:04:04.790", "Id": "212282", "ParentId": "212243", "Score": "5" } } ]
{ "AcceptedAnswerId": "212282", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T00:05:21.073", "Id": "212243", "Score": "4", "Tags": [ "c++", "c++11", "template-meta-programming" ], "Title": "Symbolic algebra using a generic smart pointer class" }
212243
<p>I am working on saving the text messaging draft of a user. The flow currently works but I am looking to make this block of code easier to read and smaller. Could anyone help me achieve this?</p> <pre><code>if (!hasDraft) { /** * This will get triggered when there is no draft * and you create one therefore we need a refresh. */ if (!TextUtils.isEmpty(enteredText)) { saveDraftAndRefreshList(); } else { /** * This should be the happy case. * User has just sent a message so no need to refresh the list */ sendMessage(); } /** * This else will only be reached if there has been a draft **/ } else { if (TextUtils.isEmpty(enteredText)) { /** * This will get reached if you had a draft but now removed the text. * Thus needing a refresh */ removePreviousDraft(); } else if (!TextUtils.isEmpty(enteredText)) { /** * This will get triggered if there was a draft and * now they decided to overwrite it. */ overwritePreviousDraft(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T04:58:01.900", "Id": "410586", "Score": "0", "body": "This question is incomplete. To help reviewers give you better answers, please add sufficient context to your question. The more you tell us about what your code does and what the purpose of doing that is, the easier it will be for reviewers to help you. [Questions should include a description of what the code does](//codereview.meta.stackexchange.com/q/1226) and in what context it's used." } ]
[ { "body": "<p>In both cases (<code>!hasDraft</code> and not <code>!hasDraft</code>) you check whether the enteredText is empty. You can hoist that into a boolean variable outside the if statement.</p>\n\n<p>Also, you are testing <code>if (!hasDraft)</code> but then also doing an <code>else</code> on that condition, which means <code>else (if not)not hasDraft</code>. That can be confusing, so unless some other part of your code flow requires it, I suggest you make your if statement be <code>if (hasDraft) {} else {}</code> so that the implied <code>not</code> from the <code>else</code> matches the <code>!hasDraft</code> case.</p>\n\n<pre><code>boolean noEnteredText = TextUtils.isEmpty(enteredText);\n\nif (hasDraft) {\n if (noEnteredText) {\n removePreviousDraft();\n else {\n overwritePreviousDraft();\n }\n} else {\n if (noEnteredText) {\n sendMessage();\n } else {\n saveDraftAndRefreshList();\n }\n}\n</code></pre>\n\n<p>This does not read well, IMO. Again, though, it might be fine in the context of your other code. But I wonder if reversing the sense of <code>noEnteredText</code> to be <code>hasEnteredText</code> would make it better?</p>\n\n<pre><code>boolean hasEnteredText = !TextUtils.isEmpty(enteredText);\n\nif (hasDraft) {\n if (hasEnteredText) {\n overwritePreviousDraft();\n else {\n removePreviousDraft();\n }\n} else {\n if (hasEnteredText) {\n saveDraftAndRefreshList();\n } else {\n sendMessage();\n }\n}\n</code></pre>\n\n<p>This still seems off. But I suspect that's probably because I don't know your app. Is it possible you're trying to do too much, and the two decisions should be at two different levels of method call?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:12:16.543", "Id": "212278", "ParentId": "212247", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T01:21:16.080", "Id": "212247", "Score": "2", "Tags": [ "java", "android" ], "Title": "Method that Saves user text messaging draft" }
212247
<p>You were all so helpful with my Tc Tac Toe games in C. I was encouraged to put it up on GitHub and two very helpful users refactored it in ways that really taught me a thing or two. While I have switched focus to Python in anticipation of the upcoming 7DRL I was so happy about the way my C projects were reviewed that this has become one of my favorite forums. So now I want your help with something else:</p> <p>Over the last week or so I've created a Blackjack game with Python 3.5.3. The logic was easy to do, especially with Python, but making a clean curses interface was more challenging. What I wound up doing was creating a blackjack game without curses to get the logic straight and then implementing curses in the form of a <code>draw_screen()</code> function that turned out to be a real monster. It is messy and repetitive compared to the rest of the code, and the function wound up being well over 100 lines long. In addition to that I'm still struggling to do things in the most "Pythonic" way, and even the behind-the-screen logic may not be implemented in a way that is ideal.</p> <p>What I want help from you guys with is to help me refactor the <code>draw_screen()</code> function into something more manageable. Should I split it up into multiple functions? How best to do that? I would also appreciate any and all feedback regarding how I could make the non-curses logic of the game more "Pythonic." </p> <p>I intend to make a Roguelike for the 7DRL event this year and I intend to do it with Python 3.5.3 and the curses library. It'll be harder than what I usually do but I'm looking forward to it. By helping me hammer out my fundamentals here you will help me to be better prepared for making a small Roguelike in the near future. </p> <p>Note: the <code>GREEN_TEXT</code> and <code>RED_TEXT</code> color pair definitions were originally going to be used for the player's funds and for busting prompts, respectively. I haven't removed them because I intend to add that functionality myself very soon, if not today. </p> <p>Here is the code itself:</p> <pre><code>""" Project: Simple 21/Blackjack File: twenty-one-curses.py Date: 24 JAN 2019 Author: sgibber2018 Description: A simple implementation of 21/Blackjack using the terminal and python. Uses the curses library for character cell graphics. """ import random import curses # init curses stdscr = curses.initscr() curses.cbreak() curses.noecho() curses.curs_set(False) curses.start_color() # init curses colors curses.init_color(curses.COLOR_RED, 900, 0, 0) curses.init_color(curses.COLOR_BLACK, 0, 0, 0) curses.init_color(curses.COLOR_GREEN, 0, 900, 0) curses.init_color(curses.COLOR_WHITE, 1000, 1000, 1000) colors_dict = {"RED_CARD":1, "BLACK_CARD":2, "GREEN_TEXT":3, "RED_TEXT":4} curses.init_pair(colors_dict.get("RED_CARD"), curses.COLOR_RED, curses.COLOR_WHITE) curses.init_pair(colors_dict.get("BLACK_CARD"), curses.COLOR_BLACK, curses.COLOR_WHITE) curses.init_pair(colors_dict.get("GREEN_TEXT"), curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(colors_dict.get("RED_TEXT"), curses.COLOR_RED, curses.COLOR_BLACK) class Card: def __init__(self, suit, value): self.suit = suit self.value = value def generate_deck(): """ Generate a list of Card objects to be used as a deck and return it """ deck = [] card_suits = ["D", "H", "S", "C"] card_nums_range = range(2, 11) card_faces = ["J", "Q", "K", "A"] for suits in range(len(card_suits)): for card_nums in card_nums_range: deck.append(Card(card_suits[suits], str(card_nums))) for card in range(len(card_faces)): deck.append(Card(card_suits[suits], card_faces[card])) random.shuffle(deck) return deck def draw(hand, num_to_draw, deck): """ takes a hand list and a number and draws that number of cards from the deck and places them in the desired hand """ for num_cards in range(num_to_draw): card = deck[-1] hand.append(card) deck.remove(card) def count_hand(hand): """ Evaluates a hand and returns the value of its cards """ card_values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8":8, "9": 9, "10":10, "J":10, "Q":10, "K":10} hand_sum = 0 hand_suits = [] for cards in hand: hand_suits.append(cards.value) if "A" in hand_suits: num_aces = 0 for card_value in hand_suits: if card_value == "A": num_aces += 1 for card in hand: if card.value != "A": hand_sum += card_values.get(card.value) if num_aces == 1: if hand_sum + 11 &gt; 21: hand_sum += 1 elif hand_sum + 11 &lt;= 21: hand_sum += 11 elif num_aces == 2: if hand_sum + 12 &gt; 21: hand_sum += 2 elif hand_sum + 12 &lt;= 21: hand_sum += 12 elif num_aces == 3: if hand_sum + 13 &gt; 21: hand_sum += 3 elif hand_sum + 13 &lt;= 21: hand_sum += 13 elif num_aces == 4: if hand_sum + 14 &gt; 21: hand_sum += 4 elif hand_sum + 14 &lt;= 21: hand_sum += 14 elif "A" not in hand_suits: for card in hand: hand_sum += card_values.get(card.value) return hand_sum def player_hits(player_hand, stdscr): """ Asks if player wants to hit """ # get dimensions wsize = stdscr.getmaxyx() prompt_line = 16 # lay out the strings prompt = "(H)it or (S)tay" prompt_hit = "Player has chosen to hit!" prompt_stay = "Player has chosen to stay!" prompt_wrong = "Invalid input! Try again..." # center the prompts prompt_x = wsize[1] // 2 - len(prompt) // 2 prompt_hit_x = wsize[1] // 2 - len(prompt_hit) // 2 prompt_stay_x = wsize[1] // 2 - len(prompt_stay) // 2 prompt_wrong_x = wsize[1] // 2 - len(prompt_wrong) // 2 # clear the entire prompt line clear_str = "" for char_cell in range(wsize[1]): clear_str += " " stdscr.addstr(prompt_line, 0, clear_str) # display the prompt stdscr.addstr(prompt_line, prompt_x, prompt) # get the input uinput = stdscr.getch() if uinput == 104 or uinput == 72: # print("Player has chosen to hit!") stdscr.addstr(prompt_line, 0, clear_str) stdscr.addstr(prompt_line, prompt_hit_x, prompt_hit) stdscr.getch() return True elif uinput == 83 or uinput == 115: # print("Player has chosen to stay!") stdscr.addstr(prompt_line, 0, clear_str) stdscr.addstr(prompt_line, prompt_stay_x, prompt_stay) stdscr.getch() return False else: # print("Invalid input! Try again...") stdscr.addstr(prompt_line, 0, clear_str) stdscr.addstr(prompt_line, prompt_wrong_x, prompt_wrong) stdscr.getch() player_hits(player_hand) def prompt(string, stdscr): """ Takes a string, clears the prompt line, and places the string on the prompt line """ wsize = stdscr.getmaxyx() prompt_line = 16 prompt_clear = "" for char_cell in range(wsize[1]): prompt_clear += " " stdscr.addstr(prompt_line, 0, prompt_clear) centered_x = wsize[1] // 2 - len(string) // 2 stdscr.addstr(prompt_line, centered_x, string) stdscr.getch() def is_busted(hand): """ Checks a hand and if it is busted, returns True """ card_values = {"2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8":8, "9": 9, "10":10, "J":10, "Q":10, "K":10} hand_sum = 0 hand_suits = [] for cards in hand: hand_suits.append(cards.value) if "A" in hand_suits: num_aces = 0 for card_value in hand_suits: if card_value == "A": num_aces += 1 for card in hand: if card.value != "A": hand_sum += card_values.get(card.value) if num_aces == 1: if hand_sum + 11 &gt; 21: hand_sum += 1 elif hand_sum + 11 &lt;= 21: hand_sum += 11 elif num_aces == 2: if hand_sum + 12 &gt; 21: hand_sum += 2 elif hand_sum + 12 &lt;= 21: hand_sum += 12 elif num_aces == 3: if hand_sum + 13 &gt; 21: hand_sum += 3 elif hand_sum + 13 &lt;= 21: hand_sum += 13 elif num_aces == 4: if hand_sum + 14 &gt; 21: hand_sum += 4 elif hand_sum + 14 &lt;= 21: hand_sum += 14 elif "A" not in hand_suits: for card in hand: hand_sum += card_values.get(card.value) if hand_sum &gt; 21: return True else: return False def game_not_over(player_funds, turn_num): """ Checks to see if the game is over. Returns True if game not over. Prints game over if game is over, then returns False """ if player_funds &lt;= 0: prompt("Player loses in " + str(turn_num) + " turns!", stdscr) return False elif player_funds &gt; 0: return True def compare_hands(dealer_hand, player_hand): """ Checks to see which hand is the winner returns "dealer" or "player" as a result In case of tie, returns "dealer" """ player_score = count_hand(player_hand) dealer_score = count_hand(dealer_hand) if player_score &gt; dealer_score: return "player" elif dealer_score &gt;= player_score: return "dealer" def dealer_hits(dealer_hand): """ Counts the dealer hand and returns true if under 17 """ count = count_hand(dealer_hand) if count &lt; 17: prompt("Dealer hits!", stdscr) return True else: prompt("Dealer Stays!", stdscr) return False def draw_screen(stdscr, dealer_hand, player_hand, turn_num, player_funds, dealer_flipped=False): """ Draws the entire game status on to the screen including a visual representation of the cards in play. Will be centered in final version. """ # clear screen stdscr.clear() # get dimensions wsize = stdscr.getmaxyx() display_height = 17 display_width = 36 # get the strings funds_str = str("Player Funds: " + str(player_funds)) turn_str = str("Turn Number: " + str(turn_num)) player_score_str = str("Player: " + str(count_hand(player_hand))) # dealer score string depends on whether dealer_flipped is flagged if dealer_flipped: dealer_score_str = str("Dealer: " + str(count_hand(dealer_hand))) if not dealer_flipped: flipped_dealer_hand = [] for card in range(len(dealer_hand)): if card != 0: flipped_dealer_hand.append(dealer_hand[card]) dealer_score_str = str("Dealer Visible: " + str(count_hand(flipped_dealer_hand))) # place the strings in their appropriate places dealer_str_coords = (0, 1) player_str_coords = (8, 1) funds_str_coords = (15, 1) turn_str_coords = (15, 20) stdscr.addstr(dealer_str_coords[0], dealer_str_coords[1], dealer_score_str) stdscr.addstr(player_str_coords[0], player_str_coords[1], player_score_str) stdscr.addstr(funds_str_coords[0], funds_str_coords[1], funds_str) stdscr.addstr(turn_str_coords[0], turn_str_coords[1], turn_str) # place the cards: # create lists of tuples with the x and y coords or each symbol on each card # List of lists of tuples: # Outer list = hand. # Inner list = card # Sets = (top-left suit, central value, bottom-right suit) # called with something like sym = dealer_hand_coords[0][0] for top-left symbol of first card in hand # first tuple doubles as a top-left coordinate for the blank card rects dealer_hand_coords = [[(2, 1), (4, 2), (6, 3)], [(2, 5), (4, 6), (6, 7)], [(2, 9), (4, 10), (6, 11)], [(2, 13), (4, 14), (6, 15)], [(2, 17), (4, 18), (6, 19)], [(2, 21), (4, 22), (6, 23)], [(2, 25), (4, 26), (6, 27)], [(2, 29), (4, 30), (6, 31)], [(2, 33), (4, 34), (6, 35)]] player_hand_coords = [[(9, 1), (11, 2), (13, 3)], [(9, 5), (11, 6), (13, 7)], [(9, 9), (11, 10), (13, 11)], [(9, 13), (11, 14), (13, 15)], [(9, 17), (11, 18), (13, 19)], [(9, 21), (11, 22), (13, 23)], [(9, 25), (11, 26), (13, 27)], [(9, 29), (11, 30), (13, 31)], [(9, 33), (11, 34), (13, 35)]] # NOTE: Re-Factor this into some more DRY-compliant code # NOTE: Re-Factor into multiple smaller functions that are easier for others # to follow along with! # player hand for card in range(len(player_hand)): # for each card in the hand value = player_hand[card].value suit = player_hand[card].suit if suit == "H" or suit == "D": color = colors_dict.get("RED_CARD") elif suit == "C" or suit == "S": color = colors_dict.get("BLACK_CARD") # place the blank card rect card_height = 5 card_width = 3 for cell_y in range(player_hand_coords[card][0][0], player_hand_coords[card][0][0] + card_height): for cell_x in range(player_hand_coords[card][0][1], player_hand_coords[card][0][1] + card_width): stdscr.addstr(cell_y, cell_x, " ", curses.color_pair(color)) # place the symbols # place two suit symbols and a value symbol stdscr.addstr(player_hand_coords[card][0][0], player_hand_coords[card][0][1], suit, curses.color_pair(color)) stdscr.addstr(player_hand_coords[card][1][0], player_hand_coords[card][1][1], value, curses.color_pair(color)) stdscr.addstr(player_hand_coords[card][2][0], player_hand_coords[card][2][1], suit, curses.color_pair(color)) # dealer hand if dealer_flipped: for card in range(len(dealer_hand)): # for each card in the hand value = dealer_hand[card].value suit = dealer_hand[card].suit if suit == "H" or suit == "D": color = colors_dict.get("RED_CARD") elif suit == "C" or suit == "S": color = colors_dict.get("BLACK_CARD") # place the blank card rect card_height = 5 card_width = 3 for cell_y in range(dealer_hand_coords[card][0][0], dealer_hand_coords[card][0][0] + card_height): for cell_x in range(dealer_hand_coords[card][0][1], dealer_hand_coords[card][0][1] + card_width): stdscr.addstr(cell_y, cell_x, " ", curses.color_pair(color)) # place the symbols # place two suit symbols and a value symbol stdscr.addstr(dealer_hand_coords[card][0][0], dealer_hand_coords[card][0][1], suit, curses.color_pair(color)) stdscr.addstr(dealer_hand_coords[card][1][0], dealer_hand_coords[card][1][1], value, curses.color_pair(color)) stdscr.addstr(dealer_hand_coords[card][2][0], dealer_hand_coords[card][2][1], suit, curses.color_pair(color)) if not dealer_flipped: for card in range(len(dealer_hand)): # for each card in the hand value = dealer_hand[card].value suit = dealer_hand[card].suit if suit == "H" or suit == "D": color = colors_dict.get("RED_CARD") elif suit == "C" or suit == "S": color = colors_dict.get("BLACK_CARD") # place the blank card rect card_height = 5 card_width = 3 for cell_y in range(dealer_hand_coords[card][0][0], dealer_hand_coords[card][0][0] + card_height): for cell_x in range(dealer_hand_coords[card][0][1], dealer_hand_coords[card][0][1] + card_width): stdscr.addstr(cell_y, cell_x, " ", curses.color_pair(color)) # place the symbols # place two suit symbols and a value symbol if card != 0: stdscr.addstr(dealer_hand_coords[card][0][0], dealer_hand_coords[card][0][1], suit, curses.color_pair(color)) stdscr.addstr(dealer_hand_coords[card][1][0], dealer_hand_coords[card][1][1], value, curses.color_pair(color)) stdscr.addstr(dealer_hand_coords[card][2][0], dealer_hand_coords[card][2][1], suit, curses.color_pair(color)) stdscr.refresh() def main(stdscr): try: # bet amount bet = 100 # starting funds player_funds = 1000 turn_num = 1 while game_not_over(player_funds, turn_num): # while the player has funds left to bet # generate a new deck deck = generate_deck() dealer_hand = [] player_hand = [] # draw two cards for each player draw(dealer_hand, 2, deck) draw(player_hand, 2, deck) # take the player's bet player_funds -= bet winner = None player_hitting = True while player_hitting: # while the player is deciding to hit or stay: # draw the screen with curses draw_screen(stdscr, dealer_hand, player_hand, turn_num, player_funds) if player_hits(player_hand, stdscr): # if the player chooses to hit: # draw a card draw(player_hand, 1, deck) if is_busted(player_hand): # If the player busts: # draw the screen again draw_screen(stdscr, dealer_hand, player_hand, turn_num, player_funds) # prompt that the player has busted prompt("Player Busted!", stdscr) player_hitting = False winner = "dealer" else: # end the loop if the player chooses to stay player_hitting = False if not is_busted(player_hand): # If the player has stayed and the player has not busted: dealer_hitting = True while dealer_hitting: # while the dealer is choosing to hit or stay: # draw the screen with curses draw_screen(stdscr, dealer_hand, player_hand, turn_num, player_funds, dealer_flipped=True) if dealer_hits(dealer_hand): # If the dealer chooses to hit: # dealer draws a card draw(dealer_hand, 1, deck) if is_busted(dealer_hand): # If the dealer busts: # draw the screen with curses draw_screen(stdscr, dealer_hand, player_hand, turn_num, player_funds, dealer_flipped=True) # prompt that the dealer has busted prompt("Dealer Busted!", stdscr) dealer_hitting = False winner = "player" # reward the player with double their bet player_funds += bet * 2 else: # if the dealer busts, break the loop dealer_hitting = False if not is_busted(dealer_hand): if not is_busted(player_hand): # If neither player has busted and both have stayed: # draw the screen with curses draw_screen(stdscr, dealer_hand, player_hand, turn_num, player_funds, dealer_flipped=True) # get the winning hand winner = compare_hands(dealer_hand, player_hand) # prompt the winner prompt(str(winner + " Wins!"), stdscr) if winner == "player": # if the player wins, reward them with double their bet player_funds += bet * 2 # increase turn num turn_num += 1 finally: # end curses window on error or exit curses.endwin() if __name__ == "__main__": main(stdscr) </code></pre> <p>And <a href="https://github.com/JanitorsBucket/twentyone-game" rel="nofollow noreferrer">here</a> is a link to the GitHub page, for those who want to contribute more directly.</p> <p>As ever, anyone who finds this useful is more than welcome to do whatever they want with it. I worked hard on it, but it was just a practice project. If it helps someone else, by all means go for it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T07:53:04.230", "Id": "410476", "Score": "2", "body": "While it's great that a review enabled you to improve your code, please do not update the code in your question to incorporate feedback from answers. Doing so goes against the Question + Answer style of Code Review, as it unfortunately invalidates the existing review(s). This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)* for ways to announce your new code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T08:04:23.457", "Id": "410477", "Score": "0", "body": "Aw shucks my bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T08:13:08.503", "Id": "410478", "Score": "1", "body": "Oh wow I was in the middle of re-editing it to add in the previous version before I realized a mod had already done it for me. Thank you and good looking out. The updated version can be seen on the GitHub page, where I have also added some credit to vnp. Although I only implemented the easiest of their suggestions at the moment I will be implementing more as well. Thanks for bearing with me." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T08:54:06.530", "Id": "410483", "Score": "1", "body": "Ah, sorry, I forgot to mention that I've rolled your changes back. By the way, when you work with `git`, you can also add some more information in the commit message. Just drop the `-m \"<msg>\"` from your command line (or add `--edit`). This enables you to credit commits explicitly to others. Best of luck with 21." } ]
[ { "body": "<ul>\n<li><p>You are not implementing standard (aka Las Vegas) rules. According to the standard rules, a player's hand of an Ace and a honeur forms a blackjack, and must be disclosed immediately. I am not even talking about the split and insurance rules.</p></li>\n<li><p>You don't give the player an opportunity to wrap up, collect her fortune and go home. The game continues until she is stripped off completely.</p></li>\n<li><p>I am afraid there are more monsters than you are aware of. To begin with, I don't see a clean MVC separation. A litmus test is to evaluate efforts required to port this code from <code>curses</code> to, say, <code>Tk</code>.</p>\n\n<p>Besides, <code>draw_screen</code> has no business to count hands' values, or to be concerned with the dealers' open card. This information shall be computed by the model, and passed to view in an appropriate form.</p></li>\n<li><p><code>count_hand</code> is suspiciously similar to <code>is_busted</code>. I expect</p>\n\n<pre><code>def is_busted(....):\n return count_hand(....) &gt; 21\n</code></pre></li>\n<li><p><code>count_hand</code> is also overcomplicated. Consider</p>\n\n<pre><code>def count_hand(hand):\n aces = 0\n hand_sum = 0\n for card in hand:\n if card.is_ace():\n aces += 1 # Initially count all aces as 1\n hand_sum += card.value\n # Now try to assign come aces an extra 10 points\n while aces &gt; 0 and hand_sum &lt;= 11:\n aces -= 1\n hand_sum += 10\n return hand_sum\n</code></pre>\n\n<p>Notice how having <code>card</code> itself an instance of the class helps.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T06:45:55.993", "Id": "410466", "Score": "0", "body": "Can you give an example of the MVC problem? I never considered porting it to Tk or any other display library. Draw screen counts hand values in order to display the score, and whether the dealer's card is flipped heavily influences how to draw the screen, and the player's response. Can you elaborate? Thanks for taking the time to review this but I'll benefit much more from you being more specific. I'm still a relative novice after all. As for the ruleset I wasn't trying to accurately mimic casino rules but you're right about giving the player a chance to walk away. Maybe bet adjustments too!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T06:50:22.943", "Id": "410467", "Score": "0", "body": "As for count_hand() and is_busted(), you're spot on. They're almost the same function and definitely could be combined. I also like the idea of adding an is_ace() method. Very good call. Thanks!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T09:21:01.390", "Id": "410484", "Score": "0", "body": "you may be interested to know that in the GitHub version I have implemented all of your suggestions except for the instant-blackjack. You seem to know a lot about best practices, so could I get you to expand on how I can better re-factor my draw_screen() function? I could blindly break it up into smaller functions, sure, but I get the feeling you have some specific pitfalls to share and I'm eager to soak up expert knowledge." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T06:02:56.133", "Id": "212258", "ParentId": "212249", "Score": "2" } } ]
{ "AcceptedAnswerId": "212258", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T02:03:31.247", "Id": "212249", "Score": "4", "Tags": [ "python", "python-3.x", "playing-cards", "curses" ], "Title": "Blackjack Game in Python 3/curses" }
212249
<p>I have a React component that generates a table based on an array of objects, which gets populated with data in an object.</p> <p>I'm trying to learn as much as I can about React.js / JavaScript. Could anyone with more experience in this area show me a way to simplify the code that I have here? Or if there are any other 'fancy' ways of doing what is being done in the code?</p> <p><strong>App.js</strong></p> <pre><code>import React, { Component } from 'react'; import Table from './Table'; //Columns defines table headings and properties to be placed into the body let columns = [ { heading: 'Name', property: 'name' }, { heading: 'Age', property: 'age' }, { heading: 'Sex', property: 'sex' }, { heading: 'Breed', property: 'breed' }, ] //Data is the array of objects to be placed into the table let data = [ { name: 'Sabrina', age: '6', sex: 'Female', breed: 'Staffordshire' }, { name: 'Max', age: '2', sex: 'Male', breed: 'Boxer' } ] class App extends Component { render() { return ( &lt;&gt; &lt;Table columns={columns} data={data} propertyAsKey='name' //The data property to be used as a key /&gt; &lt;/&gt; ); } } export default App; </code></pre> <p><strong>Table.js</strong></p> <pre><code>import React, { Component } from 'react'; class Table extends Component { buildTable = (columns, data, key) =&gt; { let headerRow = []; let dataRows = []; //Build the table header columns.forEach (col =&gt; { headerRow.push( &lt;th key={`header-${col.heading}`}&gt;{col.heading}&lt;/th&gt; ); }); //Build the rows data.forEach(item =&gt; { let dataCells = []; //Build cells for this row columns.forEach (col =&gt; { dataCells.push( &lt;td key={`${item[key]}-${col.property}`}&gt;{item[col.property]}&lt;/td&gt; ); }); //Push out row dataRows.push( &lt;tr key={`${item[key]}-row`}&gt;{dataCells}&lt;/tr&gt; ) }); return( &lt;&gt; &lt;thead&gt; &lt;tr&gt;{headerRow}&lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; {dataRows} &lt;/tbody&gt; &lt;/&gt; ); }; render() { const { columns, data, propertyAsKey } = this.props; return ( &lt;table className='table'&gt; {this.buildTable(columns, data, propertyAsKey)} &lt;/table&gt; ); } } export default Table; </code></pre>
[]
[ { "body": "<p>TL;DR Fully functionnal example :</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"true\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code snippet-currently-hidden\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>//Columns defines table headings and properties to be placed into the body\nconst columns = [{ heading: 'Name', property: 'name' }, { heading: 'Age', property: 'age' }, { heading: 'Sex', property: 'sex' }, { heading: 'Breed', property: 'breed' },]\n\n//Data is the array of objects to be placed into the table\nconst data = [{ name: 'Sabrina', age: '6', sex: 'Female', breed: 'Staffordshire' }, { name: 'Max', age: '2', sex: 'Male', breed: 'Boxer' }]\n\nconst App = props =&gt; &lt;Table columns={columns} data={data} propertyAsKey='name' /&gt;\n\nconst Table = ({ columns, data, propertyAsKey }) =&gt; \n &lt;table className='table'&gt;\n &lt;thead&gt;\n &lt;tr&gt;{columns.map(col =&gt; &lt;th key={`header-${col.heading}`}&gt;{col.heading}&lt;/th&gt;)}&lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n {data.map(item =&gt;\n &lt;tr key={`${item[propertyAsKey]}-row`}&gt;\n {columns.map(col =&gt; &lt;td key={`${item[propertyAsKey]}-${col.property}`}&gt;{item[col.property]}&lt;/td&gt;)}\n &lt;/tr&gt;\n )}\n &lt;/tbody&gt;\n &lt;/table&gt;\n \nReactDOM.render(&lt;App/&gt;, document.getElementById('root'))</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js\"&gt;&lt;/script&gt;\n&lt;script src=\"https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js\"&gt;&lt;/script&gt;\n&lt;div id='root'&gt;</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<hr>\n\n<p>The main thing that would highly reduce this code is the <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map\" rel=\"nofollow noreferrer\"><code>map</code></a> function. This function can be applied on an array, execute a callback on every item in the array and returns a new array.</p>\n\n<p>By using it you can reduce the following code :</p>\n\n<pre><code>let headerRow = [];\n\ncolumns.forEach(col =&gt; {\n headerRow.push(\n &lt;th key={`header-${col.heading}`}&gt;{col.heading}&lt;/th&gt;\n );\n});\n</code></pre>\n\n<p>Can be reduced to this with the exact same result :</p>\n\n<pre><code>const headerRow = columns.map(col =&gt; &lt;th key={`header-${col.heading}`}&gt;{col.heading}&lt;/th&gt;)\n</code></pre>\n\n<p>You can now include this function directly into your JSX :</p>\n\n<pre><code>&lt;thead&gt;\n &lt;tr&gt;{columns.map(col =&gt; &lt;th key={`header-${col.heading}`}&gt;{col.heading}&lt;/th&gt;)}&lt;/tr&gt;\n&lt;/thead&gt;\n</code></pre>\n\n<p>And the same thing with nested mapping for the body :</p>\n\n<pre><code>&lt;tbody&gt;\n {data.map(item =&gt; \n &lt;tr key={`${item[key]}-row`}&gt;\n {columns.map(col =&gt; &lt;td key={`${item[key]}-${col.property}`}&gt;{item[col.property]}&lt;/td&gt;)}\n &lt;/tr&gt;\n )}\n&lt;/tbody&gt;\n</code></pre>\n\n<p>Your full <code>buildTable</code> function is now reduced to the following :</p>\n\n<pre><code>buildTable = (columns, data, key) =&gt; {\n return (\n &lt;&gt;\n &lt;thead&gt;\n &lt;tr&gt;{columns.map(col =&gt; &lt;th key={`header-${col.heading}`}&gt;{col.heading}&lt;/th&gt;)}&lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n {data.map(item =&gt; \n &lt;tr key={`${item[key]}-row`}&gt;\n {columns.map(col =&gt; &lt;td key={`${item[key]}-${col.property}`}&gt;{item[col.property]}&lt;/td&gt;)}\n &lt;/tr&gt;\n )}\n &lt;/tbody&gt;\n &lt;/&gt;\n );\n};\n</code></pre>\n\n<p>If you want to go a little further you can also delete this function and embed this code in your <code>render</code> function JSX. I will also convert your component into a stateless function, since you are not using any state value :</p>\n\n<pre><code>const Table = ({ columns, data, propertyAsKey }) =&gt; //Deconstructs your props\n &lt;table className='table'&gt;\n &lt;thead&gt;\n &lt;tr&gt;{columns.map(col =&gt; &lt;th key={`header-${col.heading}`}&gt;{col.heading}&lt;/th&gt;)}&lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n {data.map(item =&gt;\n &lt;tr key={`${item[propertyAsKey]}-row`}&gt;\n {columns.map(col =&gt; &lt;td key={`${item[propertyAsKey]}-${col.property}`}&gt;{item[col.property]}&lt;/td&gt;)}\n &lt;/tr&gt;\n )}\n &lt;/tbody&gt;\n &lt;/table&gt;\n</code></pre>\n\n<p>(You may add brackets and a <code>return</code> statement after the arrow sign, its up to you)</p>\n\n<p>It is also not required to have a fragment as a parent element in your <code>render</code>, as long as there is a single element, it is fine :</p>\n\n<pre><code>class App extends React.Component {\n render() {\n return (\n &lt;Table\n columns={columns}\n data={data}\n propertyAsKey='name' //The data property to be used as a key\n /&gt;\n );\n }\n}\n</code></pre>\n\n<p>Your <code>App</code> component could also be converted to a stateless component:</p>\n\n<pre><code>const App = props =&gt; &lt;Table columns={columns} data={data} propertyAsKey='name' /&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T03:47:10.003", "Id": "411480", "Score": "1", "body": "This is perfect, thank you for showing me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T09:08:00.593", "Id": "212676", "ParentId": "212250", "Score": "2" } } ]
{ "AcceptedAnswerId": "212676", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T02:20:25.633", "Id": "212250", "Score": "2", "Tags": [ "javascript", "react.js" ], "Title": "Generating a table based on an array of objects" }
212250
<p><a href="https://stackoverflow.com/questions/54338230/on-form-inputs-focus-show-div-hide-div-on-blur-for-multiple-inputs-and-hidden">I posted a question on Stack Overflow</a> and got an answer that works but has a lot of duplicated code. In the future, the functionality may also require a third or more divs to be shown or hidden. The <a href="https://stackoverflow.com/questions/2426438/jquery-on-form-input-focus-show-div-hide-div-on-blur-with-a-caveat#answer-2427363">original script also came from a SO answer</a>.</p> <p>Can this code be refactored or improved to accommodate more than 2 inputs and hidden divs?</p> <p>When the client focuses in a text field the associated div is shown or hidden on blur.</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>//BASED OFF SO SINGULAR EXAMPLE //https://stackoverflow.com/questions/2426438/jquery-on-form-input-focus-show-div-hide-div-on-blur-with-a-caveat#answer-2427363 //CAN THESE TWO BE REFACTORED??? $('#search-markets').focus(function() { $('div.select-markets-filters').css('display', 'flex'); $(document).bind('focusin.select-markets-filters click.select-markets-filters',function(e) { if ($(e.target).closest('.select-markets-filters, #search-markets').length) return; $(document).unbind('.select-markets-filters'); $('div.select-markets-filters').slideUp(300); }); }); $('div.select-markets-filters').hide(); //CAN THESE TWO BE REFACTORED??? $('#search-symbols-instruments').focus(function() { $('div.select-symbols-instruments-filters').css('display', 'flex'); $(document).bind('focusin.select-symbols-instruments-filters click.select-symbols-instruments-filters',function(e) { if ($(e.target).closest('.select-symbols-instruments-filters, #search-symbols-instruments').length) return; $(document).unbind('.select-symbols-instruments-filters'); $('div.select-symbols-instruments-filters').slideUp(300); }); }); $('div.select-symbols-instruments-filters').hide();</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>#select-data-inputs { background-color: #000; } .select-filters { background-color: rgba(0, 0, 0, 0.8); border-top: 2px solid #fff; color: #fff; } #select-symbols { background-color: rgba(1, 56, 89, 0.85); } #select-markets { background-color: rgba(2, 104, 165, 0.85); } .filter-list li.list-inline-item { width: 48%; margin: 0; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous"&gt; &lt;div class="container-fluid"&gt; &lt;div class="row m-5 "&gt; &lt;div class="col-12 text-center"&gt; &lt;h1&gt;On form inputs focus, show div. hide div on blur for &lt;span class="text-danger"&gt;multiple inputs&lt;/span&gt; and hidden divs&lt;/h1&gt; &lt;p class="lead"&gt;&lt;i&gt;&lt;a href="https://stackoverflow.com/questions/2426438/jquery-on-form-input-focus-show-div-hide-div-on-blur-with-a-caveat" target="_blank"&gt;Based from SO sigular example&lt;/a&gt;&lt;/i&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="row"&gt; &lt;div id="select-data-inputs" class="controls form-row p-3 w-100"&gt; &lt;div class="col-4"&gt; &lt;input type="text" id="search-markets" class="input form-control" placeholder="Search Markets"&gt; &lt;/div&gt; &lt;div class="col-4 offset-1"&gt; &lt;input type="text" id="search-symbols-instruments" class="input form-control" placeholder="Search Symbols"&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="main-display"&gt; &lt;div id="select-markets" class="row select-filters select-markets-filters p-4"&gt; &lt;div class="select-heading col-12 pl-2"&gt; &lt;h6 class="small-sub-heading"&gt;Select markets&lt;/h6&gt; &lt;/div&gt; &lt;div class="col-4 pt-2 select-filter-items"&gt; &lt;ul class="filter-list list-unstyled pl-2"&gt; &lt;li class="list-inline-item"&gt; &lt;input class="form-check-input" type="checkbox" id="market-option-1" value="market-option-1"&gt; &lt;label class="form-check-label" for="market-option-1"&gt;Market Option 1&lt;/label&gt; &lt;/li&gt; &lt;li class="list-inline-item"&gt; &lt;input class="form-check-input" type="checkbox" id="market-option-2" value="market-option-2"&gt; &lt;label class="form-check-label" for="market-option-2"&gt;Market Option 2&lt;/label&gt; &lt;/li&gt; &lt;li class="list-inline-item"&gt; &lt;input class="form-check-input" type="checkbox" id="market-option-3" value="market-option-3"&gt; &lt;label class="form-check-label" for="market-option-3"&gt;Market-Option 3&lt;/label&gt; &lt;/li&gt; &lt;li class="list-inline-item"&gt; &lt;input class="form-check-input" type="checkbox" id="market-option-4" value="market-option-4"&gt; &lt;label class="form-check-label" for="market-option-4"&gt;Market-Option 4&lt;/label&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="select-symbols" class="row select-filters select-symbols-instruments-filters p-4"&gt; &lt;div class="select-heading col-4 offset-5 pl-2"&gt; &lt;h6 class="small-sub-heading"&gt;Select symbols&lt;/h6&gt; &lt;/div&gt; &lt;div class="col-4 offset-5 pt-2 select-filter-items"&gt; &lt;ul class="filter-list list-unstyled pl-2"&gt; &lt;li class="list-inline-item"&gt; &lt;input class="form-check-input" type="checkbox" id="symbol-option-1" value="symbol-option-1"&gt; &lt;label class="form-check-label" for="symbol-option-1"&gt;Symbol Option 1&lt;/label&gt; &lt;/li&gt; &lt;li class="list-inline-item"&gt; &lt;input class="form-check-input" type="checkbox" id="symbol-option-2" value="symbol-option-2"&gt; &lt;label class="form-check-label" for="symbol-option-2"&gt;Symbol Option 2&lt;/label&gt; &lt;/li&gt; &lt;li class="list-inline-item"&gt; &lt;input class="form-check-input" type="checkbox" id="symbol-option-3" value="symbol-option-3"&gt; &lt;label class="form-check-label" for="symbol-option-3"&gt;Symbol Option 3&lt;/label&gt; &lt;/li&gt; &lt;li class="list-inline-item"&gt; &lt;input class="form-check-input" type="checkbox" id="symbol-option-4" value="symbol-option-4"&gt; &lt;label class="form-check-label" for="symbol-option-4"&gt;Symbol Option 4&lt;/label&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js" integrity="sha384-pjaaA8dDz/5BgdFUPX6M/9SUZv4d12SUPF0axWc+VRZkx5xU3daN+lYb49+Ax+Tl" crossorigin="anonymous"&gt;&lt;/script&gt; </code></pre> </div> </div> </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T06:25:11.827", "Id": "410463", "Score": "0", "body": "Have you tried anything yourself? It's very easy to post someone else's code here and expect an even better version in return, but do you understand how and why it's written the way it is? That's [quite essential](https://codereview.stackexchange.com/help/on-topic)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T07:11:53.923", "Id": "410469", "Score": "0", "body": "Yes I have spent many hours researching the initial issue of showing the hidden div on focus in the text input but not hiding the div when focus is shifted (except the now displayed div). It was beyond my programming capability that was why I asked the question." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T07:42:47.503", "Id": "410474", "Score": "0", "body": "@Kerry7777 did you post the question (with the unregistered account)? If so, you can request your account be merged with the unregistered account via the **contact** link in the lower left corner of the page" } ]
[ { "body": "<p>The HTML and CSS are unchanged from your snippet (I did remove the preamble). </p>\n\n<p>The <code>appendTo</code> line ensures the newly-visible div is always last on the list of divs, which fixes a quirk of the original where the animation would look different depending on whether the new came before or after the old. </p>\n\n<p>The logic works like this:</p>\n\n<ul>\n<li>add a focus handler to the input fields which derives the info-box classname from the field's id. This handler hides all other (<code>.not(e)</code>) info-boxes and makes the current one visible.</li>\n<li>add a blur handler to those same fields, to hide on blur, unless it has the <code>inuse</code> class (see below)</li>\n<li>add a focusin / mousedown handler to the info-box container and its children, which add the <code>inuse</code> class to the clicked/focused box, preventing the blur handler above from hiding them. The focusin and mousedown events happen <em>before</em> the blur event fires on the input field.</li>\n<li>add a focus / click handler, as above, to remove the <code>inuse</code> class, which allows hiding. These come <em>after</em> the blur event, so they won't be hidden immediately -- only if you click or focus somewhere else later.</li>\n</ul>\n\n<p>So when you click on a visible info-box, the sequence is:</p>\n\n<ol>\n<li>nohide() fires; box becomes <code>inuse</code></li>\n<li>blurplus() fires; does nothing because <code>inuse</code></li>\n<li>allowhide() fires; box retains focus but loses <code>inuse</code> class, making it eligible to future hiding</li>\n</ol>\n\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 focusplus() { \n var e=$(`div.select-${ this.id.replace(/^search-/,'') }-filters`).first();\n if (!e.length) return;\n $('.row.select-filters:visible').not(e).slideUp(300);\n e.appendTo(\"#main-display\").css('display', 'flex');\n}\n\nfunction blurplus() { \n $('.row.select-filters:visible:not(.inuse)').slideUp(300);\n}\n\nfunction nohide(e) { \n $(e.target).closest('.row').addClass('inuse');\n}\n\nfunction allowhide(e) { \n $(e.target).closest('.row').removeClass('inuse');\n}\n\n$('.row.select-filters').hide()\n$(\"#main-display\")\n .on('focusin mousedown', '*', nohide)\n .on('click focus', '*', allowhide);\n\n$('#search-markets, #search-symbols-instruments').focus(focusplus).blur(blurplus);</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>#select-data-inputs {\n background-color: #000;\n}\n\n.select-filters {\n background-color: rgba(0, 0, 0, 0.8);\n border-top: 2px solid #fff;\n color: #fff;\n}\n\n#select-symbols {\n background-color: rgba(1, 56, 89, 0.85);\n}\n\n#select-markets {\n background-color: rgba(2, 104, 165, 0.85);\n}\n\n.filter-list li.list-inline-item {\n width: 48%;\n margin: 0;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>&lt;link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css\" integrity=\"sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS\" crossorigin=\"anonymous\"&gt; \n\n &lt;div class=\"container-fluid\"&gt;\n &lt;div class=\"row\"&gt;\n &lt;div id=\"select-data-inputs\" class=\"controls form-row p-3 w-100\"&gt;\n &lt;div class=\"col-4\"&gt;\n &lt;input type=\"text\" id=\"search-markets\" class=\"input form-control\" placeholder=\"Search Markets\"&gt;\n &lt;/div&gt;\n &lt;div class=\"col-4 offset-1\"&gt;\n &lt;input type=\"text\" id=\"search-symbols-instruments\" class=\"input form-control\" placeholder=\"Search Symbols\"&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"main-display\"&gt;\n &lt;div id=\"select-markets\" class=\"row select-filters select-markets-filters p-4\"&gt;\n &lt;div class=\"select-heading col-12 pl-2\"&gt;\n &lt;h6 class=\"small-sub-heading\"&gt;Select markets&lt;/h6&gt;\n &lt;/div&gt;\n &lt;div class=\"col-4 pt-2 select-filter-items\"&gt;\n &lt;ul class=\"filter-list list-unstyled pl-2\"&gt;\n &lt;li class=\"list-inline-item\"&gt; \n &lt;input class=\"form-check-input\" type=\"checkbox\" id=\"market-option-1\" value=\"market-option-1\"&gt;\n &lt;label class=\"form-check-label\" for=\"market-option-1\"&gt;Market Option 1&lt;/label&gt;\n &lt;/li&gt;\n &lt;li class=\"list-inline-item\"&gt; \n &lt;input class=\"form-check-input\" type=\"checkbox\" id=\"market-option-2\" value=\"market-option-2\"&gt;\n &lt;label class=\"form-check-label\" for=\"market-option-2\"&gt;Market Option 2&lt;/label&gt;\n &lt;/li&gt;\n &lt;li class=\"list-inline-item\"&gt; \n &lt;input class=\"form-check-input\" type=\"checkbox\" id=\"market-option-3\" value=\"market-option-3\"&gt;\n &lt;label class=\"form-check-label\" for=\"market-option-3\"&gt;Market-Option 3&lt;/label&gt;\n &lt;/li&gt;\n &lt;li class=\"list-inline-item\"&gt; \n &lt;input class=\"form-check-input\" type=\"checkbox\" id=\"market-option-4\" value=\"market-option-4\"&gt;\n &lt;label class=\"form-check-label\" for=\"market-option-4\"&gt;Market-Option 4&lt;/label&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;div id=\"select-symbols\" class=\"row select-filters select-symbols-instruments-filters p-4\"&gt;\n &lt;div class=\"select-heading col-4 offset-5 pl-2\"&gt;\n &lt;h6 class=\"small-sub-heading\"&gt;Select symbols&lt;/h6&gt;\n &lt;/div&gt;\n &lt;div class=\"col-4 offset-5 pt-2 select-filter-items\"&gt;\n &lt;ul class=\"filter-list list-unstyled pl-2\"&gt;\n &lt;li class=\"list-inline-item\"&gt; \n &lt;input class=\"form-check-input\" type=\"checkbox\" id=\"symbol-option-1\" value=\"symbol-option-1\"&gt;\n &lt;label class=\"form-check-label\" for=\"symbol-option-1\"&gt;Symbol Option 1&lt;/label&gt;\n &lt;/li&gt;\n &lt;li class=\"list-inline-item\"&gt; \n &lt;input class=\"form-check-input\" type=\"checkbox\" id=\"symbol-option-2\" value=\"symbol-option-2\"&gt;\n &lt;label class=\"form-check-label\" for=\"symbol-option-2\"&gt;Symbol Option 2&lt;/label&gt;\n &lt;/li&gt;\n &lt;li class=\"list-inline-item\"&gt; \n &lt;input class=\"form-check-input\" type=\"checkbox\" id=\"symbol-option-3\" value=\"symbol-option-3\"&gt;\n &lt;label class=\"form-check-label\" for=\"symbol-option-3\"&gt;Symbol Option 3&lt;/label&gt;\n &lt;/li&gt;\n &lt;li class=\"list-inline-item\"&gt; \n &lt;input class=\"form-check-input\" type=\"checkbox\" id=\"symbol-option-4\" value=\"symbol-option-4\"&gt;\n &lt;label class=\"form-check-label\" for=\"symbol-option-4\"&gt;Symbol Option 4&lt;/label&gt;\n &lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"&gt;&lt;/script&gt;\n &lt;script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.bundle.min.js\" integrity=\"sha384-pjaaA8dDz/5BgdFUPX6M/9SUZv4d12SUPF0axWc+VRZkx5xU3daN+lYb49+Ax+Tl\" crossorigin=\"anonymous\"&gt;&lt;/script&gt;\n </code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T06:19:16.217", "Id": "410462", "Score": "0", "body": "Wow so close! I just see one very minor (visual) defect where once either of the 'select-filters' div shows then you click on the title 'Select markets' or 'Select symbols' the div starts to collapse before the script triggers the reverse again.\nCan I also ask for you a quick rundown of how this works? I am still learning.\nThanks man." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T07:13:17.163", "Id": "410470", "Score": "0", "body": "I've made some edits to address that and to explain the sequencing and logic. If something still doesn't make sense, just ask." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T07:42:56.337", "Id": "410475", "Score": "0", "body": "Works like a charm now, +1 for the explanation. Think I will need to read it a few times. I can't see the accept answer check/tick under the up/down arrows?\nThanks again" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T15:07:53.230", "Id": "410504", "Score": "0", "body": "because your account and the posting account are not the same. Request your account be merged with the unregistered account via the contact link in the lower left corner of the page." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T04:11:01.190", "Id": "212254", "ParentId": "212253", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T03:19:17.583", "Id": "212253", "Score": "0", "Tags": [ "javascript", "performance", "jquery", "html", "form" ], "Title": "On form inputs focus, show div. hide div on blur for multiple inputs and hidden divs" }
212253
<p>I've implemented Dijkstra's algorithm to find the minimum path between two nodes.</p> <pre><code>class Node : CustomStringConvertible { // unique identifier required for each node var identifier : Int var distance : Int = Int.max var edges = [Edge]() var visited = false var description: String { return "identifier: " + identifier.description + ", Edges: " + edges.count.description } init(visited: Bool, identifier: Int, edges: [Edge]) { self.visited = visited self.identifier = identifier self.edges = edges } static func == (lhs: Node, rhs: Node) -&gt; Bool { return lhs.identifier == rhs.identifier } } class Edge { var from: Node // does not actually need to be stored! var to: Node var weight: Int var description : String { return "from: " + from.description + ", to: " + to.description } init(to: Node, from: Node, weight: Int) { self.to = to self.weight = weight self.from = from } } class Graph { var nodes: [Node] = [] } // Complete the quickestWayUp function below. func setupGraphwith(edges: [[Int]]) -&gt; Graph { let graph = Graph() // create all the nodes // The first and last node need to be included, so need nodes from "to" and "from" let nodeNames = Set ( edges.map{ $0[0] } + edges.map{ $0[1]} ) for node in nodeNames { let newNode = Node(visited: false, identifier: node, edges: []) graph.nodes.append(newNode) } // create all the edges to link the nodes for edge in edges { if let fromNode = graph.nodes.first(where: { $0.identifier == edge[0] }) { if let toNode = graph.nodes.first(where: { $0.identifier == edge[1] }) { let edge = Edge(to: toNode, from: fromNode, weight: edge[2]) fromNode.edges.append(edge) } } } return graph } func shortestPath (source: Int, destination: Int, graph: Graph) -&gt; Int { print (graph.nodes) var currentNode = graph.nodes.first{ $0.identifier == source }! currentNode.visited = true currentNode.distance = 0 var toVisit = [Node]() toVisit.append(currentNode) while ( !toVisit.isEmpty) { toVisit = toVisit.filter{ $0.identifier != currentNode.identifier } currentNode.visited = true // Go to each adjacent vertex and update the path length for connectedEdge in currentNode.edges { let dist = currentNode.distance + connectedEdge.weight if (dist &lt; connectedEdge.to.distance) { connectedEdge.to.distance = dist toVisit.append(connectedEdge.to) if (connectedEdge.to.visited == true) { connectedEdge.to.visited = false } } } currentNode.visited = true //set current node to the smallest vertex if !toVisit.isEmpty { currentNode = toVisit.min(by: { (a, b) -&gt; Bool in return a.distance &lt; b.distance })! } if (currentNode.identifier == destination) { return currentNode.distance } } return -1 } class dfsTests: XCTestCase { var simpleGraph = Graph() override func setUp() { simpleGraph = setupGraphwith(edges: [[1,2,4], [1,3,4], [3,4,3], [2,3,2], [3,5,1], [4,6,2], [5,6,3], [3,6,6] ]) } func testbfsReturnVals() { XCTAssertEqual(shortestPath(source: 1, destination: 6, graph: simpleGraph), 8 ) } } dfsTests.defaultTestSuite.run() </code></pre> <p>This is just to practice the implementation of the code, with a view to interviews. Any comments are appreciated.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-15T13:32:07.440", "Id": "425610", "Score": "0", "body": "I have been searching for this kind of simple implementation of Dijkastra's but couldn't get one. Thanks a ton to post this, it helped me!" } ]
[ { "body": "<h3>The algorithm</h3>\n\n<p>Let's first have a look at your implementation of Dijkstra's algorithm in the</p>\n\n<pre><code>func shortestPath(source: Int, destination: Int, graph: Graph) -&gt; Int\n</code></pre>\n\n<p>function:</p>\n\n<ul>\n<li><p>The <code>visited</code> property of a node is updated, but nowhere tested. As a consequence, the distance of <em>all</em> neighbors of a node is updated, not only the distance of unvisited neighbors. This does not lead to wrong results (as far as I can see) but causes unnecessary comparisons.</p></li>\n<li><p>It is unclear to me what this is for: </p>\n\n<pre><code> if (connectedEdge.to.visited == true) {\n connectedEdge.to.visited = false\n }\n</code></pre>\n\n<p>The Dijkstra algorithm does not mark nodes as unvisited, and I cannot see when the condition should be true at all.</p></li>\n<li><p>The algorithm does not work if start node and destination node are identical. This can be fixed by computing the next current node (and comparing it with the destination) at the beginning of the main loop, not at the end. This also removes the necessity to check <code>if !toVisit.isEmpty</code> twice (as the loop condition and again inside the loop).</p></li>\n<li><p>The <code>distance</code> of the initial node is set to zero twice.</p></li>\n</ul>\n\n<p>Here is a possible implementation which fixes the above issues:</p>\n\n<pre><code>func shortestPath(source: Int, destination: Int, graph: Graph) -&gt; Int {\n\n let startNode = graph.nodes.first{ $0.identifier == source }!\n startNode.distance = 0\n var toVisit = [startNode]\n\n while (!toVisit.isEmpty) {\n // Select node with smallest distance.\n let currentNode = toVisit.min(by: { (a, b) -&gt; Bool in\n return a.distance &lt; b.distance\n })!\n\n // Destination reached?\n if currentNode.identifier == destination {\n return currentNode.distance\n }\n\n // Mark as visited.\n currentNode.visited = true\n toVisit = toVisit.filter { $0.identifier != currentNode.identifier }\n\n // Update unvisited neighbors.\n for edge in currentNode.edges where !edge.to.visited {\n let neighbor = edge.to\n toVisit.append(neighbor)\n let dist = currentNode.distance + edge.weight\n if (dist &lt; neighbor.distance) {\n neighbor.distance = dist\n }\n }\n\n }\n\n // Destination not reachable.\n return -1\n}\n</code></pre>\n\n<p>There is one more issue: The <code>toVisit</code> array (which is build “on the fly” while traversing the graph) can contain duplicate elements. A possible fix is to use a <em>set</em> instead of an array. This would required the <code>Node</code> class to be <code>Hashable</code> – see below.</p>\n\n<h3>Code and design improvements</h3>\n\n<ul>\n<li><p>Your function returns <code>-1</code> if there is no path from the start to the destination node. The Swift way of returning a value or failure is to return an <em>optional,</em> where <code>nil</code> means “no result.”</p></li>\n<li><p>All properties of <code>class Edge</code> are never mutated after object creation, they should be declared as <em>constants</em> (with <code>let</code>).</p></li>\n<li><p>The <code>Node</code> initializer needs only the <code>identifier</code> – and that should be a constant property.</p></li>\n<li><p>It is not possible to compute the <code>shortestPath()</code> function multiple times (with different parameters) because it relies on the <code>visited</code> and <code>distance</code> property to be initialized.</p></li>\n<li><p>I would replace the function</p>\n\n<pre><code>func setupGraphwith(edges: [[Int]]) -&gt; Graph\n</code></pre>\n\n<p>by an initalizer of the <code>Graph</code> class, and</p>\n\n<pre><code>func shortestPath(source: Int, destination: Int, graph: Graph) -&gt; Int\n</code></pre>\n\n<p>by a method of that class:</p>\n\n<pre><code> class Graph {\n\n init(edgeList: [[Int]]) \n func distance(from: Int, to: Int) -&gt; Int?\n}\n</code></pre>\n\n<p>The usage would then be</p>\n\n<pre><code>let graph = Graph(edgeList: ...)\nlet distance = graph.distance(from: 1, to: 6)\n</code></pre></li>\n<li><p>The optional bindings in <code>setupGraphwith(edges:)</code> </p>\n\n<pre><code>if let fromNode = graph.nodes.first(where: { $0.identifier == edge[0] }) \nif let toNode = graph.nodes.first(where: { $0.identifier == edge[1] })\n</code></pre>\n\n<p>cannot fail because those nodes were all created before. Therefore a forced unwrap would be appropriate:</p>\n\n<pre><code>let fromNode = graph.nodes.first(where: { $0.identifier == edge[0] })!\nlet toNode = graph.nodes.first(where: { $0.identifier == edge[1] })!\n</code></pre>\n\n<p>An alternative would be to have a “find or create” method in the <code>Graph</code> class.</p></li>\n</ul>\n\n<h3>Performance improvements</h3>\n\n<p>At various points, <em>arrays</em> are used to store, locate, and remove nodes. Each lookup requires a traversal of the array. Using <em>sets</em> would be more efficient. That requires the <code>Node</code> class to be <code>Hashable</code>. I would base equality (and consequently, the hash value) on <em>object identity</em> instead of the numerical identifier.</p>\n\n<p>A <em>priority queue</em> would be more efficient to determine the node with the currently minimum distance.</p>\n\n<h3>Putting it all together</h3>\n\n<p>Summarizing the above suggestions (with the exception of the priority queue) the code code look like this. I have only omitted the <code>CustomStringConvertible</code> conformance for brevity.</p>\n\n<pre><code>class Node {\n\n let identifier: Int\n var distance = Int.max\n var edges = [Edge]()\n var visited = false\n\n init(identifier: Int) {\n self.identifier = identifier\n }\n}\n\nextension Node: Hashable {\n static func == (lhs: Node, rhs: Node) -&gt; Bool {\n return lhs === rhs\n }\n\n func hash(into hasher: inout Hasher) {\n hasher.combine(ObjectIdentifier(self).hashValue)\n }\n}\n\nclass Edge {\n let from: Node\n let to: Node\n let weight: Int\n\n init(to: Node, from: Node, weight: Int) {\n self.to = to\n self.from = from\n self.weight = weight\n }\n}\n\nclass Graph {\n var nodes: Set&lt;Node&gt;\n\n // Find or create node with the given identifier\n func node(identifier: Int) -&gt; Node {\n if let node = nodes.first(where: { $0.identifier == identifier }) {\n return node\n } else {\n let node = Node(identifier: identifier)\n nodes.insert(node)\n return node\n }\n }\n\n init(edgeList: [[Int]]) {\n nodes = []\n for edgeDescription in edgeList {\n let fromNode = node(identifier: edgeDescription[0])\n let toNode = node(identifier: edgeDescription[1])\n let edge = Edge(to: toNode, from: fromNode, weight: edgeDescription[2])\n fromNode.edges.append(edge)\n }\n }\n\n func distance(from: Int, to: Int) -&gt; Int? {\n guard let fromNode = nodes.first(where: { $0.identifier == from }) else {\n return nil\n }\n guard let toNode = nodes.first(where: { $0.identifier == to }) else {\n return nil\n }\n\n if fromNode == toNode { return 0 }\n\n for node in nodes {\n node.visited = false\n node.distance = Int.max\n }\n\n fromNode.distance = 0\n var toVisit = Set([fromNode])\n\n while !toVisit.isEmpty {\n // Select node with smallest distance.\n let currentNode = toVisit.min(by: { (a, b) -&gt; Bool in\n return a.distance &lt; b.distance\n })!\n\n // Destination reached?\n if currentNode == toNode { return currentNode.distance }\n\n // Mark as visited.\n currentNode.visited = true\n toVisit.remove(currentNode)\n\n // Update unvisited neighbors.\n for edge in currentNode.edges where !edge.to.visited {\n let neighbor = edge.to\n toVisit.insert(neighbor)\n let dist = currentNode.distance + edge.weight\n if (dist &lt; neighbor.distance) {\n neighbor.distance = dist\n }\n }\n }\n\n return nil\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T10:38:47.897", "Id": "411388", "Score": "0", "body": "Doesn't it feel redundant to use an `identifier` property and the instance object identifier?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-01T10:41:45.867", "Id": "411389", "Score": "0", "body": "@Carpsen90:The `identifier` property is still needed in the `Graph.init(edgeList:)` method, to map the input data (which uses node *numbers*) to the Node instances." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T21:30:26.467", "Id": "212585", "ParentId": "212260", "Score": "3" } } ]
{ "AcceptedAnswerId": "212585", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T09:03:53.587", "Id": "212260", "Score": "5", "Tags": [ "algorithm", "interview-questions", "graph", "swift" ], "Title": "Dijkstra algorithm implementation in Swift" }
212260
<p>I have a high performance, computation intensive application that runs on a Centos 7 machine with Python 2.7.5.</p> <p>I'll try to explain what the application does:</p> <ol> <li>The application runs an infinite loop, where it receives a message from an API call representing power levels of a device. The message is in Avro and encoded as a JSON string.</li> <li>Each of the devices gets a maximum of 8 separate power level readings (imagine each being a separate HW component within the device). 8 separate components constitute one device. There are a total of 50 of them. So (50 * 8) power level reports are possible.</li> <li>Each of this 8 HW devices produces a power report once per 30s. </li> <li>I have business logic to compute an arithmetic mean of the first 4 devices (component ids 1-4) and mean for the last 4 devices (ids 5-8).</li> <li><p>For a given device once I get all 8 readings received, I calculate the above mean and compare the difference between the mean of the group against the individual components, i.e. first 4 - mean_1, last 4 - mean_2. </p> <pre><code>for id in 1 2 3 4: do ( mean_1 - pwr_reading(id) ) for id in 5 6 7 8: do ( mean_2 - pwr_reading(id) ) </code></pre></li> <li><p>If the above difference is below a certain threshold, say <code>thresh_first</code> for first four and <code>thresh_last</code> for last four, I need to do an action.</p></li> </ol> <hr> <p>So to model the above requirements, I've created a device class where I'm holding this information</p> <pre><code>obj_list = {} class DevPwrInfo(object): """ The class provides an abstraction of all the processing we do at one device level """ def __init__(self, code): """ The constructor spins up a new device object initializing the identifiers and the necessary data structures needed for the evaluation """ self.code = code self.first4_pwr = {} self.last4_pwr = {} self.mean_val_first4 = "" self.mean_val_last4 = "" self.threshold_breach_list_first4 = [] self.threshold_breach_list_last4 = [] def reset_dev_info(self): """ Clear the data retained after finishing one round of report evaluation """ self.first4_pwr = {} self.last4_pwr = {} self.mean_val_first4 = "" self.mean_val_last4 = "" def add_dev_pwr(self, id, pwr, pwr_valid_flag): if 1 &lt;= int(id) &lt;= 4: if pwr_valid_flag: self.first4_pwr[id] = pwr else: self.first4_pwr[id] = 0.0 else: if pwr_valid_flag: self.last4_pwr[id] = pwr else: self.last4_pwr[id] = 0.0 if len(self.first4_pwr) == 4: self.mean_val_first4 = self.compute_mean(first4_pwr) self.compare_thresh('first4') self.first4_pwr.clear() if len(self.last4_pwr) == 4: self.last4_pwr = self.compute_mean(last4_pwr) self.compare_thresh('last4') self.last4_pwr.clear() def compute_mean(self, pwr_list): return (float(sum(pwr_list)) / max(len(pwr_list), 1)) def compare_thresh(self, type): low_thresh = thresh_dict[self.code] if type == 'first4': pwr_dict = self.first4_pwr mean_val = self.mean_val_first4 else: pwr_dict = self.last4_pwr mean_val = self.mean_val_last4 for id, pwr in pwr_dict.iteritems(): if int(math.floor(mean_val - ( pwr ))) &lt; int(low_thresh): print("Will add more logic here") def pwr_report_msg_decode(message): """ Handler for the raw idb message from the API """ if message is not None: # This API is called for each message from the API call, so that # each device's object is called by the string identifier and # 'add_dev_pwr' function will ensure the lists are updated obj_list[message['code']].add_dev_pwr( message['id'], message['pwr'], message['valid_flag']) # obj_dict is a dict of objects with key name as device name as value as the # dict object if __name__ == "__main__": # allowed_devices_list contains list of 44 device names allowed_devices_list = [ 'abc01', 'def01', 'xyz01' ] for device in allowed_devices_list: obj_list[device] = DevPwrInfo(device) while True: # An API producing message in the format msg = { "code": "abc01", "id": "3", "pwr": "-59.2", "valid_flag": "True'" } </code></pre> <p>So my question is how do I make each of the 44 objects run in parallel and not sequentially in one thread. I've looked about <code>ThreadPoolExecutor</code> but not sure how to make it computationally optimum? </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T10:40:51.707", "Id": "410488", "Score": "4", "body": "Please keep in mind that we don't provide code, we review code you've written. A review *might* suggest parallelism, but reviewers are free to review *any* part of your code." } ]
[ { "body": "<p>I'll also begin with the low hanging fruit mentioned by Mateusz Konieczny. <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>/pylint/etc. your code. It is decently formatted, but there are some issues. Before even considering optimizing performance, you should first optimize for the person reading your code. Until you've profiled and determined that you need to add complexity (because speed is an issue), programmer productivity (specifically, the ability to quickly glance at your code and understand it) is paramount.</p>\n\n<p>Also, you can often eek out a decent bit of performance by switching to Python 3. Perhaps your hardware prevents this, but it's usually a free performance win. If the math truly is this intensive, running under <code>pypy</code> might also give you a free performance boost.</p>\n\n<p>But, have you profile this code? Do benchmarks indicate that this needs to be optimized? As it exists right now, I find it unlikely that even sequentially this is unable to process 50*8 inputs every 30 seconds (that's 13 ops/sec or 75ms per op, which seems reasonable). If <code>print(\"Will add more logic here\")</code> is computationally intensive, why not just run it in a separate process instead of complicating this relatively simple API request parsing and math?</p>\n\n<p>Running the API requests in parallel could be as simple as using a <a href=\"https://docs.python.org/3.7/library/multiprocessing.html#multiprocessing.pool.Pool\" rel=\"nofollow noreferrer\"><code>multiprocessing.Pool</code></a> (you'll want to use it instead of threads because of the <a href=\"https://realpython.com/python-gil/\" rel=\"nofollow noreferrer\">GIL</a>):</p>\n\n<pre><code>with Pool() as pool:\n for msg in api_messages:\n pool.apply(pwr_report_msg_decode, msg)\n</code></pre>\n\n<p>Although, unfortunately it's not quite that simple. You'd need to make <code>obj_list</code> a shared object (between the processes), which between processes has overhead for writing/read (because you need locks). Also, your API requests may already come in from a threaded context. If you were on python 3, <a href=\"https://docs.python.org/3/library/asyncio.html\" rel=\"nofollow noreferrer\"><code>asyncio</code></a> could probably make expressing this logic a lot easier.</p>\n\n<p>To remedy the locking issue, you may try creating a separate <code>multiprocessing.Process</code> for each of the 50 things. Then you dispatch the API message to the appropriate process via a queue:</p>\n\n<pre><code>queues = [Queue() for _ in range(50)]\nprocesses = [Process(target=handle_thing_readings, args=(queue,))\n for queue in queues]\n\nfor msg in api_messages:\n queues[msg['code']].put(msg)\n\ndef handle_thing_readings(queue):\n device = DevPwrInfo()\n while True:\n msg = queue.get()\n device.add_dev_pwr(msg['id'], msg['pwr'],\n msg['valid_flag'])\n</code></pre>\n\n<p>This does require serializing <code>msg</code>, so you may want to replace the dictionary with a custom object that has <code>__slots__</code> defined. That said, there is still overhead, but this approach is likely better than locking.</p>\n\n<p>All of the run around here should make it clear such patterns aren't too well suited for Python, especially if performance really is a concern. In my opinion, something like Go is much better suited for a task like this. Thanks to channels and goroutines, you could express all of this complex parallel logic in maybe 10ish lines of Go (and it has some pretty nifty runtime tools for analyzing performance, checking for deadlocks, etc.).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T10:00:38.000", "Id": "411496", "Score": "0", "body": "50*8 / 30s is 75ms each, not 7." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T10:58:55.530", "Id": "411500", "Score": "0", "body": "@OhMyGoodness Indeed. Fixed" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T07:51:32.993", "Id": "212742", "ParentId": "212261", "Score": "1" } } ]
{ "AcceptedAnswerId": "212742", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T09:14:00.387", "Id": "212261", "Score": "2", "Tags": [ "python", "performance", "python-2.x", "statistics", "status-monitoring" ], "Title": "Application to monitor device power levels for deviations" }
212261
<p>This is just a basic accounting/banking system with the user being able to register an account, check their balance, make a withdrawal and deposit money etc. There is a few things a staff account can do also such as the removal of an account. </p> <p><strong>AccountSystem.h</strong></p> <pre><code>#pragma once #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; enum type_acc {customer, staff}; class Account { public: std::string username; std::string password; double balance; type_acc account_type; bool operator==(const Account&amp; rhs); }; class BankInterface { public: static Account loggedinaccount; static std::vector&lt;Account&gt; registered_accounts; static void LoginMenu(); static void RegisterAccount(); static void Login(); static void MainMenu(); static void DisplayBalance(); static void MakeWithdrawal(); static void MakeDeposit(); static type_acc AccountType(std::string uc); }; class StaffInterface { public: static void StaffMenu(); static void CustomerBalance(); static void AccountShutdown(); }; Account BankInterface::loggedinaccount; std::vector&lt;Account&gt; BankInterface::registered_accounts; </code></pre> <p><strong>AccountSystem.cpp</strong></p> <pre><code>// AccountSystem.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include "AccountSystem.h" void BankInterface::LoginMenu() { std::cout &lt;&lt; "Please select an option: \n 1. Register a new account. \n 2. Login to account.\n"; std::string user_choice; std::cin &gt;&gt; user_choice; if (user_choice == "1") { RegisterAccount(); } else if (user_choice == "2") { Login(); } else { std::cout &lt;&lt; "We did not recognise your input, please try again...\n"; LoginMenu(); } } type_acc BankInterface::AccountType(std::string uc) { if (uc == "y") { return staff; } else if (uc == "n") { return customer; } else { std::cout &lt;&lt; "We did not recognise your input, please try again.\n"; std::string user_choice; std::cin &gt;&gt; user_choice; return AccountType(user_choice); } } void BankInterface::RegisterAccount() { Account new_account; std::cout &lt;&lt; "Please enter the desired username of your account: \n"; std::cin &gt;&gt; new_account.username; std::cout &lt;&lt; "Please enter your desired password for your account.\n"; std::cin &gt;&gt; new_account.password; std::cout &lt;&lt; "Please enter your initial balance for your account.\n"; std::cin &gt;&gt; new_account.balance; std::cout &lt;&lt; "Are you a member of staff? y/n?\n"; std::string user_choice; std::cin &gt;&gt; user_choice; new_account.account_type = BankInterface::AccountType(user_choice); registered_accounts.push_back(new_account); std::cout &lt;&lt; "Account created.\n"; for (auto &amp;account : registered_accounts) { std::cout &lt;&lt; account.username &lt;&lt; "\n"; } LoginMenu(); } void BankInterface::Login() { std::cout &lt;&lt; "Please enter your username.\n"; std::string username; std::cin &gt;&gt; username; for (auto &amp;account : registered_accounts) { if (account.username == username) { std::cout &lt;&lt; "Please enter your password.\n"; std::string password; std::cin &gt;&gt; password; if (account.password == password) { loggedinaccount = account; if (loggedinaccount.account_type == customer) { MainMenu(); } else { StaffInterface::StaffMenu(); } } } } std::cout &lt;&lt; "That username does not exist in our system.\n"; Login(); } void BankInterface::MainMenu() { std::cout &lt;&lt; " 1. Check account balance.\n 2. Make a withdrawal.\n 3. Make a deposit. \n"; int user_choice = 0; std::cin &gt;&gt; user_choice; switch (user_choice) { case 1: DisplayBalance(); break; case 2: MakeWithdrawal(); break; case 3: MakeDeposit(); break; default: std::cout &lt;&lt; "We did not understand your input, please try again."; MainMenu(); break; } } void BankInterface::DisplayBalance() { std::cout &lt;&lt; "Your balance is: " &lt;&lt; loggedinaccount.balance &lt;&lt; "\n"; MainMenu(); } void BankInterface::MakeWithdrawal() { std::cout &lt;&lt; "Please enter the amount you wish to withdraw: \n"; double amt; std::cin &gt;&gt; amt; if (amt &gt; loggedinaccount.balance) { std::cout &lt;&lt; "You do not have this much money in your account, please input a feasible sum to withdraw. \n"; MakeWithdrawal(); } else if (amt &lt;= 0) { std::cout &lt;&lt; "You cannot withdraw a negative amount, or zero, dollars, please try again.\n"; MakeWithdrawal(); } else { loggedinaccount.balance -= amt; std::cout &lt;&lt; "Money withdrawn, new balance: " &lt;&lt; loggedinaccount.balance &lt;&lt; "\n"; MainMenu(); } } void BankInterface::MakeDeposit() { std::cout &lt;&lt; "How much money do you wish to deposit? \n"; double amt; std::cin &gt;&gt; amt; if (amt &lt;= 0) { std::cout &lt;&lt; "You cannot deposit a negative amount of, or zero, dollars. Please try again.\n"; MakeDeposit(); } else { loggedinaccount.balance += amt; std::cout &lt;&lt; "Your new balance is: " &lt;&lt; loggedinaccount.balance &lt;&lt; "\n"; MainMenu(); } } void StaffInterface::StaffMenu() { std::cout &lt;&lt; "1. View customer's balance.\n2. Shut down customer's account.\n"; int staff_choice = 0; std::cin &gt;&gt; staff_choice; switch (staff_choice) { case 1: CustomerBalance(); break; case 2: AccountShutdown(); break; default: std::cout &lt;&lt; "We did not understand your input, please try again."; StaffMenu(); break; } } void StaffInterface::CustomerBalance() { std::cout &lt;&lt; "Enter the customer's username to view their balance: \n"; std::string cust_name; std::cin &gt;&gt; cust_name; for (auto &amp;account : BankInterface::registered_accounts) { if (cust_name == account.username) { std::cout &lt;&lt; account.balance &lt;&lt; "\n"; StaffMenu(); } else { std::cout &lt;&lt; "We could not detect an account with that username, please try again.\n"; CustomerBalance(); } } } bool Account::operator==(const Account&amp; rhs) { if (username == rhs.username) { return true; } else { return false; } } void StaffInterface::AccountShutdown() { std::cout &lt;&lt; "Enter the customer's username of the account you want to delete.\n"; std::string username_del; std::cin &gt;&gt; username_del; for (auto &amp;account : BankInterface::registered_accounts) { if (username_del == account.username) { std::cout &lt;&lt; "Account detected, are you sure you wish to delete this account? y/n \n"; std::string confirmation; bool ans = false; while (ans != true) { std::cin &gt;&gt; confirmation; if (confirmation == "y") { auto pos = find(BankInterface::registered_accounts.begin(), BankInterface::registered_accounts.end(), account); BankInterface::registered_accounts.erase(pos); std::cout &lt;&lt; "Account deleted, returning to main staff menu. \n"; ans = true; StaffMenu(); } else if (confirmation == "n") { ans = true; StaffMenu(); } else { std::cout &lt;&lt; "We did not recognise that option, please try again.\n"; } } } } } int main() { BankInterface::LoginMenu(); } </code></pre> <p>Any help/tips are appreciated. </p>
[]
[ { "body": "<p>Focusing just on non-functional aspects:</p>\n\n<h3>Encapsulation</h3>\n\n<p>It is considered very bad practice to have any static fields, as you have in your <code>Account</code> class, because then you have no control over their use. You should make these fields private, and provide whatever methods are necessary to access and update them.</p>\n\n<h3>Candidate for Polymorphism</h3>\n\n<p>You appear to have two different types of accounts, one used by customers and the other used by staff. At the moment they are being differentiated by a type code, and then different methods are being called based upon the account being used. With polymorphism, you can call a single object on some type of <code>Account</code>, without caring whether it is a customer or staff account, and the method of the correct class will be invoked.</p>\n\n<h3>Endless Recursive Loops</h3>\n\n<p>If this application is left open too long, your call stack will grow indefinitely. This introduces the risk that other data, possibly in other programs, could be corrupted. Rather than calling <code>MainMenu</code> every time a user has completed an action, the method should instead return, and <code>MainMenu</code> should contain a loop.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T22:14:14.603", "Id": "410547", "Score": "0", "body": "As I have a seperate bank interface and account class, how exactly should I try to implement the encapsulation? Should I make the fields such as balance, username etc in the account class private and declare the bank interface class as a friend of the account class with interfacing methods?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T07:14:07.033", "Id": "410590", "Score": "0", "body": "You should provide methods in the `Account` class to read and write these fields as required." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T14:08:58.393", "Id": "212267", "ParentId": "212265", "Score": "5" } }, { "body": "<h3>Encapsulation</h3>\n\n<p>In your code, you are excessively abusing <code>static member</code> functions. I see why you are doing it. You have a <strong>circular dependency</strong> between <code>BankInterface</code> and <code>StaffInterface</code>. </p>\n\n<p>In order to break that dependency, you have to redesign your classes. I suggest using two main classes <code>AccountHandler</code> and <code>Display</code>. </p>\n\n<pre><code>class AccountHandler\n{\npublic:\n\n void create();\n void erase();\n auto login();\n\n void makeWithdrawal();\n void makeDeposit();\n void showBalance();\n\n auto getAccountType(std::string uc);\n\n const auto&amp; activeAccount() { return m_account; }\n const auto&amp; accounts() { return m_accounts; }\n\nprivate:\n Account m_account;\n std::vector&lt;Account&gt; m_accounts;\n};\n\nclass Display\n{\npublic:\n\n Display(AccountHandler&amp; acc_handler);\n\n void loginMenu();\n void mainMenu();\n void showCustomerBalance();\n void staffMenu();\nprivate:\n\n AccountHandler&amp; m_acc_handler;\n\n};\n</code></pre>\n\n<p><code>AccountHandler</code> is responsible for creating, deleting, etc. of accounts.\n<code>Display</code> is responsible for input &amp; output and has a dependency to <code>AccountHandler</code>.</p>\n\n<h3>enum class</h3>\n\n<p>Why you should use <strong>enum classes</strong>: <a href=\"https://stackoverflow.com/a/18335862/9226753\">https://stackoverflow.com/a/18335862/9226753</a></p>\n\n<h3>class vs. struct</h3>\n\n<p>If you only have <code>public</code> member variables, consider using <code>struct</code> vs. <code>class</code>. You should use classes if your class has to hold invariants. Following:</p>\n\n<pre><code>struct Account\n{\n enum class Type\n {\n Customer, Staff\n };\n\n std::string username;\n std::string password;\n\n Type type;\n double balance{0.0};\n};\n</code></pre>\n\n<h3>operator overloading</h3>\n\n<p>Consider implementing operator overloads as free functions. This way you set the <code>lhs</code> and <code>rhs</code> on same ground.</p>\n\n<pre><code>bool operator==(const Account&amp; lhs, const Account&amp; rhs)\n{\n return lhs.username == rhs.username;\n}\n</code></pre>\n\n<h3>DNRY</h3>\n\n<p>Do not repeat yourself. You have a lot of the same code looking similar to </p>\n\n<pre><code>std::string tmp;\nstd::cin &gt;&gt; tmp; \n</code></pre>\n\n<p>Instead, put that into a free function.</p>\n\n<pre><code>template&lt;typename T&gt;\nT readFromCin()\n{\n T tmp;\n std::cin &gt;&gt; tmp;\n return tmp;\n}\n</code></pre>\n\n<p>It is templated so you can read whatever type you want. Use it like this:</p>\n\n<pre><code>const auto number = readFromCin&lt;int&gt;();\nconst auto word = readFromCin&lt;std::string&gt;();\n</code></pre>\n\n<h3>STL algorithms</h3>\n\n<p>You are using a lot of <strong>raw <code>for</code> loops</strong> in your code. See <a href=\"https://www.youtube.com/watch?v=qH6sSOr-yk8\" rel=\"nofollow noreferrer\">here</a> why this is considered bad.</p>\n\n<p>Instead, try to use <strong>STL algorithms</strong> as much as possible. See <a href=\"https://www.youtube.com/watch?v=2olsGf6JIkU\" rel=\"nofollow noreferrer\">here</a> for a nice overview of all STL algorithms.\nThat being said, you can for example change this code</p>\n\n<pre><code>void StaffInterface::CustomerBalance() {\n std::cout &lt;&lt; \"Enter the customer's username to view their balance: \\n\";\n std::string cust_name;\n std::cin &gt;&gt; cust_name;\n\n for (auto &amp;account : BankInterface::registered_accounts) {\n if (cust_name == account.username) {\n std::cout &lt;&lt; account.balance &lt;&lt; \"\\n\";\n StaffMenu(); \n }\n else {\n std::cout &lt;&lt; \"We could not detect an account with that username, please try again.\\n\";\n CustomerBalance();\n }\n }\n}\n</code></pre>\n\n<p>to this </p>\n\n<pre><code>void Display::showCustomerBalance()\n{\n std::cout &lt;&lt; \"Enter the customer's username to view their balance: \\n\";\n const auto cust_name = readFromCin&lt;std::string&gt;();\n const auto&amp; accounts = m_acc_handler.accounts();\n auto it = std::find_if(accounts.begin(), accounts.end(), [&amp;cust_name](const auto&amp; account) {\n return cust_name == account.username;\n });\n\n if(it != accounts.end())\n {\n std::cout &lt;&lt; it-&gt;balance &lt;&lt; \"\\n\";\n staffMenu();\n }\n else {\n std::cout &lt;&lt; \"We could not detect an account with that username, please try again.\\n\";\n showCustomerBalance();\n }\n}\n</code></pre>\n\n<p>The usage of <code>std::find_if</code> might seem unnecessary here, but it makes the much more readable for other people, because every good C++ developer should know what each of the STL algorithms do.</p>\n\n<h3>const correctness</h3>\n\n<p>In your code you barely use <code>const</code>. Read <a href=\"https://stackoverflow.com/a/136917/9226753\">here</a> why this is considered good practice.</p>\n\n<h2>See adapted and working code <a href=\"https://ideone.com/1mZiVJ\" rel=\"nofollow noreferrer\">here</a></h2>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T03:04:04.903", "Id": "212507", "ParentId": "212265", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T12:11:50.300", "Id": "212265", "Score": "2", "Tags": [ "c++", "object-oriented" ], "Title": "An account/banking system in C++" }
212265
<p>I have a simple piece of code which connects to an API, does a request and gets back the raw data. After getting this data I create several objects (models) and persist them into a MongoDB database.</p> <p>Example of a model:</p> <pre><code>class Match: def __init__(self, data): self.data = data @property def match_id(self): """The Match id""" return self.data['attributes']['id'] ... </code></pre> <p>Example of API CLient</p> <pre><code>class Client: def __init__(self): self.session = requests.Session() def request(self, endpoint, params=None): response = self.session.get(endpoint, timeout=TIMEOUT, params=params) res_code = response.status_code if res_code != API_OK: exception = API_ERRORS.get(res_code) raise exception return response.json() </code></pre> <p>Example of the controller:</p> <pre><code>class Handler(Client): def __init__(self, api_key): super().__init__() self.api_key = api_key def query_match(self, match_id, shard='default'): res = [] url = f'{SHARD_URL}/{shard}/matches/{match_id}' res = self.request(url) return Match(res) </code></pre> <p>And then I have the logic for getting the data into mongoDB after calling <code>get_player</code></p> <pre><code>class BuildAndStore(Handler): def __init__(self, mongo_client, api_key): super().__init__(api_key) self.mongo_client = mongo_client self.players = list_players def process_matches(self, list_matches): ret = [] for m_i in list_matches: match = self.query_match(m_id) json_data = build_json(match) # Extracts certain class properties ret.append(json_data) mongo.insert_many('matches', ret) </code></pre> <p>Having in mind I want to start consulting the API in parallel (multiple threads or moving to async) my questions are:</p> <ul> <li>Is this pythonic? Is there a better way to do so?</li> <li>Currently the Handler does the query and the Model receives the payback data. Instead of proceeding passing the JSON data, should I do the query for each model within their own class, passing the <code>match_id</code> and inheriting from "Handler" <code>class Match(Handler):</code> ?</li> </ul>
[]
[ { "body": "<p>In the <code>request</code> method the <code>exception</code> variable really doesn't have to\nbe set before using it, just inline it and make the code more succinct:</p>\n\n<pre><code>def request(self, endpoint, params=None):\n response = self.session.get(endpoint, timeout=TIMEOUT, params=params)\n res_code = response.status_code\n if res_code != API_OK:\n raise API_ERRORS[res_code]\n return response.json()\n</code></pre>\n\n<p>Also, I'm guessing <code>API_ERRORS[res_code]</code> will also work and be more\nexpected for any reader.</p>\n\n<p>In the <code>query_match</code> method <code>res</code> doesn't have to be initialised, that's\nnot pythonic actually:</p>\n\n<pre><code>def query_match(self, match_id, shard='default'):\n url = f'{SHARD_URL}/{shard}/matches/{match_id}'\n return Match(self.request(url))\n</code></pre>\n\n<p>The <code>process_matches</code> method could be a bit simpler:</p>\n\n<pre><code>def process_matches(self, list_matches):\n ret = []\n for m_i in list_matches:\n ret.append(build_json(self.query_match(m_id)))\n mongo.insert_many('matches', ret)\n</code></pre>\n\n<p>Or, there's the option to go for a less imperative list comprehension\ntoo:</p>\n\n<pre><code>def process_matches(self, list_matches):\n ret = [build_json(self.query_match(m_id))\n for m_i in list_matches]] \n mongo.insert_many('matches', ret)\n</code></pre>\n\n<p>Regarding your second question, if I read it right, no, not a good idea\nfrom what I can tell from the code, leaving <code>Match</code> as a pure data\nobject will serve you better in the long run. It's better if the two\nresponsibilities aren't mixed. It'll also make it more clear what's\nbeing tested in your test cases if you can clearly distinguish between\nsomething that just holds the data and a API client (wrapper) that does\nnetworking (for example).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T21:20:38.987", "Id": "440559", "Score": "1", "body": "Thanks for the answer, the refactoring proposed makes total sense to me. For the second topic, I think `Match` is already a data object as it receives a raw JSON, it extracts the data which later will be used as property and all the logic/requests are being done by `Handler`, am I right?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T22:44:49.327", "Id": "440574", "Score": "0", "body": "Yes, that's what I meant, exactly." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-21T20:38:17.857", "Id": "226592", "ParentId": "212270", "Score": "0" } } ]
{ "AcceptedAnswerId": "226592", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T15:27:43.407", "Id": "212270", "Score": "2", "Tags": [ "python", "python-3.x" ], "Title": "API Client: Querying data out of an endpoint" }
212270
<p>As we all know, the syntax of allocating memory is a bit clunky in C. The recommended way is:</p> <pre><code> int *p; int n=10; p = malloc(n*sizeof *p); </code></pre> <p>You can use <code>sizeof (int)</code> instead of <code>sizeof *p</code> but it is bad practice.</p> <p>I made a solution to this with a macro:</p> <pre><code>#define ALLOC(p,n) do{ *p=malloc(n*sizeof **p); } while(0) </code></pre> <p>This get called this way:</p> <pre><code> int *p; int n=10; ALLOC(&amp;p, n); </code></pre> <p>The reason I want to pass the address of p rather than p, is to offer a bit of protection. When you call a function with <code>foo(x)</code>, then <code>foo</code> can never change the value of <code>x</code>. If you're not passing the address, the argument will not change. (Sure there are ways around that too.)</p> <p>Any comments?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T18:10:04.620", "Id": "410524", "Score": "0", "body": "Please see *[What to do when someone answers](/help/someone-answers)*. I have rolled back Rev 3 → 2." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T05:18:51.410", "Id": "410588", "Score": "4", "body": "I think the basic problem here is that your opinion of the \"clunkiness\" of C memory allocation is not shared by many experienced C programmers. (To me, it seems elegantly simple.) So by hiding what you're actually doing in a macro, you just introduce possible confusion." } ]
[ { "body": "<p>There are a couple questionable things here, first since <code>ALLOC()</code> is a macro you don't need to pass the address of <code>p</code>. If <code>ALLOC()</code> were a function call then you would want to pass the address of <code>p</code>.</p>\n\n<p>Second, for an array I would probably use <a href=\"https://en.cppreference.com/w/c/memory/calloc\" rel=\"nofollow noreferrer\">calloc()</a> rather than malloc().</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:54:22.913", "Id": "410523", "Score": "2", "body": "The reason for passing the address is to make it clear that the argument will be modified." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:17:54.657", "Id": "212275", "ParentId": "212271", "Score": "4" } }, { "body": "<p>You've taken an <em>expression statement</em> and unnecessarily made a <code>do/while</code> statement out of it. You need parentheses around your macro parameters. You don't need to pass in the pointer you're assigning to as a pointer.</p>\n\n<p>Put all that together and you end up with:</p>\n\n<pre><code>#define ALLOC(p, n) ((p) = malloc((n) * sizeof *(p)))\n</code></pre>\n\n<p>This puts fewer restrictions on how it is used, and allows things like</p>\n\n<pre><code>struct monster *AddMonsters(monster *monsters, int which_monster, int how_many)\n{\n int difficulty_add = ExtraMonsters();\n return ALLOC(monsters + which_monster, how_many + difficulty_add);\n}\n</code></pre>\n\n<p>Yes, you could use <code>monsters[which_monster]</code>, add the extra before using the macro, and put a separate <code>return</code> statement, but all that would be unnecessary restrictions on its use.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:18:13.393", "Id": "410517", "Score": "1", "body": "The do-while is just something I always do with macros. A bit redundant here, but it does not hurt. Parenthesis I forgot. Thanks for that. But I do have a good reason for passing it as a pointer. See my edit." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T23:24:20.220", "Id": "410557", "Score": "6", "body": "@Broman \"Does not hurt\"? Sure it does. You're unnecessarily making it illegal to use your macro where an expression is expected, such as with `if (ALLOC(...))`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T01:44:19.150", "Id": "410574", "Score": "1", "body": "I would prefer the do-while, personally. The body technically works as an expression, but it’s still an assignment. Those can be surprising in expression position, especially behind a macro." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:59:37.027", "Id": "212277", "ParentId": "212271", "Score": "8" } }, { "body": "<blockquote>\n <p>p = malloc(n*sizeof *p);</p>\n</blockquote>\n\n<p>This is dangerous if <code>n</code> gets large, because the multiplication could overflow. After the overflow, too little memory has been allocated but code will continue without detecting the error.</p>\n\n<p>This is especially dangerous if <code>n</code> comes from untrusted source, such as some file format or remote user. Then it gives attacker easy way to overwrite parts of memory with exploit code.</p>\n\n<p>The easy safe solution is to use <code>calloc()</code> which will detect the overflow (at least on most common libc implementations). If you really need to use <code>malloc()</code> for some reason, you can <a href=\"https://wiki.sei.cmu.edu/confluence/display/c/INT30-C.+Ensure+that+unsigned+integer+operations+do+not+wrap\" rel=\"noreferrer\">check for overflow separately</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T23:38:11.263", "Id": "410563", "Score": "0", "body": "Indeed, this is an often overlooked but very important point. I think that any `calloc` implementation that does not return a null pointer on overflow would not be conforming." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T23:43:11.730", "Id": "410565", "Score": "1", "body": "@jamesdlin Yes. Still, one should not ignore that `calloc()` has to zero the memory too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T19:56:04.810", "Id": "212285", "ParentId": "212271", "Score": "17" } }, { "body": "<p>First of all, <strong>remove the unnecessary parts</strong>, which can cause errors and make the code harder to read.</p>\n\n<pre><code>#define ALLOC(p,n) p=malloc(n*sizeof *p)\n</code></pre>\n\n<p>You can make your code more readable with <strong>describing names</strong>. After months it will be quite hard to understand even your own code.</p>\n\n<pre><code>#define ALLOC(pointer, size) pointer = malloc(size * sizeof *pointer)\n</code></pre>\n\n<p><strong>Parenthesizes are important</strong>! The following call: <code>ALLOC(pointer, size + 1);</code> would be equal with <code>pointer = malloc(size + 1 * sizeof *pointer);</code>, which clearly is a bug.</p>\n\n<pre><code>#define ALLOC(pointer, size) (pointer) = malloc((size) * sizeof(*pointer))\n</code></pre>\n\n<p>Use <code>calloc</code> instead of <code>malloc</code>, because of <strong>security</strong> reasons.</p>\n\n<pre><code>#define ALLOC(pointer, size) (pointer) = calloc((size), sizeof(*pointer))\n</code></pre>\n\n<p>Lastly, <strong>do not use function-like macros</strong>, instead a function would be a better choice.\n<a href=\"https://rules.sonarsource.com/c/tag/preprocessor/RSPEC-960\" rel=\"nofollow noreferrer\">https://rules.sonarsource.com/c/tag/preprocessor/RSPEC-960</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T12:48:49.070", "Id": "411648", "Score": "0", "body": "\"because of security reasons\" is very vague, and arguably untrue. It's certainly not enough to justify an obvious pessimisation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-04T14:38:33.223", "Id": "411659", "Score": "0", "body": "@jpa explained it quite well, so I did not went into details, but I focused on mentioning different, possible error sources." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T21:38:36.083", "Id": "425464", "Score": "0", "body": "Describing names are good, but for such a simple function as this I'd say it's abundantly clear. And I would like to use a function instead, but for my purpose, it is not possible. Besides, the link you gave does not illustrate an issue that could arise in this code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-05-13T21:54:34.713", "Id": "425465", "Score": "0", "body": "Your opinion is totally understandable, the function is simple, the code is not safety critical or anything like that. But I still recommend to use describing names and try to improve, refactor each part of your code whenever you can. You will improve by practicing it on these little functions. After months it helps a lot, even at these functions, when you look at their names and you totally understand what it is doing. I do not even mention when others have to look at your code. Remember, we read code way more times than it was wrote/refactored." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-02T17:53:28.263", "Id": "212763", "ParentId": "212271", "Score": "2" } }, { "body": "<p>Based on your question, a similar question I asked yesterday, and some of the answers, I did a version that tries to have the benefits of all of them.</p>\n\n<p>Disclaimer: Code is GCC specific (although probably works in similar compilers such as Clang).</p>\n\n<p>Usage:</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>int *p;\n\n/* Want &gt;int p[47];&lt; */\nif (mallocs(&amp;p, 47))\n goto err;\n...\nfree(p);\n</code></pre>\n\n<p>Properties:</p>\n\n<ul>\n<li>Avoid having to type <code>sizeof</code></li>\n<li>Can be used inside an <code>if</code></li>\n<li>Returns an <code>int</code> error code</li>\n<li>Check for invalid input pointer: <code>mallocs(NULL, 47) == EINVAL</code></li>\n<li>Check for negative nmemb: <code>mallocs(&amp;p, -47) == -EOVERFLOW</code> (and <code>p</code> set to <code>NULL</code>)</li>\n<li>Check for overflow due to high nmemb: <code>mallocs(&amp;p, TOO_HIGH) == EOVERFLOW</code> (and <code>p</code> set to <code>NULL</code>)</li>\n<li>Check for <code>malloc</code> error: <code>mallocs(&amp;p, 47) == ENOMEM</code> (and <code>p</code> set to <code>NULL</code>) (correct input, but malloc fails for some reson)</li>\n<li>Sets <code>errno</code> on any failure (malloc shall set errno on failure, so if this is going to be in a library, it would make sense to set errno on failure too)</li>\n<li>I don't need a pointer to a pointer given that this is a macro, but I think a user that doesn't know this would probably be happier passing a pointer to a pointer, and keep thinking it is a function :) I would have to read the code if some tells me that (what looks like) a function call modifies a pointer without a pointer to it.</li>\n<li>Prevents double evaluation of arguments</li>\n<li>Removes the possibility that someone may cast the result of malloc</li>\n</ul>\n\n<p>Code: (Edited: This code has problems; at the end of the answer is the fixed one)</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;errno.h&gt;\n#include &lt;stddef.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;stdlib.h&gt;\n\n\n/*\n * int mallocs(type **restrict p, ptrdiff_t nmemb);\n */\n#define mallocs(ptr, nmemb) ( \\\n{ \\\n ptrdiff_t nmemb_ = (nmemb); \\\n __auto_type ptr_ = (ptr); \\\n int err_; \\\n \\\n err_ = 0; \\\n if (ptr_ == NULL) { \\\n errno = EINVAL; \\\n err_ = EINVAL; \\\n goto ret_; \\\n } \\\n if (nmemb_ &lt; 0) { \\\n *ptr_ = NULL; \\\n errno = EOVERFLOW; \\\n err_ = -EOVERFLOW; \\\n goto ret_; \\\n } \\\n if (nmemb_ &gt; (PTRDIFF_MAX / (ptrdiff_t)sizeof(**ptr_)) { \\\n *ptr_ = NULL; \\\n errno = EOVERFLOW; \\\n err_ = EOVERFLOW; \\\n goto ret_; \\\n } \\\n \\\n *ptr_ = malloc(sizeof(**ptr_) * nmemb_); \\\n if (*ptr_ == NULL) \\\n err_ = ENOMEM; \\\nret_: \\\n err_; \\\n} \\\n)\n</code></pre>\n\n<p>I named it <code>mallocs</code> (<strong>malloc s</strong>afe)</p>\n\n<hr>\n\n<p><strong>EDIT:</strong></p>\n\n<p>After finding that the code above <a href=\"https://stackoverflow.com/a/56825345/6872717\">can only be called once in a function</a>, I improved it making use of an <code>inline</code>. Now there is the possibility to call the function or the macro, depending on your preferences (both can be called multiple times):</p>\n\n<pre class=\"lang-c prettyprint-override\"><code>#include &lt;errno.h&gt;\n#include &lt;stddef.h&gt;\n#include &lt;stdint.h&gt;\n#include &lt;stdlib.h&gt;\n\n\n#define mallocs(ptr, nmemb) ( \\\n{ \\\n __auto_type ptr_ = (ptr); \\\n \\\n *ptr_ = mallocarray((nmemb), sizeof(**ptr_)); \\\n \\\n !(*ptr_); \\\n} \\\n)\n\n\ninline\nvoid *mallocarray(ptrdiff_t nmemb, size_t size);\n\n\ninline\nvoid *mallocarray(ptrdiff_t nmemb, size_t size)\n{\n\n if (nmemb &lt; 0)\n goto ovf;\n if (nmemb &gt; (PTRDIFF_MAX / (ptrdiff_t)size))\n goto ovf;\n\n return malloc(size * nmemb);\novf:\n errno = EOVERFLOW;\n return NULL;\n}\n</code></pre>\n\n<p>I named <code>mallocarray()</code> after the BSD extension <a href=\"https://man.openbsd.org/reallocarray\" rel=\"nofollow noreferrer\"><code>reallocarray()</code></a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-29T00:14:48.513", "Id": "223175", "ParentId": "212271", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T15:39:51.233", "Id": "212271", "Score": "8", "Tags": [ "c", "memory-management", "macros" ], "Title": "Macro for allocation in C" }
212271
<p>I'm new to PHP OOP and I'm making some tests. I have 2 classes: <em>database</em> and <em>posts</em> and the two interact with each other.</p> <p><strong>Class Database:</strong></p> <pre><code>class Database { // defining some variables private $host; private $user; private $pass; private $bd; protected $dbh; /* method construct This method will be used everytime our class is called */ public function __construct() { $this-&gt;host = HOST; $this-&gt;user = USER; $this-&gt;pass = PASS; $this-&gt;bd = DB; // database connection $dsn = 'mysql:host=' . HOST . ';dbname=' . DB; // Set options $options = array( PDO::ATTR_PERSISTENT =&gt; true, PDO::ATTR_ERRMODE =&gt; PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES =&gt; false, PDO::ATTR_DEFAULT_FETCH_MODE =&gt; PDO::FETCH_ASSOC, PDO::MYSQL_ATTR_INIT_COMMAND =&gt; "SET NAMES utf8" ); //Create a new PDO instance try { $this-&gt;dbh = new PDO($dsn, USER, PASS, $options); return $this-&gt;dbh; } // Catch any errors catch(PDOException $e) { die($e-&gt;getMessage()); } } } </code></pre> <p><strong>Class Posts</strong></p> <pre><code>class Posts extends Database { /* FRONTEND METHODS */ // method to select all posts // uses a query predefined and an array of parameters // returns the array of results public function selectPosts($query, $params = array()) { // prepare the query to bind params $stmt = $this-&gt;dbh-&gt;prepare($query); // binds the params foreach($params as $key =&gt; $val) { if(is_string($val)) { $stmt-&gt;bindParam($key, $val, PDO::PARAM_STR); } elseif(is_numeric($val)) { $stmt-&gt;bindParam($key, $val, PDO::PARAM_INT); } } // execute query after parameters are binded $stmt-&gt;execute(); // returns the result return $stmt-&gt;fetchAll(); } // method to select a single posts // uses a query predefined and an array of parameters // returns a single row public function selectSingle($query, $params = array()) { // prepare the query to bind params $stmt = $this-&gt;dbh-&gt;prepare($query); // binds the params foreach($params as $key =&gt; $val) { if(is_string($val)) { $stmt-&gt;bindParam($key, $val, PDO::PARAM_STR); } elseif(is_numeric($val)) { $stmt-&gt;bindParam($key, $val, PDO::PARAM_INT); } } // execute query after parameters are binded $stmt-&gt;execute(); // returns the result - a single row return $stmt-&gt;fetch(); } /* BACKEND METHODS */ // insert posts into database // passes just the parameters public function insertPost($params = array()) { $uery = "INSERT INTO posts (...) VALUES (...)"; // prepare the query to bind params $stmt = $this-&gt;dbh-&gt;prepare($query); // binds the params foreach($params as $key =&gt; $val) { if(is_string($val)) { $stmt-&gt;bindParam($key, $val, PDO::PARAM_STR); } elseif(is_numeric($val)) { $stmt-&gt;bindParam($key, $val, PDO::PARAM_INT); } } // execute query after parameters are binded return $stmt-&gt;exeute() ? true : false; } // delete posts from the database // needs to get the id of the post to delete public function deletePost($id) { $query = "DELETE FROM posts WHERE id = :id"; // prepare the query to bind params $stmt = $this-&gt;dbh-&gt;prepare($query); // bind the params $stmt-&gt;bindParam(':id', $id, PDO::PARAM_INT); // executes query after params are binded return $stmt-&gt;exeute() ? true : false; } // updates a post // passes an array of parameters to bind public function updatePost($params = array()) { $query = "UPDATE posts SET ... WHERE id = :id"; // prepare the query to bind params $stmt = $this-&gt;dbh-&gt;prepare($query); // binds the params foreach($params as $key =&gt; $val) { if(is_string($val)) { $stmt-&gt;bindParam($key, $val, PDO::PARAM_STR); } elseif(is_numeric($val)) { $stmt-&gt;bindParam($key, $val, PDO::PARAM_INT); } } // execute query after parameters are binded return $stmt-&gt;exeute() ? true : false; } } </code></pre> <p>Example usage:</p> <pre><code>$posts = new Posts(); $query = "SELECT * FROM posts WHERE posts.id &gt; :n"; $params = [':n' =&gt; 6]; foreach($posts-&gt;selectPosts($query, $params) as $post) { echo $post['id']. ', '; } </code></pre> <p>Is this okay? how can I improve this? Is there a way to make the class Posts simpler (the 2 methods <code>selectPosts()</code> and <code>selectSingle()</code>? I had many more methods but I was able to simplify with these two, but now I have to pass the query and parameters. </p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T19:33:10.703", "Id": "410530", "Score": "0", "body": "Do one thing and do it well - kind of a OOP rule sometimes. Your product class does far to much, it should not be dealing with SQL. Worth reading up on the OOP design patterns, dependency injection will be useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T23:03:06.277", "Id": "410553", "Score": "0", "body": "return in constructor?" } ]
[ { "body": "<p>To tell you truth, this is not OOP at all. For the usage example like this, you don't actually need Posts class. You can do it with either raw PDO or a good Database class, to which selectPosts() and selectSingle() actually belong.</p>\n\n<p>With OOP, the usage example would be like</p>\n\n<pre><code>$posts = new Posts();\nforeach($posts-&gt;selectByIdBiggerThan(6) as $post) {\n echo $post['id']. ', ';\n}\n</code></pre>\n\n<p>so all internal workings being encapsulated in a class method. Which would look like</p>\n\n<pre><code>public function selectByIdBiggerThan($id) {\n $query = \"SELECT * FROM posts WHERE id &gt; ?\";\n return $this-&gt;db-&gt;selectAll($query, [$id]));\n}\n</code></pre>\n\n<p>and selectAll(), like it was said above, should belong to a database class, as there is <strong>absolutely nothing specific to Posts in this function</strong>. It is rather a generic function to run any query.</p>\n\n<p>You may also notice that the code in these functions is almost identical, which is directly opposite to the purpose of OOP. So you should make a generic function to run a query that can be then used to fetch the actual result</p>\n\n<pre><code>public function run($sql, $args = [])\n{\n if (!$args)\n {\n return $this-&gt;query($sql);\n }\n $stmt = $this-&gt;pdo-&gt;prepare($sql);\n $stmt-&gt;execute($args);\n return $stmt;\n}\npublic function selectAll($sql, $params = []) {\n return $this-&gt;run($sql, $params)-&gt;fetchAll();\n}\npublic function selectSingle($sql, $params = []) {\n return $this-&gt;run($sql, $params)-&gt;fetch();\n}\n</code></pre>\n\n<p>There are other issues with your database class, that are pretty common, so I recommend you to read my article, <a href=\"https://phpdelusions.net/pdo/common_mistakes\" rel=\"nofollow noreferrer\">Your first database wrapper's childhood diseases</a>, you can learn a lot from it.</p>\n\n<p>And the most global problem among them is that your Post class extends Database class. You can read in the article why it is so, and then make your Posts class accept a Database class instance as a <strong>constructor parameter</strong>, that will assign it to a class variable.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T11:40:09.453", "Id": "410600", "Score": "0", "body": "@YourCommonSence tks for your answer. My first approach was nothing like this. In posts class i had more methods, each one for a specific task. AS i said, im new to oop and im just trying to understand the concepts and all. So, my question, are you available for some ideas exchange through chat? tks" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T18:50:43.410", "Id": "212283", "ParentId": "212272", "Score": "2" } }, { "body": "<p>In the <code>insertPost()</code> method, there is this line:</p>\n\n<blockquote>\n<pre><code>$uery = \"INSERT INTO posts (...) VALUES (...)\";\n</code></pre>\n</blockquote>\n\n<p>I haven't seen a spread syntax (i.e. <code>(...)</code>) like that in MySQL/PHP SQL queries, nor do I see any code following that which replaces that spread syntax with a set of fields and values... Does that actually work or did you simplify this for the example? If it does work, I would like to see the documentation for this technique.</p>\n\n<p>That line also declares the variable as <code>$uery</code>, whereas the following line utilizes <code>$query</code>, which would thus be an undefined variable:</p>\n\n<blockquote>\n<pre><code>$stmt = $this-&gt;dbh-&gt;prepare($query);\n</code></pre>\n</blockquote>\n\n<hr>\n\n<p>The method <a href=\"http://php.net/manual/en/pdostatement.execute.php\" rel=\"nofollow noreferrer\">PDOStatement::execute()</a> returns a <a href=\"http://php.net/manual/en/language.types.boolean.php\" rel=\"nofollow noreferrer\"><code>bool</code></a>, so this last line of <code>deletePost()</code> can be simplified from :</p>\n\n<blockquote>\n<pre><code>return $stmt-&gt;exeute() ? true : false;\n</code></pre>\n</blockquote>\n\n<p>to simply: </p>\n\n<pre><code>return $stmt-&gt;exeute();\n</code></pre>\n\n<hr>\n\n<p>I see the following block of lines occur at least three times, in various methods:</p>\n\n<blockquote>\n<pre><code> // binds the params\n foreach($params as $key =&gt; $val) {\n if(is_string($val)) {\n $stmt-&gt;bindParam($key, $val, PDO::PARAM_STR);\n }\n elseif(is_numeric($val)) {\n $stmt-&gt;bindParam($key, $val, PDO::PARAM_INT);\n }\n }\n</code></pre>\n</blockquote>\n\n<p>That could easily be abstracted out into a separate method. </p>\n\n<p>What happens if the parameter isn't a string and isn't numeric? should an error be thrown (actually it would likely might happen at the SQL level if that is the case).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:57:58.267", "Id": "212410", "ParentId": "212272", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:02:20.037", "Id": "212272", "Score": "2", "Tags": [ "php", "object-oriented", "sql", "pdo" ], "Title": "ORM class for Posts" }
212272
<p>Is there a way to make this code run faster? I have over 6000 pictures in .jpg optimized to a maximum of 40 kB. It starts quickly but after like 2000 pictures it runs way slower. The final .xlsm file is about 380 MB.</p> <p>I'm using Excel 2016 with Windows 10 on a big server with 16 processors and 80 GiB RAM.</p> <pre><code>Sub Button5_Click() With Excel.Application .Calculation = xlCalculationManual .ScreenUpdating = False .DisplayStatusBar = False .EnableEvents = False End With With Worksheets DisplayPageBreaks = False End With ChargeTrombinoscope With Excel.Application .EnableEvents = True .DisplayStatusBar = True .ScreenUpdating = True .Calculation = xlCalculationAutomatic End With With Worksheets DisplayPageBreaks = True End With ''''CheckImageName End Sub Sub ChargeTrombinoscope() Dim Chemin As String, Fichier As String Dim nom, nom As String Dim splitArr() As String Dim Ligne As Integer Dim Largeur As Integer Dim Hauteur As Integer Dim h As Long, Rapport As Single Const hDefaut = 97 Worksheets("Pix").Activate 'Définit le répertoire contenant les fichiers Chemin = "C:\IMAGES\" 'Boucle sur tous les fichiers du répertoire (photos). Ligne = 3 Columns("K:K").ColumnWidth = 40 ' défini la largeur de la colonne Columns("H:H").ClearContents Columns("I:I").ClearContents For Each Sh In ActiveSheet.Shapes If Sh.Type = msoPicture Then 'msoPicture Then Sh.Delete End If Next Sh Fichier = Dir(Chemin &amp; "*") Do While Len(Fichier) &gt; 0 'Extraction nom splitArr = Split(Fichier, ".") nom = splitArr(0) Range("H" &amp; Ligne).Value = CStr(nom) Range("H" &amp; Ligne).NumberFormat = "@" Range("I" &amp; Ligne) = "a" &amp; Range("H" &amp; Ligne) ''' pour corriger le bogue des noms numériques 'insertion de la photo dans la colonne K Range("K" &amp; Ligne).Select '' Largeur = Range("K" &amp; Ligne).Width '' Hauteur = Range("K" &amp; Ligne).Height ActiveCell.RowHeight = 99 ' ajuste la hauteur de la ligne : 1 point = 0,035 cm h = hDefaut h = h - 4 ActiveSheet.Shapes.AddPicture(Chemin &amp; Fichier, False, True, ActiveCell.Left, ActiveCell.Top, Largeur, Hauteur).Select With Selection.ShapeRange Rapport = h / Selection.Height AjusterImage Selection, Rapport .Name = Range("I" &amp; Ligne) End With 'Fichier suivant Fichier = Dir() Ligne = Ligne + 1 Loop Range("H3").Select With Worksheets("Pix") DerLig = .Range("H" &amp; Rows.Count).End(xlUp).Row ActiveWorkbook.Names("PicTable").Delete ActiveWorkbook.Names.Add Name:="PicTable", RefersTo:="=Pix!$H$2:$H$" &amp; DerLig End With End Sub Function AjusterImage(Imag As Object, Rapport As Single) Dim Largeur As Single Dim Hauteur As Single Largeur = Imag.Width Hauteur = Imag.Height Largeur = Largeur * Rapport Hauteur = Hauteur * Rapport Imag.Width = Largeur Imag.Height = Hauteur End Function </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T04:50:45.723", "Id": "410585", "Score": "1", "body": "how does it run with resizing disabled? If that makes it fast, you could prepare the catalog images with ImageMagick or another tool that is optimized for bulk image handling. If it's still too slow, try removing the call to `AddPicture()`. If that solves it, it may simply be that Excel is the wrong tool for this job." } ]
[ { "body": "<p>Avoid Selecting of Activating Object unless absolutely necessary <a href=\"https://www.youtube.com//watch?v=c8reU-H1PKQ&amp;index=5&amp;list=PLNIs-AWhQzckr8Dgmgb3akx_gFMnpxTN5\" rel=\"nofollow noreferrer\">Excel VBA Introduction Part 5 - Selecting Cells (Range, Cells, Activecell, End, Offset)</a>. </p>\n\n<p>Writing an array of values to a worksheet is much faster than writing the values individually.</p>\n\n<p>The Worksheet.Pictures method returns a collection of pictures on the worksheet.<br>\nYou can get a subset of pictures by passing an Array of Indices as a parameter to the Worksheet.Pictures method:</p>\n\n<blockquote>\n<pre><code> ActiveSheet.Pictures(Array(1,2,30))\n</code></pre>\n</blockquote>\n\n<p>Or an Array of names:</p>\n\n<blockquote>\n<pre><code> ActiveSheet.Pictures(Array(\"Picture 1\",\"Picture 2\",\"Picture 3\"))\n</code></pre>\n</blockquote>\n\n<p>You can also work on the whole collection or subset at once:</p>\n\n<blockquote>\n<pre><code> ActiveSheet.Pictures.Delete\n</code></pre>\n</blockquote>\n\n<p>Formatting a range of cells is much faster than formatting each cell in a range.</p>\n\n<blockquote>\n<pre><code>Columns(\"H:I\").ClearContents\nColumns(\"H\").NumberFormat = \"@\"\n</code></pre>\n</blockquote>\n\n<p>Short compact code is much easier to read.</p>\n\n<p>Which is easier to read?</p>\n\n<hr>\n\n<blockquote>\n<pre><code>h = hDefaut\nh = h - 4\n</code></pre>\n</blockquote>\n\n<p>Or</p>\n\n<blockquote>\n<pre><code> h = hDefaut - 4\n</code></pre>\n</blockquote>\n\n<hr>\n\n<blockquote>\n<pre><code>Largeur = Imag.Width\nHauteur = Imag.Height\nLargeur = Largeur * Rapport\nHauteur = Hauteur * Rapport\nImag.Width = Largeur\nImag.Height = Hauteur\n</code></pre>\n</blockquote>\n\n<p>Or </p>\n\n<blockquote>\n<pre><code>Largeur = Imag.Width * Rapport\nHauteur = Imag.Height * Rapport\n</code></pre>\n</blockquote>\n\n<hr>\n\n<blockquote>\n<pre><code>With Worksheets(\"Pix\")\n DerLig = .Range(\"H\" &amp; Rows.Count).End(xlUp).Row\n ActiveWorkbook.Names(\"PicTable\").Delete\n ActiveWorkbook.Names.Add Name:=\"PicTable\", RefersTo:=\"=Pix!$H$2:$H$\" &amp; DerLig\nEnd With\n</code></pre>\n</blockquote>\n\n<p>The code above can be simplified:</p>\n\n<blockquote>\n<pre><code>With Worksheets(\"Pix\")\n .Range(\"H2\",.Range(\"H\" &amp; Rows.Count).End(xlUp)).Name = \"PicTable\"\nEnd With\n</code></pre>\n</blockquote>\n\n<p>MS Access is better suited for this type of thing. I personally would create a webpage. Whether I used Excel or a webpage I would create a paginator and avoid embedding the images. </p>\n\n<p>I refactored your code here: <a href=\"https://drive.google.com/file/d/1Pcso9HcoZUwoSU_rhRmdW0jsbGmRgfzR/view?usp=sharing\" rel=\"nofollow noreferrer\">Making a catalog of pictures.xlsm</a>. Note: I didn't make the <code>Rapport</code> size adjustments but it should be easy enough for you to implement it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T18:34:06.770", "Id": "212412", "ParentId": "212274", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:12:34.557", "Id": "212274", "Score": "2", "Tags": [ "performance", "vba", "excel", "image", "file-system" ], "Title": "Making a catalog of pictures" }
212274
<p>My Python program parses songs from a website, corrects song titles and artists with the Last.fm API, searches for the spotify uri using the Spotify API, stores all the information in a SQLite database and then uploads it into a Spotify playlist with the Spotify API.</p> <p>I would like to make the program object oriented and need some advice on how to do that. Some general python advice would also be useful.</p> <p>I have a separate config.py file with all the needed API variables.</p> <p><strong>scraper.py</strong></p> <pre><code># -*- coding: utf-8 -*- # import config file import config # import libraries from bs4 import BeautifulSoup import datetime import urllib.request as urllib import sys import time import re import sqlite3 # webdriver libraries from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By # spotipy library import spotipy import spotipy.util as util # import pylast import pylast # song class holds information about each song class Song: artist = None song = None spotify_uri = None def __init__(self, artist, song, spotify_uri): self.artist = artist self.song = song self.spotify_uri = spotify_uri def printSong(self): print(self.artist, '-', self.song, ', Uri:', self.spotify_uri) ##------------------------------------------------------------------------------ ## Get Date of latest sunday ## ## @return formatted date of last sunday as yyyymmdd # def getSundayDate(): today = datetime.date.today() sun_offset = (today.weekday() - 6) % 7 sunday_of_week = today - datetime.timedelta(days=sun_offset) sunday_date = sunday_of_week.strftime('%Y%m%d') return sunday_date ##------------------------------------------------------------------------------ ## URL Pattern ## ## https://fm4.orf.at/player/20190120/SSU ## URL pattern: ## /yyyymmdd/SSU ## /20190120/SSU ## SSU is just Sunny Side Up the show from 10am till 1pm ## URL pattern changes ever day, we need to change it every week, ## to only get sundays ## ## @return concatenated URL of website def getURLPattern(): return 'https://fm4.orf.at/player/' + getSundayDate() + '/SSU' ##------------------------------------------------------------------------------ ## Get html source from page specified by page_url ## ## @return html source as beautiful soup object # def getHtmlFromPage(): page_URL = getURLPattern() options = Options() options.headless = True profile = webdriver.FirefoxProfile() profile.set_preference("media.volume_scale", "0.0") driver = webdriver.Firefox(options=options, firefox_profile=profile) driver.get(page_URL) wait = WebDriverWait(driver, 3) wait.until(EC.presence_of_element_located((By.CLASS_NAME, 'broadcast-items-list'))) time.sleep(1) soup = BeautifulSoup(driver.page_source, "html.parser") driver.quit() return soup ##------------------------------------------------------------------------------ ## remove bad characters from list ## ## @param list, list with elements to check # def sanitize(strList): regex_remove = r'([^A-z\s\däöüÄÖÜß-][\\\^]?)' regex_ft = r'(ft\.?([^\n]\s?\w*)+)' # check for bad characters for i in range(len(strList)): strList[i] = re.sub(regex_remove, "", str(strList[i])) strList[i] = re.sub(regex_ft, "", strList[i]) ##------------------------------------------------------------------------------ ## print music ## ## @param lists to print # def printMusic(interpreter_list, title_list): for element in range(len(interpreter_list)): print(interpreter_list[element] + " : " + title_list[element]) ##------------------------------------------------------------------------------ ## parse html ## ## @param lists to write results to # def parseHtml(interpreter_list, title_list): soup = getHtmlFromPage() # find all interpreter in playlist interpreter = soup.find_all("div", {"class": "interpreter"}) # find all titles in playlist title = soup.find_all("div", {"class": "title"}) # Check for errors if (len(interpreter) != len(title)): raise Exception("The amount of interpreters don't correspond" + "to the amount of titles.") if (len(interpreter) == 0): raise Exception("No FM4 music playlist found in given url") for element in range(len(interpreter)): interpreter_list.append(interpreter[element].text) title_list.append(title[element].text) ##------------------------------------------------------------------------------ ## create Token with given credentials ## ## @return authentication token # def getToken(): # authetication token token = util.prompt_for_user_token(config.USERNAME, config.SCOPE, config.CLIENT_ID, config.CLIENT_SECRET, config.REDIRECT_URI) if token: return token else: raise Exception("Could not get authentication token from spotify!") ##------------------------------------------------------------------------------ ## search track and get spotify uri ## ## @param token, authentication token ## @param interpreter &amp;&amp; title, strings containing track info ## @return uri string # def getUri(spotify_Obj, interpreter, title): result = spotify_Obj.search(q=interpreter + ' ' + title) if (result != None): if (len(result['tracks']['items']) != 0): track_id = result['tracks']['items'][0]['uri'] uri = str(track_id) return uri ##------------------------------------------------------------------------------ ## correct artist name and track title with lastFm api ## ## @param1 artist_name, name of artist to correct ## @param2 title_name, title name to correct ## @return track_corrected, corrected Track object # def getTrackInfo(artist_name, track_name): # network authentication last_Fm = getLastFmNetworkAuth() # declare artist_name as artist object artist = last_Fm.get_artist(artist_name) # correct artist name artist_corrected_name = artist.get_correction() track = last_Fm.get_track(artist_corrected_name, track_name) track_corrected_name = track.get_correction() trackInfo = pylast.Track(artist_corrected_name, track_corrected_name, last_Fm) return trackInfo ##------------------------------------------------------------------------------ ## get last fm network authentication ## ## @return network authentication token # def getLastFmNetworkAuth(): network = pylast.LastFMNetwork(config.LASTFM_API_KEY, config.LASTFM_API_SECRET) return network ##------------------------------------------------------------------------------ ## parse music items from website, put them into a list, sanitize lists, ## correct artist names and song titles with last.fm API and save list in a ## sqlite database for further usage ## ## @return network authentication token # def parseTracksIntoSongClassList(song_list): # lists containing the Interpreter and title interpreter_list = [] title_list = [] # fill lists with results parseHtml(interpreter_list, title_list) print(datetime.datetime.now(), "Done parsing html") # remove bad characters from lists sanitize(interpreter_list) sanitize(title_list) # get Token and create spotify object sp = spotipy.Spotify(getToken()) # correct artist and title names for element in range(len(interpreter_list)): track_info = getTrackInfo(interpreter_list[element], title_list[element]) title = str(track_info.get_name()) artist = str(track_info.get_artist()) if (title != artist): if (title is not None): title_list[element] = title if (artist is not None): interpreter_list[element] = artist else: title_list[element] = title_list[element] interpreter_list[element] = interpreter_list[element] # get spotify uri for song spotify_uri = getUri(sp, interpreter_list[element], title_list[element]) if (spotify_uri != None and len(spotify_uri) != 0): track_uri = str(spotify_uri) song_list.append(Song(interpreter_list[element], title_list[element], track_uri)) print(datetime.datetime.now(), "Done parsing songs") ##------------------------------------------------------------------------------ ## insert new songs to database, checks for duplicates and ignores them ## ## @param song_list, list containing songs which need to be inserted ## into database # def updateDatabase(song_list): conn = sqlite3.connect('SongDatabase.db') c = conn.cursor() # date to insert into table today = datetime.date.today() today.strftime('%Y-%m-%d') c.execute('''CREATE TABLE IF NOT EXISTS songs (SongID INTEGER PRIMARY KEY, artist_name TEXT, song_name TEXT, spotify_uri TEXT, UploadDate TIMESTAMP, Uploaded INTEGER, UNIQUE(artist_name, song_name, spotify_uri) ON CONFLICT IGNORE)''') for item in range(len(song_list)): c.execute('''INSERT INTO songs (artist_name, song_name, spotify_uri, UploadDate, Uploaded) VALUES (?,?,?,?,?)''', (song_list[item].artist, song_list[item].song, song_list[item].spotify_uri, today, 0)) conn.commit() c.close() print(datetime.datetime.now(), "Done updating Database") ##------------------------------------------------------------------------------ ## copy Uris from song_list into new list ## ## @param song_list, list containing songs which get copied into new list ## @return track_list, list containing all song uris # def getUrisList(song_list): uri_list = [] for song in range(len(song_list)): uri_list.append(song_list[song].spotify_uri) print(uri_list) return uri_list ##------------------------------------------------------------------------------ ## Main part of the program ## get html and parse important parts into file # if __name__ == '__main__': # list to fill with corrected songs song_list = [] # parse songs into song_list parseTracksIntoSongClassList(song_list) # insert song_list into database updateDatabase(song_list) </code></pre> <p><strong>dataManager.py</strong></p> <pre><code># -*- coding: utf-8 -*- # import config file import config import sqlite3 import pandas as pd # spotipy library import spotipy import spotipy.util as util ##------------------------------------------------------------------------------ ## create Token with given credentials ## ## @return authentication token # def getToken(): # authetication token token = util.prompt_for_user_token(config.USERNAME, config.SCOPE, config.CLIENT_ID, config.CLIENT_SECRET, config.REDIRECT_URI) return token ##------------------------------------------------------------------------------ ## insert new songs to database, checks for duplicates and ignores them ## ## @param song_list, list containing songs to be inserted into database # def uploadSongsToSpotify(): # declare db name database_name = 'SongDatabase.db' # spotify auth token sp = spotipy.Spotify(getToken()) if sp: # spotify username username = config.USERNAME # spotify ide of playlist playlist_id = config.PLAYLIST_ID conn = sqlite3.connect(database_name) c = conn.cursor() c.execute("""SELECT spotify_uri FROM songs WHERE (Uploaded = 0)""") # save query results in tuple data = c.fetchall() # save uris in list, for spotipy uri_list = [] for item in range(len(data)): uri_list.append(str(data[item][0])) print(uri_list) # upload uri_list to spotify # check for empty list if (len(uri_list) != 0): sp.user_playlist_add_tracks(username, playlist_id, uri_list) # set Uploaded values in database to 1 c.execute("""UPDATE songs SET Uploaded = ? WHERE Uploaded = ?""", (1, 0)) conn.commit() else: raise Exception("There aren't any new songs in database, songs were already uploaded") c.close() else: raise Exception("Could not get token from spotify API") if __name__ == '__main__': uploadSongsToSpotify() </code></pre>
[]
[ { "body": "<p>Some simple suggestions after a first look at <code>scraper.py</code>:</p>\n\n<ol>\n<li><p><code>class Song</code> defines a method called <code>printSong</code>. Don't do this. Instead, use the dundermethod <code>__str__</code> (and maybe <code>__repr__</code>) to define a mechanism to \"stringify\" the song, and then let the normal <code>print</code> function handle it:</p>\n\n<p>print(str(song)) # or ...\nprint(repr(song))</p></li>\n<li><p>Your <code>getSundayDate</code> computes the date of the appropriate Sunday, then returns it as a string. Instead, return the date object. Let the caller handle formatting the string, since the caller is <code>getUrlPattern</code> which does nothing but format strings...</p></li>\n<li><p>Throughout your code you have these giant banner comments introducing your functions. Get rid of them, and put the descriptive text inside a docblock comment. This is why docblocks exist in Python:</p>\n\n<p><strong>No!</strong></p>\n\n<pre><code>##------------------------------------------------------------------------------\n## remove bad characters from list \n## \n## @param list, list with elements to check\n#\ndef sanitize(strList):\n</code></pre>\n\n<p><strong>Yes.</strong> </p>\n\n<pre><code>def sanitize(strList):\n \"\"\"Remove bad characters from list.\n\n @param strList, list with elements to check.\n \"\"\"\n</code></pre></li>\n<li><p>Don't raise <code>Exception</code> objects. Class <code>Exception</code> is the base class of the standard error types. If you have to install a block to catch what you're raising, you are going to have to do <code>except Exception:</code> or maybe just <code>except:</code>, and that's no good. Either create your own exception class, like <code>class SongException(Exception): ;pass</code> or use the standard types (<code>IndexError</code>, <code>ValueError</code>, and <code>TypeError</code> for the most part).</p></li>\n<li><p>In <code>parseHtml</code> you do this:</p>\n\n<pre><code>for element in range(len(interpreter)):\n interpreter_list.append(interpreter[element].text)\n title_list.append(title[element].text)\n</code></pre>\n\n<p>Written like a true Java programmer! But this isn't Java. So watch this video first: <a href=\"https://youtu.be/EnSu9hHGq5o\" rel=\"nofollow noreferrer\">Loop Like a Native</a> by Ned Batchelder. There are a couple of ways to rewrite this loop. You could zip the two source lists together, unpack them into a tuple, and operate on them:</p>\n\n<pre><code>for interp, elt in zip(interpreter, element):\n interpreter_list.append(interp.text)\n element_list.append(elt.text)\n</code></pre>\n\n<p>Or you could use a comprehension to iterate over each list separately to generate the text values, and use the <code>list.extend</code> method to implicitly <code>.append</code> each element of a sequence:</p>\n\n<pre><code>interpreter_list.extend((elt.text for elt in interpreter))\nelement_list.extend((elt.text for elt in element))\n</code></pre>\n\n<p>Have some of this Python-flavored Cool-aid! It's quite delicious... ;-)</p></li>\n<li><p>You define <code>getToken</code> in both source files. I'm not sure what that's about...</p></li>\n</ol>\n\n<p>Looking at your <code>dataManager.py</code> file, it's quite short. I'd suggest that you just roll both files into a single source file.</p>\n\n<p>Your post title asks how you can make your code more object-oriented. I don't think you need to do that, and I don't think you should try. You are writing a program that is very procedural: do this, then do that, next do the other, and finally store things here. That's not a good match for OO code, especially since the elements in question are all different. I encourage you to focus on using simple functions to ensure that you have good separation of concerns and encapsulation. I would also suggest visiting the documentation for Python's \"magic methods\" (aka dundermethods), and sitting through the Batchelder video I linked. There's a huge amount of Python mastery in that one 30-minute presentation.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T16:01:42.030", "Id": "410631", "Score": "0", "body": "thanks for the tips, really appreciate the help" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:49:56.487", "Id": "212280", "ParentId": "212276", "Score": "4" } } ]
{ "AcceptedAnswerId": "212280", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T16:43:32.123", "Id": "212276", "Score": "4", "Tags": [ "python", "object-oriented", "python-3.x", "sqlite", "selenium" ], "Title": "Uploading songs from website to database and then to Spotify" }
212276
<p>The purpose of this was to practice web scraping, regex and GUI. I use a popular bitcoin website to scrape the names and prices of the top 16 cryptocurrencies. I then create a data frame and make a GUI to display the information based on the user's selection. I am looking for any and all input on how to improve this code. </p> <pre><code>import bs4 from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup import pandas as pd my_url = 'https://coinmarketcap.com/' uClient = uReq(my_url) page_html = uClient.read() uClient.close() page_soup = soup(page_html, "html.parser") containers = page_soup.find("div", {"class": "container main-section"}) tabes = containers.find("table", {"id": "currencies"}) table_names= tabes.find("tbody") btc = table_names.find_all("tr") #Get the names and prices of the first 16 crypto coins prices = [] names = [] for i in range(16): x = btc[i] #find the price x.find("a", {"class": "price"}).text current_price = x.find("a", {"class": "price"}).text.strip() prices.append(current_price) #find the name of the crypto name = x.find("td", {"class": "no-wrap currency-name"}) q = name.text.strip() coin_name = " ".join(q.split("\n")) names.append(coin_name) #Make a dataframe with the information we have gathered df = pd.DataFrame({'Name': names, 'Price': prices, }) #Use regular expressions to create a column with just the symbol import re symbols = [] for i in df['Name']: symbols.append(re.search(r"[A-Z]{3,5}\s\s", i).group().split()[0]) df['Symbol'] = symbols #GUI from tkinter import * root = Tk() root.title('BTC Price Check') root.geometry('{}x{}'.format(950, 550)) frame = Frame(root,relief= GROOVE) frame.pack(side = BOTTOM) class CheckBox(Checkbutton): boxes = [] # Storage for all buttons def __init__(self, master=None, **options): Checkbutton.__init__(self, frame, options) self.boxes.append(self) self.var = IntVar() self.configure(variable=self.var) header = Label(height=1, width=100, text = "Welcome to BTC Price Check") header.config(font=("Courier", 20)) header.pack(side = TOP, pady = 0) text = Text(frame) text.pack(padx = 20, pady = 0, side = RIGHT) #fucntions for our buttons def display_price(): for c, box in enumerate(CheckBox.boxes): if box.var.get(): text.insert(INSERT, "The price of " + names[c] + " is: " + prices[c]) text.insert(INSERT, "\n") text.config(state=DISABLED) def clearBox(): text.config(state=NORMAL) text.delete("1.0", "end") #Use the class we created to iterate through the 16 cryptos and create a checkbox for each a=0 while a&lt;len(df['Name']): bouton=CheckBox(text = names[a],bg = 'yellow') a=a+1 bouton.pack(fill = Y, pady = 2, side = TOP) #Buttons pricefind = Button(frame, text = 'Search',width= 20, command = display_price) pricefind.pack() clearprice = Button(frame, text = 'Clear', width= 20, command = clearBox) clearprice.pack() mainloop() </code></pre>
[]
[ { "body": "<h2>Group your imports</h2>\n\n<p>You should put all of your imports at the top of the file instead of sprinkling them throughout the code. This is both a best practice and a recommendation from <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a></p>\n\n<h2>Don't use wildcard imports</h2>\n\n<p>You import Tkinter with <code>from tkinter import *</code>, but the <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a> guidelines (and best practices) say you should not. For me, the best way to import Tkinter is with <code>import tkinter as tk</code> because it avoids polluting the global namespace and gives you a short prefix for using Tkinter classes and objects. The prefix helps to make your code a bit more self-documenting.</p>\n\n<h2>Use more functions and classes</h2>\n\n<p>Most of your code exists in the global namespace. While that's fine for short programs, it becomes difficult to manage as the program grows. Its good to get in the habit of always using functions or classes for nearly all of your code.</p>\n\n<p>For example, I recommend putting all of the GUI code into a class. That will make the code a bit easier to read, and gives you the flexibility of moving the code to a separate file.</p>\n\n<h2>clearBox should restore the state of the text widget</h2>\n\n<p>Your <code>clearBox</code> function resets the state of the text widget to be editable so that it can clear the contents, but it doesn't set it back. That means that after clicking the clear button, the user could be able to type anything they want in that window. It's somewhat harmless, but is a bit sloppy.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T22:42:27.007", "Id": "212290", "ParentId": "212281", "Score": "1" } } ]
{ "AcceptedAnswerId": "212290", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T17:52:50.173", "Id": "212281", "Score": "1", "Tags": [ "python", "python-3.x", "web-scraping", "pandas", "tkinter" ], "Title": "BTC price checker with web scraping, regex and Tkinter GUI" }
212281
<p>I wrote classes to model a playing card, a deck, and a player to be used in multiple playing card games. I originally posted a <code>Card</code> class <a href="https://codereview.stackexchange.com/questions/212172/playing-card-object">here</a>, and now extended the project by adding a deck and player class and am really looking for some feedback. This is my first real object oriented design project and I feel unsure about the current way the deck and player classes are implemented.</p> <pre><code>class Card(object): """Models a playing card, each Card object will have a suit, rank, and weight associated with each. possible_suits -- List of possible suits a card object can have possible_ranks -- List of possible ranks a card object can have Suit and rank weights are initialized by position in list. If card parameters are outside of expected values, card becomes joker with zero weight """ possible_suits = ["Clubs", "Hearts", "Diamonds", "Spades"] possible_ranks = [2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K", "A"] def __init__(self, suit, rank): if suit in Card.possible_suits and rank in Card.possible_ranks: self.suit = suit self.rank = rank self.suit_weight = Card.possible_suits.index(suit) self.rank_weight = Card.possible_ranks.index(rank) else: self.suit = "Joker" self.rank = "J" self.suit_weight = 0 self.rank_weight = 0 def __str__(self): """Returns abbreviated name of card Example: str(Card('Spades', 'A') outputs 'AS' """ return str(self.rank) + self.suit[0] def __eq__(self, other): """Return True if cards are equal by suit and rank weight""" return self.suit_weight == other.suit_weight and self.rank_weight == other.rank_weight def __gt__(self, other): """Returns true if first card is greater than second card by weight""" if self.suit_weight &gt; other.suit_weight: return True if self.suit_weight == other.suit_weight: if self.rank_weight &gt; other.rank_weight: return True return False def modify_weight(self, new_suit_weight = None, new_rank_weight = None): """Modifies weight of card object""" if new_suit_weight: self.suit_weight = new_suit_weight if new_rank_weight: self.rank_weight = new_rank_weight def get_suit(self): return self.suit def get_rank(self): return self.rank def get_suit_weight(self): return self.suit_weight def get_rank_weight(self): return self.rank_weight from itertools import product from random import shuffle class Deck(object): """Models a deck of playing cards, each instance will be a list of 52 Card objects""" def __init__(self): self.cards = [Card(card[0], card[1]) for card in product(Card.possible_suits, Card.possible_ranks)] def __str__(self): return str([str(card) for card in self.cards]) def length(self): return len(self.cards) def draw(self, end = None): """Return a card object or a set of card objects from the zeroth index of the deck, while removing it""" card = self.cards[0: end] del self.cards[0: end] return card def shuffle_deck(self): """Shuffle the deck of cards in place""" shuffle(self.cards) def get_suit(self, suit): """Return all cards of suit in the deck""" cards_of_suit = [] for card in self.cards: if card.get_suit() == suit: cards_of_suit.append(card) if len(cards_of_suit) == 13: break return cards_of_suit def find(self, card_to_find): """Return position of card in deck, if card not in deck return None""" print(type(card_to_find), "; ", card_to_find) if card_to_find in self.cards: return self.cards.index(card_to_find) return None def remove(self, card_to_remove): """Remove a card from the deck""" position = self.find(card_to_remove) if position: del self.cards[position] class Player(object): """Models a Player in a playing card game, each instance will have an id, can be initialized with a hand of cards and can be initialized with a score """ def __init__(self, id, hand = None, score = None): self.id = id self.hand = hand self.score = score def __str__(self): return str(self.id) def set_hand(self, cards): """Append cards to hand""" self.hand = cards def find_card(self, card): """Finds a card in hand""" if card in self.hand: return self.hand.index(card) return None def play(self, card_to_be_played): """Return card_to_be_played from hand while removing it, return None if card not in hand""" position = self.find_card(card_to_be_played) if position: del self.hand[position] return card_to_be_played return None def update_score(self, update): """Updates the current score of the instance by adding the update""" self.score += update def get_hand(self): return [str(i) for i in self.hand] def get_score(self): return self.score </code></pre>
[]
[ { "body": "<p>You may want to make the suits and ranks Enums, so that you can make cards in a more readable and less error prone way when needed:</p>\n\n<pre><code>Card(Suit.Spade, Rank.King) # readable, clear\nCard(\"Spade\", \"K\") # prone to typos \nCard(Card.possible_suits[0], Card.possible_ranks[11]) # meaning not very clear\n</code></pre>\n\n<p>It could also be beneficial to add a dict to your Deck implementation to more efficiently query the randomized deck:</p>\n\n<pre><code># quickly retrieve cards of a suit\nsuitToCards = { \n Suits.Spade: filter(card.suit == Suits.Spade, self.cards)\n # repeat for all suits...\n} \n</code></pre>\n\n<p>This way the Deck.cards are randomized, but Deck.bySuit can be used internally by Deck.get_suit() and Deck.find and Deck.remove so you don't need to iterate over the entire deck when you know you only ever need to work with a portion of the deck for these operations.</p>\n\n<p>One more thing to consider is encapsulation of the cards in the deck. You've handled Deck.draw() well, but it looks like cards in the deck can be altered or deleted if the caller manipulates the cards returned by Deck.get_suit(). You may want to make a deep copy of the list you return in Deck.get_suit() to prevent this. </p>\n\n<p>If this is to model standard deck based games where a deck always has 1 of each card (and optional jokers), and a card will always be in the deck or not, you may want to re-evaluate your design where cards are deleted from the deck. Will you ever want to support shuffling a card or cards back into the deck once drawn? How would you prevent duplicate cards from ending up in the deck? It could be easier to add a Boolean to each card indicating if its in the deck or not. This way the deck always knows about the cards it was initialized with, and these classes will be easier to debug.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-03-02T10:16:33.177", "Id": "414983", "Score": "0", "body": "Your `filter` syntax is not valid Python. It should either be `[card for card in self.cards if card.suit == Suits.Spade]` or `filter(lambda card: card.suit == Suits.Spade, self.cards)`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T21:31:48.797", "Id": "212345", "ParentId": "212288", "Score": "1" } } ]
{ "AcceptedAnswerId": "212345", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T22:06:52.987", "Id": "212288", "Score": "1", "Tags": [ "python", "object-oriented", "playing-cards" ], "Title": "Basic playing card objects for games" }
212288
<p>This is my solution for the leetcode reverse int question:</p> <blockquote> <p>Given a 32-bit signed integer, reverse digits of an integer.</p> <p>Example 1:</p> <p>Input: 123 Output: 321 Example 2:</p> <p>Input: -123 Output: -321 Example 3:</p> <p>Input: 120 Output: 21 Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.</p> </blockquote> <pre><code>using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ArrayQuestions { /// &lt;summary&gt; /// Given a 32-bit signed integer, reverse digits of an integer. /// /// Example 1: /// /// Input: 123 /// Output: 321 /// Example 2: /// /// Input: -123 /// Output: -321 /// Example 3: /// /// Input: 120 /// Output: 21 /// Note: /// Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. /// &lt;/summary&gt; [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { int temp = 1534236469; int result = Reverse(temp); Assert.AreEqual(0, result); } [TestMethod] public void TestMethod2() { int temp = 123; int result = Reverse(temp); Assert.AreEqual(321, result); } public int Reverse(int x) { int result = 0; bool negative = false; if (x &lt; 0) { negative = true; x = -x; } int prevRevNum = 0; while (x != 0) { int currentDigit = x % 10; result = (result * 10) + currentDigit; if ((result - currentDigit) / 10 != prevRevNum) { return 0; } prevRevNum = result; x = x / 10; } if (negative) { return -result; } return result; } } } </code></pre> <p>This is the output:</p> <blockquote> <p>Runtime: 52 ms, faster than 62.65% of C# online submissions for Reverse Integer.</p> </blockquote> <p>Can you please comment on how can I make this code run faster? I guess the modulo and division are the key factors of speed here.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T22:34:56.227", "Id": "410550", "Score": "2", "body": "You should check out [`System.Math.DivRem`](https://docs.microsoft.com/en-us/dotnet/api/system.math.divrem?view=netcore-2.2) for doing the division and modulo operations in one go." } ]
[ { "body": "<p>Using a string instead of division / modulo seems to be a few percent faster than the solution from the question:</p>\n\n<pre><code> public static int Reverse(int x)\n {\n var str = x.ToString();\n int res = 0;\n int multiplier = 1;\n var negative = str[0] == '-';\n for (int i = negative ? 1 : 0; i &lt; str.Length; i++)\n {\n var num = str[i] - 48;\n if (num &gt; 0 || multiplier &gt; 1)\n {\n res += num * multiplier;\n multiplier *= 10;\n }\n }\n return negative ? -res : res;\n }\n</code></pre>\n\n<p>However, improving the solutions from the question using System.Math.DivRem (as mistertribs suggested in a comment) will be even faster :):</p>\n\n<pre><code> public static int Reverse(int x)\n {\n var result = 0;\n var negative = x &lt; 0;\n if (negative) x = -x;\n\n while (x != 0)\n {\n x = Math.DivRem(x, 10, out var rest);\n result = result * 10 + rest;\n }\n\n return negative ? -result : result;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T14:31:21.053", "Id": "410614", "Score": "1", "body": "I doubt the test `if (result > 0 || rest > 0)` is worth it, but I could be wrong." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T14:39:02.890", "Id": "410617", "Score": "0", "body": "It is required for the case 120 -> 21" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T15:34:04.460", "Id": "410628", "Score": "1", "body": "I'm in agreement with George Barwood. The 120 case [seems to work without it](https://tio.run/##bZHBTsMwDIbveQpzS2DdOo6UwQGOTELjwDl0prPUJihJQxHrs5ektOuK8CWW/9@f7Ta3Sa4Ndl1tSRXw8mUdVhljeSmthWejCyMr9s0gxEf9VlIO1kkXHq9pD1tJiote/fXEeNDK6hKXr4YcPpFCvkOPxiJfX6dCZL2xZf8wSTkYvTFv/qK9NGDQ1qWDDaTZrK6wCBCPQWng9lyld@CjKoK4gaTJ2En@PFCJwBu4CExxKk9Txwl78qF3K91h@Uh@hxVvFrBOF6BrN67mRDbrW63i9GHnO0jheOxtMRczZ4zTbUNyGfBw1TfMsfGIsM5UbKd7DLraqOl73EMy4G4G7vgL2q77AQ). If both `result` and `rest` are zero then it will always result in `result == 0` anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T15:46:30.617", "Id": "410630", "Score": "1", "body": "Indeed, 0 * 10 + 0 is actually 0. I'll never stop learning ^^. Thanks for clearification, I modified the answer." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T12:49:56.653", "Id": "212318", "ParentId": "212289", "Score": "3" } }, { "body": "<p>How fast <code>Math.DivRem</code> is depends on which implementation you're using. Some quick testing shows that .NET Core's approach (which uses subtraction and multiplication instead of a modulo operation) is roughly 30% faster on my system than the .NET Framework implementation (which just uses a modulo and division, like your code does).</p>\n\n<hr>\n\n<p>The overflow check only needs to be performed when processing the last digit (and only when there are 10 digits, but checking digit count isn't free). Moving that out of the loop yields a small performance improvement (about 10% in my tests, depending on input).</p>\n\n<p>It's also slightly faster to compare <code>result</code> against 214748364 (<code>int.MaxValue / 10</code>) and <code>currentDigit</code> against 7 (the last digit of <code>int.MaxValue</code>), instead of subtracting the last digit and dividing by 10.</p>\n\n<hr>\n\n<p>Here's what I ended up with:</p>\n\n<pre><code>public static int Reverse(int x)\n{\n var result = 0;\n var isNegative = x &lt; 0;\n if (isNegative)\n x = -x;\n // NOTE: If n == int.MinValue, it'll wrap around to itself,\n // but it will also skip all of the below code, so the result conveniently remains 0.\n\n while (x &gt; 9)\n {\n var previousX = x;\n x /= 10;\n var digit = previousX - (x * 10);\n result = (result * 10) + digit;\n }\n\n if (x &gt; 0)\n {\n // Check for overflow (only necessary for 10-digit input,\n // but checking digit count also takes work so we'll just always check the last digit):\n if (result &gt; 214748364 || (result == 214748364 &amp;&amp; x &gt; 7)) // int.MaxValue / 10\n return 0;\n\n result = result * 10 + x;\n }\n\n return isNegative ? -result : result;\n}\n</code></pre>\n\n<p>Final note: if you're using tests, why not test edge-cases such as 0, negative numbers and outliers such as <code>int.MinValue</code> and <code>int.MaxValue</code>? Giving test methods meaningful names also helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T23:53:25.007", "Id": "212434", "ParentId": "212289", "Score": "3" } } ]
{ "AcceptedAnswerId": "212318", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T22:23:30.917", "Id": "212289", "Score": "1", "Tags": [ "c#", "performance", "programming-challenge" ], "Title": "Faster code for leetcode reverse int" }
212289
<p>For some background I'm pretty much a beginner and attempting to learn Python currently. So I decided after a few days of lessons I'd look for some beginner projects to test my knowledge. A website suggested I do a 'Guess the Number' game and basically suggested I follow this guideline.</p> <ul> <li>Random function</li> <li>Variables</li> <li>Integers</li> <li>Input/Output</li> <li>Print</li> <li>While loops</li> <li>If/Else statements</li> </ul> <p>In short I read the documentation on random and decided to give it a shot. Now for the actual question. Is this a good way of doing this or can I simplify it?</p> <p>I've pretty much been working at this for longer than I would like to admit (approximately 90 minutes), because I'd get stumped and then rewrite what I was thinking.</p> <pre><code># guess the number game import random print "Welcome to guess the number!" print "You have 10 tries to guess the correct number!" print "The range of numbers will be from 0-25" # variables to store winning number, user guess and number of tries number = random.randint(0, 25) guess = raw_input("Please enter a number (0-25): ") tries = 0 # check to see if the user guessed the right number if int(guess) == number: print "Congratulations you\'ve won!" # noticed that you could input invalid numbers and it counted as a guess so this is how i solved that while int(guess) &gt; 25 or int(guess) &lt; 0: guess = raw_input("Please enter a VALID guess: ") else: # my attempt at making the game loop while tries &lt; 10 and int(guess) != number: guess = raw_input("Please guess again: ") tries = tries + 1 # i noticed if i guessed the right answer out of the loop it would just exit so i duplicated here to prevent it if int(guess) == number: print "Congratulations you\'ve won!" # implemented the lose mechanic elif tries == 10: print "You've Lost!" # same with the correct answer issue i had so i put it in the loop as well elif int(guess) &gt; 25 or int(guess) &lt; 0: while int(guess) &gt; 25 or int(guess) &lt; 0: guess = raw_input("Please enter a VALID guess: ") # this is here because I didn't want to take tries away for invalid guesses tries = tries </code></pre> <p>So the game for me works as expected. You can win, lose, guess invalid numbers (I haven't tried letters but I won't get into that yet). Just not sure if this is the most efficient I can get. But if it's good enough for a beginner, I'll take it.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T02:13:02.957", "Id": "410577", "Score": "1", "body": "Looks nice, but if you enter a letter, it errors, saying it can't convert it to a number." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T02:26:32.960", "Id": "410579", "Score": "0", "body": "Yeah that was what I figured, was just doing it for learning purposes. I'm not super far into Python 2 so it may not be too late to start on Python 3 and then continue learning and getting better! Thanks for checking it out though!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:34:09.390", "Id": "412111", "Score": "0", "body": "There isn't _that_ much different with Python 3, (I think the only thing affected in your program is that `print` is a function and not a statement, and `raw_input` is now `input`). As Python 2 is now depreciated, I would definitely move up to it right now." } ]
[ { "body": "<p>This is a good first stab at a guess the number game.</p>\n\n<p>Here's a few things:</p>\n\n<ul>\n<li>You should be learning/using Python 3 instead of Python 2. So far the only difference for you will be <code>raw_input</code> becomes <code>input</code> and <code>print \"foo\"</code> becomes <code>print(\"foo\")</code>.</li>\n<li>The line <code>tries = tries</code> doesn't do anything meaningful. You don't need it</li>\n<li>You should put all of this inside a function called <code>main</code> and then at the bottom you run it with this (tests if this script is being run standalone):</li>\n</ul>\n\n\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<ul>\n<li>You do <code>int(guess)</code> a lot. This is something that can fail (if someone types <code>abc</code> for example). You should do it once and check for failure.</li>\n</ul>\n\n\n\n<pre><code>try:\n guess = int(guess)\nexcept ValueError:``\n print('Guess must be between 0 and 25')\n # ask for another guess\n</code></pre>\n\n<ul>\n<li>It's a good idea to comment. That's a fantastic habit to get into. However, you run the risk of over-commenting. And that is more distracting than having too few. As a rule, don't explain <em>what</em>, explain <em>why</em>. More concretely, \"check to see if a user guessed the right number\" is obvious from the <code>if guess == secret_number:</code>. Finding a balance is a skill, but if you work on it and read good quality open source code, you'll pick it up.</li>\n<li>When you do your range check, you can do it in a much more pythonic way. Instead of checking <code>guess &lt; 0 or guess &gt; 25</code>, you can do <code>if not 0 &lt;= guess &lt;= 25</code></li>\n<li><code>tries = tries + 1</code> can be <code>tries += 1</code></li>\n<li>You don't need to escape <code>'</code> inside a <code>\"</code> (so <code>\"Congratulations you\\'ve won!\"</code> can be <code>\"Congratulations you've won!\"</code>)</li>\n</ul>\n\n<p>The overarching issue you have though is most of your logic is duplicated in several different places. This becomes a problem if you want to, say, change the number range from 0-25 to 0-50. You'd need to change that in 6 places. What happens if you miss one? Then your game will break in weird ways.</p>\n\n<p>What's the solution? Look to pull out duplicate logic like this into smaller, manageable chunks. In this case, it's helpful to identify the steps of your game.</p>\n\n<ol>\n<li>Generate a secret number</li>\n<li>Collect a guess from the user</li>\n<li>If the user guessed the secret or more than 10 attempts have been made, end, else go back to 2</li>\n</ol>\n\n<p>One easy thing you can pull out is \"collect a guess from the user.\" You can do this in a function that gets the number, converts it to an <code>int</code> (handling the exception), and checking it is within range.</p>\n\n<pre><code>LOW, HIGH = 0, 25\n\ndef get_guess():\n while True:\n try:\n guess = int(input(f'Guess a number between {LOW}-{HIGH}: '))\n except ValueError:\n print('Please enter a number')\n else:\n if LOW &lt;= guess &lt;= HIGH:\n return guess\n\n print(f'Number must be between {LOW} and {HIGH}')\n</code></pre>\n\n<p>Now you can use <code>get_guess()</code> when you need to guess the guess from the user without having to add any extra control structures (like wrapping everything in a while) or duplicate any logic.</p>\n\n<p>Now, when using <code>get_guess()</code> you can concern yourself with fewer facets of the game. Namely, checking the number of attempts and if the guess was correct:</p>\n\n<pre><code>from random import randint\n\nMAX_ATTEMPTS = 10\n\ndef main():\n secret = randint(LOW, HIGH)\n\n for _ in range(MAX_ATTEMPTS):\n guess = get_guess()\n\n if guess == secret:\n print('You win!')\n break\n else:\n print('Too many attempts; you lose.')\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T01:09:19.167", "Id": "410569", "Score": "0", "body": "I appreciate you checking this out! Thanks and I'll start looking into it!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T00:04:15.257", "Id": "212297", "ParentId": "212292", "Score": "4" } }, { "body": "<p>So what I did here is I took your suggestions and read up on why you were doing what you were. Seems I haven't learned Try and Except yet but I'm reading up on it. I'm very thankful for your help. I modified some things to make it work for me and very much learned from what you set up. Thanks again! Here's what I have as of now.</p>\n\n<pre><code># guess the number game\nfrom random import randint\n\nprint \"Welcome to guess the number!\"\nprint \"You have 10 tries to guess the correct number!\"\nprint \"The range of numbers will be from 0-25\"\n\n# variables for the game\nLO, HI = 0, 25\nMAX_TRIES = 10\n\n\ndef main():\n # generate random number each game\n answer = randint(LO, HI)\n\n for _ in range(MAX_TRIES):\n guess = get_guess()\n\n if guess == answer:\n print \"You Win!\"\n break\n if MAX_TRIES == 10:\n print \"Too many tries. You Lose!\"\n\n# function to determine if input was an int\ndef get_guess():\n while True:\n try:\n guess = int(raw_input(\"Please enter a number (0-25): \"))\n except ValueError:\n print \"Please enter a number: \"\n else:\n if LO &lt;= guess &lt;= HI:\n return guess\n print \"Please enter a number between %s and %s\" % (LO, HI)\n\n\nmain()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:55:07.273", "Id": "412117", "Score": "0", "body": "You haven't tried running this, have you? `MAX_TRIES` never changes, so your test as to whether you lose will _always_ trigger. If you get the answer, you will win, and then instantly lose too. I would use a local variable like so: `tries_remaining = MAX_TRIES` `while get_guess() != answer and tries_remaining > 0:` `__tries_remaining -= 1` `if tries_remaining > 0:` `__print \"You Win!\"` `else:` `__print \"Too many tries. You lose!\"` (substitute underscores for spaces at the beginning of lines, comments are not suited for answers)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-07T16:57:10.580", "Id": "412118", "Score": "0", "body": "The above fixes the issue with the duplicate result. Simply put, it moves all of the logic for the answer message out of the loop, ensuring that you can _only_ get one message. It also uses a while loop, which is more in keeping with tracking conditions, instead of a for which is usually used for iterating through an entire set or a fixed number of iterations" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T02:25:20.250", "Id": "212300", "ParentId": "212292", "Score": "0" } } ]
{ "AcceptedAnswerId": "212297", "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-26T23:22:23.913", "Id": "212292", "Score": "4", "Tags": [ "python", "beginner", "python-2.x", "number-guessing-game" ], "Title": "Guess-the-number game by a Python beginner" }
212292
<p>Yes, It's called <code>Snake++</code>. I build it to learn C++. What features and techniques can be improved? I used SDL for some basic rendering, but my concern is more about the language use.</p> <p><a href="https://i.stack.imgur.com/4OJ8t.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/4OJ8t.gif" alt="enter image description here"></a></p> <p>Things I'm very concerned about:</p> <ol> <li>Generating a new food means trying random positions over and over again till one is free. This is going to become a problem very soon. What data structures can I use here?</li> <li>Am I using references to their full potential and avoiding unnecessary copying?</li> </ol> <p><strong>Main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "Game.hpp" using namespace std; int main(int argc, char * argv[]) { Game game = Game(); Game().Run(); cout &lt;&lt; "Game has terminated successfully, score: " &lt;&lt; game.GetScore() &lt;&lt; ", size: " &lt;&lt; game.GetSize() &lt;&lt; endl; return 0; } </code></pre> <p><strong>Game.hpp</strong></p> <pre><code>#pragma once #include &lt;vector&gt; #include "SDL.h" #include "SDL_image.h" class Game { public: Game(); void Run(); int GetScore(); int GetSize(); private: bool running = false; bool alive = false; int fps = 0; static const int FRAME_RATE = 1000 / 60; static const int SCREEN_WIDTH = 640; static const int SCREEN_HEIGHT = 640; static const int GRID_WIDTH = 32; static const int GRID_HEIGHT = 32; SDL_Window * window = nullptr; SDL_Renderer * renderer = nullptr; enum class Block { head, body, food, empty }; enum class Move { up, down, left, right }; Move last_dir = Move::up; Move dir = Move::up; struct { float x = GRID_WIDTH / 2, y = GRID_HEIGHT / 2; } pos; SDL_Point head = { static_cast&lt;int&gt;(pos.x), static_cast&lt;int&gt;(pos.y) }; SDL_Point food; std::vector&lt;SDL_Point&gt; body; Block grid[GRID_WIDTH][GRID_HEIGHT]; float speed = 0.5f; int growing = 0; int score = 0; int size = 1; void ReplaceFood(); void GrowBody(int quantity); void UpdateWindowTitle(); void GameLoop(); void Render(); void Update(); void PollEvents(); void Close(); }; </code></pre> <p><strong>Game.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;ctime&gt; #include "SDL.h" #include "Game.hpp" using namespace std; Game::Game() { for (int i = 0; i &lt; GRID_WIDTH; ++i) for (int j = 0; j &lt; GRID_HEIGHT; ++j) { grid[i][j] = Block::empty; } srand(static_cast&lt;unsigned int&gt;(time(0))); } void Game::Run() { // Initialize SDL if (SDL_Init(SDL_INIT_VIDEO) &lt; 0) { cerr &lt;&lt; "SDL could not initialize! SDL_Error: " &lt;&lt; SDL_GetError() &lt;&lt; endl; exit(EXIT_FAILURE); } // Create Window window = SDL_CreateWindow("Snake Game", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN); if (window == NULL) { cout &lt;&lt; "Window could not be created! SDL_Error: " &lt;&lt; SDL_GetError() &lt;&lt; endl; exit(EXIT_FAILURE); } // Create renderer renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED); if (renderer == NULL) { cout &lt;&lt; "Renderer could not be created! SDL_Error: " &lt;&lt; SDL_GetError() &lt;&lt; endl; exit(EXIT_FAILURE); } alive = true; running = true; ReplaceFood(); GameLoop(); } void Game::ReplaceFood() { int x, y; while (true) { x = rand() % GRID_WIDTH; y = rand() % GRID_HEIGHT; if (grid[x][y] == Block::empty) { grid[x][y] = Block::food; food.x = x; food.y = y; break; } } } void Game::GameLoop() { Uint32 before, second = SDL_GetTicks(), after; int frame_time, frames = 0; while (running) { before = SDL_GetTicks(); PollEvents(); Update(); Render(); frames++; after = SDL_GetTicks(); frame_time = after - before; if (after - second &gt;= 1000) { fps = frames; frames = 0; second = after; UpdateWindowTitle(); } if (FRAME_RATE &gt; frame_time) { SDL_Delay(FRAME_RATE - frame_time); } } } void Game::PollEvents() { SDL_Event e; while (SDL_PollEvent(&amp;e)) { if (e.type == SDL_QUIT) { running = false; } else if (e.type == SDL_KEYDOWN) { switch (e.key.keysym.sym) { case SDLK_UP: if (last_dir != Move::down || size == 1) dir = Move::up; break; case SDLK_DOWN: if (last_dir != Move::up || size == 1) dir = Move::down; break; case SDLK_LEFT: if (last_dir != Move::right || size == 1) dir = Move::left; break; case SDLK_RIGHT: if (last_dir != Move::left || size == 1) dir = Move::right; break; } } } } int Game::GetSize() { return size; } void Game::GrowBody(int quantity) { growing += quantity; } void Game::Update() { if (!alive) return; switch (dir) { case Move::up: pos.y -= speed; pos.x = floorf(pos.x); break; case Move::down: pos.y += speed; pos.x = floorf(pos.x); break; case Move::left: pos.x -= speed; pos.y = floorf(pos.y); break; case Move::right: pos.x += speed; pos.y = floorf(pos.y); break; } // Wrap if (pos.x &lt; 0) pos.x = GRID_WIDTH - 1; else if (pos.x &gt; GRID_WIDTH - 1) pos.x = 0; if (pos.y &lt; 0) pos.y = GRID_HEIGHT - 1; else if (pos.y &gt; GRID_HEIGHT - 1) pos.y = 0; int new_x = static_cast&lt;int&gt;(pos.x); int new_y = static_cast&lt;int&gt;(pos.y); // Check if head position has changed if (new_x != head.x || new_y != head.y) { last_dir = dir; // If we are growing, just make a new neck if (growing &gt; 0) { size++; body.push_back(head); growing--; grid[head.x][head.y] = Block::body; } else { // We need to shift the body SDL_Point free = head; vector&lt;SDL_Point&gt;::reverse_iterator rit = body.rbegin(); for ( ; rit != body.rend(); ++rit) { grid[free.x][free.y] = Block::body; swap(*rit, free); } grid[free.x][free.y] = Block::empty; } } head.x = new_x; head.y = new_y; Block &amp; next = grid[head.x][head.y]; // Check if there's food over here if (next == Block::food) { score++; ReplaceFood(); GrowBody(1); } // Check if we're dead else if (next == Block::body) { alive = false; } next = Block::head; } int Game::GetScore() { return score; } void Game::UpdateWindowTitle() { string title = "Snakle++ Score: " + to_string(score) + " FPS: " + to_string(fps); SDL_SetWindowTitle(window, title.c_str()); } void Game::Render() { SDL_Rect block; block.w = SCREEN_WIDTH / GRID_WIDTH; block.h = SCREEN_WIDTH / GRID_HEIGHT; // Clear screen SDL_SetRenderDrawColor(renderer, 0x1E, 0x1E, 0x1E, 0xFF); SDL_RenderClear(renderer); // Render food SDL_SetRenderDrawColor(renderer, 0xFF, 0xCC, 0x00, 0xFF); block.x = food.x * block.w; block.y = food.y * block.h; SDL_RenderFillRect(renderer, &amp;block); // Render snake's body SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF); for (SDL_Point &amp; point : body) { block.x = point.x * block.w; block.y = point.y * block.h; SDL_RenderFillRect(renderer, &amp;block); } // Render snake's head block.x = head.x * block.w; block.y = head.y * block.h; if (alive) SDL_SetRenderDrawColor(renderer, 0x00, 0x7A, 0xCC, 0xFF); else SDL_SetRenderDrawColor(renderer, 0xFF, 0x00, 0x00, 0xFF); SDL_RenderFillRect(renderer, &amp;block); // Update Screen SDL_RenderPresent(renderer); } void Game::Close() { SDL_DestroyWindow(window); SDL_Quit(); } </code></pre>
[]
[ { "body": "<p><code>using namespace std;</code> is a bad practice. I'm glad to see you didn't use it in the header. Better still to not to use it at all. Please see <a href=\"https://stackoverflow.com/a/1453605/5416291\">this</a> post for more information.</p>\n<hr />\n<pre><code>int main(int argc, char * argv[])\n</code></pre>\n<p>If you are not going to use the command line arguments anyway then use the empty parameter main: <code>int main()</code></p>\n<hr />\n<p><code>return 0</code> at the end of main is unnecessary and will be supplied by the compiler.</p>\n<hr />\n<h2>Bug</h2>\n<pre><code>int main(int argc, char * argv[])\n{\n Game game = Game();\n Game().Run();\n cout &lt;&lt; &quot;Game has terminated successfully, score: &quot; &lt;&lt; game.GetScore()\n &lt;&lt; &quot;, size: &quot; &lt;&lt; game.GetSize() &lt;&lt; endl;\n return 0;\n}\n</code></pre>\n<p><code>Game().Run()</code> calls the <code>Game</code> constructor and creates a second instance of <code>Game</code> and then calls <code>Run()</code> on that instance. Your postgame stats likely aren't working correctly. No?</p>\n<hr />\n<p>Don't use <code>std::endl</code>. Prefer '\\n' instead. <code>std::endl</code> flushes the stream, which if you wanted to do you could do manually <code>&lt;&lt; '\\n' &lt;&lt; std::flush</code> and it would be more explicit what you were trying to accomplish.</p>\n<p>Read more <a href=\"https://stackoverflow.com/a/213977/5416291\">here</a>.</p>\n<hr />\n<pre><code>static const int FRAME_RATE = 1000 / 60;\nstatic const int SCREEN_WIDTH = 640;\nstatic const int SCREEN_HEIGHT = 640;\nstatic const int GRID_WIDTH = 32;\nstatic const int GRID_HEIGHT = 32;\n</code></pre>\n<p><code>constexpr</code> is better for global named constants that are known at compile time. They would need moved outside of the class but could still be in the Game header file.</p>\n<p>ALL_CAPS names are also typically used for macros. Better use snake_case, camelCase, or PascalCase. (I prefer snake_case for global constants but that's just me.)</p>\n<hr />\n<pre><code>struct { float x = GRID_WIDTH / 2, y = GRID_HEIGHT / 2; } pos;\n\nSDL_Point head = { static_cast&lt;int&gt;(pos.x), static_cast&lt;int&gt;(pos.y) };\n</code></pre>\n<p>Here you define a float that is the result of the division of two ints (which won't return a float) and then immediately cast the result to int. It's also mildly worth mentioning that your values divide cleanly (which is why you didn't notice any errors.) I see <code>pos</code> cast to <code>int</code> a few other times. Just make it an <code>int</code></p>\n<hr />\n<pre><code>srand(static_cast&lt;unsigned int&gt;(time(0)));\n</code></pre>\n<p>srand is not a very good PRNG. Learn the <a href=\"https://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow noreferrer\"><code>&lt;random&gt;</code></a> header.</p>\n<hr />\n<pre><code>bool running = false;\nbool alive = false;\n</code></pre>\n<p>You define and initialize these to false only to make them true before they can be used properly. Just initialize them to true to begin with. Also brace initialization is more idiomatic.</p>\n<pre><code>bool running{ true };\nbool alive{ true };\n</code></pre>\n<hr />\n<p>Use the C++ language supported <code>nullptr</code> over the C macro <code>NULL</code>. <code>NULL</code> will be silently converted to int at unintended times.</p>\n<hr />\n<p><code>ReplaceFood()</code> Once again avoid <code>rand</code>. But have you considered maintaining an <code>std::vector&lt;Point&gt;</code> of <code>Point</code>s that are empty. Then you can randomly index from the vector to find the location of the next food. You will have to add the previous location of the tail back to the vector and remove the location of the head on each move.</p>\n<hr />\n<pre><code>Uint32 before, second = SDL_GetTicks(), after;\nint frame_time, frames = 0;\n</code></pre>\n<p>Don't declare multiple variable on single lines. Use 1:1 lines to variables. Especially when some are assigned and some are not. This can get confusing to read. is <code>frame_time</code> assigned 0? I know the answer but its not obvious just by looking at it.</p>\n<hr />\n<p>Don't take a parameter in your <code>GrowBody()</code> function. You only ever grow your snake by one. Just increment the size internally and move on. Only grow by a size provided by a parameter if there is a possibility of different sizes being passed in as arguments.</p>\n<hr />\n<p>Your <code>Update()</code> function is a bit on the larger side. I would break it into two or three helper functions. Maybe the move + wrap in one function and the checks for the head in another.</p>\n<p>Then you'd have</p>\n<pre><code>void Game::Update()\n{\n MoveWithWrap();\n CheckHead();\n}\n</code></pre>\n<p>I also see that you did indeed need floats for the position so I will return to that. I'm not sure I would change the way you do the pos struct after all but I would seriously think about it.</p>\n<p>The way to get the result as a float requires casting before the division call:</p>\n<pre><code>struct { float x = static_cast&lt;float&gt;(GRID_WIDTH) / 2, y = static_cast&lt;float&gt;(GRID_HEIGHT) / 2; } pos;\n</code></pre>\n<p>The solution could be to have a helper function that abstracts the casts away to one location. Like this:</p>\n<pre><code>struct Position\n{\n float x;\n float y;\n};\n\nstruct Point\n{\n int x;\n int y;\n};\n\nPoint PositionToPoint(Position const&amp; position)\n{\n Point point{ static_cast&lt;int&gt;(position.x), static_cast&lt;int&gt;(position.y) };\n return point;\n}\n\nPosition pos{ grid_width / 2, grid_height / 2 };\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T14:35:14.133", "Id": "410616", "Score": "0", "body": "Thank you for the answer. 1) Moving the constants outside of the class wouldn't expose them? The whole purpose of `private` and encapsulation would be broken. Other classes that `#include \"Game.hpp\"` would have their space poluted. 2) Wouldn't `std::array` make the code very verbose as I'm using 2d arrays? 3) `GrowBody()` can be useful when adding new mechanics to the game. Does `inline`-ing solve this issue? 4) The float/int problem with positions is one that I'm very aware of. I see no other way to manage it besides annoying casts." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:28:12.800", "Id": "410738", "Score": "2", "body": "@AfonsoMatos This is a common mistake: in C++ (and similarly in other languages), classes are not the only, and not the main, mechanism for separating interfaces from implementation. Define the constants inside their own compilation unit (`Game.cpp`) to make them private." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T03:38:23.490", "Id": "212302", "ParentId": "212296", "Score": "16" } }, { "body": "<h1>Object Usage</h1>\n<p>This code:</p>\n<pre><code>Game game = Game();\nGame().Run();\ncout &lt;&lt; &quot;Game has terminated successfully, score: &quot; &lt;&lt; game.GetScore()\n &lt;&lt; &quot;, size: &quot; &lt;&lt; game.GetSize() &lt;&lt; endl;\n</code></pre>\n<p>...isn't doing what I'm pretty sure you think it is. This part: <code>Game game = Game();</code> creates an object named <code>game</code> which is of type <code>Game</code>. But, I'd prefer to use just <code>Game game;</code>, which accomplishes the same thing more easily.</p>\n<p>Then you do: <code>Game().Run();</code>. This creates another (temporary) <code>Game</code> object, and invokes the <code>Run</code> member function on that temporary <code>Game</code> object (so the <code>Game</code> object named <code>game</code> that you just creates sits idly by, doing nothing).</p>\n<p>Then you do:</p>\n<pre><code>cout &lt;&lt; &quot;Game has terminated successfully, score: &quot; &lt;&lt; game.GetScore()\n &lt;&lt; &quot;, size: &quot; &lt;&lt; game.GetSize() &lt;&lt; endl;\n</code></pre>\n<p>...which tries to print the score accumulated in the object named <code>game</code>--but <code>game</code> hasn't run. Only the temporary object has run (so by rights, the score you display should always be <code>0</code>).</p>\n<p>If I were doing this, I'd probably do something more like:</p>\n<pre><code>Game game;\ngame.run();\ncout &lt;&lt; &quot;Game has terminated successfully, score: &quot; &lt;&lt; game.GetScore()\n &lt;&lt; &quot;, size: &quot; &lt;&lt; game.GetSize() &lt;&lt; endl;\n</code></pre>\n<h1><code>using namespace std;</code> isn't just using; it's abusing!</h1>\n<p>I'd (strongly) advise against <code>using namespace std;</code>. A using directive for another namespace can be all right, but <code>std::</code> contains a huge amount of stuff, some of it with very common names that are likely to conflict with other code. Worse, every new release of the C++ standard adds still more &quot;stuff&quot; to <code>std</code>. It's generally preferable to just qualify names when you use them, so (for example) the <code>cout</code> shown above would be more like:</p>\n<pre><code>std::cout &lt;&lt; &quot;Game has terminated successfully, score: &quot; &lt;&lt; game.GetScore()\n &lt;&lt; &quot;, size: &quot; &lt;&lt; game.GetSize() &lt;&lt; std::endl;\n</code></pre>\n<h1>Avoid <code>std::endl</code></h1>\n<p>I'd advise avoiding <code>std::endl</code> in general. Along with writing a new-line to the stream, it flushes the stream. You want the new-line, but almost never want to flush the stream, so it's generally better to just write a <code>\\n</code>. On the <em>rare</em> occasion that you actually want the flush, do it explicitly: <code>std::cout &lt;&lt; '\\n' &lt;&lt; std::flush;</code>.</p>\n<h1>Avoid the C random number generation routines</h1>\n<p>C's <code>srand()</code>/<code>rand()</code> have quite a few problems. I'd generally advise using the new routines in <code>&lt;random&gt;</code> instead. This is kind of a pain (seeding the new generators well is particularly painful) but they generally produce much higher quality randomness, are much more friendly to multi-threading, and using them well will keep the cool C++ programmers (now there's an oxymoron) from calling you names.</p>\n<h1>avoid <code>exit()</code></h1>\n<p>When writing C++, it's generally better to avoid using <code>exit</code>. Calling it generally prevents destructors for objects on the stack from running, so you can't get a clean shutdown.</p>\n<p>As a general rule, I'd add a <code>try</code>/<code>catch</code> block in main, and where you're currently calling <code>exit()</code>, throw an object derived from <code>std::exception</code>. In your case, <code>std::runtime_error</code> probably make sense.</p>\n<pre><code>if (renderer == NULL)\n{\n throw std::runtime_error(&quot;Renderer could not be created!&quot;);\n}\n</code></pre>\n<p>In main:</p>\n<pre><code>try {\n game.Run();\n std::cout &lt;&lt; &quot;Game has terminated successfully, score: &quot; &lt;&lt; game.GetScore()\n &lt;&lt; &quot;, size: &quot; &lt;&lt; game.GetSize() &lt;&lt; '\\n';\n} \ncatch (std::exception const &amp;e) { \n std::cerr &lt;&lt; e.what();\n}\n</code></pre>\n<h1>Prefer <code>nullptr</code> to <code>NULL</code></h1>\n<p>Pretty much self-explanatory. In C++, <code>NULL</code> is required to be an integer constant with the value <code>0</code> (e.g., either <code>0</code> or <code>0L</code>). <code>nullptr</code> is a bit more special--it can convert to any pointer type, but <em>can't</em> accidentally be converted to an integer type. So, anywhere you might consider using <code>NULL</code>, you're almost certainly better off using <code>nullptr</code>:</p>\n<pre><code>if (renderer == nullptr)\n</code></pre>\n<p>Some also prefer to reverse those (giving &quot;Yoda conditions&quot;):</p>\n<pre><code>if (nullptr == renderer)\n</code></pre>\n<p>This way, if you accidentally use <code>=</code> where you meant <code>==</code>:</p>\n<pre><code>if (nullptr = renderer)\n</code></pre>\n<p>...the code won't compile, because you've attempted to assign to a constant (whereas <code>if (renderer = nullptr)</code> could compile and do the wrong thing, though most current compilers will at least give a warning about it).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T03:31:31.687", "Id": "410688", "Score": "3", "body": "\"You want the new-line, but almost never want to flush the stream\" — could you elaborate? In my experience, programs with fully-buffered stdout are quite annoying, since you can read their output only after they are finished (that is, if they finish without crashing so that the stdout buffers are flushed)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T05:10:11.740", "Id": "410696", "Score": "0", "body": "wait why not use `using namespace std;` if you _know_ it doesn't conflict with other code? for example if you know you aren't using any other libraries; are there duplicate named functions in the `std` namespace?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T05:11:09.923", "Id": "410697", "Score": "1", "body": "@Jeffmagma You might add a library in the future, or even just want to use one of the names yourself at some point." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T05:46:04.997", "Id": "410702", "Score": "2", "body": "@Jeffmagma: The implementation is allowed to add extra \"stuff\" to the `std` namespace, so it's essentially impossible to know what might be in there. Even if you check for now, the next version of your compiler could completely break your code." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:24:26.293", "Id": "410736", "Score": "0", "body": "Really `NULL`? Anyway, why not `!renderer`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:03:00.047", "Id": "410779", "Score": "0", "body": "@Deduplicator while I agree it should be a comparison against `nullptr`, I don't agree with `!renderer` because if you jumped to that point in code you may not know that renderer wasn't a boolean, For example, what if we were testing a `runable` object, then we checked `if(!runable)`? Now the clear default assumption is that you were testing a boolean value, not a pointer to an object, yet that value is not a boolean." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:06:18.077", "Id": "410781", "Score": "0", "body": "@opa It doesn't matter it isn't a boolean, and that's a feature, not a defect. Actually, booleans are clearly in the minority in those use-cases anyway." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:12:09.443", "Id": "410783", "Score": "0", "body": "@Deduplicator It is definitely a problem if you have to look around to figure out the type of a variable, especially when *you thought it was another type*, it simply harms ergonomics when you do `!some_pointer_var` instead of `some_pointer_var == nullptr`. This is one of those things like non braced statements which will surprise C++ programmers when you use it, and waste a lot of time. Reading ergonomics > typing ergonomics." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:18:45.763", "Id": "410788", "Score": "0", "body": "@opa You are far too hung up about knowing the exact type, when that rarely matters, and even comparison against `nullptr` at most hints at it being some pointer-like thing. What matters is what you can *do* with it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:21:46.980", "Id": "410790", "Score": "0", "body": "@Deduplicator lots of things rarely matter, that isn't a reason not to use due diligence in clearly writing code for readability. Are you trying to tell me that using boolean operators on pointers is some how more readable than explicit nullptr comparison?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:21:04.263", "Id": "410809", "Score": "0", "body": "@opa Being pointlessly long-winded is not a synonym for readable. Nor is mindlessly nailing down irrelevant details using due diligence. Anyway, I'm off." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:38:39.863", "Id": "410819", "Score": "0", "body": "@Jerry: As you point out, any half-way recent decent compiler makes yoda-conditions superfluous, and will catch the error even if both sides are variables. Also, while `NULL` is guaranteed to be a nullpointer-constant,it need not be an integer-constant. Seems you don't like the negation-operator?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:03:29.480", "Id": "410826", "Score": "0", "body": "@Deduplicator: \"A *null pointer constant* is an integral constant expression (5.19) rvalue of integer type that evaluates to zero.\" (old wording, but basic idea remains). I have nothing against negation otherwise, but I'm not particularly fond of applying it to pointers. It does work, but I don't think it's particularly good for readability. As for Yoda conditions--even quite recently, I've had to deal with existing projects that spewed reams of warnings, and wasn't given time to fix them. A style that forces the error to be an error can still be useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T18:13:16.953", "Id": "410837", "Score": "0", "body": "[A *null pointer constant* is an integer literal (\\[lex.icon\\]) with value zero or a prvalue of type `std::nullptr_­t`.](http://eel.is/c++draft/conv.ptr#def:constant,null_pointer) Yes, the basic idea remains, but accounts for the new `nullptr`. So not using negation is a personal preference, ok. My only beef with yoda-conditions is that it forces contortions when reading and writing." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-30T06:22:01.083", "Id": "411054", "Score": "0", "body": "@Joker_vD https://softwareengineering.stackexchange.com/q/386269/283695" } ], "meta_data": { "CommentCount": "15", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T03:46:24.467", "Id": "212303", "ParentId": "212296", "Score": "26" } }, { "body": "<p>Some additional points:</p>\n\n<ul>\n<li><p>Avoid \"God classes\". Your <code>Game</code> class does absolutely everything. This makes it hard to see which member variables are used where, and is one step away from using global variables. The larger the program, the harder it is to understand. Classes should follow the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a> (SRP), and be responsible for only one thing.</p></li>\n<li><p>Use the \"<a href=\"https://en.cppreference.com/w/cpp/language/raii\" rel=\"nofollow noreferrer\">Resource Acquisition Is Initialization</a>\" (RAII) approach for managing resource lifetimes. For example, the SDL context, window, and renderer can be encapsulated in an object, with initialization done in the constructor, and cleanup in the destructor.</p></li>\n<li><p>Don't use global constants. <code>GRID_WIDTH</code> etc. apply to all instances of the <code>Game</code> class, which is unnecessarily restrictive.</p></li>\n<li><p>Use unsigned types for variables that can never be negative (grid width / height, etc.). <code>SDL_Point</code> uses the wrong type (<code>int</code>), but we can easily define our own <code>Point</code> class to use instead. We can convert to the necessary SDL type only when we need to call an SDL function with it.</p></li>\n<li><p>Member functions that don't change member variables (e.g. <code>GetScore()</code>, <code>GetSize()</code>) should be marked <code>const</code> (e.g. <code>int GetScore() const;</code>).</p></li>\n<li><p>A better strategy for picking a new food position might be to add the positions of all the empty squares to a vector, and then pick one (by choosing an index less than the size of the vector).</p></li>\n</ul>\n\n<hr>\n\n<p>Here's a (pseudo-code) example of how we could split up the <code>Game</code> class. Note that there's no reason for the <code>Game</code> class to know anything about <code>SDL</code>. If we ever wanted to change to a different platform for rendering / input, it's much neater to keep it separate. Don't be afraid to use free functions as well.</p>\n\n<pre><code>namespace Snake\n{\n template&lt;class T&gt;\n struct Point\n {\n T x;\n T y;\n };\n\n struct SDLContext\n {\n SDLContext(std::size_t window_width, std::size_t window_height);\n ~SDLContext();\n\n SDL_Window * window = nullptr;\n SDL_Renderer * renderer = nullptr;\n };\n\n SDLContext::SDLContext()\n {\n // ... SDL init\n }\n\n SDLContext::~SDLContext()\n {\n // ... SDL shutdown\n }\n\n struct Board\n {\n Board(std::size_t width, std::size_t height);\n\n enum class Block { head, body, food, empty };\n\n std::size_t width;\n std::size_t height;\n\n std::vector&lt;std::vector&lt;Block&gt;&gt; grid;\n };\n\n Board::Board()\n {\n // ... init grid to \"empty\"\n }\n\n struct Food\n {\n Point&lt;std::size_t&gt; position = Point{ 0, 0 };\n };\n\n struct Snake\n {\n void Grow(int amount);\n void UpdatePosition(Board&amp; board);\n\n enum class Move { up, down, left, right };\n\n Move last_dir = Move::up;\n Move dir = Move::up;\n\n Point&lt;std::size_t&gt; headPosition;\n std::vector&lt;Point&lt;std::size_t&gt;&gt; body;\n\n int size = 1;\n float speed = 0.5f;\n int growing = 0;\n };\n\n class Game\n {\n Game(std::size_t gridWidth, std::size_t gridHeight);\n\n int GetScore() const;\n int GetSize() const;\n\n void Update();\n\n private:\n\n void ReplaceFood();\n\n Board board;\n Food food;\n Snake snake;\n\n int score = 0;\n bool alive = true;\n };\n\n Game::Game(std::size_t gridWidth, std::size_t gridHeight):\n Board(gridWidth, gridHeight)\n {\n ReplaceFood();\n }\n\n void PollEvents(SDLContext&amp;, bool&amp; quit)\n {\n // ...\n }\n\n void Render(SDLContext&amp;, Game const&amp; game)\n {\n // ...\n }\n\n void UpdateWindowTitle(SDLContext&amp;, Game const&amp; game)\n {\n // ...\n }\n\n void Run(SDLContext&amp; context, Game&amp; game, int frame_rate)\n {\n Uint32 before, second = SDL_GetTicks(), after;\n int frame_time, frames = 0;\n\n while (true)\n {\n before = SDL_GetTicks();\n\n bool quit = false;\n PollEvents(sdlContext, quit);\n\n if (quit)\n break;\n\n game.Update();\n\n Render(sdlContext, game);\n\n frames++;\n after = SDL_GetTicks();\n frame_time = after - before;\n\n if (after - second &gt;= 1000)\n {\n UpdateWindowTitle(sdlContext, game.GetScore(), frames);\n\n frames = 0;\n second = after;\n }\n\n if (frame_rate &gt; frame_time)\n {\n SDL_Delay(frame_rate - frame_time);\n }\n }\n }\n\n} // Snake\n\n\n#include &lt;SDL.h&gt;\n\n#include &lt;iostream&gt;\n#include &lt;cstddef&gt;\n\nint main(int argc, char * argv[])\n{\n using namespace Snake;\n\n const std::size_t window_width = 640;\n const std::size_t window_height = 640;\n SDLContext sdlContext(window_width, window_height);\n\n const std::size_t grid_width = 32;\n const std::size_t grid_height = 32;\n Game game(grid_width, grid_height);\n\n const int frame_rate = 1000 / 60;\n Run(sdlContext, game, frame_rate);\n\n std::cout &lt;&lt; \"Game has terminated successfully, score: \" &lt;&lt; game.GetScore()\n &lt;&lt; \", size: \" &lt;&lt; game.GetSize() &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>The functions taking the <code>SDLContext&amp;</code> don't necessarily use it, since SDL works through global functions. However, this does prove that we have properly initialized SDL at the point the function is called.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T14:44:15.300", "Id": "410619", "Score": "0", "body": "Very insightful answer and the code is pretty. 1) It was not clear how you would change `ReplaceFood()`. How do you know what blocks are empty? Are you going to do a Row * Col search? That's very inefficient isn't it?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T15:18:46.030", "Id": "410626", "Score": "1", "body": "Yes I would (and yes it is inefficient). But it's simple, and it's a fixed amount of work (for a given grid size), so if it's fast enough for small snakes, we know it will be fine for large snakes too. There are definitely quicker ways (e.g. maintaining a list of empty block positions that we update when moving the snake), but the added complexity may not be necessary." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T18:57:44.940", "Id": "410650", "Score": "0", "body": "Also in your `struct Board` you can't have variables inside the grid array declaration." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T19:21:22.850", "Id": "410655", "Score": "1", "body": "Good point, fixed. (btw, I'd probably allocate one flat vector instead of a `vector<vector<...>>` for the board. 2d coordinates can then be converted to the relevant index as `y * width + x`). This is more efficient (the allocated memory is contiguous), and we can iterate through by index if we need to)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T12:33:45.133", "Id": "410747", "Score": "0", "body": "I agree with what you're saying about \"God classes,\" but you should do some more research on the Single Responsibility Principle. It does not say that a class should only do one thing but rather that a module should be responsible to only one stakeholder. Bob Martin briefly discusses the differences in his book Clean Architecture. He also mentions that the SRP is probably the least well understood of the SOLID principles, so don't feel too bad." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:36:40.093", "Id": "410817", "Score": "0", "body": "Storing all the positions is probably a pessimisation. Just calculate the number of candidates, get a random number below that, and then find the position." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T12:02:36.307", "Id": "212315", "ParentId": "212296", "Score": "9" } } ]
{ "AcceptedAnswerId": "212303", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T00:03:49.787", "Id": "212296", "Score": "23", "Tags": [ "c++", "beginner", "snake-game", "sdl" ], "Title": "Snake++ game (in C++ with SDL)" }
212296
<p>I am using PHP to keep my webpage organized.</p> <p>The directory looks like this:</p> <pre><code>root/folder/file1 root/folder/file2 root/folder/file3 root/index.php </code></pre> <p>Each file is very simple html doc with content containing a title tag, which I use to create a nav bar.</p> <p>I want index.php to aggregate all the content from file1, file2 and file3, in addition to creating a nav bar up at the top.</p> <p>The code I have achieves this successfully, but I'm not sure if I'm doing this in a practical way.</p> <pre><code>$domain = "domain/" $dir = "folder/"; $files = scandir($dir); // loop over all the files, saving their contents and ids to arrays $contents = Array(); $titles = Array(); $ids = Array(); for ($x = 0; $x &lt; sizeof($files); $x++) { if ($files[$x] != "." &amp;&amp; $files[$x] != "..") { $filename = $domain . $dir . $files[$x]; $file = fopen($filename, "r"); $data = file_get_contents($filename); array_push($contents, $data); $regex = '#&lt;title&gt;(.*?)&lt;\/title&gt;#'; preg_match($regex, $data, $match); $title = $match[1]; array_push($titles, $title); $regex2 = '#( |-|,)#'; $id = preg_split($regex2, $title)[0]; array_push($ids, $id); } } // the first loop sets the nav bar echo "&lt;div id='navigation'&gt;"; echo "&lt;ul&gt;"; for ($x = 0; $x &lt; sizeof($contents); $x++) { echo "&lt;li&gt;&lt;a href='#" . $ids[$x] . "'&gt;" . $titles[$x] . "&lt;/a&gt;&lt;/li&gt;"; } echo "&lt;/ul&gt;"; echo "&lt;/div&gt;"; // this second loop sets the contents echo "&lt;div id='content'&gt;"; for ($x = 0; $x &lt; sizeof($contents); $x++) { echo "&lt;div id='" . $ids[$x] . "'&gt;" . $contents[$x] . "&lt;/div&gt;"; } echo "&lt;/div&gt;"; </code></pre> <p>I like the idea of having all the content on one big page and the nav bar helps a lot when I'm viewing it on my phone.</p> <p><strong>Questions</strong></p> <ol> <li>Are there any obvious problems with the way I am aggregating my files?</li> <li>Are there challenges I may encounter that I have not yet experienced?</li> <li>Is there a generally accepted way of doing this while achieving the same result?</li> </ol>
[]
[ { "body": "<p>Basically you need to remove the unused fopen() call and change ponderous operators to handy ones as for some reason you made a peculiar choice in favor of the former, like for vs. foreach, array_push vs simple assignment, etc. Also consider a cleaner way to output HTML </p>\n\n<pre><code>&lt;?php\n$pattern = \"domain/folder/*.*\";\n$files = glob($pattern);\n\n// loop over all the files, saving their contents and ids to arrays\n\n$contents = [];\n$titles = [];\n$ids = [];\nforeach ($files as $filename)\n{\n $data = file_get_contents($filename);\n $contents[] = $data;\n\n preg_match('#&lt;title&gt;(.*?)&lt;\\/title&gt;#', $data, $match);\n $titles[] = $match[1];\n\n $ids[] = preg_split('#( |-|,)#', $match[1])[0];\n}\n?&gt;\n&lt;div id='navigation'&gt;\n&lt;ul&gt;\n&lt;?php foreach ($titles as $x =&gt; $title): ?&gt;\n &lt;li&gt;&lt;a href=\"#&lt;?=$ids[$x]?&gt;\"&gt;&lt;?=$title?&gt;&lt;/a&gt;&lt;/li&gt;\n&lt;?php endforeach ?&gt;\n&lt;/ul&gt;\n&lt;/div&gt;\n\n&lt;div id='content'&gt;\n&lt;?foreach ($contents as $x =&gt; $content): ?&gt;\n &lt;div id=\"&lt;?=$ids[$x]?&gt;\"&gt;&lt;?=$content?&gt;&lt;/div&gt;\n&lt;?php endforeach ?&gt;\n&lt;/div&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T00:38:06.703", "Id": "410684", "Score": "0", "body": "This is very interesting. I don't have a lot of experience with php so you've shown me quite a bit. In line 3 of your code I simply changed $dir to $pattern, and in line 18 I changed $title to $match[1], since $title no longer exists. I'm still reviewing it but the result is the same as before which is good. Are the overall mechanics of what I'm doing (looping once to capture data, then looping 2 more times to template the content) reasonable?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T05:01:58.783", "Id": "410694", "Score": "0", "body": "Looping 2 times is the only acceptable way. Data preparation should be always separated from the output as output may vary" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T06:28:41.447", "Id": "212306", "ParentId": "212298", "Score": "3" } } ]
{ "AcceptedAnswerId": "212306", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T00:44:49.510", "Id": "212298", "Score": "5", "Tags": [ "php", "html" ], "Title": "Aggregating HTML files" }
212298
<p>I was bored so I crapped out a simple game that responds to commands and manipulates an inventory.</p> <p>I am interested in other possible ways to handle the inventory, and I think I went overboard with the linked lists</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include &lt;time.h&gt; #include &lt;editline/readline.h&gt; #include &lt;editline/history.h&gt; typedef struct command_args { struct command_args* next; char* arg; } command_args_t; void command_add_item(command_args_t, uint8_t); void command_show_inventory(command_args_t, uint8_t); void command_bye(command_args_t, uint8_t); typedef void (*command_func_t)(command_args_t, uint8_t); #define COMMAND_NUMBER 3 char* command_table[] = { "add", "inventory", "bye" }; command_func_t command_func_table[] = { &amp;command_add_item, &amp;command_show_inventory, &amp;command_bye }; #define ADD_ARGS 4 #define WEAPON 0x0001 #define ARMOR 0x0002 #define MAGIC 0x0004 #define MISC 0x0008 typedef struct items { struct items* next; char* name; uint16_t price; uint8_t weight; uint8_t type; } items; typedef struct player { uint16_t coins; uint8_t health; items i; } player; player hero; items* inventory_current = &amp;hero.i; void add_item(char* name, uint16_t price, uint8_t weight, uint8_t type) { inventory_current-&gt;next = (items*)malloc(sizeof(items)); inventory_current-&gt;next-&gt;name = strdup(name); inventory_current-&gt;next-&gt;price = price; inventory_current-&gt;next-&gt;weight = weight; inventory_current-&gt;next-&gt;type = type; inventory_current-&gt;next-&gt;next = NULL; inventory_current = inventory_current-&gt;next; return; } void command_add_item(command_args_t args, uint8_t argc) { if(argc &lt; ADD_ARGS) { printf("[!] you're missing something\n"); return; } printf("\tName: %s\n", args.arg); printf("\tPrice: %s", args.next-&gt;arg); printf("\tWeight: %s", args.next-&gt;next-&gt;arg); printf("\tType: %s\n", args.next-&gt;next-&gt;next-&gt;arg); add_item(args.arg, atoi(args.next-&gt;arg), atoi(args.next-&gt;next-&gt;arg), atoi(args.next-&gt;next-&gt;next-&gt;arg)); return; } void show_inventory() { items* current = &amp;hero.i; for(; current; current = current-&gt;next) { printf("\tINVENTORY\n"); printf("\t\tName: %s\n", current-&gt;name); printf("\t\tPrice: %d", current-&gt;price); printf("\t\t Weight: %d", current-&gt;weight); printf("\t\tType: %d\n", current-&gt;type); } return; } void command_show_inventory(command_args_t _args, uint8_t _argc) { show_inventory(); } void command_bye(command_args_t _args, uint8_t _argc) { exit(0); } void process_input(char* input) { char* term; command_func_t command = NULL; command_args_t args; uint8_t argc; term = strtok(input, " "); for(size_t i = 0; i &lt; COMMAND_NUMBER; i++) { if(strcmp(term ,command_table[i]) == 0) { command = command_func_table[i]; break; } } if(!command) { printf("How should I know how to do that?\n"); return; } args.next = malloc(sizeof(command_args_t)); command_args_t* current = &amp;args; for(argc = 0; term = strtok(NULL, " "); argc++) { current-&gt;next = malloc(sizeof(command_args_t)); current-&gt;arg = term; current = current-&gt;next; } current-&gt;next = NULL; command(args, argc); } int main() { srand(time(NULL)); hero.health = 100; hero.coins = 10; hero.i.name = "Inventory"; hero.i.weight = 0; hero.i.price = 0; hero.i.type = MISC; hero.i.next = NULL; //add_item("Inventory", 0, 0, MISC); char* input; while(input = readline("&gt; ")) { if(input == "") continue; add_history(input); process_input(input); free(input); } } </code></pre>
[]
[ { "body": "<ul>\n<li><p><code>process_input</code> leaks memory like there is no tomorrow. Memory allocated with <code>current-&gt;next = malloc(sizeof(command_args_t));</code> is never released.</p>\n\n<p>On top of that, the sequence</p>\n\n<pre><code> args.next = malloc(sizeof(command_args_t));\n command_args_t* current = &amp;args;\n for(argc = 0; term = strtok(NULL, \" \"); argc++) {\n current-&gt;next = malloc(sizeof(command_args_t));\n</code></pre>\n\n<p>allocates <code>args.next</code> and immediately overwrites this pointer on the very first iteration. Initializing with just <code>args.next = NULL;</code> is more prudent.</p></li>\n<li><p>Having parallel <code>command_table</code> and <code>command_func_table</code> is prone to errors. As the number of commands grows it is easy to lose the sync. I recommend to have a single table of</p>\n\n<pre><code>struct command {\n char * command_name;\n command_func_t command_func;\n};\n</code></pre>\n\n<p>For the same reason of avoiding double maintenance, do not hardcode <code>COMMAND_NUMBER</code>. Either guard the table by the <code>NULL</code> command name, or compute its size at the compile time with the <code>count_of</code>. If your compiler does not support <code>count_of</code>, define it yourself as</p>\n\n<pre><code>#define count_of(arr) (sizeof(arr) / sizeof(arr[0]))\n</code></pre>\n\n<p>As a side note, consider keeping command names alphabetically sorted, to binary search them. As the list of commands grows, you would feel the difference.</p></li>\n<li><p>I don't see how <code>WEAPON</code> and friends are used.</p></li>\n<li><p>I think we all agree that <code>atoi(args.next-&gt;next-&gt;next-&gt;arg)</code> smells.</p>\n\n<p>Besides, it can easily segfault (because <code>process_input</code> is unaware of how many arguments the command needs), or produce incorrect result (because <code>process_input</code> is unaware of argument types).</p>\n\n<p>I recommend to let the <em>command</em> parse its arguments (rather than do it in <code>process_input</code>). <code>process_input</code> would only parse the command name, and pass the rest of input to the command to process. Or use the <a href=\"https://www.gnu.org/software/libc/manual/html_node/Parsing-Program-Arguments.html\" rel=\"nofollow noreferrer\"><code>getopt</code></a> library.</p></li>\n<li><p>It feels very uncomfortable having <code>hero</code> and <code>current_inventory</code> as independent globals. Consider adding an <code>items * last_item;</code> field to <code>struct player</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T06:35:33.487", "Id": "212307", "ParentId": "212304", "Score": "4" } } ]
{ "AcceptedAnswerId": "212307", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T05:39:13.753", "Id": "212304", "Score": "1", "Tags": [ "c", "linked-list", "role-playing-game" ], "Title": "Simple text-based inventory manipulator" }
212304
<p>This is a shopping list program made in Python 3 and it will send the list by email. I am not very experienced but I consider this program as a starting point to what I will do next.</p> <pre><code>import smtplib from email.message import EmailMessage from getpass import getpass name = str(input("Name: ")) email = str(input("Email: ")) password = str(getpass("Password: ")) recipient = str(input("Recipient's email: ")) while True: try: productsnm = int(input(f"Hi, {name}!\nHow many products do you want to add to the shopping list? " )) except ValueError: print ("Please input a number.") else: break products = [] quantities = [] for x in range(int(productsnm)): product = str(input("Input the product name: ")) while True: try: quantity = int(input("Input the product quantity: ")) except ValueError: print ("Please input a number.") else: break products.append(product) quantities.append(quantity) print ("\nThese products have been added to the shopping list:") for x, y in zip(products, quantities): print (f'{x} x {y}') gmail_user = email gmail_password = password msg = EmailMessage() msg['Subject'] = "Shopping List" msg['From'] = gmail_user msg['To'] = [recipient] message = "" for i in range(max(len(products), len(quantities))): message = message + str(products[i]) + " x " + str(quantities[i]) + "\n" msg.set_content(message) try: s = smtplib.SMTP_SSL('smtp.gmail.com', 465) s.ehlo() s.login(gmail_user, gmail_password) s.send_message(msg) s.quit() print ("\nThe email has been sent.") except: print ("\nAn error occurred.") print ("\nHave a nice day!") exit() </code></pre>
[]
[ { "body": "<p>Welcome to Code Review. While your script works as is, it is a good practice to setup and split parts of code into functions, and place the entry point inside <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">the <code>if __name__</code> wall</a>.</p>\n\n<hr>\n\n<p>You have an extra conversion to <code>int</code> for <code>productsnm</code> (which could be better named <code>product_count</code>).</p>\n\n<hr>\n\n<p>Since each product is associated with its own quantity, say hello to a <a href=\"https://devdocs.io/python~3.7/library/collections#collections.namedtuple\" rel=\"nofollow noreferrer\"><code>namedtuple</code></a>:</p>\n\n<pre><code>from collections import namedtuple\nProduct = namedtuple('Product', ['name', 'quantity'])\n# inside the for-loop:\n products.append(Product(name=product_name, quantity=quantity))\n</code></pre>\n\n<p>You wont need the string manipulation, or the loop. Just printing out the <code>products</code> list should give you something like</p>\n\n<pre><code>[Product(name='n0', quantity=0), Product(name='n1', quantity=1), Product(name='n2', quantity=32)]\n</code></pre>\n\n<p>Each element of the list now has <code>name</code> and <code>quantity</code> as its property as well.</p>\n\n<hr>\n\n<p>You can have multiple functions as follows:</p>\n\n<ul>\n<li><code>gather_products_list</code> which returns a list of <code>N</code> products.</li>\n<li><code>generate_email_body</code> to process the <code>products</code> provided to the function and generating the raw email body.</li>\n<li><code>send_email</code> which accepts the aforementioned raw body, and sends it via the provider of choice.</li>\n<li><code>get_integer</code> which repeatedly asks the user to input an integer value. This function could accept an optional <code>prompt</code> message as well as an <code>error</code> message!</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T13:42:21.357", "Id": "212322", "ParentId": "212309", "Score": "2" } }, { "body": "<p>Functions, functions, functions. They make your life a lot easier, because they allow you to give a clear name to things and even add a <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\"><code>docstring</code></a> to it to add even more description of what the function does. It also means that instead of having to read a whole block of code it is usually enough to read the name of the function to know what is happening (if it is a good name, of course, <a href=\"https://martinfowler.com/bliki/TwoHardThings.html\" rel=\"nofollow noreferrer\">one of the harder problems in computer science</a>).</p>\n\n<p>Now, let's get to defining some functions. Ideally each function is responsible for one thing, and one thing only (the <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">Single Responsibility Principle</a>).</p>\n\n<p>First, a function that asks for user input, with a given message and a type:</p>\n\n<pre><code>def get_user_input(message, type=str):\n \"\"\"Ask the user for input using `message`.\n Enforce that the input is castable to `type` and cast it.\n \"\"\"\n while True:\n try:\n return type(input(message))\n except ValueError:\n print (f\"Please input a {type}.\")\n</code></pre>\n\n<p>Note that in your case calling <code>str</code> on <code>input</code> is not necessary in Python 3, since it always returns a <code>str</code>. But here we need it to allow accepting arbitrary types.</p>\n\n<p>Next, I would keep your products and quantities as a dictionary of <code>product_name: quantity</code> key-value pairs. This even allows you to aggregate items if I enter an item multiple times:</p>\n\n<pre><code>def add_item(shopping_list):\n \"\"\"Add an item to the shopping list.\n If the item already exists in the list, add the quantity to it.\n \"\"\"\n name = get_user_input(\"Input the product name: \")\n quantity = get_user_input(\"Input the product quantity: \", int)\n shopping_list[name] += quantity\n</code></pre>\n\n<p>This would normally lead to a <code>KeyError</code> whenever <code>name</code> is not already in the dictionary, but will work out fine if <code>items</code> is a <a href=\"https://docs.python.org/3/library/collections.html#collections.defaultdict\" rel=\"nofollow noreferrer\"><code>collections.defaultdict(int)</code></a>.</p>\n\n<p>Printing the shopping list is also easy:</p>\n\n<pre><code>def print_list(shopping_list):\n for name, quantity in shopping_list.items():\n print(name, \"x\", quantity)\n</code></pre>\n\n<p>And emailing the list to someone should also be a function:</p>\n\n<pre><code>def email_to(shopping_list, from_email, password, *recipients):\n email = EmailMessage()\n email['Subject'] = \"Shopping List\"\n email['From'] = from_email\n email['To'] = recipients\n message = \"\\n\".join(f\"{name} x {quantity}\" for name, quantity in shopping_list.items())\n email.set_content(message)\n\n try:\n s = smtplib.SMTP_SSL('smtp.gmail.com', 465)\n s.ehlo()\n s.login(from_user, password)\n s.send_message(email)\n s.quit()\n print (\"\\nThe email has been sent.\")\n except Exception as e: \n print (\"\\nAn error occurred:\", e)\n</code></pre>\n\n<p>This function could probably be split up further to allow e.g. using a different provider than GMail.</p>\n\n<p>Note that catching all exceptions with a bare <code>except</code> means also e.g. the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd>, which you usually don't want to do. Instead at least catch only <code>Exception</code> and be more specific if you can. You should also print to the user <em>which</em> exception occurred, for which you can use the <code>as</code> keyword.</p>\n\n<p>Then your main calling code becomes:</p>\n\n<pre><code>import smtplib\nfrom email.message import EmailMessage\nfrom getpass import getpass\nfrom collections import defaultdict\n\nif __name__ == \"__main__\":\n name = input(\"Name: \")\n n = get_user_input(f\"Hi, {name}!\\nHow many products do you want to add to the shopping list? \", int)\n shopping_list = defaultdict(int)\n for _ in range(n):\n add_item(shopping_list)\n print_list(shopping_list)\n\n email = input(\"Email: \")\n password = getpass(\"Password: \")\n recipient = input(\"Recipient's email: \")\n email_to(shopping_list, email, password, recipient)\n</code></pre>\n\n<hr>\n\n<p>As you can see, almost all functions actually take <code>shopping_list</code> as a first argument. So you could also make this into a class:</p>\n\n<pre><code>class ShoppingList:\n def __init__(self):\n self.items = defaultdict(int)\n\n def __str__(self):\n return \"\\n\".join(f\"{name} x {quantity}\" for name, quantity in self.items.items())\n\n def add_item(self, name, quantity):\n self.items[name] += quantity\n\n def email_to(self, from_email, password, *recipients):\n ...\n\nif __name__ == \"__main__\":\n name = input(\"Name: \")\n n = get_user_input(f\"Hi, {name}!\\nHow many products do you want to add to the shopping list? \", int)\n shopping_list = ShoppingList()\n for _ in range(n):\n name = get_user_input(\"Input the product name: \")\n quantity = get_user_input(\"Input the product quantity: \", int)\n shopping_list.add_item(name, quantity)\n print(shopping_list)\n\n email = input(\"Email: \")\n password = getpass(\"Password: \")\n recipient = input(\"Recipient's email: \")\n shopping_list.email_to(email, password, recipient)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T16:45:36.237", "Id": "410636", "Score": "0", "body": "So which is better? With or without the class?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T17:26:29.123", "Id": "410637", "Score": "0", "body": "@DavidAndrei: I think here the version with the class is better, because it bundles up all things that manipulate the shopping list (which makes it a perfect candidate to be an object). I did not write the answer with just the class, though, because I wanted to have two different knowledge steps up from your code, the first being to organize the code use functions, the second being OOP." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T18:42:13.527", "Id": "410645", "Score": "0", "body": "When I try to do the class version it throws me this error: KeyError: '__main__.ShoppingList' and I think it is because of email.set_content. Can you tell me what should I put in email.set_content please?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T19:03:32.383", "Id": "410651", "Score": "0", "body": "@DavidAndrei Just replace `shopping_list.items()` with `self.items.items()`. Otherwise it should be exactly the same as the first `email_to`." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T19:08:36.290", "Id": "410653", "Score": "0", "body": "I still get the same error. Here is my entire code: https://pastebin.com/SXu6F7zz" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T07:15:27.513", "Id": "410714", "Score": "1", "body": "Fixed, I had to make message = str(self)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T13:50:30.180", "Id": "212323", "ParentId": "212309", "Score": "2" } } ]
{ "AcceptedAnswerId": "212323", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T08:45:24.433", "Id": "212309", "Score": "4", "Tags": [ "python", "beginner", "python-3.x", "email" ], "Title": "Shopping List program" }
212309
<blockquote> <p>Write the <code>find_boundaries</code> function, which will take a list of numbers. The function should return the tuple with the smallest and largest number in the set. If there is an item in the list that is not a number, it should be ignored. If an empty list is entered, the function should return <code>None</code>.</p> </blockquote> <p>My code:</p> <pre><code>def find_boundaries(lista): if not lista: return None elif lista: max_ = lista[0] min_ = lista[0] new_lista = [] for i in lista: if int == type(i): new_lista.append(i) for i in range(len(new_lista)): if new_lista[i] &gt; max_: max_ = new_lista[i] elif new_lista[i] &lt; min_: min_ = new_lista[i] return max_, min_ </code></pre> <p>I am looking for any opinion/ suggestion on that code. It does what is expected, but would you say that this is the most efficient way to solve that task in Python? </p>
[]
[ { "body": "<p>welcome to Code Review!</p>\n\n<p>I would write your code like this:</p>\n\n<pre><code>def find_boundaries(lista):\n if not lista:\n return None\n\n int_list = [x for x in lista if type(x) == int]\n return (max(int_list), min(int_list))\n</code></pre>\n\n<p>Notice a few things:</p>\n\n<ul>\n<li><p>If you test your parameters for validity at the beginning of the function, it's perfectly fine not to use an <code>else</code> afterwards because the <code>return</code> statement exits the function (short-circuiting). This saves one level of nesting and makes the function more simple.</p></li>\n<li><p>Python is designed to let you avoid writing loops as much as possible. Loops are a nuisance to write, take longer to read and increase cognitive load. You should get familiar with Python's list and dict comprehensions. Notice how much clearer the code for filtering out the values that aren't integers is.</p></li>\n<li><p>Again, the <code>max</code> and <code>min</code> functions are built-in in Python and take any iterable (like a list) to return the largest and smallest element respectively. You don't need to deal with loop indices, the length of the list, etc. You just express what it is you want to return: a tuple that contains the largest and the smallest elements.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T17:55:18.253", "Id": "410641", "Score": "3", "body": "Non-numbers should be filtered out before checking for emptiness" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T19:57:59.003", "Id": "410660", "Score": "2", "body": "I would suggest using `isintance(x, int)` in the list comprehension." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T10:27:08.150", "Id": "212313", "ParentId": "212311", "Score": "6" } } ]
{ "AcceptedAnswerId": "212313", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T09:53:43.937", "Id": "212311", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Find minimum and maximum numbers" }
212311
<p>As an exercise, I wrote a simple context free parser modeled from a pushdown automaton for chemical formulas such as <code>NO2</code> or <code>Fe(NO3)3</code>.</p> <p>To explain a bit about the decisions made:</p> <ol> <li><p>The state functions (<code>pstart</code>, <code>pchem</code> and <code>pnum</code>) are lambdas because they carry around a lot of context. They could be methods of a class, it doesn't really matter.</p></li> <li><p>The state functions have the input character injected because I realized halfway that I have to process some more <em>after</em> the line ended and I don't want to duplicate the state functions.</p></li> </ol> <p>I am mostly concerned about the general <em>messiness</em> of the parser. There is no obvious way to know <em>where</em> variables are mutated, control flow is all over the place and consequently I find it difficult to reason about the program. Is there a better code structure?</p> <p>Finally, I'd like to know if I caught all illegal syntax. Note repeating chemicals like <code>NN</code> is allowed.</p> <pre><code>#include&lt;iostream&gt; #include&lt;stack&gt; #include&lt;unordered_map&gt; #include&lt;string&gt; #include&lt;iterator&gt; using namespace std::literals; enum class state_t { start, num, chem, error }; double parse(std::string line, const std::unordered_map&lt;std::string, double&gt;&amp; m) { auto b = line.begin(), e = line.end(); std::stack&lt;double&gt; stk; int num = 0; std::string chem; state_t state = state_t::start; auto pstart = [&amp;](char c) { if(std::isupper(c)) { chem = ""s + c; state = state_t::chem; return true; } else if(std::isdigit(c)) { if(stk.empty()) state = state_t::error; else { num = c - '0'; state = state_t::num; return true; } } else if(c == '(') { stk.push(-1); return true; } else if(c == ')') { double sum = 0; while(!stk.empty() &amp;&amp; stk.top() &gt; 0) { sum += stk.top(); stk.pop(); } if(stk.empty()) state = state_t::error; else { stk.pop(); stk.push(sum); return true; } } else state = state_t::error; return false; }; auto pnum = [&amp;](char c) { if(std::isdigit(c)) { num = 10 * num + c - '0'; return true; } else { stk.top() *= num; state = state_t::start; } return false; }; auto pchem = [&amp;](char c){ if(std::islower(c)) { chem += c; return true; } else { if(auto it = m.find(chem); it != m.end()) { stk.push(it-&gt;second); state = state_t::start; } else state = state_t::error; } return false; }; while(b != e) { switch(state) { case state_t::start: if(pstart(*b)) b++; break; case state_t::num: if(pnum(*b)) b++; break; case state_t::chem: if(pchem(*b)) b++; break; default: return -1; } } switch(state) { case state_t::num: pnum('\n'); break; case state_t::chem: pchem('\n'); break; } if(state == state_t::error) return -1; double sum = 0; while(!stk.empty() &amp;&amp; stk.top() &gt; 0) { sum += stk.top(); stk.pop(); } if(stk.size() &gt; 0) // expected ')' return -1; return sum; } int main() { std::unordered_map&lt;std::string, double&gt; m; m["Na"] = 23.5; m["Cl"] = 35.5; m["O"] = 16; m["N"] = 14; m["Fe"] = 55.8; std::string line; while(getline(std::cin, line)) std::cout &lt;&lt; parse(std::move(line), m) &lt;&lt; '\n'; } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T11:08:27.837", "Id": "410598", "Score": "1", "body": "I realized `if(stk.size() > 1)` should be `if(stk.size() > 0)`, should I edit?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T11:26:40.897", "Id": "410599", "Score": "2", "body": "Feel free to edit as long as there are no answers. But try to not edit as time goes by." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T13:13:16.663", "Id": "410604", "Score": "0", "body": "it's now possible to write elegant generator functions with coroutines... seems perfect for this application" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T14:26:46.803", "Id": "410608", "Score": "2", "body": "Note, the singular is “automaton”." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T18:50:19.450", "Id": "410646", "Score": "1", "body": "There is a standard for writing chemical formulas to be machine parsable so that they are not ambiguous. Its called SMILE [Simple Molecule Input Line Entry](https://en.wikipedia.org/wiki/Simplified_molecular-input_line-entry_system). The trouble with your system is that for more complex molecules you can't be unambiguous." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T18:53:36.940", "Id": "410648", "Score": "0", "body": "A bucky-ball [c12c3c4c5c1c6c7c8c2c9c1c3c2c3c4c4c%10c5c5c6c6c7c7c%11c8c9c8c9c1c2c1c2c3c4c3c4c%10c5c5c6c6c7c7c%11c8c8c9c1c1c2c3c2c4c5c6c3c7c8c1c23](https://en.wikipedia.org/wiki/Buckminsterfullerene)" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:32:51.797", "Id": "410739", "Score": "1", "body": "You said that you wrote a *parser* but the result of the function is `double` so clearly you’re doing way more than just parsing, and it’s not at all clear (from the names, nor the usage) *what* transformation you’re performing. I’m guessing you are calculating the molecular weight? In which case the function `parse` should be renamed appropriately." } ]
[ { "body": "<p>Using a state machine is fine, but is usually harder to get right than writing the parser with focus on the grammar. You're also mixing a computation with the parsing which adds more information to consider when analyzing the code. \nI would recommend to separate the parser code from the computation and then writing the parser strictly following the grammar you want to parse. I'll try to illustrate what I mean by giving a simplified version of your parser. Say you have a grammar:</p>\n\n<pre><code>formula = *(group)\ngroup = element [ count ]\nelement = uppercase [ lowercase ]\ncount = \"0\" .. \"9\"\n</code></pre>\n\n<p>You can now give a function for each non-terminal:</p>\n\n<pre><code>\n// formula = *(group) ; * becomes while (...) ...\nstd::list&lt;group&gt; parse_formula(std::stringstream&amp; s)\n{\n std::list&lt;group&gt; rv;\n\n while (!s.eof())\n {\n rv.push_back(parse_group(s));\n }\n\n return rv;\n}\n\n// group = element [ count ]\ngroup parse_group(std::stringstream&amp; s)\n{\n group g;\n group.element = parse_element(s);\n try\n {\n group.count = parse_count(s);\n }\n catch (const parse_failed&amp;)\n {\n group = 1;\n }\n}\n\n// element = uppercase [lowercase]\nstd::string parse_element(std::stringstream&amp; s)\n{\n if (!std::isupper(s.peek()))\n {\n throw parse_failed(...);\n }\n\n std::string element = s.get();;\n\n if (std::islower(s.peek()))\n {\n s.get(ch);\n element += ch;\n }\n\n return element;\n}\n\n// count = [0-9]\nunsigned parse_count(std::stringstream&amp; s)\n{ \n if (!std::isdigit(s.peek()))\n {\n throw parse_failed(...);\n }\n\n unsigned rv; \n s &gt;&gt; rv; // this actually violates the grammar as it reads multiple digits\n return rv;\n}\n</code></pre>\n\n<p>You can then iterate over the list of groups and compute the sum.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T12:13:53.977", "Id": "212316", "ParentId": "212312", "Score": "6" } }, { "body": "<h3>Lambdas Too Complex</h3>\n\n<p>You say that the reason behind your lambdas is that they carry a lot of state around, but it is mutating plenty of it as well. Extracting your lambdas into methods in their own right would make it easier to keep track of where your state is used and where it is mutated.</p>\n\n<h3>Methods Should Calculate Or Mutate, Not Both</h3>\n\n<p>Lambdas that calculate something and then mutate something else are notoriously difficult to debug and maintain. When you create your methods, it should either calculate something (such as the atomic weight) or change something (such as changing your state).</p>\n\n<h3>Variable Names Unclear</h3>\n\n<p>Names like <code>pstart</code>, <code>num</code> and <code>m</code> do not tell me anything about the purpose of these variables. There is nothing wrong with <code>LongVariableNamesThatExplainWhatTheyAreDoing</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T12:15:47.390", "Id": "212317", "ParentId": "212312", "Score": "6" } } ]
{ "AcceptedAnswerId": "212316", "CommentCount": "7", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T10:26:21.797", "Id": "212312", "Score": "8", "Tags": [ "c++", "parsing" ], "Title": "Chemical Formula Parser" }
212312
<p>I'm in the process of reading The Rust Programming Language, and decided to do the 3rd task at the end of the 8th chapter. The description is as follows:</p> <blockquote> <p>Using a hash map and vectors, create a text interface to allow a user to add employee names to a department in a company. For example, “Add Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve a list of all people in a department or all people in the company by department, sorted alphabetically.</p> </blockquote> <p>Please tell me if my code is any good.</p> <pre><code>use std::collections::HashMap; use std::io; use std::io::Write; use regex::Regex; fn main() { let add_regex = Regex::new(r"^(?i)Add\s(\w(?:\w|\s)*\w?)\sto\s(\w+)$").unwrap(); let list_regex = Regex::new(r"^(?i)List\s(\w+)$").unwrap(); let all_regex = Regex::new(r"^(?i)Show all$").unwrap(); let mut departments: HashMap&lt;String, Vec&lt;String&gt;&gt; = HashMap::new(); loop { let mut input = String::new(); print!("Enter command: "); io::stdout().flush(); io::stdin().read_line(&amp;mut input); input = String::from(input.trim()); let add_match = add_regex.captures(&amp;input); let list_match = list_regex.captures(&amp;input); let all_match = all_regex.captures(&amp;input); if add_match.is_some() { let unwrapped_match = add_match.unwrap(); let employee = &amp;unwrapped_match[1]; let dpt = &amp;unwrapped_match[2]; match departments.get_mut(dpt) { Some(v) =&gt; { v.push(String::from(employee)); v.sort(); }, None =&gt; { let emp_list = vec![String::from(employee)]; departments.insert(String::from(dpt), emp_list); } } } else if list_match.is_some() { let unwrapped_match = list_match.unwrap(); let employees = departments.get(&amp;unwrapped_match[1]); if !employees.is_some() { println!("No such department"); continue; } println!("Department employees: {}", employees.unwrap().join(", ")); io::stdout().flush(); } else if all_match.is_some() { for (dpt, employees) in &amp;departments { println!("{}: {}", dpt, employees.join(", ")); } } else { println!("Please enter a valid command"); } } } </code></pre> <p>Sample output:</p> <pre><code>Enter command: add f to ff Enter command: add b to ff Enter command: list ff Department employees: b, f Enter command: add Darth Vader to ff Enter command: list ff Department employees: Darth Vader, b, f Enter command: add d to zz Enter command: add 1 to zz Enter command: show all ff: Darth Vader, b, f zz: 1, d </code></pre>
[]
[ { "body": "<p>At a glance: that function is way too long and deeply nested. Three levels of loop/branch nesting is, in my experience, the most that any function should have; and the more nested it is the shorter it should be. </p>\n\n<p>Consider extracting branch and loop bodies to separate named functions.</p>\n\n<hr>\n\n<p>Your code structure also seems to be “determine what command to execute” (add / list / etc), then “execute said command”. I’d make this explicit, have the regexp parsing of an input line in a separate function that returns the command type and parameters. Dispatching this would be a natural use for <code>match</code> over your own Command type. (That said, in a realistic CLI you might need the commands available to be extensible so don’t get too married to this pattern. I’m guessing you’ll get to dynamic polymorphism later in the book.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T14:50:48.790", "Id": "212327", "ParentId": "212321", "Score": "0" } } ]
{ "AcceptedAnswerId": "212327", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T13:29:07.850", "Id": "212321", "Score": "2", "Tags": [ "beginner", "rust" ], "Title": "Text interface for employee management in Rust" }
212321
<p>Problem is taken from <a href="https://leetcode.com/problems/count-binary-substrings" rel="nofollow noreferrer">leet code</a>. Give a string s, count the number of non-empty (contiguous) substrings that have the same number of 0's and 1's, and all the 0's and all the 1's in these substrings are grouped consecutively. Substrings that occur multiple times are counted the number of times they occur.</p> <p>Example 1:</p> <pre><code>Input: "00110011" Output: 6 Explanation: There are 6 substrings that have equal number of consecutive 1's and 0's: "0011", "01", "1100", "10", "0011", and "01". Notice that some of these substrings repeat and are counted the number of times they occur. </code></pre> <p>Here is my scala implementation of the same</p> <pre><code>object SubStrings extends App { def countBinarySubstrings(s: String): Int = { val (_,_, total) = s.foldLeft((0,0,0)) { case ((count0, count1, total), c) =&gt; if(count0 == 0 &amp;&amp; count1 == 0) {= if (c == '0') (count0 + 1, count1, total) else (count0, count1 + 1, total) } else { if (c == '0' ) { val newCount0 = count0 + 1 if (count1 &gt; 0) (newCount0, count1-1, total+1) else (newCount0, count1, total) } else { val newCount1 = count1 + 1 if (count0 &gt; 0) (count0-1, newCount1,total+1) else (count0,newCount1,total) } } } total } </code></pre> <p>Solution works for few strings I tested. But it seems there is a bug in this code as it is failing for one of the test case on the leet code. I am not able to figure it out. Kindly help.</p> <p>Failing test case is this -</p> <pre><code>"1100111110110110011111111111110011001011111111100110111111111101010010011110001111110111101111110101110100001111001110011101011000111011101011111110101100101111110101101101111111001111111000011110110101111111111010101001111100010000001001101001100101111110110111110111111010011001110111101110001011100110011010001011100000001101000011100111111010110101110110000011110110111101010110010101111101011111111111110100110101111101111001101011101111111111100111011011010010110111111101110011011111111110001110110000101111111111101110011111011100010111110011110111111110111000110101011101101011101011011100011101101111110111000111110101100110111111001111110111111101101110011101110111110111111101001111100111010111011110011011100101100101010110001011100110111101111110111111111110010101100100111110101011111010101101101111110111111011011001001111001111000111010111100100110011111111100100111100011111011100001001101111011011110010101110001111010000001111110001011000110110111111000110001110101100111111100011100101000111011101110011111111111011111101111110011110111101110011111101110111110111111101111101011010111110110011011101101111100001000101010110110111011111110111111100110111011001111011100011011100101010111111111101110010101101001111011110111011110011000000110111111111101111010110010010111111100111110111000101111010111011111111111000001011111011110111111111111100100100001101101111110010000111101001111111101011010011110011011111000111010000010110011011011011111111110011111101100010111011010111011111111110101110101001101100010111111001101011011111001000101011111011111011110110101111111011011110101111001010110001101011000110110011111101100111110100101111011001000111111110100111101100101111111010110110011110010010111010111111101111101111101001110011101111110001110111010011011101111100011111111101010101101011111111100110111100111101110110010110111100011111010110011111101101101000110110001010001111011100100111111111011111011111111100101111001111110011010010010111111110110001001101111110011111010110011101111110110010000001111111000110111101101111010111110001011100011111011100100000111111011011010010100110101011001111111101111010111111000101110001011111010110110111111111111101101011100000110101001111010110111100011011110100110111111111111111100011011011110011010011100111111111110110111001110100110111010010110111111111111111110001101111011111110111010001101110111110100111110111111110110111111111011111000000101101101111011011111111111111011111000101111111101111111111111111111111100100111000011010001000110110110111111110101111000110100100001111011100111111010100101101010100000111001111101011001111110111011111011010111111011111011010100111011110001000010111110110111110111011011010001010101101111111101111100010010111101100000110100101111010100111101110111011101001101101111001110111101101111101000110110110111101111011011101010001111010011111110111011011100001111111111111000111010101001110010100011011011101111010111110011111010101101010101111110010101111010111001110000011110100011110110111101001110011101110110101111111000101111010111110111110001111110100100001101010001011111110010110110000101111110110111101000101111011111011001100000111111111101010010100111100111110111100011111101111011111100111110000101111011101001001111001101110100100101101111001111111111000110111111101010110011010010011001000111100010100111111001101111110011111000111101011101111110101111101111010110111111101111011111111111100001101100110110011111111101111111101011010010110110011101000111101111110111111011111111110110011100001111110001111011100111111101011111110100110000110011001011111001001110111011110101101101011011011010011110111011100101011011001110001001101011010111000001101011111111101011001111001001100001111110101001111111011100000111100110101010010111101110111011111010110101111101100111111110011011101011101111110011000110111010110011111111111100111011101111011111101111110011101011100101100100111111111111011011100111111111100101111111001111010100011011111001000010111101111111011111100111110111010101111111011111011010000110010111011011000111111011010000111001010101111101011111010111100011001011110111011101110001000111111111100101100110011011011110111111000100010111111011110100111010111111111001011111111111001111110110010011001111100111011110011111000101101111100110011000010100110111101100111110111101111011111100110011011111011001101010111111111010111111100101101011111111011100001111011011111111011111110010100110000000011000010111011101111101111111101101111001011111010110110101011100001110100101001111001111011101101010011010110111101111110101101111100110111101111111101010000101010010001110111000110101101100101111101101011100101111011111101111011110100001011110110111111111011000111111001111010111011010111000101110011010110010111111101111111110111011111010110111111001010111001110110101011000111110000010001101111111000011010110111100010111110010001110011111001110101001000100111011110000100111101101111010011101011010101101000011111111011101111111101111101101110111011111001110111101010111000101010111010111110110010110110111111110111111110011101111011111011111111001111110100110100010110001111101111000111100111101101010110100110110110111001111111111010011011001111111111111010111011101101010100111111011111000110111111011111010111110101110100011110110100100100101111111111111111011110001100011101011101111010111111000000011100111001011110111110110110101100011100101110010001111110011110110101011001101101110001001111110110111111110110011101100111011111011010110011010100011111101101000100010001111110110101000010110111111111111101111001011101011000000101011011101111001010110011111101100110011100101101110111100011011111100110111111111011111001110110000010010111001111110010111111010110010100011101111100111011111011110110101110101101100000001011101001111111000001110010110111011111111011110110111011001111111101000101110111110111001110001001011011010111111011000111111111101111111100000110110011110011010110101101111101000101101011110111001100110111111100111101001000001001110101110111111110011101001011111011010110111100001110110011111010111111011111110111010101110011010100100110111111111011011011010100001001100010111101110110111001110011011111101111001001111111111100110101111011110111111111010101101011110111111101001111001011011110011111110111011110101100011111111011110111101011111011011110111100100101101101111110111110011110100011010111001100011111110101111101100011111111010111011100011110110111101110001111111110011011101111111010010110010100111111111111111010101111111101111010001010001001101110001100101101101001000101111110110110011010101100101101100110011111010011000010111001011110110110101101010011110011101101100011110110011100010111100111101001000011101110111100111010101111011111001100111011010111001101101110000011011000111101111010111001101111111101110111010110111110111011111101101001001110110011111011101111010001111011111100110011100111011111111001111111111010010001111111111001011010010101110111101111111001011110010111101011111111111111000001111100101111111011101101110011110111101110110111101001100000110000111110001010010111111111011011011011111110111101101011011111101101011100111111101001111011110011101101111010111011011100111100101111111011100111101101010101000111111111101101101111111101110011111111101011101011111111010110110101111001111010011100011111011111100001101011010110101100011111101100111110011011110100110001111011110100111010111111010110111111111011001011111111011111100110110111100111110010011110110011011110110001111011100111101101110011101001101100110110111101000011110011010110101111111111011101110110100101110100011110101010101110111011111101111001011011100101011011010111111010111100000011010011111010110101001111111011101000001010011101111100101111011111111111010110111111011100110111001011001011111111101110111011001111111111111110010101101011011010011101110111000011111010111001011111111111101011111011110100011111010010101110111100110111011010000111001001001111110010110011101110101101011011110001001011100000100101111111100101111011010111111101011100011100111011100100101100111101001011110011001100110001000111110110110001110110111100110111111100111111111101110111111111000001110110101110110010011101110100111001001110110110101101111001001111111100101101101101011101111111010011011101011110111010000011101111001101011111011011110111101010101110101100111110011001111101111111011101001101111111111010001011011010110110001110111111110011111111001110100101111011111110100111110111110011111110011111101111110101100100001110110111110101110011100101111100110111111011111100101111110100001010011110010110101111110010010011100001011001011010101110111011111010101101001101010101111110111011110111101111111111110111011111010101011000110001110111111110111010110110111111110101101111001101111010111010110101110011101111011111111010111111111101010011001101111111011011101110011100101110001111011111010110111111110101011111010111111110111110011111110111001011100111111110111110101101110011011110011110101111111111011011101111110110001001111101100100000111110101010000110011111101011111101111100110011111011010011011011010000001101111111011010111100100111100101101011010101010010111110010010111010001011101011111110000011111010110111101011101101101010010011100111011010110011111110010010111111101011111111111101111111110101100101111111110000110011000101011110111010110011001011000011000001000100110011100111111110011011111111001010011110011101101110011011110010101011101011111010101011001111110010111011111001100100110011010011100110111101010111101110101011111111111111000101111111011010111111010010000101111010101001111111001111010000111111010011111111010001010011011100111111001110011111011101010001111111011001001101111111010111101000111001010111001011111111011110001001111111110111111011100110101111010111101011111111100010000111011111011000111111111111100111011001001111001111110000101110100011101111111101110111111111111111110110001101010101110111110111101111110011010111011101111110111111011101111111001111111011110111111" </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T09:21:04.790", "Id": "410726", "Score": "0", "body": "From the [don't-ask help page](https://codereview.stackexchange.com/help/dont-ask) (emphasis added): \"Code Review is for open-ended questions about code that _already works correctly_ (to the best of your knowledge).\"" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T13:11:13.423", "Id": "410753", "Score": "0", "body": "Thanks for pointing out, I will keep this in mind ad post in appropriate forum next time." } ]
[ { "body": "<p>Your algorithm does not reset the counters when necessary.</p>\n\n<p>Assume an input with a large number of <code>0</code>s followed by <code>10</code> followed by a large number of <code>1</code>s: <code>000...00010111...111</code>.</p>\n\n<p>The result should be 3 since there are three substrings <code>01</code>, <code>10</code>, and <code>01</code> that satisfy the requirement. However, since <code>count0</code> is not reset, it stays large and lets <code>total</code> be incremented for each trailing <code>1</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T16:01:35.173", "Id": "212331", "ParentId": "212324", "Score": "1" } }, { "body": "<p>By utilizing the power of pattern matching, your (faulty) algorithm can be expressed in a much more succinct manner that is also (IMHO) easier to read and comprehend.</p>\n\n<pre><code>def countBinarySubstrings(s: String): Int =\n s.foldLeft((0, 0, 0)) {\n case ((zeros,0 ,ttl), '0') =&gt; (zeros+1, 0 , ttl)\n case ((0 ,ones,ttl), '1') =&gt; (0 , ones+1, ttl)\n case ((zeros,ones,ttl), '0') =&gt; (zeros+1, ones-1, ttl+1)\n case ((zeros,ones,ttl), '1') =&gt; (zeros-1, ones+1, ttl+1)\n case _ =&gt; throw new Error(\"bad string\")\n }._3\n</code></pre>\n\n<hr>\n\n<p>Here's a reworking of your basic algorithm. It fixes the bug (I believe) by updating the running total only at the transitions from 0-to-1 or 1-to-0.</p>\n\n<pre><code>def countBinarySubstrings(s: String): Int = {\n val (runningTotal, countA, countB, _) = s.foldLeft((0, 0, 0, '_')) {\n case ((rt, otherCnt, thisCnt, prevC), currC) =&gt;\n if (prevC == currC) //same Char\n (rt, otherCnt, thisCnt + 1, currC) //increment this-Char count\n else //transition\n //update running total\n //move this-count to other-count position\n //reset this-count\n (rt + (otherCnt min thisCnt), thisCnt, 1, currC)\n }\n runningTotal + (countA min countB) //final update\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:44:02.627", "Id": "212372", "ParentId": "212324", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T13:53:20.110", "Id": "212324", "Score": "1", "Tags": [ "strings", "interview-questions", "functional-programming", "scala" ], "Title": "Count Substrings for a binary string" }
212324
<p>A simple tip calculator that asks for the total bill amount, service quality (used to determine what percentage of the total cost will be tipped), and how many people are sharing the bill (used to split the tip so that everyone pays the same amount).</p> <p>I am primarily looking for possible improvements to performance or readability, but <strong>any suggestion is welcome</strong>.</p> <p>See the code in action - <a href="http://jsfiddle.net/mvfg54e2/2/" rel="nofollow noreferrer">jsFiddle</a></p> <p>Link to repository - <a href="https://github.com/merkur0/Pure-JS-Tip-Calculator" rel="nofollow noreferrer">GitHub</a></p> <pre><code>// Pointers const billAmountAlertPointer = document.getElementById('billAmountAlert'); const tipPercentageAlertPointer = document.getElementById('tipPercentageAlert'); const numberOfPeoplePointer = document.getElementById('numberOfPeople'); const serviceQualityPointer = document.getElementById('serviceQuality'); const numberOfPeopleLabelPointer = document.getElementById('numberOfPeopleLabel'); const eachPointer = document.getElementById('each'); const soundPointer = document.getElementById('cashRegisterSound'); soundPointer.volume = 0.05; var numberOfPeople = 1; // Display the text 'people' next to the input if the number of people is higher than 1 numberOfPeoplePointer.oninput = function(){ numberOfPeople = numberOfPeoplePointer.value; numberOfPeople &gt; 1 ? numberOfPeopleLabelPointer.innerHTML = 'people' : numberOfPeopleLabelPointer.innerHTML = 'lone wolf'; }; document.getElementById('calculateButton').addEventListener('click', function() { let billAmount = document.getElementById('billAmount').value; let tipPercentage = serviceQualityPointer.value; // Only proceed if both the billAmount and the tipPercentage have a value if (billAmount !== '' &amp;&amp; tipPercentage !== ''){ setDisplay(billAmountAlertPointer, 'none'); setDisplay(tipPercentageAlertPointer, 'none'); let tipAmount = (billAmount / (100 / tipPercentage)) / numberOfPeople; document.getElementById('tipAmount').innerHTML = '$' + tipAmount; /* If the number of people sharing the bill is higher than 1, display the text 'each' next to the input. Otherwise, don't.*/ numberOfPeople &gt; 1 ? setDisplay(eachPointer, 'block') : setDisplay(eachPointer, 'none'); document.getElementById('tipAmountContainer').style.display = 'block'; // Play the cash register sound playSound(); } else{ // If the user hasn't entered the bill amount, display an alert if (billAmount === ''){ setDisplay(billAmountAlertPointer, 'inline'); } // If the user hasn't entered the tip percentage, display an alert if (tipPercentage === ''){ setDisplay(tipPercentageAlertPointer, 'inline'); } } }); function setDisplay(element, value){ element.style.display = value; } function playSound(){ soundPointer.play(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T17:46:38.527", "Id": "410640", "Score": "0", "body": "Why are `document.getElementById('billAmount')`, `document.getElementById('tipAmount')` and `document.getElementById('tipAmountContainer')` not declared at `// Pointers`?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T21:02:59.763", "Id": "410666", "Score": "0", "body": "@guest271314 That's because they are only being used once, so creating pointers for them seemed unnecessary" } ]
[ { "body": "<h1>Review</h1>\n\n<p>For what it does that is very dense code. Consider reducing variable name length.</p>\n\n<h2>Major points</h2>\n\n<ul>\n<li>Direct element reference reduces code size, improves performance, and forces you to ensure element IDs and names are unique.</li>\n<li>Adding content via <code>innerHTML</code>, clobbers events, forces reflows, and chews power.</li>\n<li>Incorrect currency handling. Money comes in cents, not fractions of a cent. Always use integer math for calculations that involve cash exchanges.</li>\n</ul>\n\n<h2>Minor points</h2>\n\n<ul>\n<li>Avoid adding event listeners directly to the element's <code>on</code> property. Use <code>addEventListener</code></li>\n<li>There are some cases where <code>innerHTML</code> can be useful, most of the time it is the worst way to add to the DON. Don't use it! </li>\n<li>Add text content via <code>element.textContent</code>.</li>\n<li>Don't change element style properties directly, create CSS rules and set the appropriate class name.</li>\n<li>Use <code>const</code> for constants.</li>\n<li>Don't add comments that point out the obvious.</li>\n<li>Use arrow functions for anon functions;</li>\n</ul>\n\n<h2>Direct element reference</h2>\n\n<p>All elements that have an Id property set can be accessed by that id directly in the global namespace.</p>\n\n<pre><code>&lt;div id=\"divEl\"&gt;Foo&lt;/div&gt;\n&lt;script&gt;\n const element = document.getElementById(\"divEl\");\n // is the same as\n const element = divEl;\n\n ...\n</code></pre>\n\n<p>This works on all browsers (and has done since netscape died). You MUST ensure that id's are unique, if not your page can not be validated and will enter quirks mode. Browser behaviour will differ if in quirks mode.</p>\n\n<p>Using direct referencing forces you to ensure id's are unique and thus avoid a very common cause of quirky DOM modes. It also greatly reduces the overhead of needing to use DOM queries to locate elements. </p>\n\n<p>Direct referenced elements are live.</p>\n\n<h2>Working with money</h2>\n\n<p>When working with currencies you need to remember that money is exchanged in integer units. For the US that is cents. Your calculations do not handle the tip correctly. eg bill = $1000, tip 10%, for 3, means each person must pay $33.33333...</p>\n\n<p>Always work in cents, always round to cent, or round up if there is an exchange priority. In this case you convert the bill to cents, calculate the tip per person, rounding up to nearest cent then convert back to dollars.</p>\n\n<pre><code>bill *= 100; // convert to cents\nbill = Math.round(bill); // round to nearest\ntip = bill / 100 * tip / people; // get tip in cents per person\ntip = Math.ceil(tip); // round up\ntotal = bill + tip * people; // Get total in cents \n</code></pre>\n\n<p>When displaying currency always use <code>Number.toLocaleString</code>. Eg displaying the above values.</p>\n\n<pre><code>tipPerPersonDisplay = (tip / 100).toLocaleString(\"en-US\", {style: \"currency\", currency: \"USD\"});\ntotalBillDisplay = (total / 100).toLocaleString(\"en-US\", {style: \"currency\", currency: \"USD\"});\n</code></pre>\n\n<h2>Example</h2>\n\n<p>Note that element ids have been prepended with <code>El</code> as I do not know what other code or markup you have.</p>\n\n<p>The code size has be reduce by half meaning its is easier to maintain and read.</p>\n\n<p>Money is handled correctly and rounded up to favour the tip (a cent per person max)</p>\n\n<pre><code>const CURRENCY = [\"en-US\", {style: \"currency\", currency: \"USD\"}];\nconst setElClass = (el, cName, show = true) =&gt; el.classList[show ? \"add\" : \"remove\"](cName);\n\nnumberOfPeopleEl.addEventListener(\"input\", () =&gt; {\n numberOfPeopleLabelEl.textContent = numberOfPeopleEl.value &gt; 1 ? \"people\" : \"lone wolf\";\n});\n\ncalculateButtonEl.addEventListener('click', () =&gt; {\n var tip = serviceQualityEl.value;\n const bill = billAmountEl.value;\n const people = numberOfPeopleEl.value;\n\n setElClass(billAmountAlertEl, \"alert--show\", isNaN(bill));\n setElClass(tipPercentageAlertEl, \"alert--show\", isNaN(tip)); \n\n if (!isNaN(bill) &amp;&amp; !isNaN(tip)) {\n tip = Math.ceil(Math.round(bill * 100) / 100 * tip / people); // in cents per person\n tipAmountEl.textContent = (tip / 100).toLocaleString(...CURRENCY);\n setElClass(eachEl, \"people-count--show\", people &gt; 1);\n tipAmountContainerEl.classList.add(\"tip-amounts--show\");\n cashRegisterSoundEl.volume = 0.05;\n cashRegisterSoundEl.play();\n }\n});\n</code></pre>\n\n<p>You will also need the following CSS rules.</p>\n\n<pre><code>.alert--show { display : inline }\n.people-count--show { display : inline }\n.tip-amounts--show { display : block }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T18:06:00.987", "Id": "212334", "ParentId": "212328", "Score": "3" } } ]
{ "AcceptedAnswerId": "212334", "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T14:58:08.030", "Id": "212328", "Score": "3", "Tags": [ "javascript", "performance", "ecmascript-6", "dom" ], "Title": "Tip Calculator in pure JS" }
212328
<p>Task: Create a service which will synchronize files on FTP server with files on local drive.</p> <ol> <li>FTP server allows up to 15 concurent connections</li> <li>Synchronize the files as fast as possible</li> <li>Files on FTP server are archived after 7 day, we should archive them too at our side</li> <li>Files once put on the FTP server do not change</li> <li>Folder structure of FTP server is unknown upfront</li> <li>There are ~1,5K folders containing ~70K files on the FTP server.</li> </ol> <p>I did the task. The service is running stable and synchronizes files within 10min usually. This was my first big attempt on async/await/parallelism.</p> <p>I'm especially interesed in comments regarding the <code>ParallelFtpClient</code>. It uses the package <code>FluentFTP</code>.</p> <p>I've tried to strip unimportant details from the code.</p> <p><code>Program.cs</code> and "main" loop:</p> <pre><code>class Program { private static ILog _logger; private Task _mainTask; private CancellationTokenSource _cancellationTokenSource; public static void Main() { var dataBase = new DataBase(...); var ftpSyncer = new FtpSyncer(config.LocalShare, config.FtpHost, config.FtpPort, config.FtpUser, config.FtpPassword, config.MaxConcurrentFtpConnections, config.FtpRootDirectory, dataBase); _cancellationTokenSource = new CancellationTokenSource(); var cancellationToken = _cancellationTokenSource.Token; _mainTask = Task.Run(async () =&gt; { while (!cancellationToken.IsCancellationRequested) { try { LogicalThreadContext.Properties["CorrelationId"] = Guid.NewGuid(); _logger.Info("Synchronizing files from FTP..."); await ftpSyncer.SynchronizeFiles(); _logger.Info("Done synchronizing files from FTP"); } catch (Exception e) { _logger.Error("An unhandled excpetion occured while synchronizing files. Execution will continue", e); } try { _logger.Info($"Sleeping for {config.DelayBetweenRunsSeconds}s before next Ftp synchronization"); await Task.Delay(TimeSpan.FromSeconds(config.DelayBetweenRunsSeconds), cancellationToken); } catch (OperationCanceledException) { // just exit loop } } }); _logger.Info("Service started"); } private void Stop() { _logger.Info("Service stopping..."); _cancellationTokenSource.Cancel(); _logger.Info("Waiting for the main task to stop..."); _mainTask.Wait(); _logger.Info("Done waiting for the main task to stop..."); } } </code></pre> <p><code>FtpSyncer.cs</code> does the job of synchronizing files:</p> <pre><code>public class FtpSyncer { private readonly ILog _logger = LogManager.GetLogger(typeof(FtpSyncer).FullName); private readonly string _localShare; private readonly string _ftpHost; private readonly string _ftpPass; private readonly int _ftpPort; private readonly string _ftpUser; private readonly int _maxConcurentFtpConnections; private readonly Database _database; private readonly string _ftpRootDirectory; private readonly int MAX_DATABASE_CONNECTION_RETRIES = 3; private readonly int MAX_DOWNLOAD_RETIRES = 3; public FtpSyncer(string localShare, string ftpHost, int ftpPort, string ftpUser, string ftpPassword, int maxConcurentFtpConnections, string ftpRootDirectory, Database database) { _localShare = localShare; _ftpHost = ftpHost; _ftpPort = ftpPort; _ftpUser = ftpUser; _ftpPass = ftpPassword; _maxConcurentFtpConnections = maxConcurentFtpConnections; _database = database; _ftpRootDirectory = ftpRootDirectory; } public async Task SynchronizeFiles() { IFtpClient factory() =&gt; new FtpClient(_ftpHost, _ftpPort, _ftpUser, _ftpPass); using (var parallelFtpClient = new ParallelFtpClient(_maxConcurentFtpConnections, factory)) { var gettingRemoteFiles = Task.Run(() =&gt; { _logger.Info("Connecting to FTP..."); parallelFtpClient.Connect(); _logger.Info($"Querying for directories under {_ftpHost}{_ftpRootDirectory} with files on FTP (excluding Archive directories)..."); var directoriesWithFiles = parallelFtpClient.ListNonArchiveDirectoresWithFiles(_ftpRootDirectory); _logger.Info($"There are {directoriesWithFiles.Count} directories with files on {_ftpHost}{_ftpRootDirectory}"); _logger.Info("Querying for files on FTP..."); var allFtpFiles = parallelFtpClient.ListFilesInDirectories(directoriesWithFiles); _logger.Info($"There are {allFtpFiles.Count} files under {_ftpHost}{_ftpRootDirectory}"); return allFtpFiles; }); var gettingLocalFiles = Task.Run(() =&gt; { _logger.Info("Querying for files already in local share..."); var allFilesOnShare = Directory.GetFiles(Path.Combine(_localShare, "20160301"), "*", SearchOption.AllDirectories); _logger.Info($"There are {allFilesOnShare.Length} files in {_localShare}"); // unify paths to format used by FTP var allFilesOnShareFtpPathFormat = allFilesOnShare .Select(x =&gt; x.Replace(_localShare, "")) .Select(x =&gt; x.Replace(@"\", "/")) .ToArray(); return allFilesOnShareFtpPathFormat; }); var filesOnFtp = await gettingRemoteFiles; var filesOnShare = await gettingLocalFiles; var toBeDownloaded = filesOnFtp .Except(filesOnShare, StringComparer.OrdinalIgnoreCase) // windows paths are case-insensitive // remove leading slash '/' from filePath (if you don't remove it Path.Combine() will not combine paths) .Select(ftpFilePath =&gt; (ftpFilePath, Path.Combine(_localShare, ftpFilePath.Substring(1)))) .ToList(); _logger.Info($"There are {toBeDownloaded.Count} files to be downloaded"); _logger.Info($"Downloading files to {_localShare}..."); List&lt;(string, string)&gt; failedDownloads; var downloadedFiles = DownloadFilesWithRetires(parallelFtpClient, toBeDownloaded, out failedDownloads); if (failedDownloads.Any()) { var dump = string.Join("\n", failedDownloads); _logger.Error($"{failedDownloads.Count} files failed to be downloaded after {MAX_DOWNLOAD_RETIRES} attempts. " + $"List:\n" + dump); } _logger.Info($"Done downloading files, {downloadedFiles.Count} files downloaded"); _logger.Info("Disconnecting FTP clinets..."); parallelFtpClient.Disconnect(); _logger.Info("Done disconnecting FTP clinets"); _logger.Info("Registering files..."); var registerInfos = MapFileToDatabaseRegisterInfo.Map(downloadedFiles); var toNotBeRegistered = registerInfos.Where(x =&gt; x.FileTypes.Count == 0).ToArray(); var toBeRegistered = registerInfos.Where(x =&gt; x.FileTypes.Count == 1).ToArray(); var filesWithMultipleMatchingFileTypes = registerInfos.Where(x =&gt; x.FileTypes.Count == 2).ToArray(); _logger.Info($"There are {toBeRegistered.Length} files to be registered"); _logger.Info($"There are {toNotBeRegistered.Length} files which will not be registered"); if (filesWithMultipleMatchingFileTypes.Any()) { _logger.Warn($"There are {filesWithMultipleMatchingFileTypes.Length} with multiple matching Database FileTypes"); foreach (var registerInfo in filesWithMultipleMatchingFileTypes) { var listing = string.Join(", ", registerInfo.FileTypes); _logger.Warn($"File {registerInfo.FullFilePath} was matched with FileTypes: {listing}"); } } var filesAreRegistered = RegisterInDatabaseWithRetries(toBeRegistered); if (filesAreRegistered) { _logger.Info("Done registering files"); } else { var dump = string.Join("\n", toBeRegistered.Select(x =&gt; x.ToJson())); _logger.Error($"Could not register files after {MAX_DATABASE_CONNECTION_RETRIES} retries. " + $"Dumping list of files which should be registered: \n{dump}"); } _logger.Info("Archiving files..."); var toBeArchived = filesOnShare .Except(filesOnFtp, StringComparer.OrdinalIgnoreCase) // windows paths are case-insensitive .Select(x =&gt; x.Substring(1)) // remove leading '/' so the path will be treated as relative .Select(x =&gt; Path.Combine(_localShare, x)) .ToArray(); _logger.Info($"There are {toBeArchived.Length} files to be archived"); MeteologicaFilesArchiver.Archive(toBeArchived); _logger.Info("Done Archiving files..."); } } private List&lt;string&gt; DownloadFilesWithRetires(ParallelFtpClient parallelFtpClient, List&lt;(string, string)&gt; toBeDownloaded, out List&lt;(string, string)&gt; failedDownloads) { List&lt;string&gt; allDownloadedFiles = new List&lt;string&gt;(); var attempt = 1; do { _logger.Info($"Downloading files - attempt {attempt}/{MAX_DOWNLOAD_RETIRES}"); var downloadedFiles = parallelFtpClient.DownloadFilesParallel(toBeDownloaded, out failedDownloads); allDownloadedFiles.AddRange(downloadedFiles); if (failedDownloads.Any()) { _logger.Warn($"{failedDownloads.Count} files were not downloaded. This was the {attempt}/{MAX_DOWNLOAD_RETIRES} attempt"); toBeDownloaded = failedDownloads; attempt++; } } while (attempt &lt;= MAX_DOWNLOAD_RETIRES &amp;&amp; failedDownloads.Any()); return allDownloadedFiles; } private bool RegisterInDatabaseWithRetries(RegisterInfo[] toBeRegistered) { var retryCount = 1; var filesAreRegistered = false; while (filesAreRegistered == false &amp;&amp; retryCount &lt;= MAX_DATABASE_CONNECTION_RETRIES) { try { _database.Register(toBeRegistered); filesAreRegistered = true; } catch (SqlException e) // catch this excetpion because it might be a timeout { _logger.Warn($"An exception occured while trying to register files in Database. " + $"This was the {retryCount} attempt out of max={MAX_DATABASE_CONNECTION_RETRIES} attempts.", e); retryCount++; if (retryCount &lt;= MAX_DATABASE_CONNECTION_RETRIES) { var sleepTime = 10 * Math.Pow(2, retryCount); _logger.Info($"Sleeping {sleepTime}s before next attempt..."); Thread.Sleep(TimeSpan.FromSeconds(sleepTime)); } } } return filesAreRegistered; } } </code></pre> <p><code>ParallelFtpClient.cs</code> usses 15 connections to get info/data from the FTP server as fast as possible:</p> <pre><code>public class ParallelFtpClient : IDisposable { private readonly ILog _logger = LogManager.GetLogger(...); private readonly int _maxConcurentConnections; private readonly Func&lt;IFtpClient&gt; _factory; private readonly List&lt;IFtpClient&gt; _ftpClients; public ParallelFtpClient(int maxConcurentConnections, Func&lt;IFtpClient&gt; factory) { _maxConcurentConnections = maxConcurentConnections; _factory = factory; _ftpClients = new List&lt;IFtpClient&gt;(); } public void Connect() { var tasks = new List&lt;Task&gt;(); for (int i = 0; i &lt; _maxConcurentConnections; i++) { var ftpClient = _factory(); _ftpClients.Add(ftpClient); var connectTask = ftpClient.ConnectAsync(); tasks.Add(connectTask); } Task.WaitAll(tasks.ToArray()); } public void Disconnect() { var tasks = _ftpClients .Select(x =&gt; x.DisconnectAsync()) .ToArray(); Task.WaitAll(tasks); } public List&lt;string&gt; ListFilesInDirectories(IEnumerable&lt;string&gt; directories) { var items = new ConcurrentBag&lt;FtpListItem&gt;(); var clients = new ConcurrentQueue&lt;IFtpClient&gt;(_ftpClients); Parallel.ForEach(directories, new ParallelOptions() {MaxDegreeOfParallelism = _maxConcurentConnections}, (path) =&gt; { IFtpClient client; clients.TryDequeue(out client); var listing = client.GetListing(path); foreach (var item in listing) { items.Add(item); } clients.Enqueue(client); }); var list = items .Where(x =&gt; x.Type == FtpFileSystemObjectType.File) .Select(x =&gt; x.FullName) .ToList(); return list; } public List&lt;string&gt; DownloadFilesParallel(IEnumerable&lt;(string,string)&gt; ftpPathLocalPathPairs, out List&lt;(string, string)&gt; failedDownloads) { var clients = new ConcurrentQueue&lt;IFtpClient&gt;(_ftpClients); var downloadedFiles = new ConcurrentBag&lt;string&gt;(); var failedDownloadsBag = new ConcurrentBag&lt;(string,string)&gt;(); Parallel.ForEach(ftpPathLocalPathPairs, new ParallelOptions() {MaxDegreeOfParallelism = _maxConcurentConnections}, (ftpPathLocalPathPair) =&gt; { IFtpClient client; clients.TryDequeue(out client); var ftpFilePath = ftpPathLocalPathPair.Item1; var destinationFilePath = ftpPathLocalPathPair.Item2; _logger.Debug($"Downloading {ftpFilePath} to {destinationFilePath}..."); try { var memoryStream = new MemoryStream(); client.Download(memoryStream, ftpFilePath); memoryStream.Position = 0; string destinationDirectory = Path.GetDirectoryName(destinationFilePath); if (!Directory.Exists(destinationDirectory)) { _logger.Info($"Creating new directory {destinationDirectory}"); Directory.CreateDirectory(destinationDirectory); } File.WriteAllBytes(destinationFilePath, memoryStream.ToArray()); downloadedFiles.Add(destinationFilePath); } catch (Exception e) { _logger.Warn($"An unhandled excetpion occured while downloading file {ftpFilePath}", e); failedDownloadsBag.Add(ftpPathLocalPathPair); } clients.Enqueue(client); } ); failedDownloads = failedDownloadsBag.ToList(); return downloadedFiles.ToList(); } public List&lt;string&gt; ListNonArchiveDirectoresWithFiles(string root) { var directoriesWithFiles = new List&lt;string&gt;(); var directoiresToQuery = new Queue&lt;string&gt;(); var clients = new ConcurrentQueue&lt;IFtpClient&gt;(_ftpClients); directoiresToQuery.Enqueue(root); var tasks = new List&lt;Task&lt;Result&gt;&gt;(); while (directoiresToQuery.Any() || tasks.Any()) { while (clients.Any() &amp;&amp; directoiresToQuery.Any()) { var path = directoiresToQuery.Dequeue(); IFtpClient client; clients.TryDequeue(out client); var task = Task.Run(() =&gt; { var childItems = client.GetListing(path); clients.Enqueue(client); return new Result() { FullName = path, Children = childItems }; }); tasks.Add(task); } var array = tasks.ToArray(); var finishedTaskIndex = Task.WaitAny(array); var finishedTask = array[finishedTaskIndex]; var finishedTaskResult = finishedTask.Result; if (finishedTaskResult.Children.Any(i =&gt; i.Type == FtpFileSystemObjectType.File)) { directoriesWithFiles.Add(finishedTaskResult.FullName); } var subdirectoriesToQuery = finishedTaskResult .Children .Where(x =&gt; x.Type == FtpFileSystemObjectType.Directory) .Where(x =&gt; x.Name != "Archive") .Select(x =&gt; x.FullName); foreach (var subdirectoryToQuery in subdirectoriesToQuery) { directoiresToQuery.Enqueue(subdirectoryToQuery); } tasks = array .Except(new[] {finishedTask}) .ToList(); } return directoriesWithFiles; } public void Dispose() { foreach (var ftpClient in _ftpClients) { ftpClient.Dispose(); } } } public class Result { public string FullName { get; set; } public FtpListItem[] Children { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T16:34:32.140", "Id": "410635", "Score": "1", "body": "This is an interesting question but _I've tried to strip unimportant details from the code._ - there are no unimportant parts here and this never does any good on Code Review. You've been warned so don't be surprised if reviews don't popup or aren't useful." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-02-10T12:59:54.347", "Id": "412391", "Score": "0", "body": "@t3chb0t thanks for you warning. Seems you were absolutely right. Yet I find it cumbersome to post ~1K LOC and ask people to review it. Especially since a lot it very specific to how my company does things." } ]
[]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T16:24:18.657", "Id": "212332", "Score": "1", "Tags": [ "c#", "async-await", "task-parallel-library" ], "Title": "Using up to 15 connections to synchronize files from a FTP server with local files" }
212332
<p>Here's my solution for the Leet Code's Three Sum problem -- would love feedback on (1) code efficiency and (2) style/formatting. This is Python 3. </p> <p>Problem:</p> <blockquote> <p>Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.</p> <p>Note:</p> <p>The solution set must not contain duplicate triplets.</p> <p>Example:</p> <p>Given array nums = [-1, 0, 1, 2, -1, -4],</p> <p>A solution set is: [ [-1, 0, 1], [-1, -1, 2] ]</p> </blockquote> <p>My solution:</p> <pre><code>def threeSum(nums): """ :type nums: List[int] :rtype: List[List[int]] """ def _twoSum(nums_small, target): ''' INPUT: List of numeric values, int target OUTPUT: list: pair(s) from nums_small that add up to target and -1*target ''' nums_dict = {} return_lst = [] for indx, val in enumerate(nums_small, target): if target - val in nums_dict: return_lst.append([val, target - val, -1*target]) nums_dict[val] = indx return return_lst return_dict = {} for indx, val in enumerate(nums): for solution in _twoSum(nums[:indx] + nums[indx+1:], -1*val): if sorted(solution) not in return_dict.values(): return_dict[str(indx)+str(solution)] = sorted(solution) # ... hacky way of storing multiple solutions to one index ... return list(return_dict.values()) </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T07:01:13.880", "Id": "410711", "Score": "1", "body": "What Python version did you write this for?" } ]
[ { "body": "<h2>Code</h2>\n\n<blockquote>\n <p>\"When all you have is a hammer, everything looks like a nail.\"</p>\n</blockquote>\n\n<p>Your tool chest seems to have <code>dict</code>, which you are using to implement a container which doesn't contain any duplicates. There is a name for that tool. It is called as <code>set</code>. Study it; you will find it very useful.</p>\n\n<p>Consider:</p>\n\n<pre><code> nums_dict = {}\n\n for indx, val in enumerate(nums_small, target):\n if target - val in nums_dict: \n pass \n nums_dict[val] = indx\n</code></pre>\n\n<p>You are never <strong>using</strong> the value <code>indx</code>; you are just storing it and never retrieving it. You could just as easily write:</p>\n\n<pre><code> nums_dict = {}\n\n for val in nums_small:\n if target - val in nums_dict: \n pass \n nums_dict[val] = True\n</code></pre>\n\n<p>which avoids the <code>enumerate()</code>, with the odd initial value, and the indices which did nothing. But this is still storing the values <code>True</code>, and never retrieving them. You don't need to do this, if you use a set:</p>\n\n<pre><code> nums_dict = set()\n\n for val in nums_small:\n if target - val in nums_dict: \n pass \n nums_dict.add(val)\n</code></pre>\n\n<p>You again use a <code>dict</code> for <code>return_dict</code> to ensure you don't have any duplicate solutions. Actually, this code is a worse that the former, because you are using <code>in return_dict.values()</code>, so instead of an <span class=\"math-container\">\\$O(1)\\$</span> key lookup, you're doing an <span class=\"math-container\">\\$O(n)\\$</span> search through the entire list of values! If that wasn't bad enough, you are sorting solutions twice: once to see if they already exist in <code>return_dict</code>, and a second time to add it into the dictionary if it wasn't found. Saving the sorted solution would avoid the second sort.</p>\n\n<p>You could replace <code>return_dict</code> with a <code>set</code> as well, but there is a catch, you can't add a <code>list</code> into a <code>set</code>, because the items in a <code>set</code> must be hashable to a constant value but lists are unhashable (because they can be mutated). You can get around this by using tuples, which can't be mutated, so they can be hashed.</p>\n\n<pre><code> return_dict = set()\n\n for index, val in ...:\n for solution in ...:\n sorted_solution = tuple(sorted(solution))\n return_dict.add(sorted_solution)\n\n return list(return_dict)\n</code></pre>\n\n<p>The above returns a list of tuples. If you need a list of lists, that can be easily obtained as well, using list comprehension ...</p>\n\n<pre><code> return [ list(solution) for solution in return_dict ]\n</code></pre>\n\n<p>... which is another useful tool for your tool chest.</p>\n\n<hr>\n\n<h2>Algorithm</h2>\n\n<p>Using <code>_twoSum()</code> to solve the <code>threeSum()</code> problem is good reuse of code. Kudos.</p>\n\n<p>However, looping over all indices and for each index, constructing a new list omitting just that one value from the list <code>nums[:indx] + nums[indx+1:]</code> is extremely inefficient.</p>\n\n<p>Since \"Leetcode\" is a puzzle solving site, I won't give you the better algorithm, but I will say that splitting <code>nums</code> into <code>len(nums)</code> different lists is not the way to go. I would split it into 2 lists, or maybe 3 lists tops. Good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T11:54:17.073", "Id": "410744", "Score": "2", "body": "It took me a while to realize that you are talking about a dictionary (`dict`) when saying `map` and not the built-in function `map`..." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:23:28.877", "Id": "410765", "Score": "1", "body": "@Graipher The dangers of too many languages, and RUI. Fixed." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-31T16:21:32.453", "Id": "411313", "Score": "0", "body": "Ah, thanks for reminders on tuples @AJNeufeld" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T05:51:48.783", "Id": "212365", "ParentId": "212337", "Score": "6" } } ]
{ "AcceptedAnswerId": "212365", "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T20:07:03.170", "Id": "212337", "Score": "2", "Tags": [ "python", "python-3.x", "programming-challenge", "k-sum" ], "Title": "Leetcode Three Sum in Python" }
212337
<p>I am about two months into programming with Python (no previous experience) and I tried to write a program which would generate a key and assign it to a student.</p> <pre><code>import random import string code_list = [] students = ["Aljoša", "Blažka", "Nana", "Kaja", "Alja", "Tjaša", "Ana", "Gal", "Danijela", "Alma", "Neja", "Žiga K.", "Patricija", "Aja", "Kristjan", "Urban", "Janja", "Lea", "Žana", "Aljaž", "Tilen", "Matic", "Marija", "Žiga T."] #It generates the code and puts it in a list size = 6 code = string.ascii_uppercase + string.digits for i in range(24): code_list.append(str(''.join(random.choice(code) for _ in range(size)))) #Combines the two lists (students and codes) into one students_plus_codes = [x + str(" - " + y) for y in students for x in code_list] #It prints only every 25th element from the combined list new = [x for i, x in enumerate(students_plus_codes) if i % 25 == 0] for i in new: print(i)` </code></pre> <p>My problem is that this code is not very elegant and just want to ask how I could write it more efficiently (especially the last part where I have to manually print out every 25th element of a list because every key gets assigned to every student).</p>
[]
[ { "body": "<p>The reason that you are getting so many more entries is because of this list comprehension:</p>\n\n<pre><code> students_plus_codes = [x + str(\" - \" + y) for y in students for x in code_list]\n</code></pre>\n\n<p>It's a nested <code>for</code> loop. If we expand it we can see what is happening:</p>\n\n<pre><code>students_plus_codes = []\nfor y in students: # students has 24 items\n for x in code_list: # code_list has 24 items\n students_plus_codes.append(x + str(\" - \" + y))\n</code></pre>\n\n<p>So for every iteration of <code>students</code> you do 24 iterations of <code>code_list</code>. </p>\n\n<p>Fortunately, python has a builtin function called <a href=\"https://docs.python.org/3/library/functions.html#zip\" rel=\"nofollow noreferrer\"><code>zip</code></a> that will merge lists for us. So we can replace the nested list comprehension with this line:</p>\n\n<pre><code>students_plus_codes = list(zip(students, code_list))\n</code></pre>\n\n<p>Which results in a list of tuples:</p>\n\n<pre><code>[('Aljoša', '256D2B'), ('Blažka', 'OEGJL9'), ('Nana', 'GB1PJL'), ('Kaja', 'F0P0F2'), \n ('Alja', '62KU94'), ... ('Matic', 'E7CJIP'), ('Marija', '1D2UCL'), ('Žiga T.', '6X1DD5')]\n</code></pre>\n\n<h3>Generating the codes:</h3>\n\n<p>First, I would replace <code>for i in range(24):</code> with <code>for i in range(len(students)):</code> as this allows you to change the number of students without having to change other aspects of your code. In this instance <code>24</code> is a <a href=\"https://en.wikipedia.org/wiki/Magic_number_(programming)\" rel=\"nofollow noreferrer\">magic number</a> that could cause issues down the line.</p>\n\n<p>You could even create a function that generates each code, then you can use an easy to read list comprehension.</p>\n\n<pre><code># &lt;=python3.5\ndef generate_code(n, characters):\n return ''.join([random.choice(characters) for _ in range(n)]) \n\n# &gt;=python3.6\ndef create_code(n, characters):\n return ''.join(random.choices(characters, k=n))\n</code></pre>\n\n<h3>Printing the codes:</h3>\n\n<p>It isn't ideal to join the names and codes as a single string as this makes it hard to use them separately later. For this reason, I used a list of tuples to match them as pairs. To print them the <code>for</code> loop has two variables, <code>student</code> and <code>code</code> that takes advantage of <a href=\"https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences\" rel=\"nofollow noreferrer\">unpacking</a> and then prints them using the <a href=\"https://docs.python.org/3/library/string.html#format-string-syntax\" rel=\"nofollow noreferrer\"><code>format</code></a> function.</p>\n\n<pre><code>for student, code in students_plus_codes:\n print('{} - {}'.format(code, student))\n</code></pre>\n\n<hr>\n\n<h3>Altogether:</h3>\n\n<pre><code>import random\nimport string\n\n\ndef create_code(n, characters):\n return ''.join(random.choices(characters, k=n))\n\n\nstudents = [\"Aljoša\", \"Blažka\", \"Nana\", \"Kaja\", \"Alja\", \"Tjaša\", \"Ana\",\n \"Gal\", \"Danijela\", \"Alma\", \"Neja\", \"Žiga K.\", \"Patricija\", \"Aja\",\n \"Kristjan\", \"Urban\", \"Janja\", \"Lea\", \"Žana\", \"Aljaž\", \"Tilen\",\n \"Matic\", \"Marija\", \"Žiga T.\"]\n\n# It generates the code and puts it in a list\nkey_size = 6\nchars = string.ascii_uppercase + string.digits\ncode_list = [create_code(key_size, chars) for _ in range(len(students))]\n\n# Combines the two lists (students and codes) into a list of tuples\nstudents_plus_codes = list(zip(students, code_list))\n\nfor student, code in students_plus_codes:\n print('{} - {}'.format(code, student))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T21:17:43.633", "Id": "410667", "Score": "0", "body": "Thank you, this was really helpful, I would never figure it out on my own :D" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T21:48:24.383", "Id": "410670", "Score": "0", "body": "I'm glad it's helped. For a next step, I would check that a key hasn't already been generated. As you have a character space of 36 and string length of 6 there are `36^6` possible codes, which is _a lot_, but it's still possible there could be a collision!" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T23:37:13.750", "Id": "410681", "Score": "0", "body": "oh cool, and how would i do that exacty? I am really that new to all this yeah haha" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:45:43.777", "Id": "410776", "Score": "0", "body": "@urbanpečoler, python has an object type called [`sets`](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset) that doesn't allow duplicates. You could add your keys to a set until it reaches the desired length using a while loop." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T21:05:12.927", "Id": "212342", "ParentId": "212338", "Score": "6" } }, { "body": "<p>I agree with the points from @Alex answer,</p>\n\n<ul>\n<li><a href=\"https://www.python.org/dev/peps/pep-0506/\" rel=\"noreferrer\">with PEP506</a> there is a Python module for generating keys <a href=\"https://docs.python.org/3/library/secrets.html\" rel=\"noreferrer\">secrets</a></li>\n<li><code>size</code> is a <a href=\"https://www.python.org/dev/peps/pep-0008/#descriptive-naming-styles\" rel=\"noreferrer\">constant (PEP8 naming styles)</a> and should be <code>UPPER_SNAKE_CASE</code></li>\n</ul>\n\n<hr>\n\n<pre><code>import secrets\nfrom string import digits, ascii_uppercase\n\nSIZE = 6\n\ndef create_code(n, characters):\n return ''.join(secrets.choice(characters) for _ in range(n))\n\nprint(create_code(SIZE, digits + ascii_uppercase))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T09:12:40.427", "Id": "212368", "ParentId": "212338", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T20:11:13.300", "Id": "212338", "Score": "4", "Tags": [ "python" ], "Title": "Key generating program in Python" }
212338
<p>This is my first programming assignment. This is a second file that is intended to test the setters and getters (both constructors and no-argument constructors). How can I clean this up (curly brackets or combining similar methods/lines) to make it look more legible and understandable? I'll be adding comments later.</p> <pre><code>/** A class to test the Assignment class */ public class AssignmentTester { public static void main(String[] args) { Assignment getterTest = new Assignment(); System.out.println("TESTING NO-ARGUMENT CONSTRUCTOR AND GETTERS"); System.out.println("=========================================== \n"); System.out.println(getterTest.getTitle()); System.out.println("Expected: Assignment 1 \n"); System.out.println(getterTest.getDueDate()); System.out.println("Expected: 01/01/2019 \n"); System.out.println(getterTest.getMaxPoints()); System.out.println("Expected: 10.0 \n"); System.out.println(getterTest.getCategory()); System.out.println("Expected: Programming Assignments \n \n"); System.out.println("Testing Setters"); System.out.println("=============== \n"); Assignment setterTest = new Assignment(); setterTest.setTitle("CodeLab 12"); System.out.println(setterTest.getTitle()); System.out.println("Expected: CodeLab 1 \n"); setterTest.setDueDate("02/09/2019"); System.out.println(setterTest.getDueDate()); System.out.println("Expected: 02/09/2019 \n"); setterTest.setMaxPoints(5.0); System.out.println(setterTest.getDueDate()); System.out.println("expected: 5.0 \n"); setterTest.setCategory("CodeLab, Quizzes, ICE"); System.out.println(setterTest.getCategory()); System.out.println("Expected: CodeLab, Quizzes, ICE \n \n"); } } </code></pre> <p>If interested, here is my first Java file. Please let me know if I can improve on this in any way:</p> <pre><code>/** Describes an assignment's title, due date, total points value, and category */ public class Assignment { private String title; //Title of assignment private String dueDate; //Due date of assignment private double maxPoints; //Max points of assignment private String category; //Category of assignment /** Initialize instance variables for assignment project (no argument-constructor) */ public Assignment() { title = "Assignment 1"; dueDate = "01/01/2019"; maxPoints = 10.0; category = "Programming Assignments"; } /** Initialize instance variables for the assignment project (argument constructor) @param t title of assignment @param d due date of assignment @param m max points for the assignment @param c category of assignment */ public Assignment(String t, String d, double m,String c) { title = t; dueDate = d; maxPoints = m; category = c; } /** Sets the value of title @param t title of assignment */ public void setTitle(String t) { title = t; } /** Sets the value of dueDate @param d due date of assignment */ public void setDueDate(String d) { dueDate = d; } /** Sets value of maxPoints @param m max points of assignment */ public void setMaxPoints(double m) { maxPoints = m; } /** Sets the value of category @param c category of assignment */ public void setCategory(String c) { category = c; } /** Returns the value of title @return title of assingment */ public String getTitle() { return title; } /** Returns the value of dueDate @return due date of assignment */ public String getDueDate() { return dueDate; } /** Returns the value of maxPoints @return max points of assignment */ public double getMaxPoints() { return maxPoints; } /** Returns the value of category @return category of assingmen */ public String getCategory() { return category; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T04:12:57.077", "Id": "410689", "Score": "0", "body": "I'd recommend evening out your indentation. A lot of seasoned programmers have developed an intuitive sense about what code is and isn't a problem. Things like haphazard indentation can trigger that sense, and so we look at your code and feel like there has to be a problem somewhere. This can be an extra factor if someone is grading your work by hand and trying to rush. If they want to average under a minute per student, they may not take the time to realize it was a false alarm - and they may not care. They may be trying to keep it under 10 seconds." } ]
[ { "body": "<p>The go to unit testing framework in Java is <a href=\"https://junit.org/junit5/\" rel=\"nofollow noreferrer\">JUnit</a> and all major IDE tools have builtin support for writing test cases.</p>\n\n<p>However, for very simple purposes and learning purpose, Java JDK has the <a href=\"https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html\" rel=\"nofollow noreferrer\"><code>assert</code></a> keyword that can be used to test assumptions and also do unit tests. in both cases (JUnit and <code>assert</code>) the rule is that failed tests throw exceptions that may have customized messages.</p>\n\n<p>an example of usage of <code>assert</code>:</p>\n\n<pre><code>assert getterTest.getTitle().equals(\"Assignment 1\") : \"wrong title default value\"\n</code></pre>\n\n<p>note that assertions need to be explicitly enabled at runtime:</p>\n\n<blockquote>\n <p>Enabling and Disabling Assertions By default, assertions are disabled\n at runtime. Two command-line switches allow you to selectively enable\n or disable assertions.</p>\n \n <p>To enable assertions at various granularities, use the\n -enableassertions, or -ea, switch. To disable assertions at various granularities, use the -disableassertions, or -da, switch.</p>\n</blockquote>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T20:11:06.527", "Id": "410854", "Score": "0", "body": "Java assertions are not a testing framework, and using them in that fashion is decidedly non-standard and will confuse other developers. The intent of the assertion framework is to provide weak Design-By-Contract support. You can read more about assertions at https://docs.oracle.com/javase/8/docs/technotes/guides/language/assert.html" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T20:30:31.257", "Id": "410860", "Score": "0", "body": "JUnit uses the same terminology (assertions) and throws the exact same exception when a test fails (`AssertionError`) and it is decidedly *the* unit testing framework in the Java world, while java assertions are not? fooled me" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T09:29:55.280", "Id": "212369", "ParentId": "212350", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T22:34:03.567", "Id": "212350", "Score": "0", "Tags": [ "java" ], "Title": "Testing an Assignment class" }
212350
<p>I am using Java 8. I want to build a final list using following data. All objects in basicData list must be added to final list. But if there is a matching object based on matching key from modData map with the basicData's id &amp; isMod set to true, I want to add that object to the final list instead of basic. For example modData's b_mod's key matches the id for an object in basicData list. I want to add the modData's object instead to final list in this case. Not only that, if I make a switch, that object goes up in order in the final list.</p> <p>Another scenario where the key and id matches but isMod is set to false. In this case, I will add the object from basicData and the object has to go up in order too.</p> <p>If there is no match at all then just add basic data's object.</p> <p>based on data above the final list should have following objects in following order:</p> <blockquote> <p>[b_mod, e_mod, d, a, c]</p> <p>A quick recap on criteria. b_mod and e_mod are at top cos they matched key to ids and also isMod set to true. d comes next cos it matched too but isMod was set to false. In this case we used the object from the basicData list but it goes up in order. no match for a and c so just added behind. f_mod was not added at all cos it doesn't exist in basicData list.</p> </blockquote> <p>Note that I can't override equals method. There is already an override (this obj has a lot more fields) with a different logic for another purpose.</p> <p>I could do nested for loops or like 3 separate for loops to get this done which all works. But they seem so inefficient.</p> <p>This is my solution which I believe is extremely inefficient. Please advice.</p> <pre><code>import java.util.*; public class DataSorter { public static void main(String[] args) { List&lt;Data&gt; basicData = new ArrayList&lt;&gt;(); // isMod always false for this list items basicData.add(new Data("100", "a", false)); basicData.add(new Data("200", "b", false)); basicData.add(new Data("300", "c", false)); basicData.add(new Data("400", "d", false)); basicData.add(new Data("500", "e", false)); Map&lt;String, Data&gt; modData = new LinkedHashMap&lt;&gt;(); modData.put("200", new Data("200", "b_mod", true)); // match. add this instead and move up the order. modData.put("400", new Data("400", "d_mod", false)); // is a match but isMod set to false. Thus still adding obj from basicData. modData.put("500", new Data("500", "e_mod", true)); // match. add this instead and move up the order. modData.put("600", new Data("600", "f_mod", true)); // this is not in basicData so not added to final list. //start solution //adding just matching data which is also set isMod to true List&lt;Data&gt; finalData = new ArrayList&lt;&gt;(); for(Data d : basicData){ Data modObj = modData.get(d.getId()); if(modObj != null){ if (modObj.isMod()){ finalData.add(modObj); } } } //adding basic objects when there was a match but isMod was false at modData map. for(Data d : basicData){ Data modObj = modData.get(d.getId()); if(modObj != null){ if (!modObj.isMod()){ finalData.add(modObj); } } } //adding remaining objects from basicData list. for (Data basicDatum : basicData) { boolean dataExists = false; Data obj = null; for (Data finalDatum : finalData) { obj = basicDatum; if (obj.getId().equals(finalDatum.getId())) { dataExists = true; break; } } if (!dataExists) { finalData.add(obj); } } // end solution // printing to test it for(Data d : finalData){ System.out.println(d); System.out.println("==============="); } } } class Data { private String id; private String name; private boolean isMod; Data(String id, String name, boolean isMod) { this.id = id; this.name = name; this.isMod = isMod; } String getId() { return id; } boolean isMod() { return isMod; } @Override public String toString() { return "Data{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", isMod=" + isMod + '}'; } } </code></pre>
[]
[ { "body": "<p>Consider having 3 lists. One of <code>modObj != null &amp;&amp; modObj.isMod()</code>. Another one of <code>modObj != null &amp;&amp; !modObj.isMod()</code>. Third one of the rest (aka <code>modObj == null</code>). Finally join them. E.g.:</p>\n\n<pre><code> List&lt;Data&gt; front_list = new ArrayList&lt;&gt;();\n List&lt;Data&gt; mid_list = new ArrayList&lt;&gt;();\n List&lt;Data&gt; tail_list = new ArrayList&lt;&gt;();\n\n for (Data d: basicData) {\n Data modObj = modData.get(d.getId());\n if (modObj == null) {\n tail_list.add(d);\n } else if (modObj.isMod()) {\n front_list.add(modObj);\n } else {\n mid_list.add(modObj);\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T04:33:33.340", "Id": "410691", "Score": "0", "body": "I think you mean `tail_list.add(d)`, not `.append(d)`. Ditto for the others." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T04:35:27.683", "Id": "410692", "Score": "0", "body": "Minor efficiency improvement: use `new ArrayList<>(basicData.size())` to preallocate enough room for all of the data." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T04:15:25.260", "Id": "212361", "ParentId": "212353", "Score": "2" } } ]
{ "AcceptedAnswerId": "212361", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-27T23:59:48.413", "Id": "212353", "Score": "1", "Tags": [ "java", "performance" ], "Title": "Combine data from a list and map based on criteria" }
212353
<pre><code>using Microsoft.AspNetCore.WebUtilities; using System.Security.Cryptography; namespace UserManager.Cryptography { public class UrlToken { private const int BYTE_LENGTH = 32; /// &lt;summary&gt; /// Generate a fixed length token that can be used in url without endcoding it /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; public static string GenerateToken() { // get secure array bytes byte[] secureArray = GenerateRandomBytes(); // convert in an url safe string string urlToken = WebEncoders.Base64UrlEncode(secureArray); return urlToken; } /// &lt;summary&gt; /// Generate a cryptographically secure array of bytes with a fixed length /// &lt;/summary&gt; /// &lt;returns&gt;&lt;/returns&gt; private static byte[] GenerateRandomBytes() { using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider()) { byte[] byteArray = new byte[BYTE_LENGTH]; provider.GetBytes(byteArray); return byteArray; } } } } </code></pre> <p>I've created the above class (C#, .Net Core 2.0) to generate a cryptographically secure string token that is URL safe, so it can be used in an URL without the necessity to be encoded.</p> <p>I will use that token as a <code>GET</code> parameter (e.g. <code>www.site.com/verify/?token=v3XYPmQ3wD_RtOjH1lMekXloBGcWqlLfomgzIS1mCGA</code>) in a user manager application where I use the token to verify the user email or to recover a user password.</p> <p>The above link will be sent as email to the user that has requested the service.</p> <p>I store the token into a DB table with an associated expiration datetime.</p> <p>I've seen other implementations on this and other sites but all seem to be unnecessarily complicated. Am I missing something?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T12:37:38.277", "Id": "410749", "Score": "1", "body": "Looks ok to me. I tend to use hex encoding rather than base64, and typically generate this in SQL server using HASHBYTES. I usually have parameters which identify the user, and an expiry date for the token (included in the hash), that way I don't have to store anything extra in the database, but perhaps that doesn't suit your security requirements." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:13:57.100", "Id": "410831", "Score": "0", "body": "\"cryptographically secure string token\" - well, it's cryptographically RANDOM, but it's only as secure as your systems protect and validate it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:48:51.760", "Id": "410922", "Score": "0", "body": "It should be obvious, but I didn't mention in my comment above that with that approach, it's essential to include some secret key material in the hash ( or there is no security at all )." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:09:29.450", "Id": "410933", "Score": "0", "body": "Considering the fact that the token is used to verify email or to recover lost password and has an expiration datetime, is not safe to just store it in the DB with a SHA256 hash without any salt or secure key?" } ]
[ { "body": "<p>Minor suggestions:</p>\n\n<pre><code>public class UrlToken\n</code></pre>\n\n<p>The class has no instance data, so it could be made <code>static</code>:</p>\n\n<pre><code>public static class UrlToken\n</code></pre>\n\n<p><a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/general-naming-conventions\" rel=\"noreferrer\">Microsoft's Naming Guidelines</a> and their <a href=\"https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/capitalization-conventions\" rel=\"noreferrer\">Framework Design Guidelines</a> suggest not using underscores and also using PascalCasing for constants, so</p>\n\n<pre><code> private const int BYTE_LENGTH = 32; \n</code></pre>\n\n<p>could be:</p>\n\n<pre><code> private const int ByteLength = 32; \n</code></pre>\n\n<p>However, even that name doesn't tell us much of what it is for. Let's try again:</p>\n\n<pre><code> private const int NumberOfRandomBytes = 32; \n</code></pre>\n\n<p>Typo/misspelling in the XML doc comment: \"encoding\" is written as \"endcoding\".</p>\n\n<p>There is mixed curly brace formatting. Microsoft guidelines (see links above) suggest the opening and closing curly braces should be on their own line.</p>\n\n<pre><code> using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider()) { \n</code></pre>\n\n<p>to:</p>\n\n<pre><code> using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider())\n { \n</code></pre>\n\n<p>By the way, kudos to you on your proper use of the <code>using</code> construct! Looks fantastic!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:14:12.190", "Id": "410935", "Score": "0", "body": "Hi, thanks for the advices; making the class static has any performance benefit or usability improvement or is just a stylish thing?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T13:42:51.650", "Id": "410976", "Score": "1", "body": "@S.Orioli yes, it prevents wasteful constructs like `var thing = new UrlToken();` from being able to be written." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T17:39:42.597", "Id": "212406", "ParentId": "212370", "Score": "5" } }, { "body": "<p>There are not much to work with in a review besides what mr. Slicer has already written.</p>\n\n<hr>\n\n<p>To make it a little more flexible you could though provide the number of bytes as an argument instead of a constant member value:</p>\n\n<pre><code> public static string GenerateToken(int numberOfBytes = 32)\n</code></pre>\n\n<p>Refactoring the class to handle that could be:</p>\n\n<pre><code>public class ReviewdUrlToken\n{\n /// &lt;summary&gt;\n /// Generate a fixed length token that can be used in url without endcoding it\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string GenerateToken(int numberOfBytes = 32)\n {\n return WebEncoders.Base64UrlEncode(GenerateRandomBytes(numberOfBytes));\n }\n\n /// &lt;summary&gt;\n /// Generate a cryptographically secure array of bytes with a fixed length\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private static byte[] GenerateRandomBytes(int numberOfBytes)\n {\n using (RNGCryptoServiceProvider provider = new RNGCryptoServiceProvider())\n {\n byte[] byteArray = new byte[numberOfBytes];\n provider.GetBytes(byteArray);\n return byteArray;\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>The class is OK as is, if you use it now and then in separate occasions, but if you want to generate more codes at the same time, you could consider to implement a factory like static method: </p>\n\n<pre><code> public static IEnumerable&lt;string&gt; GenerateTokens(int numberOfBytes = 32)\n</code></pre>\n\n<p>The benefit of that is that you can avoid the (possible expensive) instantiation of a new number generator for each token.</p>\n\n<p>A revision of the class to accommodate to that could be:</p>\n\n<pre><code>public class NewUrlToken : IDisposable\n{\n RNGCryptoServiceProvider _provider = new RNGCryptoServiceProvider();\n int _numberOfBytes;\n\n public NewUrlToken(int numberOfBytes)\n {\n _numberOfBytes = numberOfBytes;\n }\n\n /// &lt;summary&gt;\n /// Generate a cryptographically secure array of bytes with a fixed length\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n private byte[] GenerateRandomBytes()\n {\n byte[] byteArray = new byte[_numberOfBytes];\n _provider.GetBytes(byteArray);\n return byteArray;\n }\n\n public void Dispose()\n {\n // TODO Implement the proper Disposable pattern.\n if (_provider != null)\n {\n _provider.Dispose();\n _provider = null;\n }\n }\n\n private string GenerateToken()\n {\n return WebEncoders.Base64UrlEncode(GenerateRandomBytes());\n }\n\n /// &lt;summary&gt;\n /// Generate a fixed length token that can be used in url without endcoding it\n /// &lt;/summary&gt;\n /// &lt;returns&gt;&lt;/returns&gt;\n public static string GenerateToken(int numberOfBytes = 32)\n {\n return GenerateTokens(numberOfBytes).First();\n }\n\n public static IEnumerable&lt;string&gt; GenerateTokens(int numberOfBytes = 32)\n {\n using (NewUrlToken factory = new NewUrlToken(numberOfBytes))\n {\n while (true)\n {\n yield return factory.GenerateToken();\n }\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p>Usage:</p>\n\n<pre><code> foreach (string token in NewUrlToken.GenerateTokens().Take(10))\n {\n Console.WriteLine(token);\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T07:41:38.007", "Id": "212446", "ParentId": "212370", "Score": "3" } } ]
{ "AcceptedAnswerId": "212406", "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T10:06:50.550", "Id": "212370", "Score": "5", "Tags": [ "c#", "asp.net-core" ], "Title": "Generate secure URL safe token" }
212370
<p>I had an intuition that the maximal trajectory lengths for collatz conjecture numbers would be produced by numbers of the form <code>(2**n)-1</code> so I wrote a program to test it (I was wrong). I thought I would put it up for review to catch any coding sins I committed, and see how others would improve my code.</p> <h3>Orginal Code</h3> <pre><code>''' * I had a conjecture that maximal trajectory lengths for the collatz conjecture were yielded by numbers of the form (2**n)-1. This program attempts to test it. * &quot;conjecture()&quot; finds the number with the highest trajectory lengths in a given range. The ranges are of the form [2**n, 2**(n+1)). ''' import math, pprint f = open(&quot;CollatzConjecture.txt&quot;) text = f.read() def key(value, dct): for key in dct.keys(): if dct[key] == value: return key return None def conjecture(text): traj = {int(j.split(&quot; &quot;)[0]): int(j.split(&quot; &quot;)[1]) for j in text.split(&quot;\n&quot;)} #Processes the text file into a dict mapping numbers to their trajectory length. result = {} bound = math.floor(math.log(len(traj),2)) traj2 = {num: traj[num] for num in list(traj.keys())[:2**bound+1]} #Slices the dictionary to receive the section of interest. for st in (2**x for x in range(1, bound+1)): #Generator for powers of 2. slce = list(traj2.items())[int((math.log(st,2)-1)**2):st] #Slices &quot;traj2&quot; into powers of 2. result[st] = key(max([n[1] for n in slce]), traj2) return pprint.pformat(result) print(conjecture(text)) </code></pre> <p><a href="https://oeis.org/A006577/b006577.txt" rel="nofollow noreferrer">&quot;CollatzConjecture.txt&quot;</a> is a text file containing <code>number trajectoryLength</code> on separate lines. I wanted to find the number corresponding to the maximum trajectory length between successive powers of 2 in order to test my hypothesis.</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T13:53:13.637", "Id": "410758", "Score": "0", "body": "Can you add an example input textfile?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:01:42.370", "Id": "410759", "Score": "1", "body": "Where is the `key` function actually used?" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:16:59.150", "Id": "410762", "Score": "0", "body": "@Ludisposed I'll link the actual text file I used: https://oeis.org/A006577/b006577.txt" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:18:25.197", "Id": "410763", "Score": "0", "body": "@Graipher key is no longer been used in the current version. I used it in an older version. I'll edit it to remove it." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:25:16.003", "Id": "410767", "Score": "0", "body": "Please do not update the code in your question to incorporate feedback from answers, doing so goes against the Question + Answer style of Code Review. This is not a forum where you should keep the most updated version in your question. Please see *[what you may and may not do after receiving answers](//codereview.meta.stackexchange.com/a/1765)*. The existing answer explicitly mentions a piece of code you tried to remove, so your edit would invalidate it. We can't have that." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:30:58.063", "Id": "410770", "Score": "0", "body": "@Mast Aah. I would replace the code with the code I used initially:" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:33:15.850", "Id": "410771", "Score": "0", "body": "@TobiAlafin: I rolled it back to your first revision and added the link to OEIS manually. I hope that did not screw it up further but is now actually your original code, to which the answer by Ludisposed belongs." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:34:16.427", "Id": "410772", "Score": "1", "body": "Now that you have improved code it might make sense to ask a new question with the updated code, linking back to this one, as stated in the link provided by Mast." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:42:34.263", "Id": "410775", "Score": "0", "body": "@Graipher I overwrote your edit. I'll roll back the addition of the edited version." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T14:47:23.510", "Id": "410777", "Score": "3", "body": "@TobiAlafin: Hm, what a nice edit mess :) I'll let you figure it out, but if I were you, I would just roll it back to your first first revision (again) and then forget about this question. Instead spend the effort on making the follow-up question look good." } ]
[ { "body": "<blockquote>\n<pre><code>def key(value, dct):\n for key in dct.keys():\n if dct[key] == value:\n return key\n return None\n</code></pre>\n</blockquote>\n\n<p>This is really inefficient and not how dictionaries should be used.</p>\n\n<ul>\n<li>The point of a <code>dict</code> is O(1) lookup, this is essentially O(n) and it doesn't make sense</li>\n<li>You should remove your blockcomments, and create a nice docstring. That will make the purpose of the code clearer</li>\n<li>You don't close the file, a nice addition is using the <code>with</code> statement to automatically open/close files <a href=\"https://www.python.org/dev/peps/pep-0343/\" rel=\"noreferrer\">PEP343</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T13:49:22.407", "Id": "410757", "Score": "0", "body": "`key(value, dct)` gets the key corresponding to a value. `dict.get()` gets the value corresponding to a key. I'll edit my code to make it clearer." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T20:18:50.757", "Id": "410857", "Score": "4", "body": "@TobiAlafin: If you need to map both ways (A -> B and B -> A), *use two dictionaries to get O(1) lookups in each direction*. A linear search O(n) in one direction vs. an O(1) in the other, doesn't make sense, unless that direction is almost never used, and you can't afford to double the storage cost by keeping a reverse dictionary. Or there are probably custom data structures that can index on both sets of data without duplicating the storage... like what a relational database would use for a table with 2 columns, and an index on each column. For short keys two dicts is totally fine." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T01:40:00.227", "Id": "410888", "Score": "0", "body": "Peter Cordes thank you. I had not thought of that, I'll apply that in the future." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T13:44:13.467", "Id": "212380", "ParentId": "212377", "Score": "10" } }, { "body": "<p>It's desirable to try to break one's code into small, more reusable segments. For example, it would be preferable (in my opinion) to create a small function to open the text file, extract its contents, and return the <code>dict</code> of trajectories you desire:</p>\n\n<pre><code>def load_trajectories(file_name):\n traj = {}\n with open(file_name, 'r') as f:\n for line in f.readlines():\n S = line.split(' ')\n num, traj_len = int(S[0]), int(S[1])\n traj[num] = traj_len\n return traj\n</code></pre>\n\n<p>Note here that I used the context manager <code>with open(file_name, 'r') as f:</code>, since in Python we need to first open a file, do things with it, and then close it. The context manager handles the opening and closing of the file for us, and within it we can access the file.</p>\n\n<p>From my searching there doesn't seem to be a universally accepted way to find the \"inverse\" of a value in a dictionary, but I like yours for the most part. As one change, I would iterate over the <code>key:value</code> pairs to simplify things a bit:</p>\n\n<pre><code>def find_key(target_value, dct):\n for key, val in dct.items():\n if val == target_value:\n return key\n raise Exception('Value not found!')\n</code></pre>\n\n<p>With this, it really only remains to clean up the <code>conjecture</code> function. Here, we can pass the <code>traj</code> dictionary as an argument, as well as the (un-exponentiated) bound. </p>\n\n<p>In the parlance of your code, note that <code>st</code> is always of the form <code>2**x</code>, so when we compute <code>math.log(st, 2)</code>, it always evaluates to <code>x</code>, so one line of your code reads (equivalently)</p>\n\n<pre><code>slce = list(traj2.items())[(x-1)**2:st]\n</code></pre>\n\n<p>which isn't the 'slicing into power of 2' that you desire. Moreover, it's not (necessarily) guaranteed that <code>traj2.items()</code> will be turned into a list in the way you desire, so it'll be better to be more explicit:</p>\n\n<pre><code>slce = [key, val for key, val in traj.items() if key in range(2**(x-1), 2**x)]\n</code></pre>\n\n<p>Together, along with splitting our imports onto different lines, <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">adding a <code>if __name__ == '__main__':</code></a> guard, and some other minor reorganization yields the following code:</p>\n\n<pre><code>import math\nimport pprint\n\ndef find_key(target_value, dct):\n for key, val in dct.items():\n if val == target_value:\n return key\n raise Exception('Value not found!')\n\ndef load_trajectories(file_name):\n traj = {}\n with open(file_name, 'r') as f:\n for line in f.readlines():\n S = line.split(' ')\n num, traj_len = int(S[0]), int(S[1])\n traj[num] = traj_len\n return traj\n\ndef conjecture(traj):\n \"\"\"Checks the conjecture that the maximum 'Collatz length' among the integers in [2**n, 2**(n+1)) is 2**n - 1.\n\n The conjecture is false.\n \"\"\"\n bound = math.floor(math.log(len(traj),2))\n exp_bound = 2**bound\n\n traj = {key:val for key, val in traj.items() if key &lt; exp_bound} # Only include numbers of interest.\n result = {}\n\n for n in range(1,bound+1):\n exp_n = 2**n\n slce = [key, val for key, val in traj.items() if key in range(2**(n-1), exp_n)]\n result[exp_n] = find_key(max([val for key, val in slce]), traj)\n\n return pprint(pformat(result))\n\nif __name__ == \"__main__\":\n\n file_name = \"CollatzConjecture.txt\"\n print(conjecture(file_name))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T08:56:59.040", "Id": "410932", "Score": "0", "body": "\"*I would iterate over the `key:value` pairs to simplify things a bit*\": it's not just a question of simplifying. It's also more efficient, because advancing the iterator doesn't involve any search so is as cheap as possible, whereas the lookup potentially has to resolve hash collisions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T15:51:35.213", "Id": "212388", "ParentId": "212377", "Score": "3" } }, { "body": "<p>First of all, thumbs up on including a documentation block at the beginning.</p>\n\n<p>When trying to run the segment, I get</p>\n\n<pre><code>Traceback (most recent call last):\n File \"conjecture.py\", line 28, in &lt;module&gt;\n print(conjecture(text))\n File \"conjecture.py\", line 19, in conjecture\n traj = {int(j.split(\" \")[0]): int(j.split(\" \")[1]) for j in text.split(\"\\n\")} #Processes the text file into a dict mapping numbers to their trajectory length.\n File \"conjecture.py\", line 19, in &lt;dictcomp&gt;\n traj = {int(j.split(\" \")[0]): int(j.split(\" \")[1]) for j in text.split(\"\\n\")} #Processes the text file into a dict mapping numbers to their trajectory length.\nIndexError: list index out of range\n</code></pre>\n\n<p>Turns out that when I saved the output of the link, there were empty trailing lines. After fixing that, I could get it to run.</p>\n\n<p>Furthermore, I see several issues with this implementation:</p>\n\n<ol>\n<li>The <code>conjecture</code> function is doing a lot of the work, with several lines that are quite filled with operations, meaning it's hard to find out what it's doing.</li>\n<li>A dictionary can contain a value multiple times, and in fact does. For instance, both 5 and 32 have a length of 5 (5 -> 16 -> ...) and (32 -> 16 -> ...). For longer lengths, there will be more ways in which it can be obtained.</li>\n<li>Floating point arithmetic in a fully integral problem seems like an issue.</li>\n<li>The file is opened, and then not immediately closed. For this it's not really an issue, but in general one should use a contextmanager to clean up used resources as quickly as possible.</li>\n<li>The semantics of the output isn't really clear to me, but I'll probably figure out a bit during picking it apart.</li>\n<li>It doesn't use a <code>__main__</code> block, which would be beneficial for re-usable code.</li>\n<li>The <code>conjecture</code> function returns a string, instead of a dictionary.</li>\n</ol>\n\n<p>So let's start with your implementation:</p>\n\n<pre><code>'''\n* I had a conjecture that maximal trajectory lengths for the collatz conjecture were yielded by numbers of the form (2**n)-1. This program attempts to test it.\n* \"conjecture()\" finds the number with the highest trajectory lengths in a given range. The ranges are of the form [2**n, 2**(n+1)).\n'''\n\nimport math, pprint\n\nf = open(\"CollatzConjecture.txt\")\ntext = f.read()\n\ndef key(value, dct):\n for key in dct.keys():\n if dct[key] == value:\n return key\n return None\n\n\ndef conjecture(text):\n traj = {int(j.split(\" \")[0]): int(j.split(\" \")[1]) for j in text.split(\"\\n\")} #Processes the text file into a dict mapping numbers to their trajectory length.\n result = {}\n bound = math.floor(math.log(len(traj),2))\n traj2 = {num: traj[num] for num in list(traj.keys())[:2**bound+1]} #Slices the dictionary to receive the section of interest.\n for st in (2**x for x in range(1, bound+1)): #Generator for powers of 2.\n slce = list(traj2.items())[int((math.log(st,2)-1)**2):st] #Slices \"traj2\" into powers of 2.\n result[st] = key(max([n[1] for n in slce]), traj2)\n return pprint.pformat(result)\n\nprint(conjecture(text))\n</code></pre>\n\n<h1>Use a <code>if __name__ == '__main__'</code> segment.</h1>\n\n<p>One of the best places to start with such a script (especially if you want to make it reusable!) is to place the \"main\" code (file-mangling) inside a <code>main</code> block:</p>\n\n<pre><code>... function definitions ...\n\nif __name__ == '__main__':\n f = open(\"CollatzConjecture.txt\")\n text = f.read()\n print(conjecture(text))\n</code></pre>\n\n<h1>Move parsing the trajectories out of <code>conjecture</code>.</h1>\n\n<p>Your conjecture has nothing to do with the piece of text, but about the length of the trajectories. We shouldn't care how these lengths are generated, calculated or parsed inside the <code>conjecture</code> function. But the current implementation does.</p>\n\n<p>By moving out the <code>text</code> to <code>traj</code> transformation, we make <code>conjecture</code> more general.</p>\n\n<pre><code>...\n\ndef conjecture(traj):\n result = {}\n bound = math.floor(math.log(len(traj),2))\n ...\n\nif __name__ == '__main__':\n f = open(\"CollatzConjecture.txt\")\n text = f.read()\n traj = {int(j.split(\" \")[0]): int(j.split(\" \")[1]) for j in text.split(\"\\n\")} #Processes the text file into a dict mapping numbers to their trajectory length.\n print(conjecture(traj))\n</code></pre>\n\n<p>And we can then split the parsing into a separate function, where we use a context manager.</p>\n\n<pre><code>...\n\ndef parse_lengths(filename):\n with open(filename) as fp:\n #Processes the text file into a dict mapping numbers to their trajectory length.\n return {int(j.split(\" \")[0]): int(j.split(\" \")[1]) for j in fp}\n\n...\n\nif __name__ == '__main__':\n traj = parse_lengths(\"CollatzConjecture.txt\")\n print(conjecture(traj))\n</code></pre>\n\n<p>And similarly, move the pformat out of conjecture:</p>\n\n<pre><code>def conjecture(text):\n result = {}\n ...\n return result\n\nif __name__ == '__main__':\n traj = parse_lengths(\"CollatzConjecture.txt\")\n pprint.pprint(conjecture(traj))\n</code></pre>\n\n<h1>Simplify <code>conjecture</code>.</h1>\n\n<p>Now that we're left with a <code>conjecture</code> method that does only things related to the conjecture, we can look at it a bit more:</p>\n\n<pre><code>def conjecture(traj):\n result = {}\n bound = math.floor(math.log(len(traj),2))\n traj2 = {num: traj[num] for num in list(traj.keys())[:2**bound+1]} #Slices the dictionary to receive the section of interest.\n for st in (2**x for x in range(1, bound+1)): #Generator for powers of 2.\n slce = list(traj2.items())[int((math.log(st,2)-1)**2):st] #Slices \"traj2\" into powers of 2.\n result[st] = key(max([n[1] for n in slce]), traj2)\n return result\n</code></pre>\n\n<p>Starting with this expression: <code>int((math.log(st,2)-1)**2)</code>, what does it even do?! First it takes the 2-logarithm, substracts 1, and then squares it. At first I suspected that you wanted the previous power of two (and tested it). But, what actually happens is that 64 (2<sup>6</sup>) becomes 25 (5<sup>2</sup>), and also 2048 (2<sup>11</sup>) becomes 100 (10<sup>2</sup>). My basic guess is that this is incorrect, and you mean 64 => 32, 128 => 64, and so forth. Assuming that's what you want, you can just divide by two.</p>\n\n<pre><code>def conjecture(traj):\n result = {}\n bound = math.floor(math.log(len(traj),2))\n traj2 = {num: traj[num] for num in list(traj.keys())[:2**bound+1]} #Slices the dictionary to receive the section of interest.\n for st in (2**x for x in range(1, bound+1)): #Generator for powers of 2.\n slce = list(traj2.items())[st // 2:st] #Slices \"traj2\" into powers of 2.\n result[st] = key(max([n[1] for n in slce]), traj2)\n return result\n</code></pre>\n\n<p>Surprisingly, though, this does not alter the output.</p>\n\n<p>Next up is the fact that I see slices being taken of dictionaries (after casting to a list). In older Python versions (before 3.6) that might cause surprising results, as dictionaries are not necessarily ordered by value, though in this case it does turn out to be that way it seems. It's better to explicitly filter out the values that you want.</p>\n\n<h1>Final:</h1>\n\n<p>In the end, I found myself settling on this.</p>\n\n<pre><code>'''\n* I had a conjecture that maximal trajectory lengths for the collatz conjecture were yielded by numbers of the form (2**n)-1. This program attempts to test it.\n* \"conjecture()\" finds the number with the highest trajectory lengths in a given range. The ranges are of the form [2**n, 2**(n+1)).\n'''\n\nimport pprint\n\ndef key(value, dct):\n for key in dct.keys():\n if dct[key] == value:\n return key\n return None\n\n\ndef parse_lengths(filename):\n with open(filename) as fp:\n #Processes the text file into a dict mapping numbers to their trajectory length.\n return {int(j.split(\" \")[0]): int(j.split(\" \")[1]) for j in fp}\n\n\ndef conjecture(traj):\n result = {}\n traj_size = len(traj)\n lower, higher = 1, 2\n while True:\n if higher &gt; traj_size:\n # We don't have all the data for this range available.\n break\n\n max_in_slice = max(length for num, length in traj.items() if lower &lt;= num &lt;= higher)\n\n result[higher] = key(max_in_slice, traj)\n\n # Prepare data for next iteration.\n lower, higher = lower * 2, higher * 2\n\n return result\n\nif __name__ == '__main__':\n traj = parse_lengths('CollatzConjecture.txt')\n pprint.pprint(conjecture(traj))\n</code></pre>\n\n<p>I'm also not quite happy with this yet, as the \"key\" function is still bothering me as well (we could iterate over <code>.items()</code> instead of <code>.keys()</code> to simplify).</p>\n\n<p>I hope this at least helps a bit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T16:24:19.490", "Id": "212397", "ParentId": "212377", "Score": "4" } }, { "body": "<p>The existing answers cover most of the issues that I spotted. There's just one thing that I think it's useful to add:</p>\n\n<blockquote>\n<pre><code> for st in (2**x for x in range(1, bound+1)): #Generator for powers of 2.\n slce = list(traj2.items())[int((math.log(st,2)-1)**2):st] #Slices \"traj2\" into powers of 2.\n result[st] = key(max([n[1] for n in slce]), traj2)\n</code></pre>\n</blockquote>\n\n<p>This converts the <code>dict</code> into a list every time through the loop. The suggestions, which don't rely on undocumented behaviour, instead filter the <code>dict</code> each time through the loop. But you can instead invert the loop:</p>\n\n<pre><code> best = [0] * (bound + 1)\n for key, value in traj2.items():\n x = int(math.log(key, 2)) + 1\n if value &gt; best[x] or (value == best[x] and key &lt; result[2**x]):\n best[x] = value\n result[2**x] = key\n</code></pre>\n\n<p>This gives straightforward linear running time and allows you explicit control over tie-breaking. (I'm not sure whether I've got the tie-breaking correct for your conjecture, but you can easily fix that).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-29T09:07:39.357", "Id": "212452", "ParentId": "212377", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-01-28T13:10:23.297", "Id": "212377", "Score": "3", "Tags": [ "python", "beginner", "collatz-sequence" ], "Title": "Testing a Collatz Conjecture Conjecture (Python)" }
212377