body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p><a href="http://jsfiddle.net/xkuZF/6/" rel="nofollow">http://jsfiddle.net/xkuZF/6/</a></p> <pre><code>function func() { document.body.scrollTop++; } window.onmouseover = function() { clearInterval(interval); }; window.onmouseout = function() { interval = setInterval(func); }; var interval = setInterval(func); </code></pre> <p>Do you think that there are any better ways of doing this code? </p> <p>Better:</p> <ul> <li>More options</li> <li>Less code</li> </ul>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T18:12:04.020", "Id": "5192", "Score": "1", "body": "In the future, please avoid using pastebins. As stated in the [faq], it's much easier to review code when it's here, and your code is very short." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T18:36:42.597", "Id": "5193", "Score": "0", "body": "@Michael, you may have changed his original question which is to say about creating scroll bar manually.http://jsfiddle.net/xkuZF/6/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T19:02:56.453", "Id": "5195", "Score": "0", "body": "@didxga That is the only js code I found at that fiddle - what am I missing? If there's more code, would you suggest an edit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T19:18:27.010", "Id": "5196", "Score": "0", "body": "No, he is talking about how you deleted the top 25% of my post..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T19:44:43.323", "Id": "5197", "Score": "0", "body": "@Michael, the <br>s thingy?" } ]
[ { "body": "<p>To your questions:</p>\n\n<ul>\n<li><p>More options; sure you could provide a wait time to setInterval to control the speed of the scrolling down, you could also increase the scrollTop increment to make it scroll down faster.</p></li>\n<li><p>Less code; I think this is pretty much the bare minimum, a little too bare really.</p></li>\n</ul>\n\n<p>I think <code>func</code> and <code>interval</code> are very generic names, I wasnt even sure if the code works / what it does until I clicked the fiddle link.</p>\n\n<p>I would counter propose the following code, it is longer, but far more readable.</p>\n\n<pre><code>var scrollDownInterval;\n\nfunction scrollDown() {\n document.body.scrollTop++;\n}\n\nfunction startScrollingDown(){\n scrollDownInterval = setInterval( scrollDown );\n}\n\nfunction stopScrollingDown(){\n clearInterval( scrollDownInterval );\n}\n\nwindow.onmouseover = function() {\n stopScrollingDown();\n};\n\nwindow.onmouseout = function() {\n startScrollingDown();\n};\n\n//Start scrolling down immediately\nstartScrollingDown(); \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-28T01:18:09.437", "Id": "40227", "ParentId": "3464", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T18:03:18.463", "Id": "3464", "Score": "3", "Tags": [ "javascript" ], "Title": "Better ways of making a scroller" }
3464
<p>I'm new to sockets and servers in general and I would like to know if I'm doing something really wrong in the following server loop for spawning threads to process requests.</p> <pre><code>private static ServerSocket server; private static final Object request_counter_lock = new Object(); private static int request_counter = 0; private static boolean exit = false; public static void main(String[] args) { try { server = new ServerSocket(8000,100); // Loop until one of the clients sends an exit request. while (!exit) { try { final Socket socket = server.accept(); // When a connection is accepted we increment the request // counter so when the server starts to shut down it waits // until all requests are finished processing. synchronized(request_counter_lock) { request_counter++; } // Fire up a new thread to process requests. new Thread(new Runnable() { @Override public void run() { try { processConnection(socket); } catch (IOException e) { logger.error("unable to process request: " + e.getMessage()); } finally { // Make sure we close the socket. SocketCloser.close(socket); // Also decrement the request counter because we just closed // the request socket which means we are done with this client. synchronized(request_counter_lock) { request_counter--; } } } }).start(); // Fire up the thread. } catch (IOException e) { logger.error("error accepting socket connection: " + e.getMessage()); } } } catch (IOException e) { logger.fatal("unable to start server: " + e.getMessage()); } finally { // If the while loop breaks that means we received an exit request from // one of the clients but it's possible that there are still some requests // in progress so we can't shut down the server right away. We have to wait // until the request counter drops down to 0. synchronized(request_counter_lock) { logger.info("acquired lock for request_counter"); while(request_counter &gt; 0) { logger.info("request counter is above 0 so waiting"); try { // Wait 1 second for ongoing clients to finish with their work. request_counter_lock.wait(1000); } catch (InterruptedException e1) { logger.error("error in request_counter synchronized block: " + e1.getMessage()); } } } logger.info("request counter reached 0 so going to close server"); try { server.close(); } catch (IOException e1) { logger.error("unable to close server: " + e1.getMessage()); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T22:27:00.197", "Id": "29667", "Score": "0", "body": "Could you please clarify who is responsible for changing `exit` flag ? Currently looks like you have an infinite loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-02-06T12:34:39.163", "Id": "292359", "Score": "0", "body": "Is \"try-catch with resources\" available?" } ]
[ { "body": "<p>I wouldn't recommend creating new Threads on your own or using Threads without holding onto their references. It makes it too hard to shut down properly. In your example, I think that if <code>SocketCloser.close(socket)</code> throws, then the <code>request_counter</code> will be off by one.</p>\n\n<p>I recommend starting with a thread pool.</p>\n\n<pre><code>ExecutorService pool = ExecutorService.newCachedThreadPool();\n</code></pre>\n\n<p>You can use a fixed size pool if an infinite pool causes you problems. Then you can submit Runnables to it in the same place you're creating Threads now. Finally, when you want to shut down, you can use the methods <code>shutdownNow()</code> and <code>awaitTermination()</code> on the pool.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T14:09:38.800", "Id": "5392", "Score": "0", "body": "You make a good point about exceptions in the finally block but I make sure that `SocketCloser.close` doesn't throw any exceptions. Everything is logged and handled in `SocketCloser.close` so the finally block won't throw any exceptions related to closing a socket." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:17:20.000", "Id": "3578", "ParentId": "3472", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T23:03:05.640", "Id": "3472", "Score": "1", "Tags": [ "java", "multithreading", "thread-safety" ], "Title": "Simple multi-threaded Java server loop" }
3472
<p>The following code solves this problem:</p> <blockquote> <p>The 3072 characters below contain a sequence of 5 characters which is repeated. However, there is a twist: one of the sequences has a typo. To be specific, you're looking for two groups of 5 characters which share 4 of those characters. Enter the 4 shared characters below to proceed.</p> </blockquote> <p>Any suggestions on how it can be improved using idiomatic Lisp/Clojure?</p> <pre><code>(ns slurp.slurp) (defn get-five [in] (if (&gt; (.length in) 4) (subs in 0 5) nil)) (defn how-good [a b position goodness bad-position] (if (= position 5) (list goodness bad-position) (if (= (subs a position (+ 1 position)) (subs b position (+ 1 position))) (recur a b (+ 1 position) (+ 1 goodness) bad-position) (recur a b (+ 1 position) goodness position)))) (defn matches [a b] (let [x (how-good a b 0 0 -1)] (list (&gt; (first x) 3) (last x)))) (defn remove-bad-char [in-string bad-index] (str (subs in-string 0 bad-index) (subs in-string (+ 1 bad-index)))) (defn sub-parse [left in] (let [right (get-five in)] (if (not (= right nil)) (let [match-result (matches left right)] (if (first match-result) (let [bad-index (last match-result)] (println left "is a match. bad-position:" (last match-result) "ans: "(remove-bad-char right bad-index))) (recur left (subs in 1))))))) (defn parse [in] (let [left (get-five in)] ;; as soon as we hit the ass end of the input string, get-five returns null and we stop trying to match. (if (not (= left nil)) (do (sub-parse left (subs in 1)) (recur (subs in 1)))))) (parse (slurp "/Users/clojure/challange.txt")) ;; https://www.readyforzero.com/challenge/491f97bc25574346aed237d43e7d0404 ;; (answer is i2+r) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T01:51:12.413", "Id": "5281", "Score": "0", "body": "Actual URL of input data appears to be: https://www.readyforzero.com/challenge-data/2315ff7b4e1d47deb54e5457bd3334a9/1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T20:39:07.077", "Id": "5309", "Score": "0", "body": "this isn't common-lisp. tag is incorrect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T08:36:41.613", "Id": "5931", "Score": "0", "body": "Yeah, I've done the ready for zero programming challenge too... :)" } ]
[ { "body": "<p>I'd start bottom-up on this one if you want to do it in a slightly more idiomatic / functional style. Also it's good to get the data in Clojure sequences rather than strings as it makes it a bit easier to manipulate.</p>\n\n<p>You're trying to work on groups of five adjacent characters so I'd set up a sequence of such adjacent groups:</p>\n\n<pre><code>; define some source data, right answer is \"1235\"\n(def char-seq (seq \"dfyfgvbufi12345idvdfhopshbsopgeobvufpdhbugphp123a5ghauoyhewqojbvrbon\"))\n\n; now partition into adjacent overlapping groups of five (with a step of 1)\n(def char-groups (partition 5 1 char-seq))\n\n; prove it works\n(take 3 char-groups)\n=&gt; ((\\d \\f \\y \\f \\g) (\\f \\y \\f \\g \\v) (\\y \\f \\g \\v \\b))\n</code></pre>\n\n<p>Now we want to define what a valid match means: in this case 4 characters should be the same in two groups being compared. </p>\n\n<pre><code>; helper function to count the number of true values in a collection / sequence\n(defn count-true [coll]\n (reduce \n #(+ %1 (if %2 1 0))\n 0 \n coll))\n\n; function to determine if exactly four characters are equal in two groups\n(defn matches? [group1 group2]\n (= 4\n (count-true (map = group1 group2))))\n</code></pre>\n\n<p>Finally you just need to run the matches? function over all possible groups:</p>\n\n<pre><code>(def results\n (distinct\n (keep identity\n (for [group1 char-groups \n group2 char-groups]\n (if (matches? group1 group2)\n (filter identity (map #(if (= %1 %2) %1 nil) group1 group2))\n nil)))))\n\n\nresults\n=&gt; ((\\1 \\2 \\3 \\5))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T20:58:37.697", "Id": "5218", "Score": "0", "body": "thanks mikera. I got to learn some new stuff:\n\npartition\nreduce\ndistinct\nkeep\nindentity\nfilter \nmap\nfor. \n\nbtw, why did you need (keep identity ....) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T21:15:28.710", "Id": "5219", "Score": "0", "body": "I see that the keep identity is used to filter the nil's returned by:\n\n (for [group1 char-groups\n group2 char-groups]\n (println group1 group2)) \n\nBut I can't understand where the nils come from when\n\n char-groups\n \nDoes not return any nils. Why is the for putting them in?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T17:44:16.840", "Id": "5273", "Score": "0", "body": "the (for ....) construct returns nils when there is no match via the if statement. This is an artifact of the way the for construct works (it creates a lazy sequence over all possible combinations of char groups). Incidentally this is also why you need the \"distinct\" because it will match the char-groups twice (once in normal order, once in reverse order)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T11:25:28.893", "Id": "3480", "ParentId": "3473", "Score": "1" } }, { "body": "<p>Here is my version. Works on any seq (not just strings) and is fully lazy.</p>\n\n<pre><code>(def data (slurp \"data.txt\"))\n\n(defn same-pos \n \"Return all the elements of xs and ys that match, position-wise. e.g.\n (same-pos [\\\\a \\\\x \\\\c] [\\\\a \\\\r \\\\c]) returns [\\\\a \\\\c]. Returns nil if xs\n and ys have different lengths.\"\n [xs ys]\n (when (= (count xs) (count ys))\n (filter (complement nil?) (map #(if (= %1 %2) %1) xs ys))))\n\n(def answer\n (let [ps (partition 5 1 data)] ; build seq of sliding 5-tuples\n (-&gt;&gt; (for [x ps y ps] (same-pos x y)) ; n^2 FTW\n (filter (comp (partial = 4) count)) ; 4 of 5 positions must match\n (first))))\n\n(println (apply str \"Answer: \" answer)) ; will print \"Answer: i2+r\"\n</code></pre>\n\n<p><strong>Update:</strong> I didn't read other answers beforehand (wanted to figure it out myself), but it looks like I've got basically the same thing as <a href=\"https://codereview.stackexchange.com/questions/3473/how-can-i-improve-this-code/3480#3480\">mikera</a>. So maybe not a whole lot to learn here :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T03:25:53.607", "Id": "3533", "ParentId": "3473", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T23:06:05.817", "Id": "3473", "Score": "3", "Tags": [ "programming-challenge", "lisp", "clojure" ], "Title": "Searching for repeated characters in a sequence of characters" }
3473
<blockquote> <p>The following text is an in-order traversal of a binary tree with 1023 nodes. What is the sum of the digits appearing in the leaves?</p> </blockquote> <p>How can I improve this Clojure code? It looks strange to me to have two recurs in the <code>if</code>.</p> <pre><code>(ns fun2) (defn parse [in sum] (println "sum" sum) (if (&gt; (.length in) 1) (let [next-char (subs in 0 1)] (if (.matches next-char "[0-9]") (recur (subs in 2) (+ sum (Integer/parseInt next-char))) (recur (subs in 2) sum))))) (parse (slurp "/Users/clojure/challange2.txt") 0) ;; ans 331 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T02:11:12.443", "Id": "5206", "Score": "1", "body": "Are we assuming this is a complete binary tree? Otherwise I don't think a single inorder traversal is enough to reliably figure out what the leaves are." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T08:43:48.447", "Id": "5210", "Score": "0", "body": "depends on whats important to you, readability, speed, memory etc. the readability there can definitely use some improvement." } ]
[ { "body": "<p>This code is doing several distinct things and one of the really great things about clojure is that it lets you make things simple by decomposing things that do more than one task into a series of individual tasks.</p>\n\n<p>if is:</p>\n\n<ul>\n<li>taking every other letter in a string (perhaps you meant to take every letter)</li>\n<li>picking out the digits</li>\n<li>convert them into numbers.</li>\n<li>adding them all up. </li>\n</ul>\n\n<p>take every other character:</p>\n\n<pre><code>(apply str (flatten (partition-all 1 2 in)))\n</code></pre>\n\n<p>pick out the digits:</p>\n\n<pre><code>(re-seq #\"[0-9]\" ...\n</code></pre>\n\n<p>turn them into integers:</p>\n\n<pre><code>(map #(Integer/parseInt (str %)) ...\n</code></pre>\n\n<p>add them all up, keeping the intermediates:</p>\n\n<pre><code>(reductions + ...\n</code></pre>\n\n<p>so if i compose these i end up with:</p>\n\n<pre><code>(reductions + \n (map #(Integer/parseInt (str %)) \n (re-seq #\"[0-9]\" \n (apply str (flatten (partition-all 1 2 in))))))\n</code></pre>\n\n<p>producing:</p>\n\n<pre><code>(2 11 15 15 19 20 24 33 34 35 44 46 48 48 55 63 67 \n 76 77 79 83 90 95 102 106 109 114 121 \n 121 127 136 144 151 160 168 174 174 176 \n 180 182 191 199 204 211 214 216 222 226\n 235 242 246 247 250 252 260 263 270 275 \n 276 277 278 282 288 295 299 299 304 308 \n 310 315 323 326 326 331)\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p>In your example the lines </p>\n\n<pre><code> (recur (subs in 2) (+ sum (Integer/parseInt next-char)))\n (recur (subs in 2) sum)))))\n</code></pre>\n\n<p>combined with:</p>\n\n<pre><code>(let [next-char (subs in 0 1)]\n</code></pre>\n\n<p>work out the same as taking every other letter. I'm only looking at the code and not the problem you are trying to solve so I can't say if this is what you want or not. If by chance this is a bug then your could change the 2 to a 1 and get all the letters:</p>\n\n<pre><code>(defn parse [in sum]\n (println \"sum\" sum)\n (if (&gt; (.length in) 1)\n (let [next-char (subs in 0 1)]\n (if (.matches next-char \"[0-9]\")\n (recur (subs in 1) (+ sum (Integer/parseInt next-char)))\n (recur (subs in 1) sum)))))\n</code></pre>\n\n<p>producing an answer of 679.</p>\n\n<p>the reduced clojure-map-reduce-style form of this code would become a bit simpler:</p>\n\n<pre><code>(reductions + (map #(Integer/parseInt (str %)) (re-seq #\"[0-9]\" in)))\n\n(4 7 9 18 26 28 32 41 50 53 53 57 64 72 79 85 88 89 \n 90 99 103 112 113 114 120 124 130 131 137 142 143 \n 152 159 159 159 161 168 170 170 177 180 188 189 193\n 198 198 207 208 209 217 219 223 230 235 242 249 251 \n 255 257 261 264 269 276 276 285 291 297 306 314 320 \n 327 329 338 339 347 356 362 362 370 377 379 383 385 \n 394 402 407 415 419 426 427 430 434 436 442 446 447 \n 449 456 465 472 475 479 484 485 488 492 493 498 500 \n 508 517 520 527 532 533 534 535 539 541 549 555 563 \n 570 574 574 579 585 589 589 591 591 596 604 613 618 \n 622 631 634 640 647 650 654 654 661 666 675 679)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T01:21:35.917", "Id": "3477", "ParentId": "3475", "Score": "1" } }, { "body": "<p>Here's a version of the function that I find nicer:</p>\n\n<pre><code>(defn parse [s]\n (apply + (-&gt;&gt; s\n (partition-all 2) ; iterate pairs of chars in s\n (map (comp str first)) ; leaf node is the first in the pair\n (filter (partial re-find #\"\\d\")) ; keep only digits\n (map #(Integer/parseInt %))))) ; turn 'em into ints\n</code></pre>\n\n<p>I imagine it can be further reduced to be more idiomatic Clojure, but I find this pretty readable.</p>\n\n<p>Important assumption: this algorithm only works if the input is an inorder traversal of a <em>complete</em> binary tree. If the original tree was not complete, a single inorder traversal is not sufficient to reconstruct it and find the leaves.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T02:45:59.350", "Id": "3478", "ParentId": "3475", "Score": "5" } }, { "body": "<p>I find it useful to think in seqs and built-in functions.</p>\n\n<p>Assuming that the the numbers are leaves. You can extract all the leaves using <code>re-seq</code>, then map them to numbers and then use apply <code>+</code> to all the numbers to get the sum:</p>\n\n<pre><code> (defn sum-leaves [s]\n (apply + (map #(- (int (first %)) (int \\0)) (re-seq #\"[0-9]\" s))))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T05:26:46.447", "Id": "3485", "ParentId": "3475", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T23:36:22.530", "Id": "3475", "Score": "6", "Tags": [ "programming-challenge", "tree", "clojure" ], "Title": "Finding the sum of the digits appearing in the leaves via in-order traversal" }
3475
<pre><code>$('#step-holder a').click(function (e) { e.preventDefault(); $('#step-holder div').each(function () { if ($(this).attr('class') == 'step-dark-left') { $(this).removeClass('step-dark-left'); $(this).addClass('step-light-left'); } if ($(this).attr('class') == 'step-dark-right') { $(this).removeClass('step-dark-right'); $(this).addClass('step-light-right'); } if ($(this).attr('class') == 'step-no') { $(this).removeClass('step-no'); $(this).addClass('step-no-off'); } if ($(this).attr('class') == 'step-dark-round') { $(this).removeClass('step-dark-round'); $(this).addClass('step-light-round'); } }); if ($(this).parent().attr('class') == 'step-light-left') $(this).parent().attr('class', 'step-dark-left'); if ($(this).parent().next().attr('class') == 'step-light-right') $(this).parent().next().attr('class', 'step-dark-right'); if ($(this).parent().next().attr('class') == 'step-dark-round') $(this).parent().next().attr('class', 'step-light-round'); if ($(this).parent().next().attr('class') == 'step-light-round') $(this).parent().next().attr('class', 'step-dark-round'); $(this).parent().prev().attr('class', 'step-no'); }); </code></pre>
[]
[ { "body": "<p>One quick refactoring jumps out at me. Start out your each with:</p>\n\n<pre><code>$('#step-holder div').each(function () {\n var $this = $(this);\n</code></pre>\n\n<p>Every time you call it (possibly 12 times?) its performing a lookup ... you should look up that object once, store the result, and then reuse it. </p>\n\n<p>I'm going to assume each of these objects has only one class -- otherwise your <code>.attr('class')</code> test would fail (by the way, use <code>.hasClass('x')</code> to test so if it has multiple classes you can still tell if it has <em>that</em> class). Based on that assumption, you can shorten the first few <code>if</code> statements like this:</p>\n\n<pre><code>$('#step-holder div').each(function () {\n var $this = $(this);\n\n if( $this.hasClass('step-dark-left') ) {\n $this.attr('class','step-left-light');\n }\n else if( $this.hasClass('step-dark-right') ) {\n $this.attr('class','step-light-right');\n } \n ... etc ...\n});\n</code></pre>\n\n<p>I also suggest you use <code>if ... else if ... else if ... etc</code> because only one of those can be true -- no reason to evaluate them all. Again, this assumption is based on your code, and I'm reading a lot into your class test, when it could in fact be an error on your part.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T08:43:50.903", "Id": "5224", "Score": "0", "body": "thx erik, i have applied your changes ( beside the linked if's, i dont like the visual look of it )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T13:41:23.870", "Id": "5263", "Score": "0", "body": "... it has nothing to do with visual look. You're executing branches needlessly. If only one of those conditions can be true then multiple IF statements are not the best way of handling it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T04:32:48.577", "Id": "3484", "ParentId": "3481", "Score": "1" } } ]
{ "AcceptedAnswerId": "3484", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T12:12:53.540", "Id": "3481", "Score": "-1", "Tags": [ "javascript", "jquery" ], "Title": "How can i shorten/refactor this jquery?" }
3481
<p>This code removes repeated words from a word array (2D char array). I want to optimize this as much possible for speed.</p> <pre><code>#include "stdio.h" #include "string.h" main() { char words[2000][20]; /*This array is populated by some other module. possible example of this array is given below, but in reality it would far more elements. char words[6][20] = { {"barrack"}, {"david"}, {"John"}, {"david"}, {"benjamin"}, {"barrack"} };*/ int names_found = 10; char out_words[6][20]; int i,j; int act_names=0; for (i = 0; i &lt; names_found; i ++) { j = i + 1; while (j &lt; names_found) { if (strcmp(words[i], words[j]) == 0) { memmove(words + j, words + (names_found - 1), sizeof(words[0])); -- names_found; } else ++ j; } } for(i=0;i&lt;names_found;i++) { printf("%s\n",words[i]); } } </code></pre> <ol> <li><p>How can the 2 <code>for</code> loops for <code>i</code> and <code>j</code> above be optimized?</p></li> <li><p>As you see, the above logic currently outputs to same input buffer (in-place processing). Can it be optimized further if we allow a second buffer say <code>char out_words[2000][20]</code>?</p></li> </ol>
[]
[ { "body": "<ol>\n<li><p>Your algorithm is \\$O(n^2)\\$. You can reduce this to \\$O(n)\\$ by first inserting them into a closed hash table (i.e., one with bucket chains).</p></li>\n<li><p>I'd optimise is rather than copying the whole items, just copy pointers to the original strings (unless you intend to alter their contents later on).</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T11:00:29.443", "Id": "5226", "Score": "0", "body": "Thanks. Could you point to more details about your first point of closed hash table." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T21:49:16.653", "Id": "5248", "Score": "0", "body": "Sorry, that was probably too fine a detail. With a closed hash table, insertion is trivial (you don't have to do multiple probes) and it gathers all items with the same hash in the same bucket chain (hopefully your hash function will not map too many different strings to the same number)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T07:45:26.620", "Id": "3489", "ParentId": "3488", "Score": "6" } }, { "body": "<ul>\n<li><p>The <code>#include</code>s should use <code>&lt;&gt;</code> since these are libraries. You should only use <code>\"\"</code> for your own header files.</p></li>\n<li><p>Consider splitting this program into separate functions. You could have two: one for doing the modifications and another for doing the displaying. You could then have <code>main()</code> call these functions, one at a time.</p></li>\n<li><p>The display loop looks unsafe:</p>\n\n<blockquote>\n<pre><code>for(i=0;i&lt;names_found;i++)\n{\n printf(\"%s\\n\",words[i]);\n}\n</code></pre>\n</blockquote>\n\n<p>Before entering this loop, you should make sure that <code>names_found</code> is not too large, otherwise the loop will access the array go out-of-bounds.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-28T03:26:53.813", "Id": "51885", "ParentId": "3488", "Score": "2" } } ]
{ "AcceptedAnswerId": "3489", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T07:07:56.460", "Id": "3488", "Score": "4", "Tags": [ "optimization", "c", "strings", "array" ], "Title": "Remove repeated words from a 2D character array" }
3488
<p>I love lambdas, and functional programming etc. But sometimes I wonder if I take it too far..</p> <pre><code>public static T With&lt;T&gt;(this T source, Action&lt;T&gt; action) { action(source); return source; } public static IEnumerable&lt;T&gt; ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T&gt; action) { return source.Select(x =&gt; x.With(action)); } </code></pre> <p>thoughts?</p> <h3>UPDATE</h3> <p>Some good points, some I agree with, some I don't, but a few details:</p> <p>I understand that <code>Linq</code> may not be intended to handle side effects, especially since <code>List.ForEach</code> returns void, however I disagree that functional programming can't contain side effects, a monad is simply a chunk of code to execute for a given structure.</p> <p>The <code>ForEach</code> and <code>With</code> extensions, are meant to be a syntactic sugar. Perhaps the name is poorly chosen, and it should be something like <code>OnEnumerate</code>, however I wonder if this could get confusing down the line, as its whole point is to invoke side effects at that particular point in the expression, and this could occur multiple times, perhaps I should stick with my <code>With</code> convention and do <code>WithEach</code>.</p> <p>The comments about using <code>Select</code> internally are probably true, as I'm not really projecting, and <code>yield return</code> saves a method call. (premature optimization anyone?)</p> <pre><code>public static IEnumerable&lt;T&gt; WithEach&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T&gt; action) { foreach(var x in source) yield return x.With(action); } </code></pre> <p>To be honest I probably wouldn't use <code>WithEach</code> often, unless its an edge case where I'm passing an <code>IEnumerable&lt;T&gt;</code> that may or may not be enumerated. I can imagine it being effective in generating complex hierarchies. However <code>With</code> I use quite often, usually as a way to chain things together, i.e:</p> <pre><code>this.SomeObservable = someObservable .With(o =&gt; o.Subscribe(this.OnNext) .With(this._disposables.Add)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:21:32.773", "Id": "5227", "Score": "12", "body": "Causing side-effects is not about functional programming at all. Yep, this is too dirty." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:26:53.027", "Id": "5228", "Score": "1", "body": "Can't you just use the normal C# foreach statement?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:27:18.340", "Id": "5229", "Score": "0", "body": "@Snowbear: Your comment is an answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:28:45.747", "Id": "5230", "Score": "0", "body": "In general, LINQ avoids mutating operations like that in favor of selecting a new argument instead." } ]
[ { "body": "<p>I don't think this really provides a lot of value beyond the existing .Select() projection. Anything you write into your action you could also write into a .Select() lambda.</p>\n\n<p>For example:</p>\n\n<pre><code>myItems.Select(item =&gt; \n{\n item.DoSomethingWeird();\n return item;\n}).Select(item =&gt;\n{\n item.DoSomethingWeird(); //again\n return item;\n});\n</code></pre>\n\n<p>Also, I wouldn't appropriate the <code>ForEach</code> name here. It has other, conflicting means. \"WithAll()\" might be a better name.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:32:10.290", "Id": "5231", "Score": "0", "body": "I'd agree (perhaps OP could describe what extra value they are attempting to add). Also, \"ForEach\" would be a bit misleading, because the actions won't take place until the returned Enumerable is enumerated. Someone reading a Select, however, knows about the delayed nature." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:29:40.750", "Id": "3492", "ParentId": "3491", "Score": "2" } }, { "body": "<p>All that as opposed to this?:</p>\n\n<pre><code>foreach(var item in source)\n{\n //do something?\n}\n</code></pre>\n\n<p>Extension methods are great when they don't cause side effects but this would violate the standard functional approach taken with LINQ.</p>\n\n<p>It can hide the point of your method chain: </p>\n\n<pre><code> source.Where(x =&gt; x.IsValid)\n .With(x =&gt; x.MakeInvalid())\n .Count();\n</code></pre>\n\n<p>Obviously a contrived example but the point is that using chains with side effects can be a pattern which hide the code's meaning.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:32:49.880", "Id": "5232", "Score": "0", "body": "He's going for syntactic sugar -- the ability to include his action as part of a method chain." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:31:11.577", "Id": "3493", "ParentId": "3491", "Score": "0" } }, { "body": "<p>Because the <code>List&lt;T&gt;</code> already defines <code>ForEach()</code> as a void method, I would not want to get that mixed up with a \"<code>ForEach()</code>\" that is also a <code>Select()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:33:11.133", "Id": "3494", "ParentId": "3491", "Score": "1" } }, { "body": "<p>My advice: don't do this.</p>\n\n<ol>\n<li><p>Building devices that encourage you to write expressions that are useful only for their side effects is poor functional style.</p></li>\n<li><p>You are abusing \"Select\" when you use it as an implementation detail of \"ForEach\". \"Select\" does not have the semantics of \"ForEach\"! The purpose of \"Select\" is to compute a projection, not to cause a side effect.</p></li>\n<li><p>You are building yourself a little time bomb. Because your implemenation of ForEach is to build a Select query, the \"ForEach\" executes lazily. When you say \"blah.ForEach(whatever);\" <strong>that doesn't do anything</strong>. It just builds up an object that represents <em>doing the side effects in the future</em>. Since you never use that object for anything, the side effects remain undone. If, by contrast, you do use that object, you run the risk of using it <em>twice</em> and causing the same side effects again.</p></li>\n</ol>\n\n<p>That said, the <em>idea</em> of what you're doing is sound; the idea of representing a sequence of side-effecting operations in a lazily-evaluated object is how side effects are represented in Haskell. But if that's what you want to do, then <em>actually build yourself a real monad that clearly and unambiguosly represents the semantics of \"I'm building an object that represents a sequence of side effects in the future\"</em>. Don't be all coy about it! Be explicit that that's what you're doing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:49:56.583", "Id": "5233", "Score": "5", "body": "I get what your saying, but I have no idea how I would go about building the mentioned monad." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:48:56.537", "Id": "3495", "ParentId": "3491", "Score": "25" } }, { "body": "<p>Enumerating something using an extension is not supposed to cause side effects.</p>\n\n<p>If you make an extension that is intended to cause side effects, it can easily come back and bite you. As the enumeration uses deterred execution, something like this would have no effect:</p>\n\n<pre><code>myList.Foreach(x =&gt; Console.WriteLine(x));\n</code></pre>\n\n<p>As you are not consuming the result, there is nothing that pulls the iteration, so it won't iterate anything at all. It will just create code that is capable of iterating, and throw it away.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:49:21.507", "Id": "3496", "ParentId": "3491", "Score": "2" } }, { "body": "<p>In addition to the semantic problems described by Eric Lippert, you should avoid this because it causes namespace pollution.</p>\n\n<p>By adding extension methods to <em>any</em> object, you're diluting the usefulness of intellisense. You should avoid this because it can become messy (and confusing) quickly. C# already has syntax for calling methods, you should ask yourself if you really want another way of expressing the same thing.</p>\n\n<p>Alternatively, consider a higher-order function:</p>\n\n<pre><code>static Func&lt;T,T&gt; SideEffect(Action&lt;T&gt; action) { return x=&gt;{action(); return x;} }\n</code></pre>\n\n<p>Which you might use as follows:</p>\n\n<pre><code>var lazylist = \n something.Select(\n SideEffect(item =&gt; Console.WriteLine(\"iteration logged \"+item)));\n</code></pre>\n\n<p>Note that side effects make code much harder to understand; this is explained in other answers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T16:15:48.957", "Id": "3497", "ParentId": "3491", "Score": "1" } }, { "body": "<p>I am guessing <a href=\"https://codereview.stackexchange.com/users/4318/eric-lippert\">EricLippert</a> was referring to something like this when stating:</p>\n\n<blockquote>\n <p>That said, the <em>idea</em> of what you're doing is sound; the idea of representing a sequence of side-effecting operations in a lazily-evaluated object is how side effects are represented in Haskell. But if that's what you want to do, then <em>actually build yourself a real monad that clearly and unambiguosly represents the semantics of \"I'm building an object that represents a sequence of side effects in the future\"</em>. </p>\n</blockquote>\n\n<pre><code>//was ForEach\n/// &lt;summary&gt;\n/// Causes some action when the element in the enumeration is touched. \n/// The action will only happen the first time the element is touched.\n/// &lt;/summary&gt;\n/// &lt;typeparam name=\"T\"&gt;The type of element in the enumerable&lt;/typeparam&gt;\n/// &lt;param name=\"source\"&gt;The enumerable source&lt;/param&gt;\n/// &lt;param name=\"action\"&gt;the action to execute&lt;/param&gt;\n/// &lt;returns&gt;An enumerable representing the source which will execute the action when elements are enumerated&lt;/returns&gt;\npublic static IEnumerable&lt;T&gt; OnEnumeration&lt;T&gt;(this IEnumerable&lt;T&gt; source, Action&lt;T&gt; action) \n{\n return new FutureSideEffect&lt;T&gt;(source, x =&gt; x.With(action));\n}\n\npublic class FutureSideEffect&lt;T&gt; : IEnumerable&lt;T&gt;, IEnumerator&lt;T&gt; \n{\n readonly IEnumerable&lt;T&gt; enumerable;\n readonly List&lt;T&gt; enumerated = new List&lt;T&gt;();\n readonly Stack&lt;IEnumerator&lt;T&gt;&gt; enumeratorStack = new Stack&lt;IEnumerator&lt;T&gt;&gt;();\n\n public FutureSideEffect(IEnumerable&lt;T&gt; enumerable, Action&lt;T&gt; action) \n {\n this.enumerable = enumerable.Select(x =&gt;\n {\n action(x); \n return x;\n }\n );\n }\n\n public IEnumerator&lt;T&gt; GetEnumerator()\n {\n return this;\n }\n\n IEnumerator IEnumerable.GetEnumerator()\n {\n return GetEnumerator();\n }\n\n public bool MoveNext()\n {\n IEnumerator&lt;T&gt; enumerator = null;\n if (enumeratorStack.Count != 0) \n {\n enumerator = enumeratorStack.Peek();\n if (enumerator == null) \n {\n enumeratorStack.Pop();\n enumerator = enumerated.GetEnumerator();\n enumeratorStack.Push(enumerator);\n }\n }\n else\n {\n enumerator = enumerable.GetEnumerator();\n enumeratorStack.Push(enumerator);\n }\n var result = enumerator.MoveNext();\n if (!result &amp;&amp; enumeratorStack.Count &gt; 1)\n {\n enumeratorStack.Pop();\n return MoveNext();\n }\n return result;\n }\n public void Reset() \n {\n IEnumerator&lt;T&gt; enumerator = null;\n if (enumeratorStack.Count != 0) \n {\n enumerator = enumeratorStack.Peek();\n }\n if (enumerator == null)\n {\n return;\n }\n enumeratorStack.Push(null);\n }\n public T Current \n {\n get \n {\n var current = enumeratorStack.Peek().Current;\n if (enumeratorStack.Count == 1)\n {\n enumerated.Add(current);\n }\n return current;\n }\n }\n object IEnumerator.Current \n {\n get \n {\n return Current;\n }\n }\n\n public void Dispose() \n {\n Dispose(true);\n GC.SuppressFinalize(this);\n }\n\n //finalizer unnecessary because there are no unmanaged resources\n protected virtual void Dispose(bool disposing) \n {\n if (disposing) \n {\n enumerated.Clear();\n while (enumeratorStack.Count != 0)\n {\n var enumerator = enumeratorStack.Pop();\n if (enumerator != null) \n {\n enumerator.Dispose();\n enumerator = null;\n }\n }\n //don't touch enumerable because I don't own it\n }\n }\n}\n</code></pre>\n\n<p>I built a small console app to play around with this, but I can't really think of any reason I might want to use it and I didn't bother remotely trying to consider aspects of thread safety.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-27T22:11:12.823", "Id": "15115", "ParentId": "3491", "Score": "2" } } ]
{ "AcceptedAnswerId": "3495", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T15:19:11.620", "Id": "3491", "Score": "7", "Tags": [ "c#", "extension-methods" ], "Title": "Extension methods, is this too dirty?" }
3491
<p>I'm using Codeigniter but this goes for any project in PHP. Let's say I have the following code in my view. I've been struggling, trying to figure out how best to indent and display PHP code within standard HTML code.</p> <pre><code>... ... &lt;div id="subcontent"&gt; &lt;?php if ($this-&gt;session-&gt;flashdata('message')) { ... ... ?&gt; &lt;div class="blah blah"&gt; ... ... &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; </code></pre> <p>So notice how I nested HTML within the PHP code by escaping w/ the PHP syntax. This can get out of hand if you have lines and lines of code. I'm using Komodo and I've enabled "Indentation Guidelines" but even with that, most of my code doesn't line up. So my question is, how best to handle this?</p> <p>I've actually resorted to keeping the PHP marker <code>&lt;?php ?&gt;</code> to the far left and not indenting them. Seems to work so far ...</p>
[]
[ { "body": "<p>This is really an individual opinion..</p>\n\n<p>Personally I'm all for putting the <code>&lt;?php ?&gt;</code> markers at the far left because they indicate different code 'segments'.. There is just no 'best way to do it.. Just choose a way and stick to it..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:20:48.053", "Id": "5234", "Score": "0", "body": "Yea, i actually came across this by accident. I had indented all my code to the far left to \"reset\" everything. I forgot to indent the `<?php` part and viola I said to myself, \"woah that doesn't look too bad.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:34:29.923", "Id": "5235", "Score": "0", "body": "Just making sure you know this syntax as wel, but if you just want to include a single PHP value inside a HTML line you can best use `<?= $val ?>`.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:47:46.313", "Id": "5236", "Score": "1", "body": "i removed the \"short\" syntax (whatever it's called) due to JS compatibility." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:17:26.987", "Id": "3499", "ParentId": "3498", "Score": "2" } }, { "body": "<p>You can use other kind of syntax:</p>\n\n<pre><code>...\n...\n&lt;div id=\"subcontent\"&gt;\n &lt;?php if ($this-&gt;session-&gt;flashdata('message')): ?&gt;\n &lt;div class=\"blah blah\"&gt;\n ...\n ...\n &lt;/div&gt;\n &lt;?php endif; ?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>So, <code>&lt;?php ?&gt;</code> can be in 1 line and I think it's beauty:)</p>\n\n<p>Anyway, There are no any 'right' way to do it. You can(and should) choose your own one</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:19:41.327", "Id": "3500", "ParentId": "3498", "Score": "5" } }, { "body": "<p>I prefer opening PHP scripts with the same indentation as their parent, and then having the actual code and the subsequent tags be indented.</p>\n\n<pre><code>&lt;div&gt;\n&lt;?\n $query = mysql_query(\"SELECT * FROM `table`\");\n while($row = mysql_fetch_assoc($query)):\n?&gt;\n &lt;div&gt;&lt;?=$row['content']?&gt;&lt;/div&gt;\n&lt;? \n endwhile;\n?&gt;\n&lt;/div&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T15:11:33.950", "Id": "5271", "Score": "2", "body": "Beware Short Tags http://stackoverflow.com/questions/200640/are-php-short-tags-acceptable-to-use" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:21:09.217", "Id": "3501", "ParentId": "3498", "Score": "0" } }, { "body": "<p>That's a question about personal preferences. I always work with templates (smarty) to seperate views from logic.</p>\n\n<p>Your example seems to be a bit confusing.</p>\n\n<pre><code>&lt;div id=\"subcontent\"&gt;\n&lt;?php \n if ($this-&gt;session-&gt;flashdata('message')) {\n do something;\n do something else;\n?&gt;\n &lt;div class=\"blah blah\"&gt;\n &lt;div id=\"one\"&gt;some text&lt;/div&gt;\n &lt;div id=\"two\"&gt;another text&lt;/div&gt;\n &lt;/div&gt;\n&lt;?php\n }\n?&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>might imho be a better way! The condition is on the same level as your first div. ist nested in your opening div, so it needs an indent. Same to the following divs, which are nested in the blah-div. An indent of 2 blanks should be enough. </p>\n\n<p>But note, that's just my opinion. The only requirement to good code is that the code must be readable and maintanable. You can find several coding guides in the web (google for coding guidelines php). Look at them, read the explanations and choose these guidelines that you like best!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:49:05.253", "Id": "5237", "Score": "0", "body": "I indent w/ 4 spaces (used to coding in Python as well), but I get what you are saying." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:40:56.793", "Id": "3502", "ParentId": "3498", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T16:12:13.023", "Id": "3498", "Score": "5", "Tags": [ "php" ], "Title": "Best practice for lining up PHP syntax in HTML page" }
3498
<p>I wrote a simple function that calculates and returns the maximum drawdown of a set of returns. I am trying to squeeze as much efficiency for speed out of the code as possible. I've got it down to about as fast as I can go. Does anyone have suggestions on how to write this function more efficiently, perhaps through list comprehensions etc.?</p> <pre><code>import numpy as np def max_drawdown(returns): draw_series = np.array(np.ones(np.size(returns))) max_return = 0; max_draw = 1; draw = 1 returns = returns + 1 for r in range(returns.count()-1, 0, -1): if returns[r] &gt; max_return: max_return = returns[r] else: draw = returns[r] / max_return if draw &lt; max_draw: max_draw = draw draw_series[r-1] = -(1 - max_draw) return draw_series </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:54:19.583", "Id": "5238", "Score": "0", "body": "What type of object is `returns`? `returns = returns + 1` suggests it might be an integer, or a numpy array, but neither of those has a `count` method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:57:53.390", "Id": "5239", "Score": "0", "body": "It is actually a Pandas TimeSeries object which acts like a numpy array. returns.count() is the same as len(returns)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T22:11:50.263", "Id": "5240", "Score": "0", "body": "This is minor and more aesthetic than performance-related, but note that `numpy.ones` returns an array, so passing it to `numpy.array` is redundant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T22:19:50.413", "Id": "5241", "Score": "0", "body": "Thanks @senderle. I found some optimization stuff on loops here, http://www.python.org/doc/essays/list2str.html." } ]
[ { "body": "<p>Don't just optimize this or optimize that by educated guessing.</p>\n\n<p>Find out which lines of code are responsible for a large fraction of time,\nas shown in <a href=\"https://stackoverflow.com/questions/4295799/how-to-improve-performance-of-this-code/4299378#4299378\">this answer</a>,\nand focus your attention there.</p>\n\n<p>Then when you've optimized that, do it all again, until you can't improve it any more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T22:03:07.403", "Id": "5242", "Score": "0", "body": "That's good advice, thanks. However, I'm not exactly sure what you are doing in your other post. I get the idea of identifying which lines of code are taking the most time, but I do not know how are you getting there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T23:18:21.987", "Id": "5243", "Score": "0", "body": "@strimp099: I thought I made it pretty clear, but I'll admit not everybody gets it right away. You give the program enough data, or you simply loop it enough times so it takes at least several seconds. During that time, you hit Ctrl-C to halt it, and capture the call stack. Do that a few times. Whether a line of code is a function call or not, the fraction of time it costs is the fraction of samples that show it. If something shows up on >1 stack, if you can optimize it, you win. If something never shows up, you can be sure it's too small to worry about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T23:24:05.927", "Id": "5244", "Score": "0", "body": "@strimp099: Continued (forgive me)... If you look at the other answers to that question, people say things like \"your bottleneck is *this* ...\", which is a plausible guess and it's wrong. However, sampling the stack does locate the big time-drain. *If that is fixed so it takes less time*, then it's a new game, and what was not the big time-taker before may now become a big time-taker, percentage-wise, because the pond is smaller." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:53:31.513", "Id": "3504", "ParentId": "3503", "Score": "1" } }, { "body": "<p>If you want high-performance code, Python probably isn't the right language. You don't seem to be doing anything that's much more intensive than what is necessary to achieve your intended computation, so it is unlikely you can increase performance much more.</p>\n\n<p>If you must use Python for whatever reason (such as your data structures coming from a Python environment), you could always use Swig or a similar tool to write a C program that does what you need and link that program to Python. This won't be worth it unless you're working on a very large dataset. Another possibility is to simply dump your data to a file, have a C program process it and dump an output file which could then be read by your program. Of course, you run the risk of spending more time in I/O operations, which could well outweigh any performance gains of this approach.</p>\n\n<p>A less radical proposal: Do you expect that the if statement here:</p>\n\n<pre><code> if returns[r] &gt; max_return:\n max_return = returns[r]\n</code></pre>\n\n<p>will be true only rarely? If so, try the following. I doubt it will improve performance substantially, but it's easy to give it a try. It may also make performance worse (it all depends on your general type of dataset):</p>\n\n<p>Change the if-else:</p>\n\n<pre><code> if returns[r] &gt; max_return:\n max_return_reciprocal = 1.0/returns[r]\n else:\n draw = returns[r] * max_return_reciprocal\n #...then the if draw &lt; \n</code></pre>\n\n<p>This could spare you from a lot of floating-point divisions, which are quite slow compared to multiplies. This probably won't substantially improve performance, though, because I expect that most of the slowness comes from the overhead associated with Python (interpretation of code). You might also want to look at what exactly this line does:</p>\n\n<pre><code>draw_series = np.array(np.ones(np.size(returns)))\n</code></pre>\n\n<p>Can you time it and see if it is causing the performance problem?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T23:53:30.713", "Id": "3505", "ParentId": "3503", "Score": "1" } }, { "body": "<p>You are correct to point out that your implementation is terribly inefficient compared to most built-in Numpy operations of similar complexity. 100X speedup would be reasonable for large arrays once you eliminate the python loop. It would be trivial to replace your python loop with some Numpy indexing or broadcasting if it weren't for the pesky <code>draw_series[r-1] = -(1 - max_draw)</code> line which operates on the next-to-be-computed item in the array. This is analogous to Numpy's <a href=\"http://docs.scipy.org/doc/numpy/reference/generated/numpy.ufunc.accumulate.html\">accumulate</a> but obviously there's no implementation of it for your particular algorithm. You have three options as I see it:</p>\n\n<ol>\n<li><p>Study your problem hard and see if you decompose it into numpy-only\naccumulate and regular operations. </p></li>\n<li><p>See if your algorithm can be expressed as a compiled <a href=\"http://code.google.com/p/numexpr/\">numexpr</a>\nexpression. </p></li>\n<li><p>Compile this function using <a href=\"http://cython.org/\">Cython</a>, <a href=\"http://www.scipy.org/Cookbook/F2Py\">f2py</a> or <a href=\"http://docs.python.org/library/ctypes.html#module-ctypes\">ctypes</a></p></li>\n</ol>\n\n<p>One minor improvement is to replace <code>returns = returns + 1</code> with <code>returns += 1</code> which will operate in-place and avoid re-allocating the <code>returns</code> array.</p>\n\n<p>Hope this helps. good luck.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-16T00:35:35.693", "Id": "3506", "ParentId": "3503", "Score": "5" } }, { "body": "<p>The fastest I could get this using python only is a bit less than twice the speed before. My best attempt was</p>\n\n<pre><code> def max_drawdown(returns):\n\n draw_series = np.empty(returns.size)\n\n max_return = 0; min_draw = 1; draw = 1\n returns += 1.0\n\n for r in range(returns.size,0,-1):\n ret = returns[r-1]\n if ret &gt; max_return:\n max_return = ret\n else:\n draw = ret / max_return\n if draw &lt; min_draw:\n min_draw = draw\n\n draw_series[r-1] = min_draw\n returns -= 1.0 # otherwise side effects\n data_series -= 1.0\n\n return draw_series\n</code></pre>\n\n<p>I should note though that this attempts to fix some things that looked weird in your function such as the draw_series / max-return index offset. But these can be fixed relatively easily.</p>\n\n<p><code>np.empty</code>: initializes the array but doesn't bother to set the inside so you save looping through the array as you would have to with <code>np.ones</code>.</p>\n\n<p><code>returns +(-)= 1</code> changes the value of returns in place, so it should not be considered a thread-safe function with this addition. I've negated the change so that there are no side effects after the execution has completed, but this still represents a problem if you plan to thread this.</p>\n\n<p><code>draw_series - 1.0</code> executes the same as the min_draw - 1 setting in the draw series, but some how seems to make python happier (or as you have it <code>-(1 - max_draw)</code>)</p>\n\n<p>I tried both having a new array to hold the max_returns and execute them element wise at the end and storing the <code>1.0 / max_return</code> value and multiplying through but each seemed to slow down the execution for some reason. </p>\n\n<p>It didn't seem like the iterator <code>enumerate(reversed(returns))</code> helped at all with the loop even though it simplified the logic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T22:27:26.383", "Id": "3514", "ParentId": "3503", "Score": "0" } }, { "body": "<p>Untested, and probably not quite correct. I think it may actually apply operations backwards, but you should be easily able to flip that.</p>\n\n<pre><code>import numpy as np\n\ndef max_drawdown(returns):\n returns += 1\n max_returns = np.maximum.accumulate(returns)\n draw = returns / max_returns\n max_draw = np.minimum.accumulate(draw)\n draw_series = -(1 - max_draw)\n\n return draw_series\n</code></pre>\n\n<p>Comments on your code:</p>\n\n<pre><code>import numpy as np\n\ndef max_drawdown(returns):\n\n draw_series = np.array(np.ones(np.size(returns)))\n</code></pre>\n\n<p>np.ones, returns an array. There is no reason to pass it to np.array afterwards. If you aren't going to use the ones you store in the array use numpy.empty which skips the initialization step.</p>\n\n<pre><code> max_return = 0; max_draw = 1; draw = 1\n</code></pre>\n\n<p>You declare draw far away from where it used. Just assign to it in the scope its used in. Multiple assignments on one lined is also frowned upon in python. </p>\n\n<pre><code> returns = returns + 1\n</code></pre>\n\n<p>Use a compound assignment</p>\n\n<pre><code> for r in range(returns.count()-1, 0, -1):\n</code></pre>\n\n<p>I have to recommend against r, as its not a common abbreviation and I think it makes the code hard to read.</p>\n\n<pre><code> if returns[r] &gt; max_return:\n max_return = returns[r]\n\n else:\n draw = returns[r] / max_return\n if draw &lt; max_draw:\n max_draw = draw\n</code></pre>\n\n<p>Your math seems inscrutable, but perhaps it makes sense in context. Consider some comments to explain the reasoning</p>\n\n<pre><code> draw_series[r-1] = -(1 - max_draw)\n\n return draw_series\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T05:08:22.697", "Id": "5250", "Score": "0", "body": "+1 I was writing up the exact same thing eariler, but got busy and never posted it. This is definitely the way to go! (It's also ~3 orders of magnitude faster for large-ish arrays.) For the OP, note that you can create a reversed view of the array by returning `return draw_series[::-1]`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T03:19:25.400", "Id": "3519", "ParentId": "3503", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-15T21:48:58.460", "Id": "3503", "Score": "6", "Tags": [ "python", "performance", "numpy" ], "Title": "Calculating the maximum drawdown of a set of returns" }
3503
<p>An animation is composed of frames. I have the following class:</p> <pre><code>class Frame { private: sf::IntRect rect; unsigned int duration; public: Frame(sf::IntRect rect, unsigned int duration); unsigned int getDuration(); sf::IntRect&amp; getRect(); }; </code></pre> <p>At the animation class I have the following function:</p> <pre><code>void Animation::addFrame(sf::IntRect rect, unsigned int duration) // public { frames.push_back(Frame(rect, duration)); // ps: private std::vector&lt;Frame&gt; frames; } </code></pre> <p>should it actually be:</p> <pre><code>void Animation::addFrame(Frame frame) // public { frames.push_back(frame); } </code></pre> <p>thus showing how animation is implemented underneath? I'm also in doubt if the frame class shouldn't simply be a struct with rect and duration. Thanks a lot in advance!</p>
[]
[ { "body": "<p>This is actually a matter of taste. for my preference, i would choose </p>\n\n<pre><code>void Animation::addFrame(sf::IntRect rect, unsigned int duration) // public\n{\n frames.push_back(Frame(rect, duration)); // ps: private std::vector&lt;Frame&gt; frames;\n}\n</code></pre>\n\n<p>because it hides the implementation.</p>\n\n<p>Writing class is good(again this is my preference) when you have member variables(which should be kept private usually).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T00:00:30.550", "Id": "3516", "ParentId": "3509", "Score": "0" } }, { "body": "<p>Never lie in your code. If you say: addFrame, I expect that passing Frame should be absolutely fine. The first function you have to provide as this class' interface is addFrame(Frame const&amp;). Then, if you firmly believe that having the (IntRect, uint) overload is really useful when writing real client code, add this overload. But (Frame const&amp;) should go first (I mean when you think whether or not).</p>\n\n<p>BTW, I'm not sure what the Frame is, but you should consider passing it by constant reference - that's idiomatic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T19:26:33.583", "Id": "3546", "ParentId": "3509", "Score": "2" } }, { "body": "<p>I'd have the addFrame take a Frame&amp;</p>\n\n<p>Keeps the interface simple, and then if your frames become more complex, you won't have to make as many changes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:03:55.217", "Id": "3549", "ParentId": "3509", "Score": "1" } } ]
{ "AcceptedAnswerId": "3546", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T14:11:28.507", "Id": "3509", "Score": "2", "Tags": [ "c++" ], "Title": "Should I hide or show this implementation?" }
3509
<p>I am trying to express the classical TDD kata of mastermind in the most idiomatic scala I can. Here is a scalatest, test suite : </p> <pre><code>package eu.byjean.mastermind import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner import org.scalatest.FlatSpec import org.scalatest.matchers.ShouldMatchers @RunWith(classOf[JUnitRunner]) class MastermindSpec extends FlatSpec with ShouldMatchers { behavior of "Mastermid" it should "find no good and no misplaced for a wrong guess" in { Mastermind.check (guess='red)(secret='blue) should equal (0,0) } it should "find all good if guess equals secret of one" in { Mastermind.check('blue)('blue) should equal (1,0) } it should "find one good if guess has one good in a secret of two" in { Mastermind.check('blue,'red)('blue,'green) should equal (1,0) Mastermind.check('green,'red)('blue,'red) should equal (1,0) } it should "find two good if guess has two good in a secret of three" in { Mastermind.check('blue,'red,'red)('blue,'green,'red) should equal (2,0) } it should "find one misplaced blue in a guess of two" in { Mastermind.check('blue,'red)('green,'blue) should equal (0,1) } it should "find two misplaced in a guess of four" in { Mastermind.check('blue,'blue,'red,'red)('green,'yellow,'blue,'blue) should equal (0,2) } it should "find two misplaced colors in a guess of four" in { Mastermind.check('green,'blue,'yellow,'red)('green,'yellow,'blue,'blue) should equal (1,2) } } </code></pre> <p>and my current implementation</p> <pre><code>package eu.byjean.mastermind object Mastermind { def check(guess: Symbol*)(secret: Symbol*): (Int, Int) = { val (goodPairs, badPairs) = guess.zip(secret).partition { case (x, y) =&gt; x == y } val(guessMiss,secMiss)=badPairs.unzip val misplaced=guessMiss.sortBy(_.toString).zip(secMiss.sortBy(_.toString())).filter{case (x,y)=&gt;x==y} (goodPairs.size, misplaced.size) } </code></pre> <p>In the imperative form, some people employ a map and count for each color the number of occurences of the color in the secret and in the guess (only as far as misplaced go of course). I tried an approach using foldLeft on the badPairs list of tuple, which lead me to variable naming problems and calling map.updated twice in the foldLeft closure which didnt seem right</p> <p>Any thoughts on how to improve on the above code. It doesn't feel perfect. how would you improve it along the following axis: </p> <ul> <li>bugs: have I missed something obvious ?</li> <li>performance : this version with zip, unzip, sort, zip again most likely isn't the fastest</li> <li>readability : how would I define an implicit ordering for Symbol so I don't have to pass _.toString ,</li> <li>idiomatic scala: is there globally a more "scala-ish" way of solving this ?</li> </ul> <p>Thanks</p>
[]
[ { "body": "<p>This has <em>worse</em> performance, but I hope it's a little bit more readable:</p>\n\n<pre><code>def check(guess: Symbol*)(secret: Symbol*): (Int, Int) = {\n def goodBad(f: Seq[Symbol] =&gt; Seq[Symbol], s1: Seq[Symbol], s2:Seq[Symbol]) = \n f(s1) zip f(s2) partition {case (x, y) =&gt; x == y }\n val (goodPairs, badPairs) = goodBad(identity, guess, secret)\n val (guessMiss, secMiss) = badPairs unzip\n val misplaced = goodBad(_.sortBy(_.toString), guessMiss, secMiss)._1\n (goodPairs.size, misplaced.size) \n}\n</code></pre>\n\n<p>The main problem is that Scala's <code>Tuple2</code> is just too dumb: You can't do much with it except pattern matching, there is no <code>map</code> or <code>copy</code> method etc.</p>\n\n<p>The <code>String</code>-based sorting isn't nice, but I don't know a better way.</p>\n\n<p>I wouldn't sweat too much about performance. Often you have to make a choice between fast and pretty, and in this context I would choose \"pretty\".</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T13:20:11.370", "Id": "5262", "Score": "0", "body": "Thanks for your answer, not exactly what I was expecting :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T19:36:12.140", "Id": "3512", "ParentId": "3510", "Score": "0" } }, { "body": "<p>All this zipping and unzipping looks really convoluted. I think the problem here is getting too much enamored with what you can do with a Scala collection instead of focusing on the problem at hand.</p>\n\n<p>One way of decreasing <code>zip</code> cost is to do it on a <code>view</code>. This way, no intermediary collection is created -- though that depends a bit on the methods being called. At any rate, <code>zip</code> is one of these methods.</p>\n\n<p>It wouldn't work on your case, however, because you then go on to <code>partition</code> and <code>unzip</code> -- I'd be wary of calling such methods on a <code>view</code>, because they may end up being more expensive, not less.</p>\n\n<p>I think the map approach is better, because it avoids the O(n log n) sorting. A HashMap can be built in O(n), and looked up in constant time. This is how I'd do it:</p>\n\n<pre class=\"lang-scala prettyprint-override\"><code>object Mastermind {\n def check(guess: Symbol*)(secret: Symbol*): (Int, Int) = {\n val numOfGoodPairs = guess.view zip secret count { case (a, b) =&gt; a == b }\n val guessesForSymbol = guess.groupBy(identity).mapValues(_.size)\n val secretsForSymbol = secret.groupBy(identity).mapValues(_.size)\n val unorderedGuesses = for {\n symbol &lt;- guessesForSymbol.keys.toSeq\n secrets &lt;- secretsForSymbol get symbol\n guesses = guessesForSymbol(symbol)\n } yield secrets min guesses\n val numOfMisplaced = unorderedGuesses.sum - numOfGoodPairs\n (numOfGoodPairs, numOfMisplaced)\n }\n}\n</code></pre>\n\n<p>The first line should be pretty fast -- it will iterate once through both guess and secret, counting each time they are equal.</p>\n\n<p>Computing both maps is more expensive, but it should be cheaper than sorting. Note that <code>mapValues</code> return a <em>view</em> of the values -- it does not copy any data. This is particularly interesting because it will only compute the size of map elements for keys present in both guess and secret. It is a small optimization, but you gain it almost for free.</p>\n\n<p>We avoid most of the complexity by simply subtracting the number of correct guesses from the number of unordered guesses.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T20:14:12.393", "Id": "5493", "Score": "0", "body": "hello daniel, thank you very much for your answer. however, it doesn't pass the tests. one of the problem is trivial (numOfMisplaced is > 0) the other much less : given green,blue, yellow,red guess for green, yellow, blue,blue returns 1,0 instead of 1,2 ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T20:19:03.563", "Id": "5494", "Score": "0", "body": "it looks like the problem is in the for comprehension it returns a set, not a list and therefore multiple 1 are converted to a single 1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T21:01:22.320", "Id": "5497", "Score": "0", "body": "@Jean You are correct, the problem is the `Set`. I had tested against the examples you gave, but at the last minute I decided to get `guessesForSymbol.keys` instead of `guessesForSymbol`, so that I could avoid the `count` for `guesses`. That changed the result from `Iterable` to `Set`, causing the problem. Sorry about that..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T07:13:25.600", "Id": "5498", "Score": "0", "body": "Ok that did it thanks. A suggestion and a question: the first line of the for comprehension can be rewritten as (symbol,guesses) <- guessesForSymbol.elements.toSeq avoids a second call to get further down. Also I remember reading that for comprehension were logically equivalent to using one of map, flatMap or something like that. Do you know which ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T07:27:31.507", "Id": "5499", "Score": "0", "body": "I think I got it:val unorderedGuesses = guessesForSymbol.map {\n case (symbol, guesses) => secretsForSymbol.getOrElse(symbol,0) min(guesses)\n } not sure it brings much to the table" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T16:02:07.067", "Id": "5505", "Score": "0", "body": "@Jean the first line can be written as `(symbol, guesses) <- guessesForSymbol` -- no need to transform it further. That's what I had originally written, but that will compute `_.size` on all elements of `guessesForSymbol`. Since that's a list, `size` is O(n). The way I wrote it, I'll only compute `_.size` for guesses that actually match a secret." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T16:04:10.403", "Id": "5507", "Score": "0", "body": "@Jean And, yes, for comprehensions map to `flatMap`, `map` and either `withFilter` or `filter` (depending on availability) if they `yield` something, or `foreach` and `withFilter`/`filter` if they do not. See [this question](http://stackoverflow.com/q/1052476/53013) for details." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T07:16:47.427", "Id": "5518", "Score": "0", "body": "regarding the form (symbol, guesses) <- guessesForSymbol, you say that it will compute _size on all elements of guessesForSymbol. Does that mean that it is not computed already on line 4. I haven't understood scala lazy eval yet. I know it exists but not how it works." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T15:10:17.417", "Id": "5524", "Score": "0", "body": "@Jean Yes, it means `_.size` is not computed on line 4. I'll let the description on Scaladoc to speak for itself: \"The resulting map wraps the original map without copying any elements.\" Technically, we call this non-strict instead of lazy. We reserve \"lazy\" for those instances where the value if computed only once and cached. In this case, every time you access an element of the resulting collection, `_.size` will be recomputed. If you have further doubts, ask on Stack Overflow, please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T17:22:10.920", "Id": "5526", "Score": "0", "body": "Thank you for your answer and comments they were very helpful. I'll read up on non strict and lazy, ask my questions later." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T15:13:28.640", "Id": "3628", "ParentId": "3510", "Score": "2" } } ]
{ "AcceptedAnswerId": "3628", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T15:19:09.350", "Id": "3510", "Score": "2", "Tags": [ "functional-programming", "scala" ], "Title": "Scala mastermind solver, which is the most scala-ish" }
3510
<p>I am writing a piece of code which models the evolution of a social network. The idea is that each person is assigned to a node and relationships between people (edges on the network) are given a weight of +1 or -1 depending on whether the relationship is friendly or unfriendly. </p> <p>Using this simple model you can say that a triad of three people is either "balanced" or "unbalanced" depending on whether the product of the edges of the triad is positive or negative. </p> <p>Finally, what I am trying to do is implement an ising type model. In other words, random edges are flipped and the new relationship is kept if the new network has more balanced triangles (a lower energy) than the network before the flip, if that is not the case then the new relationship is only kept with a certain probability.</p> <p>I have written the following code, however the dataset I have contains ~120k triads, and as a result it will take 4 days to run! </p> <p>Could anyone offer any tips on how I might optimise the code?</p> <pre><code>#Importing required librarys try: import matplotlib.pyplot as plt except: raise import networkx as nx import csv import random import math def prod(iterable): p= 1 for n in iterable: p *= n return p def Sum(iterable): p= 0 for n in iterable: p += n[3] return p def CalcTriads(n): firstgen=G.neighbors(n) Edges=[] Triads=[] for i in firstgen: Edges.append(G.edges(i)) for i in xrange(len(Edges)): for j in range(len(Edges[i])):# For node n go through the list of edges (j) for the neighboring nodes (i) if set([Edges[i][j][1]]).issubset(firstgen):# If the second node on the edge is also a neighbor of n (its in firstgen) then keep the edge. t=[n,Edges[i][j][0],Edges[i][j][1]] t.sort() Triads.append(t)# Add found nodes to Triads. new_Triads = []# Delete duplicate triads. for elem in Triads: if elem not in new_Triads: new_Triads.append(elem) Triads = new_Triads for i in xrange(len(Triads)):# Go through list of all Triads finding the weights of their edges using G[node1][node2]. Multiply the three weights and append value to each triad. a=G[Triads[i][0]][Triads[i][1]].values() b=G[Triads[i][1]][Triads[i][2]].values() c=G[Triads[i][2]][Triads[i][0]].values() Q=prod(a+b+c) Triads[i].append(Q) return Triads ###### Import sorted edge data ###### li=[] with open('Sorted Data.csv', 'rU') as f: reader = csv.reader(f) for row in reader: li.append([float(row[0]),float(row[1]),float(row[2])]) G=nx.Graph() G.add_weighted_edges_from(li) for i in xrange(800000): e = random.choice(li) # Choose random edge TriNei=[] a=CalcTriads(e[0]) # Find triads of first node in the chosen edge for i in xrange(0,len(a)): if set([e[1]]).issubset(a[i]): # Keep triads which contain the whole edge (i.e. both nodes on the edge) TriNei.append(a[i]) preH=-Sum(TriNei) # Save the "energy" of all the triads of which the edge is a member e[2]=-1*e[2]# Flip the weight of the random edge and create a new graph with the flipped edge G.clear() G.add_weighted_edges_from(li) TriNei=[] a=CalcTriads(e[0]) for i in xrange(0,len(a)): if set([e[1]]).issubset(a[i]): TriNei.append(a[i]) postH=-Sum(TriNei)# Calculate the post flip "energy". if postH&lt;preH:# If the post flip energy is lower then the pre flip energy keep the change continue elif random.random() &lt; 0.92: # If the post flip energy is higher then only keep the change with some small probability. (0.92 is an approximate placeholder for exp(-DeltaH)/exp(1) at the moment) e[2]=-1*e[2] </code></pre>
[]
[ { "body": "<p>The following lines seem particularly costly:</p>\n\n<pre><code>G.clear()\nG.add_weighted_edges_from(li)\n</code></pre>\n\n<p>Why are you clearing the entire graph and recreating it? Isn't there a more direct way to modify the graph without recreating it from scratch? When I looked at the reference I found methods like <code>Graph.remove_edge(u,v)</code> and <code>Graph.add_weighted_edges_from(ebunch,**attr[,attr_dict])</code> that seem like better ways of adding and removing edges without recreating the entire graph from scratch.</p>\n\n<p>You should also look into adding some kind of caching to <code>CalcTriads(n)</code> because the neighbors of <code>n</code> don't change and for a fixed <code>n</code> you are constantly recalculating the neighbors from scratch which is unnecessary because only the weights of the edges changes not the actual nodes connected to <code>n</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T11:28:32.803", "Id": "5253", "Score": "0", "body": "I could not work out how to change the weight of an edge on the graph. But I see how to do it now." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T23:07:51.330", "Id": "3515", "ParentId": "3511", "Score": "0" } }, { "body": "<pre><code>#Importing required librarys\n</code></pre>\n\n<p>I can see that. Don't comment on what's obvious from the syntax</p>\n\n<pre><code>try:\n import matplotlib.pyplot as plt\nexcept:\n raise\n</code></pre>\n\n<p>Catching an exception only to rethrow it? That's a waste </p>\n\n<pre><code>import networkx as nx\nimport csv\nimport random\nimport math\n\ndef prod(iterable):\n p= 1\n for n in iterable:\n p *= n\n return p\n</code></pre>\n\n<p>You may want to look at numpy, it has function like this written in efficient C. </p>\n\n<pre><code>def Sum(iterable):\n p= 0\n</code></pre>\n\n<p>p? why p?</p>\n\n<pre><code> for n in iterable:\n p += n[3]\n return p\n</code></pre>\n\n<p>The python style guide recommends lowercase_with_underscores for global function names. The name also suggests its a generic summing function which its not. No indication is given for what kind of data it expects. A docstring should at least explain that.</p>\n\n<pre><code>def CalcTriads(n): \n firstgen=G.neighbors(n)\n</code></pre>\n\n<p>Don't use global variables. Instead pass G in as a parameter. Also, I recommend against calling it G.</p>\n\n<pre><code> Edges=[]\n Triads=[]\n</code></pre>\n\n<p>Python style guide recommemnds lowercase_with_underscores for local variables names</p>\n\n<pre><code> for i in firstgen:\n Edges.append(G.edges(i))\n</code></pre>\n\n<p>I recommend a list comprehnsion</p>\n\n<pre><code>Edges = [G.edges(i) for i in firstgen]\n\n\n for i in xrange(len(Edges)):\n</code></pre>\n\n<p>Don't iterate over the integers, iterate over the edges. Use for edge in Edges:</p>\n\n<pre><code> for j in range(len(Edges[i])):# For node n go through the list of edges (j) for the neighboring nodes (i)\n</code></pre>\n\n<p>I recommend putting the comment on a seperate line from the if. Otherwise it tends to wrap off the side of the screen and that's annoying. Also, iterate over the container, not the indexes. Use something like for source, dest in edges:</p>\n\n<pre><code> if set([Edges[i][j][1]]).issubset(firstgen):# If the second node on the edge is also a neighbor of n (its in firstgen) then keep the edge.\n</code></pre>\n\n<p>Create a list with a single element, putting that in a set, simply to call issubet is silly. Use Edges[i][j][1] in firstgen.</p>\n\n<pre><code> t=[n,Edges[i][j][0],Edges[i][j][1]]\n t.sort()\n Triads.append(t)# Add found nodes to Triads.\n\n\n new_Triads = []# Delete duplicate triads.\n for elem in Triads:\n if elem not in new_Triads:\n new_Triads.append(elem)\n Triads = new_Triads \n</code></pre>\n\n<p>That is an inefficient way of doing that. Instead, make Triads a set and put tuples rather then lists in it. That'll be faster and easier to read.</p>\n\n<pre><code> for i in xrange(len(Triads)):# Go through list of all Triads finding the weights of their edges using G[node1][node2]. Multiply the three weights and append value to each triad.\n</code></pre>\n\n<p>This code would be way cleaner if you used for triad in Triads:</p>\n\n<pre><code> a=G[Triads[i][0]][Triads[i][1]].values()\n b=G[Triads[i][1]][Triads[i][2]].values()\n c=G[Triads[i][2]][Triads[i][0]].values()\n Q=prod(a+b+c)\n Triads[i].append(Q)\n\n return Triads\n\n\n\n###### Import sorted edge data ###### \nli=[]\n</code></pre>\n\n<p>Bad name, gives no idea what it intends</p>\n\n<pre><code>with open('Sorted Data.csv', 'rU') as f:\n</code></pre>\n\n<p>I think you are supposed to read csv files in a binary mode.</p>\n\n<pre><code> reader = csv.reader(f)\n for row in reader:\n li.append([float(row[0]),float(row[1]),float(row[2])])\n</code></pre>\n\n<p>Use for source, dest, value in row: li.append(float(source), float(dest), float(value))</p>\n\n<p>Do you really want floats? Are the source and destination really floats or are they ints?</p>\n\n<pre><code>G=nx.Graph()\nG.add_weighted_edges_from(li)\n\n\nfor i in xrange(800000):\n</code></pre>\n\n<p>Don't execute loop at the module level. Code written inside a function will run faster.\n e = random.choice(li) # Choose random edge</p>\n\n<pre><code> TriNei=[]\n a=CalcTriads(e[0]) # Find triads of first node in the chosen edge\n</code></pre>\n\n<p>Don't use variable names like a, a one letter variable name is terrible waste of information capacity.</p>\n\n<pre><code> for i in xrange(0,len(a)):\n</code></pre>\n\n<p>Don't use xrange to iterate over containers.</p>\n\n<pre><code> if set([e[1]]).issubset(a[i]): # Keep triads which contain the whole edge (i.e. both nodes on the edge)\n TriNei.append(a[i]) \n preH=-Sum(TriNei) # Save the \"energy\" of all the triads of which the edge is a member\n\n\n e[2]=-1*e[2]# Flip the weight of the random edge and create a new graph with the flipped edge \n G.clear()\n G.add_weighted_edges_from(li)\n</code></pre>\n\n<p>You should be able to find and change the edge weight directly. Reconstructing the whole graph is going to be kinda slow. </p>\n\n<pre><code> TriNei=[]\n a=CalcTriads(e[0]) \n for i in xrange(0,len(a)):\n if set([e[1]]).issubset(a[i]):\n TriNei.append(a[i])\n postH=-Sum(TriNei)# Calculate the post flip \"energy\". \n</code></pre>\n\n<p>Seeing the same piece of code in two place is a big hint. Write a function!</p>\n\n<pre><code> if postH&lt;preH:# If the post flip energy is lower then the pre flip energy keep the change\n continue\n\n elif random.random() &lt; 0.92: # If the post flip energy is higher then only keep the change with some small probability. (0.92 is an approximate placeholder for exp(-DeltaH)/exp(1) at the moment)\n e[2]=-1*e[2]\n</code></pre>\n\n<p>What you should consider doing is writing a function which given a node calculates the change in \"energy\" that would occour if it was flipped. Right now you calculate before and after, but you should be able to simply calculate the delta without changing it. If you can effeciently calculate the delta, that's all you need.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T11:26:02.790", "Id": "5252", "Score": "0", "body": "Wow. Thanks. Yeah this is the first thing I've ever attempted in python, and the second time I have tried to write a program. I'm a physicist!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T04:25:57.953", "Id": "3520", "ParentId": "3511", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-17T19:09:54.193", "Id": "3511", "Score": "4", "Tags": [ "python", "performance", "random", "graph", "matplotlib" ], "Title": "Social network evolution" }
3511
<p>Context: I wrote a simple as an <a href="https://unix.stackexchange.com/questions/16849/importing-csv-contacts-into-evolution-3-0-2/16858#16858">answer</a> to a problem in <a href="http://unix.stackexchange.com">Unix.SE</a> and it was suggested to me to post it here for review.</p> <p>A comma separated file is generated by an application. On the first column it contains a last name, on the second a first name and on the tenth column a telephone number. For each row of this csv an vcard entry should be generated.</p> <p>This was my solution:</p> <pre><code>#!/usr/bin/python import csv import sys def convert(file): reader = csv.reader(open(file, 'rb')) for row in reader: print 'BEGIN:VCARD' print 'VERSION:2.1' print 'N:' + row[0] + ';' + row[1] print 'FN:' + row[1] + ' ' + row[0] print 'TEL;HOME;VOICE:' + row[9] print 'END:VCARD' def main(args): if len(args) != 2: print "Usage:" print args[0] + " filename" return convert(args[1]) if __name__ == '__main__': main(sys.argv) </code></pre> <p>Outputting the generated vcard on stdout was fine for me, I just redirected it into an appropriate file.</p>
[]
[ { "body": "<p>Use sys.exit to indicate success or failure of the program.</p>\n\n<p>file is a builtin python function, its best to avoid naming your variables the same thing.</p>\n\n<pre><code>for row in reader:\n print 'BEGIN:VCARD'\n print 'VERSION:2.1'\n print 'N:' + row[0] + ';' + row[1]\n print 'FN:' + row[1] + ' ' + row[0]\n print 'TEL;HOME;VOICE:' + row[9]\n print 'END:VCARD'\n</code></pre>\n\n<p>I'd recommend putting in something like</p>\n\n<pre><code>foo = row[0]\n</code></pre>\n\n<p>and then printing foo to make it clearer what the different values are.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T04:41:29.683", "Id": "3521", "ParentId": "3517", "Score": "3" } }, { "body": "<p>Read about the <code>with</code> statement and ALWAYS use it with file operations</p>\n\n<pre><code>with open( somefilename, 'rb' ) as source:\n reader = csv.reader( source )\n for row in reader:\n etc.\n</code></pre>\n\n<p>That guarantees that the file is closed and all OS resources released.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T21:14:39.473", "Id": "3528", "ParentId": "3517", "Score": "5" } }, { "body": "<p>Even for something this trivial, use <a href=\"http://docs.python.org/dev/library/argparse.html\" rel=\"nofollow\">argparse</a>.</p>\n\n<pre><code>import argparse\n\nparser = argparse.ArgumentParser(description='Convert a CSV or whatever.')\nparser.add_argument('filenames', type=argparse.FileType('rb'), nargs='+',\n help='a file to convert')\n\nargs = parser.parse_args()\nfor sourcefile in args.filenames:\n convert( sourcefile )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T21:31:42.407", "Id": "5278", "Score": "0", "body": "(meta) Is it proper here to update the original question with the reviews applied?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T22:11:59.327", "Id": "5279", "Score": "1", "body": "You could, but you'd have to leave the original code in place. However. I don't think that would accomplish much. You can beat a single example \"to death\" through over-analysis. What do you think you might learn from posting the revised code?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T21:19:34.747", "Id": "3529", "ParentId": "3517", "Score": "3" } }, { "body": "<p>Python Manual mentions that you should open a file with <code>newline=''</code> <a href=\"http://docs.python.org/3.2/library/csv.html\" rel=\"nofollow\">csv</a></p>\n\n<p>Thus:</p>\n\n<pre><code>with open( somefilename, 'rb', newline='') as source:\n etc\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-16T22:06:25.647", "Id": "22796", "ParentId": "3517", "Score": "1" } }, { "body": "<p>Whenever you assemble text for future computer interpretation, whether by string concatenation or interpolation, alarm bells should go off: some escaping mechanism is essential! Failure to do so would expose you to a class of bugs akin to XSS and SQL injection.</p>\n\n<p>According to the vCard <a href=\"http://www.imc.org/pdi/vcard-21.txt\" rel=\"nofollow\">version 2.1 specification</a>, semicolons must be escaped with a backslash. The <a href=\"http://www.w3.org/2002/12/cal/rfc2426.html\" rel=\"nofollow\">3.0 specification</a> mandates the use of escape sequences <code>\\\\</code>, <code>\\;</code>, <code>\\,</code>, and <code>\\n</code> as well.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-27T22:06:37.103", "Id": "75016", "ParentId": "3517", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T01:47:28.223", "Id": "3517", "Score": "6", "Tags": [ "python", "converting", "csv" ], "Title": "Converting a csv to vcards in Python" }
3517
<p>I'm implementing argument check in a method where one parameter is a <code>List</code> of <code>LocalDate</code> objects (from <a href="http://joda-time.sourceforge.net/" rel="nofollow">Joda-Time</a>). I want to make sure that <code>List</code> contains <strong>at most one <code>LocalDate</code> per month</strong>. </p> <pre><code>public List&lt;LocalDate&gt; generateAllDates(List&lt;LocalDate&gt; firstYearDates, ...) { } </code></pre> <p>Thus, for example</p> <pre><code>Arrays.asList( new LocalDate(2012, 3, 25), new LocalDate(2012, 4, 30), new LocalDate(2013, 3, 26) ) </code></pre> <p>would be an illegal argument because there are <em>two dates whose month is March</em>.</p> <p>Currently I have something like this (making use of <a href="http://code.google.com/p/guava-libraries/" rel="nofollow">Guava</a>'s Multimap):</p> <pre><code>Multimap&lt;Integer, LocalDate&gt; monthToDates = HashMultimap.create(); for (LocalDate date : firstYearDates) { monthToDates.put(date.getMonthOfYear(), date); } for (Integer i : monthToDates.keySet()) { if (monthToDates.get(i).size() &gt; 1) { throw new IllegalArgumentException( "firstYearDates must contain at most one entry per month"); } } </code></pre> <p>Question is, <strong>how would you simplify that</strong>? Using any API features of JDK 1.6, Guava or Joda-Time is fine.</p>
[]
[ { "body": "<p>I understood that you only need to know if a month has been found before or not. I wouldn't then go through the trouble of using a Multimap if there is no other reason for it. </p>\n\n<pre><code>boolean[] monthFound = new boolean[12];\nfor(LocalDate date : firstYearDates) {\n if(monthFound[date.getMonthOfYear() - 1]) {\n throw new IllegalArgumentException(\n \"firstYearDates must contain at most one entry per month\");\n } else {\n monthFound[date.getMonthOfYear() - 1] = true;\n }\n}\n</code></pre>\n\n<p>If you need the map then just check <code>containsKey(month)</code> before each <code>put</code> and throw an exception if the method returns true. </p>\n\n<p>If you just want to use Guava then one way of doing this might be </p>\n\n<pre><code>Function&lt;LocalDate, Integer&gt; months = new Function&lt;LocalDate, Integer&gt;() { \n public Integer apply(LocalDate date) { return date.getMonthOfYear(); }\n};\n\nif(new HashSet(Collections2.transform(firstYearDates, months)).size() &lt; firstYearDates.size()) {\n throw new IllegalArgumentException(\n \"firstYearDates must contain at most one entry per month\");\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T12:53:22.270", "Id": "5260", "Score": "0", "body": "+1. I guess I sometimes get carried away by Guava's fancy data structures and become blind to plain old Java options like boolean arrays. Good point about containsKey too. If fact, I'll probably use a plain map and containsKey, as I'm not a fan of array indexing minutiae [ `date.getMonthOfYear() - 1` ] if it can be avoided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T13:58:42.817", "Id": "5266", "Score": "0", "body": "You can create a 13 element array if you are not starving for memory :) You could also use bit arrays if you want to go old school." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T12:36:35.523", "Id": "3524", "ParentId": "3523", "Score": "1" } }, { "body": "<p>Bit late but there is Guava built-in method for that - <a href=\"http://docs.guava-libraries.googlecode.com/git-history/v12.0/javadoc/com/google/common/collect/Maps.html#uniqueIndex%28java.lang.Iterable,%20com.google.common.base.Function%29\" rel=\"nofollow\">Maps.uniqueIndex</a> - given:</p>\n\n<pre><code>List&lt;LocalDate&gt; dates = Arrays.asList(\n new LocalDate(2012,3,25), new LocalDate(2012,4,30), new LocalDate(2013,3,26);\n</code></pre>\n\n<p>with JDK 8:</p>\n\n<pre><code>Maps.uniqueIndex(dates, LocalDate::getMonthOfYear);\n</code></pre>\n\n<p>or with JDK &lt;7:</p>\n\n<pre><code>Maps.uniqueIndex(dates, new Function&lt;LocalDate, Integer&gt;() {\n @Override\n public Integer apply(final LocalDate date) {\n return date.getMonthOfYear();\n }\n});\n</code></pre>\n\n<p>It will throw </p>\n\n<pre><code>java.lang.IllegalArgumentException: duplicate key: 3\n</code></pre>\n\n<p>in this example.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T19:38:16.803", "Id": "12901", "ParentId": "3523", "Score": "3" } } ]
{ "AcceptedAnswerId": "12901", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T12:18:11.710", "Id": "3523", "Score": "2", "Tags": [ "java", "guava", "jodatime" ], "Title": "At most one LocalDate per month in a list" }
3523
<p>I am looking for ideas to optimize the below code for speed. I'm also looking for some good improvement in execution time. </p> <p>This code reads a text file. The text file has many lines of ASCII text. Then it finds words out of them (space/tab delimiter). It has to neglect any punctuation symbol in the file. Then it uses those words to form a combinations as <code>[word1][word2]</code> to pass to the hashing function to get a result. </p> <pre><code>#include "stdio.h" #include "string.h" #include "stdlib.h" #include "ctype.h" main(int argc,char *argv[]) { FILE *fin; unsigned int i,k,j=0,m=0; char c; char *ptr, *p; char line_buf[1500]; char word[75]; unsigned int line_no = 1; char encrypted_pass[120];//Currently it would support MD5,DES,SHA256,SHA512(max - 104 character encrypted password) char *result; char pass_key[120]; char num[6] = {'0','2','4','8','\0'}; unsigned int words_found = 0,len=0; char words[1500][8]; fin = fopen(argv[1], "rt"); if(fin == NULL) { //Exit if file not found printf("Error opening input file,...exiting...\n"); exit(-1); } //Read lines from the file until end of file while(!feof(fin)) { //Initialize a index to point to current character in line buffer i=0; //Initialize a index to current character to be stored in word string k=0; //read one line at time, from the file ptr = fgets(line_buf,1500,fin); if(ptr == NULL)//End of file has reached,stop reading { break; } if(line_buf[i] == '\n')//End of line has reached,continue to read next line { continue; } if(line_no == 1)//This is the line containing encrypted password { line_no++; //Remove any leading spaces,tabs present in the encrypted password line while(isspace((unsigned char)(line_buf[m]))) { m++; } strcpy(encrypted_pass,&amp;line_buf[m]); //Remove any trailing spaces,tabs present in the encrypted password line len = strlen(encrypted_pass); while ((len &gt; 0) &amp;&amp; (isspace((unsigned char)encrypted_pass[len - 1]))) { encrypted_pass[--len] = 0; } len = strlen(encrypted_pass); if(len == 15)//DES-based algorithm where encryped password is 13 characters { if(encrypted_pass[len-2] == '\r') { encrypted_pass[len-2] = '\0';//for \r\n newline character } } else if(len == 14)//DES-based algorithm where encryped password is 13 characters { if(encrypted_pass[len-1] == '\n') { encrypted_pass[len-1] = '\0';//for \n newline character } } else if(len == 36)//MD5-based algorithm where encryped password is 34 characters { if(encrypted_pass[len-2] == '\r') { encrypted_pass[len-2] = '\0';//for \r\n newline character } } else if(len == 35)//MD5-based algorithm where encryped password is 34 characters { if(encrypted_pass[len-1] == '\n') { encrypted_pass[len-1] = '\0';//for \n newline character } } /* else if(len == 63)//SHA256-based algorithm where encryped password is 61 characters { if(encrypted_pass[len-1] == '\n') { encrypted_pass[len-1] = '\0';//for \n newline character } } else if(len == 62)//SHA256-based algorithm where encryped password is 61 characters { if(encrypted_pass[len-1] == '\n') { encrypted_pass[len-1] = '\0';//for \n newline character } } else if(len == 106)//SHA512-based algorithm where encryped password is 104 characters { if(encrypted_pass[len-1] == '\n') { encrypted_pass[len-1] = '\0';//for \n newline character } } else if(len == 105)//SHA512-based algorithm where encryped password is 104 characters { if(encrypted_pass[len-1] == '\n') { encrypted_pass[len-1] = '\0';//for \n newline character } } */ continue; } //Parse any leading space/tabs present at start of line //while(((line_buf[i] == ' ')||(line_buf[i] == '\t'))&amp;&amp;((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t'))) while((isspace((unsigned char)(line_buf[i])))&amp;&amp;(isspace((unsigned char)(line_buf[i+1])))) { i++; } //while((line_buf[i] == '\t')||(line_buf[i] == ' ')) while(isspace((unsigned char)(line_buf[i]))) { i++; } //Parse each character in the current line to construct words from it while((c=line_buf[i])!=' ') { /* if(line_buf[i] == 0)//End Of File reached { break; } */ if((c=='(')||(c=='[')||(c=='{'))//neglect these characters { i++; continue; } //Deduce that a word is found based on these character delimeters if((c==',')||(c=='.')||(c==';')||(c=='!')||(c=='?')||(c==')')||(c==']')||(c=='}')) { i++; //Insert a null character to terminate the word string word[k] = '\0'; //Check the length of the word found //len = strlen(word); len = k; //Only those words whose length is less than 7 characters are valid due to restriction on password length(8 chars) if(len != 0) { if(len &lt; 7) { //one word found, so increment the counter words_found++; //convert that word to lower case as password consists of lower case words only //lower_case_str(word); for (p = word; *p != '\0'; p++) { *p = (char) tolower(*p); } //store the word from word string to the word buffer strcpy(words[j],word); //Point to the next row in the 2D words buffer array for words found in the file j++; } } //reset the index in the word string k=0; if(line_buf[i] == '\n')//It is end of current line, go to read next line { break; } //while(((line_buf[i] == ' ')||(line_buf[i] == '\t'))&amp;&amp;((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))//there are multiple space characters, so consume them as long as you reach non-space char while((isspace((unsigned char)(line_buf[i])))&amp;&amp;(isspace((unsigned char)(line_buf[i+1])))) { i++; } //while((line_buf[i] == ' ')||(line_buf[i] == '\t')) while(isspace((unsigned char)(line_buf[i]))) { i++; } /* while(((line_buf[i] == '\t')||(line_buf[i] == ' '))&amp;&amp;((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))//there are multiple tabs here, so consume them as long as you reach non-tab char { i++; } while((line_buf[i] == '\t')||(line_buf[i] == ' ')) { i++; } */ if((line_buf[i] == ' '))//Continue to parse next character { i++; if(line_buf[i] == '\n')//It is end of current line, go to read next line { break; } } continue;//Continue to parse next character } if(isalpha((unsigned char)(c))) { //Current character is a valid alphabetic letter, so //Store the current character in the word string word[k] = c; //Point to the next position in the word string k++; } else { //Current character is not a alphabetic letter, so neglect it word[k] = '\0'; } //Point to the next character in the line buffer i++; if(line_buf[i] == 0)//End Of File reached { word[k] = '\0'; //len = strlen(word); len = k; if(len != 0) { if(len &lt; 7) { words_found++; //lower_case_str(word); for (p = word; *p != '\0'; p++) { *p = (char) tolower(*p); } strcpy(words[j],word); j++; } } break; } if((line_buf[i] == ' ')&amp;&amp;((line_buf[i-1] != '\t')&amp;&amp;(line_buf[i-1] != ' ')&amp;&amp;(isalpha((unsigned char)(line_buf[i-1])))))//A word found, based on space delimiter { i++; word[k] = '\0'; //len = strlen(word); len = k; if(len != 0) { if(len &lt; 7) { words_found++; //lower_case_str(word); for (p = word; *p != '\0'; p++) { *p = (char) tolower(*p); } strcpy(words[j],word); j++; } } k=0; } if((line_buf[i] == '\t')&amp;&amp;((line_buf[i-1] != ' ')&amp;&amp;(line_buf[i-1] != '\t')&amp;&amp;(isalpha((unsigned char)(line_buf[i-1])))))//A word found, based on horizontal tab delimiter { i++; word[k] = '\0'; //len = strlen(word); len = k; if(len != 0) { if(len &lt; 7) { words_found++; //lower_case_str(word); for (p = word; *p != '\0'; p++) { *p = (char) tolower(*p); } strcpy(words[j],word); j++; } } k=0; } if((line_buf[i] == '-')&amp;&amp;(isalpha((unsigned char)(line_buf[i-1]))))//A word found, based on - delimeter { i++; word[k] = '\0'; //len = strlen(word); len = k; if(len != 0) { if(len &lt; 7) { words_found++; //lower_case_str(word); for (p = word; *p != '\0'; p++) { *p = (char) tolower(*p); } strcpy(words[j],word); j++; } //strcpy(pass_key,word); //puts(pass_key); } k=0; } if((isspace((unsigned char)(line_buf[i])))&amp;&amp;(k&gt;0)) { i++; word[k] = '\0'; //len = strlen(word); len = k; if(len != 0) { if(len &lt; 7) { words_found++; //lower_case_str(word); for (p = word; *p != '\0'; p++) { *p = (char) tolower(*p); } strcpy(words[j],word); j++; } //strcpy(pass_key,word); //puts(pass_key); } k=0; } if((ispunct((unsigned char)(line_buf[i-1])))&amp;&amp;(k&gt;0)) { i++; word[k] = '\0'; //len = strlen(word); len = k; if(len != 0) { if(len &lt; 7) { words_found++; //lower_case_str(word); for (p = word; *p != '\0'; p++) { *p = (char) tolower(*p); } strcpy(words[j],word); j++; } //strcpy(pass_key,word); //puts(pass_key); } k=0; } //while(((line_buf[i] == ' ')||(line_buf[i] == '\t'))&amp;&amp;((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))//there are multiple space characters, so consume them as long as you reach non-space char while((isspace((unsigned char)(line_buf[i])))&amp;&amp;(isspace((unsigned char)(line_buf[i+1])))) { i++; } //while((line_buf[i] == ' ')||(line_buf[i] == '\t')) while(isspace((unsigned char)(line_buf[i]))) { i++; } /* while(((line_buf[i] == '\t')||(line_buf[i] == ' '))&amp;&amp;((line_buf[i+1] == ' ')||(line_buf[i+1] == '\t')))//there are multiple tabs here, so consume them as long as you reach non-tab char { i++; } while((line_buf[i] == '\t')||(line_buf[i] == ' ')) { i++; } */ if(line_buf[i] == '\n')//Last character in the current line(newline). { //Insert a null character to terminate the word string word[k] = '\0'; //Check the length of the word found //len = strlen(word); len = k; //Only those words whose length is less than 7 characters are valid due to restriction on password length(8 chars) if(len != 0) { if(len &lt; 7) { //one word found, so increment the counter words_found++; //convert that word to lower case as password consists of lower case words only //lower_case_str(word); for (p = word; *p != '\0'; p++) { *p = (char) tolower(*p); } //store the word from word string to the word buffer strcpy(words[j],word); //Point to the next row in the 2D words buffer array for words found in the file j++; } } break;//go to read next line } else//in between a word, continue scanning for next character { continue;//Continue to parse next character } } } //Remove duplicate words for (i = 0; i &lt; words_found; i ++) { j = i + 1; while (j &lt; words_found) { if (strcmp(words[i], words[j]) == 0) { memmove(words + j, words + (words_found - 1), sizeof(words[0])); -- words_found; } else ++ j; } } for(k=0;k&lt;4;k++) { //Form all possible combination of 2 words found with a number in between for(i=0;i&lt;words_found;i++) { for(j=i+1;j&lt;words_found;j++) { strcpy(pass_key,words[i]); strncat(pass_key,(const char*)(&amp;num[k]),1); strcat(pass_key,words[j]); len = strlen(pass_key); if((len &gt;= 5)&amp;&amp;(len &lt;= 8)) { result = crypt(pass_key, encrypted_pass); if(!strcmp(result,encrypted_pass)) { printf("%s\n",pass_key); exit(-1); } } } } } fclose(fin); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T16:19:28.267", "Id": "5272", "Score": "0", "body": "The somewhat random indentation of your code makes the structure hard to see. You may get more reviews quicker if you use consistent indentation (either 2 or 4 characters per indent)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T19:54:01.090", "Id": "5274", "Score": "0", "body": "Did your profiling software tell you where the hot spots are?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T02:55:03.530", "Id": "5282", "Score": "1", "body": "What is your performance goal? Just improvement? 1%, 10% 90% 99%? What is the problem? Have you used a profiler to identify a bottleneck?" } ]
[ { "body": "<p>First, a note for those who might wonder why I'd help somebody who's apparently trying to build a tool to do dictionary attacks on passwords. The reason is pretty simple: first, there are tools that do the job pretty well already, so this is hardly unleashing anything new on the world. Second, this doesn't seem to allow for salt, which means it's pretty much obsolete anyway (and anybody who doesn't use salt deserves to be broken into in any case). Ultimately it comes down to this: I don't think helping out on this will cause any real reduction in security.</p>\n\n<p>While I suppose I can guess at why you've crammed everything into <code>main</code>, I think it's a mistake anyway. On a reasonably modern processor, the overhead of calling a function is <em>extremely</em> minimal (to the point of being essentially impossible to even measure, in most cases). At the same time, the size of cache (especially level 1 cache) is limited, so eliminating redundancy can and will help speed by fitting more of your code into the cache.</p>\n\n<p>Other than that, your code seems to have quite a bit of redundancy. For example: </p>\n\n<pre><code>if((line_buf[i] == ' ')&amp;&amp;( \n\n (line_buf[i-1] != '\\t')&amp;&amp;\n (line_buf[i-1] != ' ')&amp;&amp;\n (isalpha((unsigned char)(line_buf[i-1]))))\n\n)\n</code></pre>\n\n<p>Now, let me ask a question: do you think it's possible for <code>isalpha(x)</code> to return true, if <code>x=='\\t'</code> or <code>x==' '</code> was true? I'm pretty sure the definition of <code>isalpha</code> precludes that possibility, so you can dispense with those tests. All you appear to need is: </p>\n\n<pre><code>if(line_buf[i] == ' ') &amp;&amp; isalpha((unsigned char)line_buf[i-1]))\n</code></pre>\n\n<p>If you're trying to avoid the \"overhead\" of calling <code>isalpha</code>, be aware that in most C libraries it's implemented as a macro that uses a table lookup, so testing for ' ' and '\\t' separately is more likely to be a loss than a gain. Even when/if it's a function, modern processors reduce function call overhead to the point that the extra tests are probably a loss anyway.</p>\n\n<p>You then have code like:</p>\n\n<pre><code> for (p = word; *p != '\\0'; p++)\n { \n *p = (char) tolower(*p);\n }\n strcpy(words[j],word);\n</code></pre>\n\n<p>This is quite inefficient. First it walks through the code modifying it in place, then it copies the modified data to a new location. You should be able to improve speed by combining the two:</p>\n\n<pre><code>for (i=0; p[i]; i++)\n words[j][i] = tolower(p[i]);\nwords[j][i] = '\\0';\n</code></pre>\n\n<p>Looking at a slightly higher level, you seem to care very little about the overall line structure of the input, and are interested primarily (exclusively?) in words. That being the case, you'd probably be better off <em>not</em> reading a line at a time. The result would be simpler, and probably faster as well. For example, you have a pretty big block of code to read the encrypted/hashed password and eliminate leading/trailing white space:</p>\n\n<pre><code> if(line_no == 1)//This is the line containing encrypted password \n {\n line_no++;\n //Remove any leading spaces,tabs present in the encrypted password line\n while(isspace((unsigned char)(line_buf[m])))\n {\n m++;\n }\n strcpy(encrypted_pass,&amp;line_buf[m]);\n\n //Remove any trailing spaces,tabs present in the encrypted password line\n len = strlen(encrypted_pass);\n while ((len &gt; 0) &amp;&amp; (isspace((unsigned char)encrypted_pass[len - 1])))\n {\n encrypted_pass[--len] = 0;\n }\n\n len = strlen(encrypted_pass);\n if(len == 15)//DES-based algorithm where encryped password is 13 characters \n {\n if(encrypted_pass[len-2] == '\\r')\n {\n encrypted_pass[len-2] = '\\0';//for \\r\\n newline character\n }\n }\n else if(len == 14)//DES-based algorithm where encryped password is 13 characters\n {\n if(encrypted_pass[len-1] == '\\n')\n {\n encrypted_pass[len-1] = '\\0';//for \\n newline character\n }\n }\n else if(len == 36)//MD5-based algorithm where encryped password is 34 characters\n {\n if(encrypted_pass[len-2] == '\\r')\n {\n encrypted_pass[len-2] = '\\0';//for \\r\\n newline character\n }\n }\n else if(len == 35)//MD5-based algorithm where encryped password is 34 characters\n {\n if(encrypted_pass[len-1] == '\\n')\n {\n encrypted_pass[len-1] = '\\0';//for \\n newline character\n }\n }\n</code></pre>\n\n<p>It appears that this entire block of code works our roughly equivalent to:</p>\n\n<pre><code>fscanf(\" %119[^ \\r\\n]\", encrypted_pass);\n</code></pre>\n\n<p>I've changed the maximum length to 119 based on the buffer length you provided. If you prefer to limit it to 34, that's pretty easy to handle as well. I'd note, however, that not only is this dramatically <em>shorter</em>, but probably faster as well -- for example, your code copies data you don't really want, then walks through all that data to find the length, truncates some of it, walks through to find the length <em>again</em>, and redundantly attempts to truncate the same data again (perhaps you didn't realize that <code>'\\r'</code> and <code>'\\n'</code> are classified as white space, at least in the \"C\" locale?) Using <code>fscanf</code>, you read (only) the data you care about, and you're done.</p>\n\n<p>Similarly, most of the rest of your code for reading words from the file can probably be collapsed down to a single call to <code>fscanf</code> with an appropriate conversion. I haven't looked at all of it in sufficient detail to be sure of the exact conversion, but it looks like <code>%7[A-Za-z]</code> is somewhere in the ballpark of a reasonable start.</p>\n\n<p>Ultimately, however, all of this is pretty much a fart in a hurricane as far as effect on speed goes. You can scan and copy buffers dozens of extra times, and the time it takes will still be down in the noise level compared to what it takes to copy that data from the disk drive into memory. There are really two places you can gain enough to notice:</p>\n\n<ol>\n<li>More efficient disk transfers</li>\n<li>parallel processing in the dictionary attack</li>\n</ol>\n\n<p>Note that the two aren't mutually exclusive, but both generally require non-portable code (e.g., on Linux, you'd probably use <code>mmap</code>, but on Windows <code>CreateFile</code> and <code>ReadFile</code> to read the data).</p>\n\n<p>At a guess, the latter is the part that's taking the most time, and also the place you stand the best chance of improving speed enough to care much about.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T10:42:36.650", "Id": "5291", "Score": "0", "body": "@Jerry - Thanks for comments. Yes I am trying to learn cryptography libraries and crypt seemed to be the simplest to start. Actually after posting here, I have cleaned up many redundant if checks, incorporated library functions straightway in my code. You review inputs were good. I will do thsoe changes as well. Thanks really for the last two bits of input - improving disk transfer and exploiting parallelism in the core function. Here do you mean using threads or you mean some kind of data parallelism by writing SIMD code if underlying processor has multicores and/or SIMD?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T17:53:54.847", "Id": "5305", "Score": "0", "body": "@goldenmean: the primary place to use SIMD code would be in the implementation of the hash function itself. The main thing you want to do is threading to do more than one hash at a time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T22:01:17.510", "Id": "10719", "Score": "0", "body": "+1 This is a brilliant answer, from the first paragraph (which made me chuckle) right to the end. Superb!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T19:39:41.683", "Id": "3526", "ParentId": "3525", "Score": "11" } } ]
{ "AcceptedAnswerId": "3526", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T13:43:06.943", "Id": "3525", "Score": "6", "Tags": [ "optimization", "c", "cryptography" ], "Title": "Forming word combinations from file" }
3525
<p>I've written code to parse dollars and cents entered by the user. The value returned is the total number of cents.</p> <p>For example:</p> <pre><code>f('$1.50') = 150 f('1.5') = 150 f('0') = 0 f('1000') = 1000 f('$12,500.00') = 12500000 functions.GetTotalCents = function (dollarsAndCentsString) { // Cast the value passed in to a string in case a number was passed in. dollarsAndCentsString = dollarsAndCentsString.toString(); // First, discard the '$' glyph, if it was passed in. if (dollarsAndCentsString.split('$').length == 2) dollarsAndCentsString = dollarsAndCentsString.split('$')[1]; // If the user delimmited the groups of digits with commas, remove them. dollarsAndCentsString = dollarsAndCentsString.replace(/,/g, ''); // Next, divide the resulting string in to dollars and cents. var hasDecimal = (dollarsAndCentsString.split('.')).length == 2; var dollarsString, centsString; dollarsString = dollarsAndCentsString.split('.')[0]; var centsString = hasDecimal ? dollarsAndCentsString.split('.')[1] : '0'; var dollars = parseInt(dollarsString, 10); var cents; if (centsString.length == 1) cents = parseInt(centsString, 10) * 10; else cents = parseInt(centsString, 10); if (cents &gt; 99 || isNaN(cents) || isNaN(dollars) || !isFinite(dollars) || !isFinite(cents)) return 0; var totalCents = dollars * 100 + cents; return totalCents; }; </code></pre> <p>Anyone care to critique my code?</p>
[]
[ { "body": "<p>Wouldn't it be simpler to:</p>\n\n<ul>\n<li>strip out any '$' and ',' characters;</li>\n<li>convert to a real number;</li>\n<li>multiply by 100;</li>\n<li>take the integer part.</li>\n</ul>\n\n<p>You can probably do that in one line (my Javascript is a bit rusty):</p>\n\n<pre><code>return Math.round(100 * parseFloat(dollarsAndCentsString.replace(/[$,]/g, '')));\n</code></pre>\n\n<p>Having said that, I think your f('1000') example is probably wrong: my intuition says I should interpret '1000' as dollars, not cents.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T14:14:14.537", "Id": "5348", "Score": "0", "body": "I'll consider your ideas. For what it's worth, the reason that I consider the dollars and cents separately as real numbers is to avoid floating point arithmetic round-off errors. Perhaps they are not relevant in this context. 0.1 + 0.2 = 0.30000000000000004." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T14:17:44.600", "Id": "5349", "Score": "0", "body": "And you're right f('1000') should be 10000." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T23:48:23.610", "Id": "3530", "ParentId": "3527", "Score": "10" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-18T20:51:25.340", "Id": "3527", "Score": "5", "Tags": [ "javascript", "parsing" ], "Title": "Code to Parse dollars and cents?" }
3527
<p>I have a view function that allows a user to Add / Edit / Delete an object. How does the following function look, and in what ways could I improve it? I was thinking about separating aspects of the function into different parts, but since no 'component' is more than four-five lines of code, I thought that would be a bit overkill. </p> <pre><code>@login_required def edit_education(request, edit=0): profile = request.user.get_profile() education = profile.education_set.order_by('-class_year') form = EducationForm(data=request.POST or None, request=request) if request.method == 'POST': ##### to add a new school entry ###### if 'add_school' in request.POST: if form.is_valid(): new_education = form.save(commit=False) new_education.user = profile new_education.save() return redirect('edit_education') ##### to delete a school entry ##### for education_id in [key[7:] for key, value in request.POST.iteritems() if key.startswith('delete')]: Education.objects.get(id=education_id).delete() return redirect('edit_education') ###### to edit a school entry -- essentially, re-renders the page passing an "edit" variable ##### for education_id in [key[5:] for key, value in request.POST.iteritems() if key.startswith('edit')]: edit = 1 school_object = Education.objects.get(id = education_id) form = EducationForm(instance = school_object, request=request) return render(request, 'userprofile/edit_education.html', {'form': form, 'education':education, 'edit': 1, 'education_id': education_id} ) ##### to save changes after you edit a previously-added school entry ###### if 'save_changes' in request.POST: instance = Education.objects.get(id=request.POST['education_id']) form = EducationForm(data = request.POST, instance=instance, request=request, edit=1) if form.is_valid(): form.save() return redirect('edit_education') return render(request, 'userprofile/edit_education.html', {'form': form, 'education': education}) </code></pre> <p>And in my template, if this help to clarify anything:</p> <pre><code>{% for education in education %} &lt;p&gt;&lt;b&gt;{{ education.school }}&lt;/b&gt; {% if education.class_year %}{{ education.class_year|shorten_year}}, {% endif %} {{ education.degree}} &lt;input type="submit" name="edit_{{education.id}}" value='Edit' /&gt; &lt;input type="submit" name="delete_{{education.id}}" value="Delete" /&gt; &lt;/p&gt; {% endfor %} </code></pre>
[]
[ { "body": "<p>The if conditions can be simplified.</p>\n\n<pre><code>fpv_list = [ item.partition(\"_\") for item in request.POST.iteritems() ]\ndeletes = [ v for f,p,v in fpv_list if f == 'delete' ]\nfor education_id in deletes:\n whatever\n\nedits = [ v for f,p,v in fpv_list if f == 'edit' ] \nfor education_id in edits:\n whatever\n</code></pre>\n\n<p>This removes the dependence on knowing the length of 'delete' and the length of 'edit' prefixes on the buttons.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:18:29.183", "Id": "3539", "ParentId": "3532", "Score": "4" } }, { "body": "<p>This procedure is too long. I'll never believe you gonna stop with this logic. Sooner or later you'll decide adding anything else here and then this piece of code will become even longer. You have 4 absolutely great blocks there, so why don't you just separate them into 4 separate procedures, leaving only the higher-level logic in original edit_education?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T19:20:21.247", "Id": "3545", "ParentId": "3532", "Score": "3" } }, { "body": "<p>Separate view functions according to functionality:</p>\n\n<pre><code>def addSome(request):\n # Your Add logic here\n\ndef editSome(request):\n # Your Edit related logic .. \n\ndef deleteSome(request):\n # Your Edit related logic ..\n</code></pre>\n\n<p>Now you can easly manage future updates in functionality(no more if/else)\nand think about url-name separations also.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-05-03T12:29:53.240", "Id": "162399", "ParentId": "3532", "Score": "2" } } ]
{ "AcceptedAnswerId": "3545", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T02:19:13.110", "Id": "3532", "Score": "2", "Tags": [ "python", "django" ], "Title": "Django view function" }
3532
<p>I am working on a PHP/MySQL application that uses a different time zone from the server it runs on, and neither of the timezones are UTC. I'm converting displayed times to be in the user's timezone, and am wondering whether my approach is sensible. I would love any feedback you might have.</p> <p>Firstly, the application's current time is written to the output HTML page as a <code>meta</code> value:</p> <pre><code>&lt;meta name="date" content="&lt;?php echo date('Y-m-d H:i:s') ?&gt;" /&gt; </code></pre> <p>And, every instance of a <code>datetime</code> string is wrapped thus:</p> <pre><code>&lt;span class="datetime-convert"&gt;&lt;?php echo $data-&gt;datetime_column ?&gt;&lt;/span&gt; </code></pre> <p>Then, after the page is loaded, the following JQuery gets the application time, the user time, figures out the difference between these, and adds that difference to the datetime data:</p> <pre><code>$("span.datetime-convert").each(function(){ var serverTime = parseDatetime($("meta[name='date']").attr("content")); var userTime = new Date(); var userOffset = new Date(userTime.getTime() - serverTime.getTime()); var timeToConvert = parseDatetime($(this).text()); var convertedTime = new Date(timeToConvert.getTime() + userOffset.getTime()); $(this).text(convertedTime.toLocaleString()); }); function parseDatetime(value) { var a = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/.exec(value); if (a) { return new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]); } return null; } </code></pre> <p>What am I doing wrong?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T06:02:04.310", "Id": "5285", "Score": "0", "body": "What is going wrong? I made fiddle out of this http://jsfiddle.net/xXVPC/" } ]
[ { "body": "<p>I would think it would be easier and more reliable to use timezone offsets rather than exact server time vs. client time. You can get the client-side offset using <code>new Date().getTimezoneOffset()</code> which returns the offset in minutes from UTC. When the timezone is +2 then the offset is -120. </p>\n\n<p><strong>PHP</strong></p>\n\n<pre><code>&lt;meta name=\"timezoneoffset\" content=\"&lt;?php echo date('P') ?&gt;\" /&gt;\n</code></pre>\n\n<p><strong>HTML</strong></p>\n\n<pre><code>&lt;meta name=\"timezoneoffset\" content=\"+0200\" /&gt;\n</code></pre>\n\n<p><strong>JavaScript</strong></p>\n\n<pre><code>var serverTimeZone= $(\"meta[name='timezoneoffset']\").attr(\"content\").substring(0,3);\n// getTimezoneOffset returns (client timezone * -60). \n// With timezones the the formula would be (clientTz - serverTz) * 60 * 60000\nvar timezoneOffset = (new Date().getTimezoneOffset() + (serverTimeZone * 60)) * 60000;\n$(\"span.datetime-convert\").each(function(){\n var date = parseDatetime($(this).text());\n if(date) { // If date is not wellformed the script would crash without this guard\n var offsetDate = new Date(date.getTime() + timezoneOffset);\n $(this).text(offsetDate .toLocaleString());\n }\n});\nfunction parseDatetime(value) {\n var a = /^(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/.exec(value);\n if (a) {\n return new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]);\n }\n return null;\n}\n</code></pre>\n\n<p>Also there's no need to calculate the offset for each individual date. It can be actually a bit misleading when the offset is slighlty different for each date.</p>\n\n<p><a href=\"http://jsfiddle.net/xXVPC/1/\" rel=\"nofollow\">http://jsfiddle.net/xXVPC/1/</a></p>\n\n<p>More <em>functional</em>: </p>\n\n<pre><code>var serverTimeZone= $(\"meta[name='timezoneoffset']\").attr(\"content\").substring(0,3);\n// getTimezoneOffset returns (client timezone * -60). \n// With timezones the the formula would be (clientTz - serverTz) * 60 * 60000\nvar timezoneOffset = (new Date().getTimezoneOffset() + (serverTimeZone * 60)) * 60000;\n$(\"span.datetime-convert\").each(function(){\n var e = $(this);\n parseDatetime(e.text(), new function(date) {\n var offsetDate = new Date(date.getTime() + timezoneOffset);\n e.text(offsetDate.toLocaleString());\n });\n});\nfunction parseDatetime(value, callback) {\n var a = /^(\\d{4})-(\\d{2})-(\\d{2}) (\\d{2}):(\\d{2}):(\\d{2})$/.exec(value);\n if (a) {\n callback(new Date(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6]));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T06:45:24.063", "Id": "5286", "Score": "0", "body": "All very good points. Thank you very much! I've incorporated them into my project." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T02:51:21.750", "Id": "5326", "Score": "0", "body": "I ended up changing the timezoneoffset meta value to be in seconds, to allow for offsets that are not multiples of 1 hour, and avoid the string manipulation. Also, what's your thinking behind adding the callback to parseDatetime? (See my update for my current solution.) Thanks for helping!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T03:08:21.680", "Id": "5327", "Score": "0", "body": "The idea is to avoid duplication of the condition `if(a)` and to get rid of one assignment operation. The first reason is the important one as you may or may not remember to check for nulls and undefined as you go along and use parseDatetime again in some other context of the program or if you happen to reuse the function is some other context altogether." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T06:14:57.243", "Id": "3535", "ParentId": "3534", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T04:12:23.347", "Id": "3534", "Score": "3", "Tags": [ "javascript", "datetime", "converting" ], "Title": "Conversion of datetime strings in PHP pages to user's timezone" }
3534
<p>I'm just refactoring some code I've come across whilst fixing a bug, but just wanted a quick sanity check to make sure I'm not missing any reason for keeping what I'm going to remove.</p> <p>The current code:</p> <pre><code>uxButton.Enabled = ((from a in actions select a).Distinct().Count() == 1); </code></pre> <p>There really doesn't seem to be a need for the LINQ query, so:</p> <pre><code>uxButton.Enabled = actions.Distinct().Count() == 1; </code></pre> <p>Should do the trick, right?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:24:01.727", "Id": "5297", "Score": "0", "body": "I'm not sure what the title of this question has to do with the content. You might consider revising it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T14:49:27.997", "Id": "5300", "Score": "0", "body": "You may well be right, I was a bit unsure of a title - basically what I meant was that the LINQ query is a select which returns the original set of objects... if that makes sense? If you can think of a better title, I'll happily change it :)" } ]
[ { "body": "<p>They both do the same thing. The first one just looks bizarre. Looks like the original author just didn't understand Linq.</p>\n\n<p>I'm not sure why you are checking to see if the count is 1. Looks like, in this situation</p>\n\n<pre><code>uxButton.Enabled = actions.Distinct().Any()\n</code></pre>\n\n<p>would be more appropriate and more performant.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:30:20.093", "Id": "5298", "Score": "0", "body": "You missed the “`.Distinct()`”." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T14:52:15.263", "Id": "5301", "Score": "1", "body": "I need the Count to be 1, as if it's more than 1, it should be disabled. Otherwise, I would have used Any. But thanks for confirming my thoughts." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T15:50:35.567", "Id": "5304", "Score": "1", "body": "Just out of curiosity. If there should only be one action available, why is it using a list of actions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:25:07.657", "Id": "5336", "Score": "0", "body": "There can be more than one action in the list of actions, but the button can only be enabled if there is 1 action in the list. For all other counts, it should be disabled." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:19:34.130", "Id": "3540", "ParentId": "3536", "Score": "0" } }, { "body": "<p>Yes, you are right, the LINQ query is superfluous and you can just write <code>actions</code> instead.</p>\n\n<p>The only comment I’d have about the code is that <code>.Distinct().Count()</code> will go through the entire collection, but you can stop when a non-distinct element is found. So personally I’d use this instead:</p>\n\n<pre><code>uxButton.Enabled = actions.Distinct().Skip(1).Any();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T14:08:06.097", "Id": "5299", "Score": "1", "body": "Your code will give different result for `Count() == 1`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T14:55:39.163", "Id": "5302", "Score": "0", "body": "Won't this return true for a collection of more than 1? I need it to be false for anything other than 1, hence the check for Count() == 1; Unless there's another method which returns true only for collections with a single element, I believe Count() to be the only option...?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T13:33:12.167", "Id": "3541", "ParentId": "3536", "Score": "-1" } }, { "body": "<p>As the other answers stated your given code does do the same thing, but could give performance issues for big collections since the entire collection is traversed when calling <code>Count()</code>.</p>\n\n<p>The following code should solve this:</p>\n\n<pre><code>var distinct = actions.Distinct();\nuxButton.Enabled = distinct.Take( 2 ).Count() == 1;\n</code></pre>\n\n<p>Perhaps you could turn this into an extension method:</p>\n\n<pre><code>uxButton.Enabled = actions.Distinct().CountOf( 1 );\n</code></pre>\n\n<hr>\n\n<p>It seemed useful, so <a href=\"https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.System/Linq/Extensions.IEnumerable.cs\" rel=\"nofollow\">I added it to my library</a>, along <a href=\"https://github.com/Whathecode/Framework-Class-Library-Extension/blob/master/Whathecode.System.Tests/Linq/IEnumerableExtensionsTest.cs\" rel=\"nofollow\">with a unit test</a>.</p>\n\n<pre><code>/// &lt;summary&gt;\n/// Returns whether the sequence contains a certain amount of elements.\n/// &lt;/summary&gt;\n/// &lt;typeparam name = \"T\"&gt;The type of the elements of the input sequence.&lt;/typeparam&gt;\n/// &lt;param name = \"source\"&gt;The source for this extension method.&lt;/param&gt;\n/// &lt;param name = \"count\"&gt;The amount of elements the sequence should contain.&lt;/param&gt;\n/// &lt;returns&gt;\n/// True when the sequence contains the specified amount of elements, false otherwise.\n////&lt;/returns&gt;\npublic static bool CountOf&lt;T&gt;( this IEnumerable&lt;T&gt; source, int count )\n{\n Contract.Requires( source != null );\n Contract.Requires( count &gt;= 0 );\n\n return source.Take( count + 1 ).Count() == count;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:39:36.293", "Id": "5338", "Score": "1", "body": "Nice, I like this. I've added this method to our project now, but have called it CountIs - collection.CountIs(1) sounds more logical than collection.CountOf(1) to me, seeing as it's returning a bool. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T23:13:53.030", "Id": "5369", "Score": "1", "body": "More efficient alternative: `actions.Distinct().Take(2).Count() == 1`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T15:43:09.030", "Id": "3542", "ParentId": "3536", "Score": "2" } } ]
{ "AcceptedAnswerId": "3542", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T08:33:18.583", "Id": "3536", "Score": "2", "Tags": [ "c#", "linq" ], "Title": "LINQ Query returning all original objects" }
3536
<p>Since I'm venturing more and more into the multithreading, I now need to think about how to protect my precious <code>OdbcConnection</code> from breaking at random times.</p> <p>The project specifications:</p> <ul> <li>.NET-2.0</li> <li>ODBC-Connection via MySQL-Connector 3.51 to MySQL 5.0</li> </ul> <p>The main structure of my project in question looks like this:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>+ Assembly +--+&gt; Namespace1 +--&gt; Data-Layer +--+&gt; Namespace2 +--&gt; Data-Layer ... </code></pre> </blockquote> <p>There's also an abstraction layer in place with interfaces and implementations, but I think that doesn't matter, because my question is about the ODBC implementation. They do also implement <code>IDisposable</code>.</p> <p>This means I'm passing around an <code>OdbcConnection</code> to different classes and create these <code>Data</code> classes if asked to, like this:</p> <pre class="lang-java prettyprint-override"><code>public class MainDataSource { private OdbcConnection _conn = &lt;Yes, It's initialized&gt;; public Namespace1.Data CreateNamespace1Data() { return new Namespace1.Data(_conn); } public Namespace2.Data CreateNamespace2Data() { return new Namespace2.Data(_conn); } } </code></pre> <p>The <code>Data</code> classes itself are containing methods to fetch objects from the database. The only interesting thing here is that every <code>Data</code> class is holding its very own <code>OdbcCommand</code> objects, none of these are shared in any way. The only thing they have in common is the source <code>OdbcConnection</code>.</p> <p>Since some of these classes (like the <code>Setting</code> class) might be called from multiple threads at the same time, I need to think about the best way to lock and protect these. My first idea was to lock the whole <code>OdbcConnection</code>:</p> <pre class="lang-java prettyprint-override"><code>public class Data { private OdbcConnection _conn; private OdbcCommand _cmd; public Data(OdbcConnection conn) { _conn = conn; _cmd = _conn.CreateCommand(); _cmd.CommandText = &lt;FromResource&gt;; _cmd.Parametersblabla; } public MyDataObject GetObjects(String searchterm) { lock(_conn) { _cmd.Parameters[0].Value = searchterm; using(OdbcDataReader reader = _cmd.ExecuteReader()) { // Do stuff here and return MyDataObject } } } } </code></pre> <p>This seems a little bit too strict to me, so I also thought about only locking the <code>OdbcCommand</code>:</p> <pre class="lang-java prettyprint-override"><code>public class Data { private OdbcCommand _cmd; public Data(OdbcConnection conn) { _cmd = conn.CreateCommand(); _cmd.CommandText = &lt;FromResource&gt;; _cmd.Parametersblabla; } public MyDataObject GetObjects(String searchterm) { lock(_cmd) { _cmd.Parameters[0].Value = searchterm; using(OdbcDataReader reader = _cmd.ExecuteReader()) { // Do stuff here and return MyDataObject } } } } </code></pre> <p>But I still feel like I've missed something very important here. Do I have other options? Did I miss something important?</p>
[]
[ { "body": "<p>The <a href=\"http://msdn.microsoft.com/en-us/library/system.data.odbc.odbcconnection%28v=VS.80%29.aspx\" rel=\"nofollow\">OdbcConnection</a> is not thread-safe in any way, therefor it needs a locking mechanism.</p>\n\n<p>My observation is that the <code>OdbcConnection</code> does send it's received commands down into the Connector. If this is happening in a multi-threaded environment, the sequence of commands is interrupted and you'll receive an exception with this or a similar message:</p>\n\n<blockquote>\n <p>ERROR [HY000] [MySQL][ODBC 3.51 Driver]Commands out of sync; you can't run this command now</p>\n</blockquote>\n\n<p>The driver is confused because the sequence was interrupted. This can not only happen on a <code>OdbcCommand</code> level, but on a <code>OdbcConnection</code> level. The <code>OdbcConnection</code> needs to be locked.</p>\n\n<p>An additional note is that you should lock the <code>OdbcConnection</code> the moment you start to work with a command:</p>\n\n<pre><code>_cmd.Parameters[0].Value = argument;\nlock(_conn)\n{\n _cmd.ExecuteNonQuery();\n}\n</code></pre>\n\n<p>This is bad, because it could happen in a multi-threaded environment that the parameter gets overridden by another thread before <code>ExecuteNonQuery</code> can be called.</p>\n\n<pre><code>lock(_conn)\n{\n _cmd.Parameters[0].Value = argument;\n _cmd.ExecuteNonQuery();\n}\n</code></pre>\n\n<p>This keeps the execution as one atomic operation which can't be interrupted.</p>\n\n<p>Further investigations revealed that the MySQL Odbc-Connector has a locking mechanism...but only on a statement level:</p>\n\n<blockquote>\n <p>MySQL ODBC Connector, 5.1.9, execute.c</p>\n</blockquote>\n\n<pre><code> 39: SQLRETURN do_query(STMT FAR *stmt,char *query, SQLULEN query_length)\n 40: {\n ...\n 55: MYLOG_QUERY(stmt, query);\n 56: pthread_mutex_lock(&amp;stmt-&gt;dbc-&gt;lock);\n ...\n 96: exit:\n 97: pthread_mutex_unlock(&amp;stmt-&gt;dbc-&gt;lock);\n ...\n114: }\n</code></pre>\n\n<p>And to make it clear: If you have a non-thread-safe connection, lock the whole connection.</p>\n\n<p>And to make it further clear, using an <code>OdbcDataReader</code> counts as using the connection. As long as you work with an <code>OdbcDataReader</code>, you should keep the lock on the connection. </p>\n\n<p>This includes disposing of the resources, f.e. a DataReader. You should always use <code>using</code> inside the <code>lock</code>ed parts to make sure that the resources are freed again, otherwise it could happen that a DataReader lingers on and is later destroyed by the Garbage Collector and a rather inconvenient moment, like this:</p>\n\n<pre><code>Thread Action\n 1 Lock Connection\n 1 Create Statement\n 2 Lock Connection -&gt; Wait\n 1 Prepare Statement\n 1 Execute Statement\n 1 Get Reader\n 1 Use Reader\n 1 Unlock Connection\n 2 Lock Connection\n 2 Prepare Statement\n 2 Execute Statement\n GC Destroy Statement from thread #1\n GC Destroy Reader from thread #1\n</code></pre>\n\n<p>In code it would like this:</p>\n\n<pre><code>lock (connection)\n{\n IDbCommand command = connection.CreateCommand();\n command.CommandText = \"SQL\";\n IDataReader reader = command.ExecuteReader();\n // Do something the reader\n return valuesFromTheReader;\n}\n</code></pre>\n\n<p>This is bad as it allows resources to linger on and the GC will later destroy them, with possible disastrous results. My tests revealed that from the exception</p>\n\n<blockquote>\n <p>Attempted to read or write protected memory.</p>\n</blockquote>\n\n<p>to a simple deadlock of the application on an arbitrary line<sup>1</sup> everything is possible if you fail to correctly synchronize database access.</p>\n\n<p>The best pattern is to always destroy everything while in inside the lock:</p>\n\n<pre><code>lock (connection)\n{\n using (IDbCommand command = connection.CreateCommand())\n {\n command.CommandText = \"SQL\";\n using (IDataReader reader = command.ExecuteReader())\n {\n // Do something the reader\n return valuesFromTheReader;\n }\n }\n}\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup>: I'm not kidding, I could reliable reproduce a hang on the following instruction inside the <code>System.Data.Odbc.OdbcDataReader.NextResult(bool, bool)</code></p>\n\n<pre><code>IL_0099: ldarg.1\n00000099 8B F8 mov edi,eax\n</code></pre>\n\n<p>when I did not properly dispose of a DataReader.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-16T10:11:16.890", "Id": "6091", "ParentId": "3538", "Score": "6" } }, { "body": "<p>Is there any reason why you need to have only one connection? I would have each method that needs to interact with the database open its own connection and dispose it when it is finished. If you ensure connection pooling is enabled it will take care of reusing connections so you won't overload the database server with connection requests. </p>\n\n<p>I'd also create a static method that creates and opens the connection, it would take care of getting your connection string and would simply return an open connection. Calling code would then just need to start a using block calling this function. </p>\n\n<p>This also has the advantage that multiple threads can be performing data access at the same time, otherwise youmay be limiting the benefit of your multithreading. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-22T19:07:24.003", "Id": "24256", "ParentId": "3538", "Score": "1" } } ]
{ "AcceptedAnswerId": "6091", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T10:07:37.727", "Id": "3538", "Score": "5", "Tags": [ "c#", "database", "synchronization", "odbc" ], "Title": "Synchronization of an ODBC connection" }
3538
<p>This is working as expected, except in the speed area + I need to make it more readable and shorter if possible, I probably have lot's of things I don't need :).</p> <p><strong>Edit</strong> it is working now </p> <pre><code>charset = dict(opening='{[(&lt;',\ closing='}])&gt;',\ string = ('"', "'"),\ comment=(('&lt;!--', '--&gt;'), ('"""', '"""'), ('#', '\n'))) allowed = ''.join([x[0][0] + x[1][0] for x in charset['comment']]) allowed += ''.join(charset['string']) allowed += charset['opening'] allowed += charset['closing'] def brace_check(text): o = [] c = [] notr = [] found = [] busy = False last_pos = None for i in xrange(len(text)): ch = text[i] if not busy: cont = True for comment in charset['comment']: if ch == comment[0][0]: como = text[i:len(comment[0])] if como == comment[0]: busy = comment[1] if ch in charset['opening']: last_pos = i cont = False break if cont: if ch in charset['string']: busy = ch elif ch in charset['opening']: o.append((ch, i)) elif ch in charset['closing']: c.append((ch, i)) else: if ch == busy[0]: if len(busy) == 1: comc = ch else: comc = text[i:i + len(busy)] if comc == busy: if last_pos is not None: if busy[-1] in charset['closing']: found.append((last_pos, i)) last_pos = None text = text[:i] + '\n' * len(comc) +\ text[i + len(comc):] busy = not busy elif busy in charset['string']: if ch == '\n': busy = not busy for t, e in reversed(o): try: n = next((b, v) for b, v in c\ if b == charset['closing'][\ charset['opening'].find(t)] and v &gt; e) c.remove(n) n = n[1] if found != []: if e &lt; found[-1][0] and n &gt; found[-1][0] and n &lt; found[-1][1]\ or e &lt; found[-1][1] and n &gt; found[-1][1] and e &gt; found[-1][0]: found.append((n, False)) n = False except StopIteration: n = False found.append((e, n)) for t, e in c: found.append((e, False)) return found </code></pre>
[]
[ { "body": "<p>You can drop the <code>del</code> statements. They don't help much.</p>\n\n<p>It's much easier to break this into separate functions and simply allow Python's ordinary namespace rules handle the deletes.</p>\n\n<p>The <code>if type(mn) == type(str()):# if there only is one element</code> is a needless volume of code for one special case that isn't really special. </p>\n\n<p>Make the '\"\"\"' completely separate from <code>multi</code> and remove the needless <code>if</code> statement. Process it in a separate pass with no <code>if</code> statement in the loop.</p>\n\n<p>Golden Rule: If statements are expensive. Find ways to remove them. </p>\n\n<p>Two \"nearly the same\" loops for <code>multi</code> and for the <code>\"\"\"</code> case avoids an if statement, and improves speed.</p>\n\n<p>Also. <code>multi</code>, <code>single</code> and <code>string</code> aren't proper lists. They're immutable tuples. Eliminate a tiny bit of <em>potential</em> overhead by making them proper tuples.</p>\n\n<p><code>newline = [m.start() for m in re.finditer('\\n', string)] # every newline</code> may be needless complexity. In the <code>single</code> case, a newline character is the implicit \"closing\" for both of the \"single\" comments. Perhaps single should be <code>( ('#','\\n'), ('//','\\n') )</code> so that it can be just the same as multi.</p>\n\n<p>Also, <code>if not last</code> at the top of a loop usually means that the <code>last= True</code> line should have been a <code>break</code> statement instead. </p>\n\n<p>In this case, however, it's worse than that. If <code>if not last</code> at the top of the loop is there to step to the next item in the iterator (<code>xrange(len(rep))</code>)</p>\n\n<p>There are two better ways to handle this, both with explicit iterator objects.</p>\n\n<p>This is minimally disruptive</p>\n\n<pre><code>range_iter= iter( xrange( len( rep ) ) )\nfor i in range_iter:\n s= rep[i] \n ... much logic ...\n next( range_iter ) # Skip the next item. No last=True business.\n ... more logic ...\n</code></pre>\n\n<p>This is what you meant. To assign <code>s</code> from <code>rep</code> directly.</p>\n\n<pre><code>rep_iter = iter( rep )\nfor s in rep_iter:\n ... much logic ... \n next( rep_iter ) # Skip the next item. No last=True\n ... more logic ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:21:15.557", "Id": "5335", "Score": "0", "body": "I had the '\"\"\"' the same as the others before, but since it is the same on both ends, op and cl had the same values and it got screwed up :/. Any idea how to fix that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:59:27.113", "Id": "5342", "Score": "0", "body": "@thabubble: `finditer()` is -- obviously -- a bad choice of ways to find comment punctuation in general. It's easily fooled by \"nested\" comments that should not be paired up. `#\"\"\"\\n` is a legal `#...\\n` with a partial comment hidden in the middle. I'll update my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T14:33:32.567", "Id": "5350", "Score": "0", "body": "doesn't \"break\" break the whole loop so that any other can't be checked? if last = False, previous haven't been paired properly for example '(\")\\n\")\\n)' should show \"[(0, 7)]\" but the only thing I can think that not using last will result in \"[(0, 5), (7, False)]\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T15:11:02.643", "Id": "5351", "Score": "0", "body": "\"doesn't `break` break the whole loop\"? What do you think you mean by whole loop? When you set `last = True`, you're going to exit the loop, right? Isn't that the point of setting `last = True`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T15:35:56.203", "Id": "5352", "Score": "0", "body": "Nope, sorry, it is there for the pairing of the strings, for example if there is a newline between two supposedly paired quotes, i.e \"\\n\" then they aren't paired, the newline invalidates it. So if the last two quotes where paired correctly then it selects a new, before I had \"for i in xrange(0, len(rep), 2):\" to select every other, but if there was a newline between it broke it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T18:59:44.120", "Id": "5360", "Score": "0", "body": "@thabubble: The `if not last` if statement is only there to consume one item from the `xrange` iterator? That's bad, then." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:14:39.470", "Id": "3550", "ParentId": "3543", "Score": "2" } }, { "body": "<pre><code>def brace_check(string):\n</code></pre>\n\n<p>string is the name of a python module, it might be best to avoid it</p>\n\n<pre><code> # Imports\n import re\n</code></pre>\n\n<p>imports should be done at the module level not inside a function</p>\n\n<pre><code> # Configuration\n charset = dict(opening='{[(&lt;',\\\n closing='}])&gt;',\\\n string = ['\"', \"'\"],\\\n single=['#', '//'],\\\n multi=[['/*', '*/'], '\"\"\"', ['&lt;!--', '--&gt;']])\n</code></pre>\n\n<p>Constant values should be at the module level not inside the function</p>\n\n<pre><code> found = []# found objects\n</code></pre>\n\n<p>found isn't used until way later. Declare it way later.</p>\n\n<pre><code> notr = []# busy locations\n</code></pre>\n\n<p>notr and its comment don't suggest anything the same.</p>\n\n<pre><code> temp = {}# temporary holding for opening braces\n end = {}# temporary holding for closing braces\n</code></pre>\n\n<p>All variables are temporary. Don't give names or comments that tell me such obvious things</p>\n\n<pre><code> # Find all ocurrances and its position\n newline = [m.start() for m in re.finditer('\\n', string)] # every newline\n\n for mn in charset['multi']:# find every multiline comment\n if type(mn) == type(str()):# if there only is one element\n op = [m.start() for m in re.finditer(re.escape(mn), string)]\n cl = op[1::2]\n op = op[0::2]\n mn = (mn, mn)\n\n else:\n op = [m.start() for m in re.finditer(re.escape(mn[0]), string)]\n cl = [m.start() for m in re.finditer(re.escape(mn[1]), string)]\n</code></pre>\n\n<p>These short cryptic variables name are asking for confusion.</p>\n\n<pre><code> for i in xrange(len(op)):# find and close every comment\n om = op[i]\n</code></pre>\n\n<p>Use the enumerate function. It lets you use a foreach loop and get the indexes at the same time\n try:\n cm = next(v for v in cl if v > om) + len(mn[1])</p>\n\n<p>add a line like: start_comment, end_comment = mn, that way you can avoid the indexes are your code will be clearer.</p>\n\n<pre><code> if mn[0][0] in charset['opening'] and\\\n mn[1][-1] in charset['closing']:\n for i in xrange(om + 1, cm - 1):\n if i not in notr:\n notr.append(i)\n</code></pre>\n\n<p>Rather the constantly checking whether a value is in notr, use a set. Then the last three lines can simply be notr.add( xrange(om + 1, cm - 1) )</p>\n\n<pre><code> else:\n for i in xrange(om, cm):\n if i not in notr:\n notr.append(i)\n</code></pre>\n\n<p>Did we really need that special case? </p>\n\n<pre><code> except:\n</code></pre>\n\n<p>Don't catch all exceptions, you'll hide bugs that way. Instead, catch only the specific type of exception you are interested in. Also, you want as little code in the try block as possible to avoid catching other stray exceptions</p>\n\n<pre><code> for i in xrange(om, len(string)):\n if i not in notr:\n notr.append(i)\n</code></pre>\n\n<p>You at least need a comment explaining why this make sense.</p>\n\n<pre><code> del op, cl\n</code></pre>\n\n<p>Don't del variables, its rarely useful. </p>\n\n<pre><code> for sn in charset['single']:\n rep = [m.start() for m in re.finditer(re.escape(sn), string)]\n for s in rep:\n try:\n new = next(v for v in newline if v &gt; s)\n except:\n new = len(string)\n newline.append(len(string))\n</code></pre>\n\n<p>Why not use the string search functions rather then having built a newline list? Also, if you need to treat the end of input as a newline, put that in when you create the list not in an exception handler.</p>\n\n<pre><code> if not s in notr:\n for i in xrange(s, new):\n if i not in notr:\n notr.append(i)\n newline.remove(new)\n del rep\n\n for sn in charset['string']:\n rep = [m.start() for m in re.finditer(re.escape(sn), string)]\n last = False\n for i in xrange(len(rep)):\n if not last:\n s = rep[i]\n if s not in notr:\n try:\n new = next(v for v in newline if v &gt; s)\n except:\n new = len(string)\n newline.append(len(string))\n</code></pre>\n\n<p>If code repeats, you need a function. </p>\n\n<pre><code> try:\n n = next(v for v in rep if v &gt; s)\n except:\n n = new + 1\n if n &lt; new:\n last = True\n for i in xrange(s, n + 1):\n if i not in notr:\n notr.append(i)\n else:\n for i in xrange(s, new):\n if i not in notr:\n notr.append(i)\n newline.remove(new)\n else:\n last = False\n del rep\n\n for cn in charset['closing']:\n on = charset['opening'][charset['closing'].find(cn)]\n end[on] = [m.start() for m in re.finditer(re.escape(cn), string)\\\n if m.start() not in notr]\n</code></pre>\n\n<p>Given the cn is a single character, use of a regular expression to find it is overkill. </p>\n\n<pre><code> for on in charset['opening']:\n op = [m.start() for m in re.finditer(re.escape(on), string)\\\n if m.start() not in notr]\n for i in xrange(len(op)):\n temp[op[i]] = on\n\n for k in sorted(temp.keys(), reverse=True):\n try:\n c = next(v for v in end[temp[k]] if v &gt; k and v not in notr)\n end[temp[k]].remove(c)\n for i in xrange(k, c + 1):\n if i not in notr:\n notr.append(i)\n except:\n c = False\n found.append((k, c))\n</code></pre>\n\n<p>It seems to me that using a stack would be simpler then what you are doing here.</p>\n\n<pre><code> for v in end.values():\n for c in v:\n found.append((c, False))\n</code></pre>\n\n<p>No explanation is given for what you are putting inside found. I have no idea what the return value means.\n return found</p>\n\n<p>General thoughts:</p>\n\n<p>The code is complicated, it really should be split up into a lot of functions. </p>\n\n<p>Rather then all that code matching different types of comments and strings, have a set of ignore regexes. The regex should match an entire comment or string which can then be removed.</p>\n\n<p>Your code builds lists of everything which would only serve to complicate what is going on. Lists can be great, but they aren't the solution to every problem. </p>\n\n<p>My rewrite of your code: (I didn't start with your code, but it should support the same features:)</p>\n\n<pre><code>from nose.tools import assert_equal\nimport re\n\nclass SimpleTokenizer(object):\n \"\"\"\n The constructor takes a dictionary of keys which should be regular \n expression strings to arbitrary value. The tokenize method will produce\n all the substrings in the text which match the regular expression.\n It will return the value provided in the original dictionary\n to identify which expression was matched\n \"\"\"\n def __init__(self, data):\n # I need a consistent order from data, so I dump the dictionary\n # into a list\n data = list(data.items())\n self.values = [value for key, value in data]\n # this regular expression matches any key\n self.expression = '|'.join('(%s)' % key for key, value in data)\n\n def tokenize(self, text):\n for match in re.finditer(self.expression, text):\n # group 0 is the whole string, we subtract one\n # to make up for that\n yield match.start(), self.values[match.lastindex - 1]\n\nCLOSER = 0\nOPENER = 1\nIGNORE = 2\nclass Language(object):\n \"\"\"\n Provides brace checking\n \"\"\"\n def __init__(self, opening, closing, ignore = ()):\n \"\"\"\n opening and closing should be sequences of the same size denoting\n the start and end symbols that should matched. Ignore should be a\n sequence of regular expression which should be ignored for the\n purpose of matching such as comments, strings, etc.\n \"\"\"\n\n data = {}\n for opener, closer in zip(opening, closing):\n data[re.escape(opener)] = (OPENER, closer)\n data[re.escape(closer)] = (CLOSER, closer)\n for ignore in ignore:\n data[ignore] = (IGNORE, None)\n self._tokenizer = SimpleTokenizer(data)\n\n\n def check(self, text):\n \"\"\"\n Given text produces the location of the various braces\n returns a list of tuple, start, end where a pair of matches\n braces exist. If either brace is missing it will be recorded\n as None.\n \"\"\"\n\n braces = []\n\n waiting = []\n # waiting is a stack holding the braces which have been opened\n # but not yet closed\n for idx, (category, extra) in self._tokenizer.tokenize(text):\n if category == OPENER:\n waiting.append( (extra, len(braces)) )\n # we start with None as the end of a brace, it'll be \n # updated if we find it\n braces.append( (idx, None) )\n elif category == CLOSER:\n # find the last entry that matches\n index = None\n for element, element_index in reversed(waiting):\n if element == extra:\n index = element_index\n break\n\n if index is None:\n # no matches found\n # in that case, record the start as None\n braces.append( (None, idx) )\n else:\n # we found the match, replace the existing record\n # with a new one\n position, waste = braces[index]\n braces[index] = (position, idx)\n # elminate anything we had to ignore\n del waiting[index:]\n\n return braces\n\nLANGUAGE_TESTS = [\n (\"[()]\", [(0, 3), (1, 2)]),\n (\"[(a)]\", [(0, 4), (1, 3)]),\n (\"[(]\", [(0, 2), (1, None)]),\n (\"[()\", [(0, None), (1, 2)]),\n (\"[(])\", [(0, 2), (1, None), (None,3)]),\n (\"])\", [(None, 0), (None, 1)]),\n (\"(])\", [(0, 2), (None, 1)]),\n]\n\ndef test_basic_language():\n language = Language(\n opening = '[(',\n closing = '])')\n def inner(text, expected):\n result = language.check(text)\n assert_equal(list(result), expected)\n\n for text, expected in LANGUAGE_TESTS:\n yield inner, text, expected\n\n\nSTRING_LANGUAGE = [\n ('[(\")]\")]', [(0, 7), (1, 6)])\n]\ndef test_string_language():\n language = Language(\n opening = '[(',\n closing = '])',\n ignore = [r'\"[^\"]*\"']\n )\n def inner(text, expected):\n result = language.check(text)\n assert_equal(list(result), expected)\n\n for text, expected in STRING_LANGUAGE:\n yield inner, text, expected\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T14:05:51.933", "Id": "5347", "Score": "0", "body": "notr is the range where there are comments, other braces and strings. I don't understand what you mean with to use a set and to use a for loop for checking is what I already have done but it was slower on large text. Found returns the position of opening and closing braces, if there isn't a opeing/closing brace to pair with or it is nested wrongly it returns the position and false." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T22:42:54.527", "Id": "5368", "Score": "0", "body": "@thabubble, don't tell me what you variables are for, give them better names. With a set you don't need a for loop for checking. I'd be surprised if using the set like that was slower, can your provide the code/data you tested with? Don't tell me what found contains, document it in your function. (Also, what is position? character index? line number?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T02:55:46.757", "Id": "5370", "Score": "0", "body": "@thabubble, I added my own version of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T02:59:09.183", "Id": "5371", "Score": "0", "body": "thanks, but I just got it working, will check yours too, bet there is a lot to learn from there:) Thank you for your help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T03:01:29.383", "Id": "5372", "Score": "0", "body": "Wow your code looks really neat! :)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T11:10:47.853", "Id": "3558", "ParentId": "3543", "Score": "6" } } ]
{ "AcceptedAnswerId": "3558", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T18:39:35.823", "Id": "3543", "Score": "3", "Tags": [ "python", "regex" ], "Title": "Brace pairing ({}[]()<>) cleanup/speedup" }
3543
<p>I have two quite mutually exclusive desires - detailed logs and keeping my code clean. It appears that you can only get either of these. By "logging" I mean logging and not tracing, so AOP adepts wouldn't appreciate it.</p> <p>What I want to have is real description of action my program does, why it does these actions and so forth. For instance, 'failures' could either be real failures like 'fatal errors', or absolutely normal behavior depending on context: I don't like to check whether or not file exists before reading, I'll just try to open it and that could either fail or succeed. If it fails, I'll have an exception. But if reading this file is not really critical, the exception I get is not an error, it could be treated as just 'warning'.</p> <p>When something really interesting happens, I want to see it directly without scrolling up and down my 500KB log file and trying to remember the code.</p> <p>I've implemented a draft solution for this problem and I'd like to know what you think:</p> <pre><code>sealed class FileReader { private readonly string _fileName; public FileReader(string fileName) { _fileName = fileName; } public string GetData(ExecutionContext context) { var fileExists = context.Execute( string.Format("checking if {0} exists", _fileName), ctx =&gt; File.Exists(_fileName)); if(!fileExists) { throw new FileNotFoundException(); } var data = context.Execute( string.Format("reading data from {0}", _fileName), delegate { // can easily use lambdas and anonymous delegates return File.ReadAllText(_fileName); }); return data; } public override string ToString() { return string.Format("FileReader(file={0})", _fileName); } } ... sealed class FileProcessor { private readonly FileReader _fileReader; private readonly DataProcessor _dataProcessor; public FileProcessor(FileReader fileReader, DataProcessor dataProcessor) { _fileReader = fileReader; _dataProcessor = dataProcessor; } public void Process(ExecutionContext context) { var data = context.Execute("reading data", ctx =&gt; _fileReader.GetData(ctx)); context.Execute("processing data read", ctx =&gt; _dataProcessor.Process(ctx, data)); } public override string ToString() { return string.Format( "FileProcessor(reader={0},processor={1})", _fileReader, _dataProcessor); } } ... static void Main() { try { var context = new ExecutionContext("root"); // var fileReader = new FileReader("1.txt") var fileReader = context.Execute("creating file reader", ctx =&gt; new FileReader("1.txt")); // var dataProcessor = new DataProcessor() var dataProcessor = context.Execute("creating data processor", ctx =&gt; new DataProcessor()); // var fileProcessor = new FileProcessor(fileReader, dataProcessor) var fileProcessor = context.Execute( "creating file processor", ctx =&gt; new FileProcessor(fileReader, dataProcessor)); // fileProcessor.Process() context.Execute("running file processor", ctx =&gt; fileProcessor.Process(ctx)); } catch(Exception ex) { Console.WriteLine("Fatal error: {0}", ex.Message); } } </code></pre> <p>The results for this code:</p> <pre><code>/creating file reader - succeeded [FileReader(file=1.txt)] /creating data processor - succeeded [DataProcessor] /creating file processor - succeeded [FileProcessor(reader=FileReader(file=1.txt),processor=DataProcessor)] /running file processor/reading data/checking if 1.txt exists - succeeded [False] /running file processor/reading data - failed: Unable to find the specified file. /running file processor - failed: Unable to find the specified file. Fatal error: Unable to find the specified file. </code></pre> <p>I really like the result but I'm not sure if it's worth it. Any ideas?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T21:42:55.453", "Id": "5313", "Score": "2", "body": "I'm a bit unclear on what the ExecutionContext object is. It appears that the ExecutionContext decides if the function is critical or not and handles writing log messages. The Execute function seems to returns the results of your delegate/lambda. Am I on the right track so far?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T18:33:51.150", "Id": "5788", "Score": "0", "body": "Since you don't seem to be using the ExecutionContext root, why do you need to create a context object?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T18:40:30.147", "Id": "5789", "Score": "2", "body": "Without the definition of ExecutionContext, it is had to be thorough.\n\nCouldn't you create a class with static members and just reference the static class and not pass the ExecutionContext everywhere?\n\nAlso, I don't like passing the executable steps into the logging code, it creates a funny execution flow (to me) plus overhead and peculiar function calling - I would prefer if context.Execute was always void and the delegate handled the assignment, for example.\n\n(*SIGH* split comment due to dumb Enter function plus DUMB comment timeout)" } ]
[ { "body": "<p>I think you should use a logging library instead of reinventing the wheel. See the very good <a href=\"http://logging.apache.org/log4net/\">log4net</a>.</p>\n\n<p>You can simply do</p>\n\n<pre><code>log.DebugFormat(\"creating file reader for file {0}\", fileName);\nlog.Error(\"Unable to find the specified file\");\n</code></pre>\n\n<p>And depending on the configuration you specify, it could be output like</p>\n\n<pre><code>Debug - 15:04:00.657 - (ThreadName) - FileReader - creating file reader for file foobar.txt\nError - 15:04:02.542 - (ThreadName) - FileReader - Unable to find the specified file\n</code></pre>\n\n<p>etc. </p>\n\n<p>This allows you to specify a log level, that will help you with parsing the file while looking for the important bits. </p>\n\n<p>You can also configure which messages get output at all by specifying the overall log level from an external XML file. For example the production version would be set on \"Info\" while the dev version would be on \"Debug\".</p>\n\n<p>The line format is completely configurable so you can add many extra informations or change the order and formatting. It also handles log rotation and recycling.</p>\n\n<p>When coding, you'll have some logging code around but if they are sufficiently clear, they can replace a comment.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T05:23:12.230", "Id": "25157", "Score": "0", "body": "Did you even read the question?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-11T20:16:50.013", "Id": "25191", "Score": "1", "body": "Sorry if I missed something, your goal is to have a real description of action your program does, why it does these actions and so forth, and to that end you have devised an (imho) overengineered solution, and coupled all your classes to a particular piece of infrastructure. Please enlighten me with what's wrong with `log.Info(\"message\");`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T07:12:48.970", "Id": "25207", "Score": "0", "body": "The topic says: \"Detailed logs and keeping code clean\". Your advice of using log4net has nothing to do with both parts. Using log4net directly will cause the code to become twice longer, just because for every `func()`, you'll have to write corresponding `log(\"func()\")`. The question is about getting rid of this boilerplate code. You may use `Console.WriteLine()` if there's anything you can advise from the design standpoint. The way messages are logged doesn't matter in fact." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-12T07:58:28.620", "Id": "25210", "Score": "2", "body": "I certainly think the code is cleaner if you separate the concern of logging the operation with the one of performing it. Using a logging lib is better than Console.Writeline because it allows you to specify a log level, and later filter your logs based on that level without _scrolling up and down your 500KB log file_." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T13:08:16.777", "Id": "15477", "ParentId": "3544", "Score": "5" } }, { "body": "<p>For what it's worth after all this time you asked the question:</p>\n\n<blockquote>\n <p>Is it worth it?</p>\n</blockquote>\n\n<p>The answer is: No.</p>\n\n<p>You said one requirement is to keep your code clean. You have fully achieved the total opposite of this. Lets take <code>GetData()</code> as an example. Without the <code>ExecutionContext</code> code the method would read this:</p>\n\n<pre><code>public string GetData(ExecutionContext context)\n{\n if(!File.Exists(_fileName))\n {\n throw new FileNotFoundException();\n }\n return File.ReadAllText(_fileName);\n}\n</code></pre>\n\n<p>A reasonably experienced developer can read this code and understand what it is doing in about 5sec.</p>\n\n<p>You have turned this four-liner into a mess of disjoint statements which take about 10 times longer to read through and understand what the code is doing.</p>\n\n<p>You also run into the same problem as you do with commenting every statement: You write the code twice. Once for the compiler to execute and once for the developer/log file to read/record. Admittedly with detailed logging you can run into similar issues.</p>\n\n<p>You also said you don't want tracing while in fact at least your example code boils down to exactly that. So using an AOP framework might be the better alternative in your case. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-31T08:32:16.197", "Id": "40520", "ParentId": "3544", "Score": "12" } }, { "body": "<p>An alternative to resorting to AOP, could be to extract a <code>IFileReader</code> interface, and to <em>decorate</em> the <code>FileReader</code> with some <code>LoggingEnabledFileReader</code> - note that <code>sealed</code> explicitly <em>prevents</em> your code from being extensible, I'd drop it (un-sealing a class shouldn't be a breaking change). This solution is a bit of a merge of the other two answers.</p>\n\n<p>One thing though, as this <code>FileReader</code> is a utility class, I'd pass the filename to the <code>GetData</code> method, not as a single-use, private <code>readonly</code> field - your code will be more flexible and reusable that way.</p>\n\n<pre><code>public interface IFileReader\n{\n string GetData(string fileName);\n}\n</code></pre>\n\n<p>You keep the basic implementation to-the-point - note that I'm not throwing a <code>FileNotFoundException</code> and not bothering with verifying that the file exists - <code>File.ReadAllText</code> will throw that very same exception if the file can't be found, or it could throw some security exception if it's a permission issue. Basically, just let it throw whatever it throws:</p>\n\n<pre><code>public class FileReader : IFileReader\n{\n public string GetData(string fileName)\n {\n return File.ReadAllText(fileName);\n }\n}\n</code></pre>\n\n<p>Then you implement the decorator - I like <code>NLog</code>, and with <code>Ninject.Extensions.Logging</code> I can constructor-inject a logger in any class without even thinking about it:</p>\n\n<pre><code>public class LoggingEnabledFileReader : IFileReader\n{\n private readonly IFileReader _reader;\n private readonly ILogger _logger;\n\n public LoggingEnabledFileReader(IFileReader reader, ILogger logger)\n {\n _reader = reader; \n _logger = logger;\n }\n\n public string GetData(string fileName)\n {\n string result;\n try\n {\n _logger.Trace(string.Format(\"Reading data from '{0}'...\", fileName));\n result = _reader.GetData(fileName);\n }\n catch(Exception ex)\n {\n // we only need a warning-level log entry here\n _logger.WarnException(string.Format(\"Error with file '{0}'.\", fileName), ex);\n }\n\n return result;\n }\n}\n</code></pre>\n\n<p>This way you have a very straightforward <code>FileReader</code> class, and a very straightforward <code>LoggingEnabledFileReader</code> class, both implementing the same <code>IFileReader</code> interface. If <code>FileProcessor</code> took an <em>abstraction</em> as a dependency instead of a specific <em>implementation</em>...</p>\n\n<pre><code>private readonly IFileReader _fileReader;\n\npublic FileProcessor(IFileReader fileReader /*, ... */)\n</code></pre>\n\n<p>...then when a <code>FileProcessor</code> calls <code>_fileReader.GetData</code>, it has no clue whether the reader is logging-enabled or not, and it doesn't have to care either.</p>\n\n<p>The <code>FileReader</code> code is as simple as it gets, and the <code>LoggingEnabledFileReader</code> code is nothing more and nothing less than what it says it is; the logging concern is taken care of in an explicitly logging-concerned class.</p>\n\n<hr>\n\n<p>The <code>ExecutionContext</code> stuff looks over-engineered, over-complicated and overall over-the-top overboard with overusing lambdas and delegates and anonymous methods.</p>\n\n<p><em>KISS - Keep It Simple, Stupid</em>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-27T13:52:32.367", "Id": "45497", "ParentId": "3544", "Score": "3" } } ]
{ "AcceptedAnswerId": "40520", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T18:47:21.573", "Id": "3544", "Score": "7", "Tags": [ "c#" ], "Title": "Detailed logs and keeping code clean (not AOP)" }
3544
<p>What i'm doing</p> <p>I have a string with html information like this:</p> <pre><code>&lt;p&gt; &lt;span class="fieldText" fieldId="field-4"&gt;Some text&lt;/span&gt; this is a test&lt;/p&gt; </code></pre> <p>My goal in the method is to create a dictionary with this value:</p> <pre><code>**key** **value** field-4 Some text </code></pre> <p>This is the code that i'm using to accomplish my task:</p> <pre><code>public static Dictionary&lt;int,String&gt; getFields(String mensaje) { Dictionary&lt;int,String&gt; fields = new Dictionary&lt;int,string&gt;(); Match m = Regex.Match(mensaje, @"^(.*?&lt;span .*?&gt;(.*?)&lt;/span&gt;.*?)+$", RegexOptions.Singleline); for (int i = 0; i &lt; m.Groups[2].Captures.Count; i++) { String value = m.Groups[1].Captures[i].Value; Match m2 = Regex.Match(value, "^(.*?fieldId=.*?\"(.*?)\"&gt;.*?)+$", RegexOptions.Singleline); String fieldId = m2.Groups[2].Captures[0].Value; fieldId = fieldId.Replace("field-", String.Empty); fields.Add(int.Parse(fieldId),m.Groups[2].Captures[i].Value); } return fields; } </code></pre> <p>How can i improve my code?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T20:38:00.713", "Id": "5308", "Score": "4", "body": "What about your gold?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T21:50:15.203", "Id": "5314", "Score": "0", "body": "@Steven Jeuris, hi, what do you mean with about change my gold??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T21:52:00.613", "Id": "5315", "Score": "0", "body": "You used the word 'gold' in your question where I think you meant to say 'goal'. Steve is just teasing you a bit =)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T21:53:18.023", "Id": "5316", "Score": "0", "body": "_\"My gold in the method it's a dictionary with this value\"_, I'm guessing you mean something along the lines of _\"My goal is to extract the values into a dictionary as follows:\"_, but I'm not quite sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T22:05:13.543", "Id": "5317", "Score": "0", "body": "@Steven Jeuris thank's for you concern I'm reaylly appreciate" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-16T18:44:19.350", "Id": "9446", "Score": "0", "body": "Read this http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454" } ]
[ { "body": "<p>I know this is <em>Code Review</em> not <em>Rewrite My Code</em>, however I would suggest using a third-party Html parser (like the <a href=\"http://htmlagilitypack.codeplex.com/\">Html Agility Pack</a> for example) over regular expressions if that's an option. </p>\n\n<p>I realize you're doing very trivial parsing here, but from my personal experiences regular expressions grow to unmaintainable status quicker than anything in software development.</p>\n\n<p>If you were to use a Html parser, you could do something like this:</p>\n\n<pre><code>string htmlToParse = \"&lt;p&gt;&lt;span class=\\\"fieldText\\\" fieldId=\\\"field-4\\\"&gt;Some text&lt;/span&gt; this is a test&lt;/p&gt;&lt;p&gt;&lt;span class=\\\"fieldText\\\" fieldId=\\\"field-5\\\"&gt;Some more text&lt;/span&gt; this is another test&lt;/p&gt;\";\nconst string ElementToParse = \"span\";\nconst string IdField = \"FieldId\";\n\nHtmlDocument htmlDocument = new HtmlDocument();\nhtmlDocument.LoadHtml(htmlToParse);\n\nint fieldId = default( int );\n\nDictionary&lt;int,string&gt; fieldValuesTable = \n(\n from\n htmlNode in htmlDocument.DocumentNode.DescendantNodes()\n where\n htmlNode.Name.Equals( ElementToParse, StringComparison.InvariantCultureIgnoreCase )\n &amp;&amp;\n htmlNode.Attributes.Contains( IdField )\n let\n id = htmlNode.Attributes[ IdField ].Value\n where\n Int32.TryParse( id.Substring( id.IndexOf( \"-\" ) + 1 ), out fieldId ) // this is stil not ideal,\n select\n new { Id = fieldId, Text = htmlNode.InnerText }\n).ToDictionary( f =&gt; f.Id, f =&gt; f.Text );\n</code></pre>\n\n<p>You get the output:</p>\n\n<pre><code>4 : Some text\n5 : Some more text\n</code></pre>\n\n<p>IMHO, it's much cleaner and maintainable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T02:26:47.850", "Id": "3552", "ParentId": "3547", "Score": "9" } } ]
{ "AcceptedAnswerId": "3552", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-19T20:29:01.187", "Id": "3547", "Score": "4", "Tags": [ "c#", "html", "parsing" ], "Title": "Extracting text fields from <span> tags in an HTML message" }
3547
<p>I have never done anything functional before. These two functions are hideous to look at. II think the first step to do is extract the inner bits out and then map over my arrays. What else can I do to make this code a bit more functional?</p> <p><a href="https://github.com/dbousamra/scalacloth/blob/master/src/cloth/Cloth.scala">https://github.com/dbousamra/scalacloth/blob/master/src/cloth/Cloth.scala</a></p> <p>Specifically:</p> <pre><code> def verletIntegration() = { for (row &lt;- grid) { for (p &lt;- row) { if (p.stuck) p.setCurrentPos(p.getPreviousPos) var multiplyByTime = Tuple2(p.getForces * timestep * timestep, gravity * timestep * timestep) var minusPrevPos = Tuple2(p.getCurrentPos.getX - p.getPreviousPos.getX, p.getCurrentPos.getY - p.getPreviousPos.getY) var together = Tuple2(multiplyByTime._1 + minusPrevPos._1 , multiplyByTime._2 + minusPrevPos._2) p.setPreviousPos(p.getCurrentPos) p.setCurrentPos(new Position(p.getCurrentPos.getX + together._1, p.getCurrentPos.getY + together._2)) } } } def satisfyConstraints() = { for (row &lt;- grid) { for (p &lt;- row) { if (p.stuck) p.setCurrentPos(p.getPreviousPos) else { var neighbors = p.getNeighbors for (constraint &lt;- neighbors) { val c2 = grid(constraint.getX)(constraint.getY).getCurrentPos val c1 = p.getCurrentPos val delta = Tuple2(c2.getX - c1.getX, c2.getY - c1.getY) val deltaLength = math.sqrt(math.pow((c2.getX - c1.getX), 2) + math.pow((c2.getY - c1.getY),2)) val difference = (deltaLength - 1.0f) / deltaLength val dtemp = Tuple2(delta._1 * 0.5f * difference, delta._2 * 0.5f * difference) p.setCurrentPos(new Position(c1.getX + dtemp._1.floatValue, c1.getY + dtemp._2.floatValue)) grid(constraint.getX)(constraint.getY).setCurrentPos(new Position(c2.getX - dtemp._1.floatValue, c2.getY - dtemp._2.floatValue)) // } } } } } } </code></pre>
[]
[ { "body": "<p>There is an idea for scala for-loops: You can include the assignments into the production part:</p>\n\n<pre><code>for (constraint &lt;- neighbors) {\n val c2 = grid (constraint.getX) (constraint.getY).getCurrentPos\n val c1 = p.getCurrentPos\n val delta = Tuple2 (c2.getX - c1.getX, c2.getY - c1.getY)\n // ...\n</code></pre>\n\n<p>Then you don't need the keyword 'val':</p>\n\n<pre><code>for (constraint &lt;- neighbors;\n c2 = grid (constraint.getX) (constraint.getY).getCurrentPos\n c1 = p.getCurrentPos\n delta = Tuple2 (c2.getX - c1.getX, c2.getY - c1.getY)\n // ...\n</code></pre>\n\n<p>however - I expect a yield, following a for </p>\n\n<pre><code>val x = for (y)\n yield z\n</code></pre>\n\n<p>And methods which don't take parameters and don't return anything are either useless, or doing sideeffects. Too much vars are the same smell: mutable state. </p>\n\n<p>Try to reach your goal without mutable state, and you will find more functional patterns. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T05:28:27.207", "Id": "5328", "Score": "0", "body": "Hmm yeah these methods are void which is probably not good." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T05:13:09.133", "Id": "3554", "ParentId": "3553", "Score": "3" } }, { "body": "<pre><code>for (row &lt;- grid) {\n for (p &lt;- row) {\n\n//should be written as:\n\nfor(row &lt;- grid; p &lt;- row) {\n\n\nTuple2(\"bla\", 42)\n\n//should be written as\n\n(\"bla\", 42)\n</code></pre>\n\n<p>I don't really understand why you use tuples when you have already a class for doing exactly such kind of math, namely <code>Position</code>.</p>\n\n<p>The code could be more functional by using immutable case classes for <code>Position</code>s (but it depends on the problem if this is the right thing to do):</p>\n\n<pre><code>case class Position(x: Float, y: Float) {\n def -(that:Position) = Position(this.x - that.x, this.y - that.y)\n def +(that:Position) = Position(this.x + that.x, this.y + that.y)\n}\n</code></pre>\n\n<p>Then you can write things like <code>pos1 + pos2</code>. Note that you don't need the getter methods, as you can write <code>pos1.x</code>, and no setter methods, as you can write and <code>pos1.copy(x=12)</code>. The <code>new</code> isn't required any longer: <code>val p = Position(1, 3)</code>. </p>\n\n<p>How to proceed with the refactoring would depend on your decision if you keep <code>Position</code> as it is, or if you want to go with immutable <code>Position</code>s.</p>\n\n<p><strong>[Edit]</strong></p>\n\n<p>Here is how I would refactor it:</p>\n\n<p>Run.scala:</p>\n\n<pre><code>package cloth\n\nobject Run {\n\n def main(args: Array[String]): Unit = {\n\n import javax.swing.JFrame\n\n val test = new Screen\n val frame = new JFrame(\"scalacloth\")\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE)\n frame.setPreferredSize(new java.awt.Dimension(640, 720))\n frame.getContentPane().add(test)\n test.init\n frame.pack\n frame.setVisible(true)\n }\n\n}\n\nimport processing.core._\n\nclass Screen extends PApplet {\n\n val cloth = new Cloth(\n rows = 20, \n columns = 20, \n gravity = 0.001f,\n timestep = 0.8f,\n fixedParticles = List(Coordinate(19,0))\n )\n\n override def setup() {\n cloth.createGrid()\n size(640, 720)\n background(255)\n smooth()\n noStroke()\n fill(0, 102)\n }\n\n override def draw() {\n background(255)\n fill(255)\n stroke(0)\n\n def drawLines(particle: Particle):Unit = particle.neighbors.foreach { n =&gt;\n line(particle.currentPos.x * 20 + 20, particle.currentPos.y * 20 + 20,\n cloth.grid(n.x)(n.y).currentPos.x * 20 + 20, cloth.grid(n.x)(n.y).currentPos.y* 20 + 20)\n }\n\n for(column &lt;- cloth.grid; particle &lt;- column) drawLines(particle)\n cloth.verletIntegration\n cloth.satisfyConstraints\n }\n}\n</code></pre>\n\n<p>Position.scala:</p>\n\n<pre><code>package cloth\n\ncase class Position(x: Float, y: Float) {\n def -(that:Position) = Position(this.x - that.x, this.y - that.y)\n def +(that:Position) = Position(this.x + that.x, this.y + that.y)\n def *(scalar:Float) = Position(this.x * scalar, this.y * scalar)\n def length = math.sqrt(x*x + y*y).toFloat\n}\n</code></pre>\n\n<p>Particle.scala:</p>\n\n<pre><code>package cloth\n\nclass Particle(\n var currentPos: Position, \n var previousPos: Position, \n val gridIndex: Coordinate, \n val restLength: Float,\n val neighbors: Array[Coordinate],\n var stuck: Boolean \n ) {\n\n val forces = 0.0f\n}\n</code></pre>\n\n<p>... and Cloth.scala:</p>\n\n<pre><code>package cloth\n\nimport scala.collection\n\ncase class Coordinate(x: Int, y: Int)\n\nclass Cloth(\n val rows: Int, \n val columns: Int, \n var gravity: Float,\n val timestep: Float,\n val fixedParticles: List[Coordinate]\n) {\n\n val grid = new Array[Array[Particle]](rows, columns)\n\n def createGrid(): Unit = for (x &lt;- 0 until rows; y &lt;- 0 until columns) {\n val coord = Coordinate(x, y)\n val pos = Position(x, y)\n grid(x)(y) = new Particle(pos, pos, coord, 1.0f, findNeighbors(coord),\n fixedParticles.contains(coord))\n }\n\n def findNeighbors(coord: Coordinate): Array[Coordinate] = Array(\n coord.copy(x = coord.x - 1),\n coord.copy(y = coord.y - 1),\n coord.copy(x = coord.x + 1),\n coord.copy(y = coord.y + 1)\n ).filter(isOccupied(_))\n\n def isOccupied(coord: Coordinate): Boolean = \n (0 &lt;= coord.x &amp;&amp; coord.x &lt; rows &amp;&amp; \n 0 &lt;= coord.y &amp;&amp; coord.y &lt; columns)\n\n def verletIntegration(): Unit = for (row &lt;- grid; p &lt;- row) \n p.currentPos = \n if (p.stuck) p.previousPos else {\n val multiplyByTime = Position(p.forces * timestep * timestep, gravity * timestep * timestep)\n val together = multiplyByTime + p.currentPos - p.previousPos\n p.previousPos = p.currentPos\n p.currentPos + together\n }\n\n def satisfyConstraints() {\n\n def calculateConstraint(constraint: Coordinate, p: Particle) {\n val c2 = grid(constraint.x)(constraint.y).currentPos\n val c1 = p.currentPos\n val delta = c2 - c1\n val difference = 0.5f * (1.0f - 1.0f / delta.length)\n val dtemp = delta * difference\n p.currentPos = c1 + dtemp\n grid(constraint.x)(constraint.y).currentPos = c2 - dtemp\n }\n\n for(row &lt;- grid; p &lt;- row) \n if (p.stuck) p.currentPos = p.previousPos\n else p.neighbors.foreach(calculateConstraint(_, p))\n }\n\n}\n</code></pre>\n\n<p>Hope that helps...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T07:27:26.477", "Id": "5330", "Score": "0", "body": "Great post! Yeah I am not sure why I didn't use the position class. I was tired (well thats my excuse :P)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T09:46:55.803", "Id": "5332", "Score": "0", "body": "Hmm my scala version borks when i try to not use \"new\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T10:06:26.550", "Id": "5334", "Score": "0", "body": "That should definitely work: When you write `case class`, you don't need `new`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T16:36:27.720", "Id": "5356", "Score": "0", "body": "@Dominic: You have 2 ways to say 'Great post!', no. 1 is upvoting the answer by hitting the up-arrow ^ at the top of the answer with your mouse, no. 2 is accepting it as the best answer, by marking the check mark." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T18:04:02.290", "Id": "5359", "Score": "0", "body": "@Dominic Bou-Samra: I updated my answer. Cool application, by the way..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T21:34:58.353", "Id": "5363", "Score": "0", "body": "Thanks! I did some refactoring earlier, so you can see my changes on github. Ended up doing similar things, though I like how you've done things more." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T06:18:24.790", "Id": "3556", "ParentId": "3553", "Score": "8" } }, { "body": "<p>Ooh, Processing with Scala! Good combination...</p>\n\n<p>I took the excellent rewriting of your code by Landei as a base for my own experimentations...\nI fixed a deprecation warning (Array initialization), made some more variables immutable, improved the Processing side (don't forget: size() must be the first call of setup())... then I went crazy with refactoring, changing names to fit my understanding of the algorithm, etc.</p>\n\n<p>As I am a Scala newbie myself, I found it was a good exercise, but it still has Unit functions...<br>\nMaybe you might be interested to see my version of your code:<br>\n<a href=\"http://bazaar.launchpad.net/~philho/+junk/Scala/files/head:/_SmallPrograms/ClothSimulation/\" rel=\"nofollow\">http://bazaar.launchpad.net/~philho/+junk/Scala/files/head:/_SmallPrograms/ClothSimulation/</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T22:19:53.867", "Id": "5434", "Score": "0", "body": "Congratultions! I find it a great way to learn a language, because once you understand the theory, it's not a hard program, but 10x more interesting then other things. Wow your code is a lot nicer then mine, and far simpler. I espeically like how you've simplified the verlet method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T22:22:05.783", "Id": "5435", "Score": "0", "body": "I've started on an implementation of a gameboy emulator in scala. Maybe you want to take a look :P (feel free to commit if you want). It's another good exercises that's hard enough to flex Scala's power (I hope) but easy enough to knock over in a week." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T15:33:00.323", "Id": "3597", "ParentId": "3553", "Score": "1" } } ]
{ "AcceptedAnswerId": "3556", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T04:42:25.380", "Id": "3553", "Score": "6", "Tags": [ "scala" ], "Title": "Decided to learn Scala. Here's an attempt at a Cloth simulation" }
3553
<p>I've created this code to send a response to Flash which can be handled with AS2/AS3:</p> <pre><code>&lt;?php /** * Basic server-side API controls for Flash-PHP communication * @author Marty Wallace * @version 1.0.2 */ class API { // MySQL private $con; private $sql_hostname = ''; private $sql_username = ''; private $sql_password = ''; private $sql_database = ''; // Properties public $response; /** * Constructor */ public function __construct() { // Attempt connection $this-&gt;con = mysql_connect( $this-&gt;sql_hostname, $this-&gt;sql_username, $this-&gt;sql_password ); // Connection could not be established if(!$this-&gt;con) { $this-&gt;response = array( "status" =&gt; "no_connection", "message" =&gt; "Could not connect to MySQL, try again later." ); $this-&gt;respond(); } // Select database mysql_select_db($this-&gt;sql_database); } /** * Send response back to Flash */ public function respond() { $ar = array(); foreach($this-&gt;response as $key =&gt; $value) array_push($ar, $key . "=" . $value); die(implode("&amp;", $ar)); } } ?&gt; </code></pre> <p>I'm not that great with PHP and the <code>respond()</code> function seems like it could be written a little better.. Any suggestions?</p>
[]
[ { "body": "<p>I have used PHP for a few years now, and here are my suggestions:</p>\n\n<p><code>array_push()</code> can be used to add multiple values into an array at once, but in your case, your pushing only one value in at a time which means you can use:</p>\n\n<p><code>$ar[] = $key . \"=\" . $value</code></p>\n\n<p>This should also speed up your code a little( <a href=\"https://stackoverflow.com/a/559859/1076164\">What's better to use in PHP $array[] = $value or array_push($array, $value)?</a>).</p>\n\n<p><code>die()</code> is normally used when there is an error. It spits out a message to the user. If you are using this code to just connect to a MySQL database then change <code>die(implode(\"&amp;\", $ar));</code> to <code>echo(implode(\"&amp;\", $ar));</code></p>\n\n<p>But honestly, you should be able to take out the <code>respond()</code> function if you are only using it to send an array to flash.</p>\n\n<pre><code> // Connection could not be established\n if(!$this-&gt;con)\n {\n $this-&gt;response = array(\n \"status\" =&gt; \"no_connection\",\n \"message\" =&gt; \"Could not connect to MySQL, try again later.\"\n );\n\n echo(implode(\"&amp;\", $this-&gt;response));\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-05T19:39:17.447", "Id": "7498", "ParentId": "3555", "Score": "3" } }, { "body": "<p>Firstly, you don't appear to be using the database, however for my answer I will assume that you use it elsewhere in the class.</p>\n\n<p>With OOP it is good to use Dependency Injection. Dependency injection helps to ensure that the objects you create are only responsible for what they need to be.</p>\n\n<p>Note how your API object is currently responsible for creating a connection to a database. Lets look at the Pros and Cons for this:</p>\n\n<ul>\n<li><strong><code>Pros</code></strong> - None that I can see (sorry), although you could say that everything is done in the one place for the API object (I see this as a disadvantage).</li>\n<li><strong><code>Cons</code></strong> - Tightly coupled to mysql database, API object has responsibility for database actions, using mysql_* which is now softly deprecated, code duplication for database actions, password connection details are spread throughout the classes rather than being in one place. </li>\n</ul>\n\n<p>Here is how your code would look using Dependency Injection:</p>\n\n<pre><code>class API\n{\n protected $db;\n\n /**\n * Constructor\n */\n public function __construct($db)\n {\n $this-&gt;db = $db;\n }\n\n /**\n * Send response back to Flash\n */\n public function respond()\n {\n // This is rewritten as Chillie suggested.\n $ar = array();\n foreach($this-&gt;response as $key =&gt; $value)\n $ar[] = $key . \"=\" . $value;\n\n echo implode(\"&amp;\", $ar);\n }\n}\n</code></pre>\n\n<p>I would handle database connection errors at the usage level:</p>\n\n<pre><code>try\n{\n $FlashResponder = new API(new PDO($dsn, $user, $password));\n}\ncatch (Exception $ex)\n{\n echo \"status=no_connection&amp;message=Could not connect to database, try again later.\";\n\n}\n</code></pre>\n\n<p>Dependency Injection now allows any database to be used by the API object. When the database connection details change or a new database needs to be connected to the values are no longer hardcoded into the API class making maintenance easier. The code for the API class is also simpler as the database code was making it harder to read and understand.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-05T03:47:58.190", "Id": "10635", "ParentId": "3555", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T05:17:15.983", "Id": "3555", "Score": "3", "Tags": [ "php" ], "Title": "PHP Class for sending a response to Flash" }
3555
<p>I want to keep things DRY, so I'm trying to figure out: Is it possible to remove repetitive parameters and code from ASP.NET MVC Controller actions? eg given these Actions:</p> <pre><code>public ActionResult List(string key, string signature) { GetSignature(key); // etc } public ActionResult Add(string key, string signature) { GetSignature(key); // etc } public ActionResult Update(string key, int id, string signature) { GetSignature(key, id.ToString()); // etc} public ActionResult Delete(string key, int id, string signature) { GetSignature(key, id.ToString()); // etc} public ActionResult Action1(string key, string x, string y, string z, string signature) { GetSignature(key, x, y, z);//etc} </code></pre> <p>Is there any way to refactor out the repetitive <code>key</code> and <code>signature</code> parameters, and the call to <code>GetSignature()</code>? </p> <p>There are two obstacles to refactoring I can think of:</p> <ol> <li>It's MVC so the Actions are the first port of call - it may not be possible to have a refactored method that is called before the Action.</li> <li>The GetSignature() method is called using all of the Action's parameters, so it may be difficult to refactor.</li> </ol>
[]
[ { "body": "<p>You could create a factory to create ActionResults, and make the key and signature members of the factory. Unless you are reusing the same key and signature a lot of the time, it's likely to look like:</p>\n\n<pre><code>myList = new ActionResultsFactory(key, signature).List();\n</code></pre>\n\n<p>Which hardly seems better than</p>\n\n<pre><code>myList = new List(key, signature);\n</code></pre>\n\n<p>but maybe it has value in some situations.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T11:44:19.997", "Id": "3559", "ParentId": "3557", "Score": "0" } }, { "body": "<p>Of course, my suggestion would be to encapsulate your properties in a class:</p>\n\n<pre><code>public class MySignatureThing\n{\n public string Key {get;set;}\n public int Id {get;set;}\n public string Signature {get;set;}\n public string X {get;set;}\n public string Y {get;set;}\n public string Z {get;set;}\n}\n</code></pre>\n\n<p>Then your action methods change to this:</p>\n\n<pre><code>public void Add(MySignatureThing thing) { GenerateSignature(thing); }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T14:12:59.843", "Id": "3562", "ParentId": "3557", "Score": "1" } }, { "body": "<p>I like the direction Scott started but would recommend to take it another layer down so that the GenerateSignature method does not have to do discovery with the thing object (Do I have an Id or do I have string X/Y/Z or do I only have Key/Signature, etc).</p>\n\n<pre><code>public class MySignatureCreateRead\n{\n public string Key { get; set; }\n public string Signature { get; set; }\n}\n\npublic class MySignatureUpdateDelete : MySignatureCreateRead\n{\n public int Id { get; set; }\n}\n\npublic class MySignatureAction : MySignatureCreateRead\n{\n public string X { get; set; }\n public string Y { get; set; }\n public string Z { get; set; }\n}\n</code></pre>\n\n<p>Which puts the ActionResults like:</p>\n\n<pre><code>public ActionResult List(MySignatureCreateRead signature) { GetSignature(signature); /* etc */ }\npublic ActionResult Add(MySignatureCreateRead signature) { GetSignature(signature); /* etc */ }\npublic ActionResult Update(MySignatureUpdateDelete signature) { GetSignature(signature); /* etc */ }\npublic ActionResult Delete(MySignatureUpdateDelete signature) { GetSignature(signature); /* etc */ }\npublic ActionResult Action1(MySignatureAction signature) { GetSignature(signature); /* etc */ }\n</code></pre>\n\n<p>This also gives you objects to strongly bind views to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-12T02:02:42.077", "Id": "4048", "ParentId": "3557", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T11:08:20.530", "Id": "3557", "Score": "2", "Tags": [ "c#", "asp.net-mvc-2" ], "Title": "Removing repetitive code in ASP.NET MVC Controller actions?" }
3557
<p>I'm developing an application using ASP.NET MVC 3 and Entity Framework 4.1. In that application I have a lot of paged lists. Users can filter and sort these lists.</p> <p>This results in code like the one below. I'm not really happy with this code. Is there a better way to do the filtering and sorting with Entity Framework?</p> <p>Some of you might suggest putting that code into a service class and not in the controller, but that would just move the ugly code somewhere else. Instead of ugly code in a controller, I'd end up with ugly code in a service.</p> <pre><code>public UsersController : Controller { private const int PageSize = 25; public ActionResult Index(int page = 1, string sort = "", UserSearchViewModel search) { // Get an IQueryable&lt;UserListItem&gt; var users = from user in context.Users select new UserListItem { UserId = user.UserId, Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, UsertypeId = user.UsertypeId, UsertypeDescription = users.Usertype.Description, UsertypeSortingOrder = users.Usertype.SortingOrder }; // Filter on fields when needed if (!String.IsNullOrWhiteSpace(search.Name)) users = users.Where(u =&gt; u.FirstName.Contains(search.Name) || u.LastName.Contains(search.Name)); if (!String.IsNullOrWhiteSpace(search.Email)) users = users.Where(u =&gt; u.Email.Contains(search.Email)); if (search.UsertypeId.HasValue) users = users.Where(u =&gt; u.UsertypeId == search.UsertypeId.Value); // Calculate the number of pages based on the filtering int filteredCount = users.Count(); int totalPages = Convert.ToInt32(Math.Ceiling((decimal)filteredCount / (decimal)PageSize)); // Sort the items switch(sort.ToLower()) { default: users = users.OrderBy(u =&gt; u.FirstName).ThenBy(u =&gt; u.LastName); break; case "namedesc": users = users.OrderByDescending(u =&gt; u.FirstName).ThenByDescending(u =&gt; u.LastName); break; case "emailasc": users = users.OrderBy(u =&gt; u.Email); break; case "emaildesc": users = users.OrderByDescending(u =&gt; u.Email); break; case "typeasc": users = users.OrderBy(u =&gt; u.UsertypeSortingOrder); break; case "typedesc": users = users.OrderByDescending(u =&gt; u.UsertypeSortingOrder); break; } // Apply the paging users = users.Skip(PageSize * (page - 1)).Take(PageSize); var viewModel = new UsersIndexViewModel { Users = users.ToList(), TotalPages = totalPages }; return View(viewModel); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T14:16:41.307", "Id": "5393", "Score": "0", "body": "I am not sure about what your actual concern is. The code is readable and at least a first pass looks like it should work as expected. It is easy to follow. Sometimes the logic requires this type of complexity but to me its looks pretty clean. I could write the query as a single line but runtime effectively will be the same but it would be much harder to understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T14:19:22.313", "Id": "5394", "Score": "0", "body": "I was hoping there was some cleaner/shorter way to do the filtering (the three if-statements in this case) and the sorting (the switch-statement). In this example, I'm only filtering and sorting on 3 fields, but I also have list where I needs 6 fields or more. That quickly leads to a lot of code and it looks ugly. How would you write it on a single line and where does my logic suck? :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T14:21:29.060", "Id": "5395", "Score": "0", "body": "I could write the entire line as a single line of code. That would not make it any better just shorter. Code golf is fine for honing skills but making readable, and maintainable code is far more valuable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T14:25:46.717", "Id": "5396", "Score": "0", "body": "And I edited my first comment. Your logic doesnt suck. Sometimes the logic gets complex which sucks. As I said I would be quite happy if i was handed this to maintain. By contrast as a single command line would include many compares that replace the if statements. The end result query that gets executed would probably be the same or maybe even worse. But it would be much harder to follow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T14:33:18.953", "Id": "5397", "Score": "0", "body": "Oh, OK, I understand. I agree that the code is easy to read and understand, but it's kind of a drag to _write_ it :-) I was hoping for some improvement in that department without sacrificing the readability." } ]
[ { "body": "<p>I've written a TON of code like this as well... </p>\n\n<p>I've read about \"dynamic LINQ\" but that's not going to address the issue when you need to orderby().thenby(). The only things I've done differently is using enums for field names and sort directions which works great in my WebForms apps using ViewState but I'm not sure how I'd maintain the \"sort state\" in MVC ;)</p>\n\n<p>If your table gets large you may consider server-side paging in stored procedures rather than bringing back the whole database then sorting it locally, but that's another topic :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T08:16:54.373", "Id": "5376", "Score": "4", "body": "Oh, the deferred execution of Entity Framework ensures the paging is done server side. In fact a call to the database is only made when I do `users.ToList()`. (A call is also made for `users.Count()`)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T21:51:38.380", "Id": "3572", "ParentId": "3560", "Score": "0" } }, { "body": "<p>I'd consider using EntitySQL as a replace to LINQ to Entities. With EntitySQL you would concatenate the sort field name with a statement. Although there is a big disadvantage of no compile time check.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-20T14:57:04.120", "Id": "4260", "ParentId": "3560", "Score": "1" } }, { "body": "<p>I know this is old, but thought it may be helpful for anyone reading this. If you want to clean up the code, you can always refactor it.. something like this is more readable than the original:</p>\n\n<pre><code>public UsersController : Controller\n{\n private const int PageSize = 25;\n\n public ActionResult Index(int page = 1, string sort = \"\", UserSearchViewModel search)\n {\n var users = GetUsers(search, sort);\n var totalPages = GetTotalPages(users);\n\n var viewModel = new UsersIndexViewModel\n {\n Users = users.Skip(PageSize * (page - 1)).Take(PageSize).ToList(),\n TotalPages = totalPages\n };\n\n return View(viewModel);\n }\n\n private UserListItem GetUsers(UserSearchViewModel search, string sort)\n {\n var users = from user in context.Users\n select new UserListItem\n {\n UserId = user.UserId,\n Email = user.Email,\n FirstName = user.FirstName,\n LastName = user.LastName,\n UsertypeId = user.UsertypeId,\n UsertypeDescription = users.Usertype.Description,\n UsertypeSortingOrder = users.Usertype.SortingOrder\n };\n\n users = FilterUsers(users, search);\n users = SortUsers(users, sort);\n\n return users;\n }\n\n private UserListItem SortUsers(object users, string sort)\n {\n switch (sort.ToLower())\n {\n default:\n users = users.OrderBy(u =&gt; u.FirstName).ThenBy(u =&gt; u.LastName);\n break;\n case \"namedesc\":\n users = users.OrderByDescending(u =&gt; u.FirstName).ThenByDescending(u =&gt; u.LastName);\n break;\n case \"emailasc\":\n users = users.OrderBy(u =&gt; u.Email);\n break;\n case \"emaildesc\":\n users = users.OrderByDescending(u =&gt; u.Email);\n break;\n case \"typeasc\":\n users = users.OrderBy(u =&gt; u.UsertypeSortingOrder);\n break;\n case \"typedesc\":\n users = users.OrderByDescending(u =&gt; u.UsertypeSortingOrder);\n break;\n }\n return users;\n }\n\n private UserListItem FilterUsers(object users, UserSearchViewModel search)\n {\n if (!String.IsNullOrWhiteSpace(search.Name)) users = users.Where(u =&gt; u.FirstName.Contains(search.Name)\n || u.LastName.Contains(search.Name));\n if (!String.IsNullOrWhiteSpace(search.Email)) users = users.Where(u =&gt; u.Email.Contains(search.Email));\n if (search.UsertypeId.HasValue) users = users.Where(u =&gt; u.UsertypeId == search.UsertypeId.Value);\n return users;\n }\n\n private int GetTotalPages(UserListItem users)\n {\n var filteredCount = users.Count();\n return Convert.ToInt32(Math.Ceiling((decimal)filteredCount / (decimal)PageSize));\n }\n}\n</code></pre>\n\n<p>You can then refactor this further by moving these methods into a service class if you want to.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-19T17:06:52.497", "Id": "4910", "ParentId": "3560", "Score": "16" } }, { "body": "<blockquote>\n <p><strong>EDIT:</strong> I apologize from my earlier sample that didn't quite compile. I've fixed it and added a more complete example.</p>\n</blockquote>\n\n<p>You could associate each condition with a <a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"noreferrer\">strategy</a> for changing the query. Each strategy (called <code>SearchFieldMutator</code> in this example) will hold two things:</p>\n\n<ol>\n<li>A way to decide if to apply the strategy.</li>\n<li>The strategy itself.</li>\n</ol>\n\n<p>The first part is a delegate (of type <code>Predicate&lt;TSearch&gt;</code>) that returns <code>true</code> or <code>false</code> based on the data in the <code>UserSearchViewModel</code> (or any other type, since it only defines a generic type <code>TSearch</code>). If it return <code>true</code>, the strategy is applied. If it returns <code>false</code>, it's not applied. This is the type of the delegate:</p>\n\n<pre><code>Predicate&lt;TSearch&gt;\n</code></pre>\n\n<p><sup>(it could also have been written as <code>Func&lt;TSearch, bool&gt;</code>)</sup></p>\n\n<p>The second part is the strategy itself. It is supposed to 'mutate' the query by applying a LINQ operator to it, but really just returns a new query with the added operator, and the caller of it should discard the old query and keep the new one. So it's not really mutation, but it has the same effect. I've created a new delegate type for it, so its usage is clear:</p>\n\n<pre><code>public delegate IQueryable&lt;TItem&gt; QueryMutator&lt;TItem, TSearch&gt;(IQueryable&lt;TItem&gt; items, TSearch search);\n</code></pre>\n\n<blockquote>\n <p><strong>NOTE:</strong> I've defined both the item type and the search data as generic types (as <code>TItem</code> and <code>TSearch</code>, respectively) so this code is usable in multiple locations in your code. But if this is confusing, you can remove the generics completely, and replace any <code>TItem</code> with <code>UserListItem</code> and any <code>TSearch</code> with <code>UserSearchViewModel</code>.</p>\n</blockquote>\n\n<p>Now that we have defined the two types of the strategy, we can create a class that holds them both, and also does the (simulated) mutation:</p>\n\n<pre><code>public class SearchFieldMutator&lt;TItem, TSearch&gt;\n{\n public Predicate&lt;TSearch&gt; Condition { get; set; }\n public QueryMutator&lt;TItem, TSearch&gt; Mutator { get; set; }\n\n public SearchFieldMutator(Predicate&lt;TSearch&gt; condition, QueryMutator&lt;TItem, TSearch&gt; mutator)\n {\n Condition = condition;\n Mutator = mutator;\n }\n\n public IQueryable&lt;TItem&gt; Apply(TSearch search, IQueryable&lt;TItem&gt; query)\n {\n return Condition(search) ? Mutator(query, search) : query;\n }\n}\n</code></pre>\n\n<p>This class holds both the condition and the strategy itself, and by using the <code>Apply()</code> method, we can easily apply it to a query if the condition is met.</p>\n\n<p>We can now go create out list of strategies. We'll define some place to hold them (on one of your classes), since they only have to be created once (they are stateless after all):</p>\n\n<pre><code>List&lt;SearchFieldMutator&lt;UserListItem, UserSearchViewModel&gt;&gt; SearchFieldMutators { get; set; }\n</code></pre>\n\n<p>We'll then populate the list:</p>\n\n<pre><code>SearchFieldMutators = new List&lt;SearchFieldMutator&lt;UserListItem, UserSearchViewModel&gt;&gt;\n{\n new SearchFieldMutator&lt;UserListItem, UserSearchViewModel&gt;(search =&gt; !string.IsNullOrWhiteSpace(search.Name), (users, search) =&gt; users.Where(u =&gt; u.FirstName.Contains(search.Name) || u.LastName.Contains(search.Name))),\n new SearchFieldMutator&lt;UserListItem, UserSearchViewModel&gt;(search =&gt; !string.IsNullOrWhiteSpace(search.Email), (users, search) =&gt; users.Where(u =&gt; u.Email.Contains(search.Email))),\n new SearchFieldMutator&lt;UserListItem, UserSearchViewModel&gt;(search =&gt; search.UsertypeId.HasValue, (users, search) =&gt; users.Where(u =&gt; u.UsertypeId == search.UsertypeId.Value)),\n new SearchFieldMutator&lt;UserListItem, UserSearchViewModel&gt;(search =&gt; search.CurrentSort.ToLower() == \"namedesc\", (users, search) =&gt; users.OrderByDescending(u =&gt; u.FirstName).ThenByDescending(u =&gt; u.LastName)),\n new SearchFieldMutator&lt;UserListItem, UserSearchViewModel&gt;(search =&gt; search.CurrentSort.ToLower() == \"emailasc\", (users, search) =&gt; users.OrderBy(u =&gt; u.Email)),\n // etc...\n};\n</code></pre>\n\n<p>We can then try to run it on a query. Instead of an actual Entity Framework query, I'm going to use a simply array of <code>UserListItem</code>s and add a <code>.ToQueryable()</code> on to it. It will work the same if you replace it with an actual database query. I'm also going to create a simple search, for the sake of the example:</p>\n\n<pre><code>// This is a mock EF query.\nvar usersQuery = new[]\n{\n new UserListItem { FirstName = \"Allon\", LastName = \"Guralnek\", Email = null, UsertypeId = 7 },\n new UserListItem { FirstName = \"Kristof\", LastName = \"Claes\", Email = \"whoknows@example.com\", UsertypeId = null },\n new UserListItem { FirstName = \"Tugboat\", LastName = \"Captain\", Email = \"tugboat@ahoy.yarr\", UsertypeId = 12 },\n new UserListItem { FirstName = \"kiev\", LastName = null, Email = null, UsertypeId = 7 },\n}.AsQueryable();\n\nvar searchModel = new UserSearchViewModel { UsertypeId = 7, CurrentSort = \"NameDESC\" };\n</code></pre>\n\n<p>The following actually does all the work, it changes query inside the <code>usersQuery</code> variable to the one specified by all the search strategies:</p>\n\n<pre><code>foreach (var searchFieldMutator in SearchFieldMutators)\n usersQuery = searchFieldMutator.Apply(searchModel, usersQuery);\n</code></pre>\n\n<p>That's it! This is the result of the query: </p>\n\n<p><a href=\"https://i.stack.imgur.com/4ZYmq.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4ZYmq.png\" alt=\"Result of query\"></a></p>\n\n<p>You can try running it yourself. Here's a <a href=\"http://www.linqpad.net/\" rel=\"noreferrer\">LINQPad</a> query for you to play around with:</p>\n\n<p><a href=\"http://share.linqpad.net/7bud7o.linq\" rel=\"noreferrer\">http://share.linqpad.net/7bud7o.linq</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-24T17:01:37.357", "Id": "152784", "Score": "2", "body": "This should be the accepted answer. However the posted code doesn't compile which is probably why it doesn't have more votes and is likely a barrier to many due to the generics involved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-31T17:36:26.647", "Id": "187598", "Score": "0", "body": "anyone successfully implement this approach? This line bombs delegate IQueryable<T, in T1> QueryMutator<T>(IQueryable<T> item, T1 condition);\nCS1960 C# Invalid variance modifier. Only interface and delegate type parameters can be specified as variant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-11T08:04:10.297", "Id": "196501", "Score": "1", "body": "@kiev: I've fixed the code so it complies (plus a working sample). I've also added a more detailed explanation." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-08-22T15:00:35.760", "Id": "440514", "Score": "1", "body": "This the most elegant solution I have ever seen. I wish I could upvote it thousands of times." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-21T18:19:04.997", "Id": "5506", "ParentId": "3560", "Score": "27" } }, { "body": "<p>If you used the ADO.NET Entity Framework Generator for EF 4.1, you can write your code like below.</p>\n\n<p>the way is to construct a sort string. \" order by personname asc\" will be written like below\n\"it.personname asc\" - the \"<strong>it</strong>\" is used internally by EF.</p>\n\n<pre><code>string sortfield = \"personname\";\nstring sortdir= \"asc\";\n\nIQueryable&lt;vw_MyView&gt; liststore= context.vw_MyView\n .OrderBy(\"it.\" + sortfield + \" \" + sortdir)\n .Where(c =&gt; c.IsActive == true\n &amp;&amp; c.FundGroupId == fundGroupId\n &amp;&amp; c.Type == 1\n );\n</code></pre>\n\n<p>I've used this only for the ADO.NET EF generator. DBcontext for EF 4.3.1 do not support this feature.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T07:10:37.027", "Id": "13773", "ParentId": "3560", "Score": "2" } }, { "body": "<p>Sorting functionality may be implemented in more declarative syntax. First declare associative dictionary as private member of the class.</p>\n\n<pre><code> private Dictionary&lt;string, Func&lt;IQueryable&lt;UserListItem&gt;, IQueryable&lt;UserListItem&gt;&gt;&gt; _sortAssoc = new Dictionary&lt;string, Func&lt;IQueryable&lt;UserListItem&gt;, IQueryable&lt;UserListItem&gt;&gt;&gt;(StringComparer.OrdinalIgnoreCase)\n {\n { default(string), users =&gt; users.OrderBy(u =&gt; u.FirstName).ThenBy(u =&gt; u.LastName)},\n { \"namedesc\", users =&gt; users.OrderByDescending(u =&gt; u.FirstName).ThenByDescending(u =&gt; u.LastName)} ,\n { \"emailasc\", users =&gt; users.OrderBy(u =&gt; u.Email) },\n { \"emaildesc\", users =&gt; users.OrderByDescending(u =&gt; u.Email) },\n //... \n };\n</code></pre>\n\n<p>then you can call suitable sorting method this way:</p>\n\n<pre><code>users = _sortAssoc.ContainsKey(sort) ? _sortAssoc[sort](users) : _sortAssoc[default(string)](users);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T08:43:24.530", "Id": "18588", "ParentId": "3560", "Score": "6" } }, { "body": "<p>Another option:</p>\n\n<ul>\n<li>Create a domain object that takes the parameters needed for the <strong><em>filter</em></strong></li>\n<li>Create a function on the repository that takes that <strong><em>filter</em></strong> domain object and within that repository function handle the filtering/sorting/paging</li>\n<li>Call that function from your upper layers (whether it is the business layer/service or MVC controller) passing in the <strong><em>filter</em></strong> domain object</li>\n</ul>\n\n<p>Advantages: </p>\n\n<ol>\n<li>If you ever want to enlarge the filter you need only add to the '<strong><em>filter</em></strong>' domain object</li>\n<li>AND modify the repository to handle that new <strong><em>filter</em></strong></li>\n<li>Everywhere else you want to get that set of data, the caller only needs to populate the <strong><em>filter</em></strong> as needed in that situation</li>\n</ol>\n\n<p>Anyhow for what it's worth, that has proved to be the best way for handling this situation with scalability in mind as well as reducing chance of duplication of code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-25T08:13:31.713", "Id": "91692", "ParentId": "3560", "Score": "1" } } ]
{ "AcceptedAnswerId": "4910", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T12:40:05.767", "Id": "3560", "Score": "37", "Tags": [ "c#", "asp.net-mvc-3", "entity-framework" ], "Title": "Dynamic filtering and sorting with Entity Framework" }
3560
<p>this is a basic PHP auth class I've put together for use with simple sites I do from time to time which don't warrant using a framework. I'm wondering if i'm separating out responsibilities all that well, even at this early stage! For example, I'm not sure where I should be filtering user input with mysql_real_escape_string, and I don't know if I should be passing the DB into the constructor, but then I need it to be able to run my auth check. </p> <p>Anyway, any pointers would be great thanks!</p> <pre><code>class Auth { protected $db; /** * Auth::__construct() * * @return */ public function __construct($db = null) { $this-&gt;db = $db; } /** * Auth::login() * * @param mixed $username * @param mixed $password * @return */ public function login($username, $password) { $query = $this-&gt;db-&gt;query("SELECT username, password FROM users WHERE username = '".mysql_real_escape_string($username)."' AND password = '".self::crypt_pass(mysql_real_escape_string($password))."' "); $result = $this-&gt;db-&gt;fetch_array($query); if (count($result) == 0) { return FALSE; } else { //set session variable Session::instance()-&gt;set('logged_in', TRUE); return TRUE; } } /** * Auth::logout() * * @return */ public function logout() { //set session variable return Session::instance()-&gt;delete('logged_in'); } private function crypt_pass($pass) { if (CRYPT_BLOWFISH == 1) { $salt = SHA1('acssalty457'); $blowfish_salt = "\$2a\$07\$".substr($salt, 0, CRYPT_SALT_LENGTH); return crypt($pass, $blowfish_salt); } } } </code></pre>
[]
[ { "body": "<p>Not sure what version of php they implemented this in, but you don't need to use the <code>__construct</code>, you can use <code>Auth</code> instead like many other OOP langs. </p>\n\n<p>You should check if <code>$this-&gt;db</code> is <code>null</code> before you do any <code>sql</code> work, otherwise <code>login</code> will fail with errors when used. </p>\n\n<p>Another thing you should look into is using <code>PDO</code> (or anything that supports <strong>prepared statements</strong>). <code>mysql_real_escape_string</code> is not secure these days. \n<a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow\">http://php.net/manual/en/book.pdo.php</a></p>\n\n<p>You should also filter the email and password using regex (<code>preg_match</code>) or the php filter function: <a href=\"http://www.php.net/manual/en/filter.examples.sanitization.php\" rel=\"nofollow\">http://www.php.net/manual/en/filter.examples.sanitization.php</a><br>\n<a href=\"http://www.php.net/manual/en/book.filter.php\" rel=\"nofollow\">http://www.php.net/manual/en/book.filter.php</a><br>\n<a href=\"http://www.php.net/manual/en/function.filter-input.php\" rel=\"nofollow\">http://www.php.net/manual/en/function.filter-input.php</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T00:05:02.833", "Id": "5630", "Score": "3", "body": "Actually, depending on the version of PHP it is much better to use `__construct()`. [With namespaces in 5.3.3+ the class name is not used as constructor.](http://www.php.net/manual/en/language.oop5.decon.php) Granted, the use case for this might be small but there is nothing wrong with the use of `__construct()` and may actually be preferred if using namespaces." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T01:19:32.053", "Id": "5635", "Score": "0", "body": "@Charles Sprayberry what's the difference mechanically? I just like to use it as it matches other langs I program it so it's just one less difference I have to remember. I didn't mean to imply there's anything wrong with using it, just pointing out it can be used and may be more readable and/or future proof." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T01:31:57.347", "Id": "5637", "Score": "5", "body": "There may not be any difference mechanically...as long as you aren't using namespaces in 5.3.3. But, for PHP the `Auth` method in the `Auth` class used as constructor is included for backward compatibility purposes. Using this mechanic actually appears to be *less* future proof as it changes depending on the situation, whereas `__construct()` is always seen as the class constructor." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T16:24:42.400", "Id": "3564", "ParentId": "3563", "Score": "1" } }, { "body": "<p>This part doesn't make sense to me:</p>\n\n<pre><code>private function crypt_pass($pass)\n{\n if (CRYPT_BLOWFISH == 1)\n {\n $salt = SHA1('acssalty457');\n $blowfish_salt = \"\\$2a\\$07\\$\".substr($salt, 0, CRYPT_SALT_LENGTH);\n return crypt($pass, $blowfish_salt);\n }\n}\n</code></pre>\n\n<p>Functions that only return on condition are a bad idea. You should return something anyway, even if it's false. Now for the specific problem, what if <code>CRYPT_BLOWFISH != 1</code>? It's ok to want to use blowfist, but why cripple the library for everyone else? You could rewrite as:</p>\n\n<pre><code>private function crypt_pass($pass) {\n $salt = \"acssalty457\";\n\n if (CRYPT_BLOWFISH == 1) {\n $blowfish_salt = \"\\$2a\\$07\\$\" . substr($salt, 0, CRYPT_SALT_LENGTH);\n return crypt($pass, $blowfish_salt);\n }\n\n return sha1($pass . $salt); \n}\n</code></pre>\n\n<p>Notice that I don't hash the salt? That's because security wise that's useless. You can ask around at <a href=\"https://crypto.stackexchange.com/\">Cryptography Stack Exchange</a> for more. If you want to make the sha1 crypted pass a little bit harder you could do something weird like: </p>\n\n<pre><code>return sha1(strrev($salt) . $pass . $salt);\n</code></pre>\n\n<p>I'm using <code>sha1</code> as an example of a natively included function, you can use any <a href=\"http://www.php.net/manual/en/function.hash.php\" rel=\"nofollow noreferrer\">hash</a> algorithm you like.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-12T03:24:04.533", "Id": "5979", "ParentId": "3563", "Score": "3" } }, { "body": "<p>Try these blowfish wrapper functions on for size:</p>\n\n<p><a href=\"https://gist.github.com/1151912\" rel=\"nofollow\">https://gist.github.com/1151912</a></p>\n\n<p>They wrap the functionality, restrict it to where it's available (php 5.3), and provide the hash generation function, and a test for whether a hash is blowfish or not, making it easier to move from an earlier hash system to a newer hash system.</p>\n\n<p>And yeah, skip mysql_real_escape_string and move towards parameterized queries from PDO, you'll be better off:</p>\n\n<p>I just have a set of parameterized PDO wrapper functions like this: </p>\n\n<pre><code>query('select * from users where user_id = :user_id', array(':user_id'=&gt;$user_id));\n</code></pre>\n\n<p>To make parameterizing queries at dead simple as possible, so that it becomes the default as opposed to a troublesome addition.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-13T18:17:31.917", "Id": "6012", "ParentId": "3563", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T15:03:33.583", "Id": "3563", "Score": "5", "Tags": [ "php", "design-patterns", "object-oriented" ], "Title": "Simple PHP Auth Class feedback" }
3563
<p>Also, I've commented out a function I was trying to do to count the elements of an array; I realized that is not possible due to the fact that I won't be be able to return a NULL on an array.</p> <p>Although this part of a beginner to C exercise, I'd like to know if there is anything I can do to improve my coding.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;math.h&gt; #define MAX_ITEM 1000 double x[MAX_ITEM]; int arr_count(double x[]); double sum(double x[], int arr_count); double mean(double sum, int arr_count); double sum_sqr(double x[], int arr_count); double st_dev(double sum_sqr, double mean, int arr_count); /* int arr_count(double x[]) { int i = 0; int count = 0; for (i = 0; i &lt; MAX_ITEM; i++) { if (x[i] != NULL){ count++; } } return count; } */ double sum(double x[], int arr_count){ int i = 0; double my_sum = 0; for (i = 0; i &lt; arr_count; i++){ my_sum += x[i]; } return my_sum; } double mean(double sum, int arr_count) { return sum / arr_count; } double sum_sqr(double x[], int arr_count){ int i = 0; double my_sum = 0; for (i = 0; i &lt; arr_count; i++){ my_sum += x[i] * x[i]; } return my_sum; } double st_dev(double sum_sqr, double mean, int arr_count) { return sqrt(sum_sqr/ arr_count - mean * mean); } int main(void){ int i; int num; int my_arr_count = 0; double my_sum = 0; double my_mean = 0; double my_st_dev = 0; printf("Enter the number of elements you want in the array between 0 and 1,000\n"); scanf("%d", &amp;num); //generate elements for (i = 0; i &lt; num; i++) { x[i] = rand(time(NULL)); } // print the generated elements printf("The elements are:\n"); for (i = 0; i &lt; num; i++){ printf("[%d] %lf\n", i+ 1, x[i]); } // my_arr_count = arr_count(x); my_arr_count = num; my_sum = sum(x, my_arr_count); my_mean = mean(my_sum, my_arr_count); my_st_dev = st_dev(sum_sqr(x,my_arr_count), my_mean, my_arr_count); printf("There are %d elements in the random array", my_arr_count); printf("the Sum is %lf", my_sum); printf("The Mean is %lf", my_mean); printf("The Standard Deviation is %lf", my_st_dev); } </code></pre>
[]
[ { "body": "<p>see where you have done</p>\n\n<pre><code> //generate elements\n for (i = 0; i &lt; num; i++) {\n x[i] = rand(time(NULL));\n }\n</code></pre>\n\n<p>Thats a good indication you need a function. Same deal for the other place you put a comment</p>\n\n<p>x shouldn't be a global. Should just be a local in main.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T11:44:01.070", "Id": "5379", "Score": "0", "body": "Thanks! In other words, any loop, condition statement, or data manipulation can be made into its own function. I'm assuming this has to do with code maintenance and debugging as well as easy of read/use?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T14:50:05.857", "Id": "5398", "Score": "1", "body": "Actually anytime you have a logical process that includes multiple steps. You do not neceesarily need a function to add two numbers. But if you have a process that adds two numbers then does something then adds the result that would be a logical process that should be its own function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T21:35:47.733", "Id": "5404", "Score": "0", "body": "its more to do with design, but it does lead to easier to understand code, and easier to debug. If you spend time creating functions that make it easier to express ideas in code around your problem domain, you tend to create less code, cleaner code, and also you start thinking at a higher level. As opposed to thinking about the mechanics of creating loops, branching, managing resources, adding numbers, etc to achieve the result you want." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T21:29:22.457", "Id": "3570", "ParentId": "3566", "Score": "5" } }, { "body": "<p>Capture the seed returned from time(NULL) into a variable and use the same value to seed rand. This prevents you from making unnecessary calls to time(NULL) thus making it faster, and also has the added bonus that it allows you to do controlled tests by assigning the seed to a fixed value (receive the same 'random' numbers in each run). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T20:51:53.110", "Id": "5496", "Score": "0", "body": "It's not so much that the calls to `time(NULL)` are necessary, rather they don't make any sense (`rand` doesn't take any argument, and `srand` doesnt' return a random number)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-20T14:25:08.887", "Id": "7371", "Score": "0", "body": "Using a seed allows you to test your program with the same random numbers which is reason in of itself." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T11:29:02.577", "Id": "3577", "ParentId": "3566", "Score": "2" } }, { "body": "<h3>Let the compiler help you</h3>\n\n<p>The first thing to do is to compile with a decent compiler and look at the warnings. With <code>gcc -O -Wall -W</code>:</p>\n\n<pre><code>dassouki.c: In function ‘main’:\ndassouki.c:70: warning: implicit declaration of function ‘rand’\ndassouki.c:70: warning: implicit declaration of function ‘time’\ndassouki.c:90: warning: control reaches end of non-void function\n</code></pre>\n\n<p>You're missing two headers, <code>stdlib.h</code> and <code>time.h</code>, where the functions <code>rand</code> and <code>time</code> are declared. Once you add them you see another error:</p>\n\n<pre><code>small_fixes.c: In function ‘main’:\nsmall_fixes.c:72: error: too many arguments to function ‘rand’\n</code></pre>\n\n<p>For now, to get code that compiles, remove the arguments to <code>rand</code>, it doesn't take any. I'll explain about <code>rand</code> below.</p>\n\n<p>The last warning is there because <code>main</code> function returns an <code>int</code> value; you neglected to do that. If your implementation conforms to <a href=\"http://en.wikipedia.org/wiki/C99\">C99</a> (few do, and the one I compiled with doesn't), there is a special dispensation for the <code>main</code> function: you can omit the <code>return</code> statement, and it's as if you'd written <code>return EXIT_SUCCESS</code>. For utmost portability, return <code>EXIT_SUCCESS</code> to indicate success, or <code>EXIT_FAILURE</code> to indicate failure. On unix and Windows, <code>EXIT_SUCCESS</code> is 0 and <code>EXIT_FAILURE</code> is 1, though any nonzero value (positive and up to 255, though you should stick to small values) indicates failure. If you don't return a value from <code>main</code> (and aren't using a C99 compiler), the effect on most platforms is that your program returns whatever was in a particular register when <code>main</code> finishes executing, which is not good.</p>\n\n<h3>General style</h3>\n\n<p>Generally speaking, your code is well-organized and well-presented, congratulations. Here are a few minor improvements:</p>\n\n<ul>\n<li>The array <code>x</code> doesn't actually need to be global, you can make it local to <code>main</code>. If you make it global, give it a longer name — global variables should be used sparingly and should be easily noticeable and searchable.</li>\n<li>Don't use abbreviations in the names of global variables or functions. Call your functions <code>square_sum</code> or <code>sum_of_squares</code>, <code>standard_deviation</code>.</li>\n<li>The proper type for an array length is <code>size_t</code>. On some machines, you can have arrays whose size doesn't fit into an <code>int</code>. Note that <code>size_t</code> is an unsigned type, which has the advantage that you won't run into the occasional difficulties of signed arithmetic, but you need to be careful with downwards loops (<code>for (i=n; i&gt;=0; i--)</code> is an infinite loop if <code>i</code> is unsigned).</li>\n</ul>\n\n<h3>Output</h3>\n\n<ul>\n<li>You're missing newlines (<code>\\n</code>) at the end of several <code>printf</code> calls.</li>\n<li>The <code>printf</code> conversion specifier for a <code>double</code> is <code>%f</code> (or <code>%e</code> or <code>%g</code>), not <code>%lf</code>. Many implementations allow <code>%lf</code> as a synonym for <code>%f</code>, but this is not universal.</li>\n<li><p>The <code>printf</code> conversion specified for a <code>size_t</code> is <code>%z</code>, but that only exists if your implementation conforms to <a href=\"http://en.wikipedia.org/wiki/C99\">C99</a>, which is still not the norm today. In C89 (the prevalent standard today), your best bet is to cast to <code>unsigned long</code>, e.g.</p>\n\n<pre><code>printf(\"[%lu] %lf\\n\", (unsigned long)i, x[i]);\n</code></pre></li>\n<li><p>Why are you printing <code>i+1</code> next to element number <code>i</code>? It's confusing. Print <code>i</code> and <code>x[i]</code> (as above).</p></li>\n</ul>\n\n<h3>Random number generation</h3>\n\n<p><code>rand()</code> generates a random integer between 0 and <code>RAND_MAX</code>. On many platforms, <code>RAND_MAX</code> is 32767. Here, you're storing this into a floating point array, so it looks like you want to generate a random floating-point number. This is a difficult problem, and the solution depends on what distribution you want. On unix/POSIX platforms, there is a function <a href=\"http://pubs.opengroup.org/onlinepubs/007908799/xsh/drand48.html\"><code>drand48</code></a> which generates a random floating-point number in the range [0,1] with a uniform distribution. This issue is unrelated to the meat of your program, so you may be content with generating a random integer with <code>rand()</code>.</p>\n\n<p>A second issue is that <code>rand()</code> and friends use a <a href=\"http://en.wikipedia.org/wiki/Pseudorandom_number_generator\">pseudo-random number generator</a>. This means that they will always return the same sequence of numbers if they are initialized in the same way. Initializing a random generator is called <em>seeding</em> it, and the function to seed the PRNG is <code>srand(int)</code>. If you never call that function, your program will always fill the array with the same values. A common way of initializing the PRNG for testing is <code>srand(time(NULL))</code>; this will make your program use different values every second (on most machines).</p>\n\n<p>Random number generation is a fairly complex topic; I recommend reading the <a href=\"http://c-faq.com/lib/index.html\">clc FAQ</a>, questions 13.15–13.20, especially <a href=\"http://c-faq.com/lib/srand.html\">Each time I run my program, I get the same sequence of numbers back from rand()</a> and <a href=\"http://c-faq.com/lib/fprand.html\">How can I generate floating-point random numbers?</a>.</p>\n\n<p>For the time being, add <code>srand(time(NULL));</code> near the beginning of your <code>main()</code> function, and fix the call to <code>rand()</code>.</p>\n\n<h3>Input validation</h3>\n\n<p>You read an integer with <code>scanf</code>. This function is convenient for quick tests but tricky to use correctly. It's difficult to react properly if the user enters garbage.</p>\n\n<p>Since <code>num</code> should be a positive integer, make it an unsigned type. In C99, make it <code>size_t</code> and call <code>scanf(\"%z\", &amp;num)</code>. In C89, make it <code>unsigned long</code> and call <code>scanf(\"%lu\", &amp;num)</code>.</p>\n\n<p>Perform at least some token validation of <code>num</code>. The number should be positive (if you want to allow 0, you need to add a special case to some of your calculations). And it must not be larger than the size of the array.</p>\n\n<pre><code>scanf(\"%lu\", &amp;num);\nif (num == 0 || num &gt;= sizeof(x)/sizeof(x[0])) {\n printf(\"Invalid number of elements, goodbye.\\n\");\n return EXIT_FAILURE;\n}\n</code></pre>\n\n<p><code>sizeof(x)/sizeof(x[0])</code> (which can also be written <code>sizeof(x)/sizeof(*x)</code>) is an idiom to denote the number of elements in the array <code>x</code>: it's the size of the array divided by the size of one element. Note that this only works if <code>x</code> is an array, not if <code>x</code> is a pointer. Pointers to arrays don't contain any indication of the size of the array, and the size needs to be specified separately (hence your <code>arr_count</code> argument when you pass a pointer to the array to the various functions).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-09T14:35:44.163", "Id": "5960", "Score": "0", "body": "%lf was introduced as a valid specifier for double in C99. So %lf _is_ universal.(C99 7.24.2.2.11)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-12T10:45:43.653", "Id": "21964", "Score": "0", "body": "What's a better way than scanf to read user input?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T20:49:16.217", "Id": "3631", "ParentId": "3566", "Score": "14" } }, { "body": "<p>I don't believe that you are using <code>rand()</code> correctly. <a href=\"http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html\" rel=\"nofollow\"><code>rand()</code></a> takes no parameters. You may be thinking of <code>srand(unsigned *seed)</code>, which you should call once at the beginning, before calling <code>rand()</code>.</p>\n\n<p>Also, you should <code>#include &lt;stdlib.h&gt;</code> for <code>rand()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-23T06:44:13.533", "Id": "45130", "ParentId": "3566", "Score": "2" } } ]
{ "AcceptedAnswerId": "3570", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T17:00:35.367", "Id": "3566", "Score": "8", "Tags": [ "c", "beginner", "statistics" ], "Title": "Calculate sum, mean, sum of squares, and standard deviation of array elements" }
3566
<p>I need to write a function that "packs" an array of bytes (integers between 0 and 255) into a string. I also need to be able to perform the reverse operation, to get my byte array from the string that it was packed into. This needs to be done as fast as possible. Seeing as JavaScript has 16-bit strings, I packed two bytes per character. Here is my code and tests:</p> <pre><code>function pack(bytes) { var str = ""; for(var i = 0; i &lt; bytes.length; i += 2) { var char = bytes[i] &lt;&lt; 8; if (bytes[i + 1]) char |= bytes[i + 1]; str += String.fromCharCode(char); } return str; } function unpack(str) { var bytes = []; for(var i = 0; i &lt; str.length; i++) { var char = str.charCodeAt(i); bytes.push(char &gt;&gt;&gt; 8); bytes.push(char &amp; 0xFF); } return bytes; } var tests = [ [], [126, 0], [0, 65], [12, 34, 56], [0, 50, 100, 150, 200, 250] ]; console.log("starting tests"); tests.forEach(function(v) { var p = pack(v); console.log(v, p, unpack(p)); }); </code></pre> <p>And the output to that is:</p> <pre><code>starting tests [] "" [] [126, 0] "縀" [126, 0] [0, 65] "A" [0, 65] [12, 34, 56] "ఢ㠀" [12, 34, 56, 0] [0, 50, 100, 150, 200, 250] "2撖죺" [0, 50, 100, 150, 200, 250] </code></pre> <p>I have a few things I'd like feedback on:</p> <ol> <li>This was the first time I used bitwise operators. Is this how it should be done?</li> <li>Are there any speed improvements that could be made?</li> <li>Can you guys think of any way to discard that last 0 byte when encoding then decoding an array with an odd number of bytes? (see test #4)</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T05:17:43.627", "Id": "5373", "Score": "1", "body": "Regarding 3., just add a sentinel to the end of your packed array indicating whether the final byte should be included or not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T13:04:15.367", "Id": "5387", "Score": "0", "body": "Good idea. I was gonna have 2 bytes at the beggining indicating length, but that would have limited the length to 65535. Using your method I can have more. Not that I need it, but it's always nice to break barriers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T13:14:09.697", "Id": "5388", "Score": "0", "body": "Why on earth would you want to encode bytes on the client side? Seems like it should be something to do on the server." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T13:52:06.203", "Id": "5391", "Score": "2", "body": "Who said that was client side?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T15:21:47.717", "Id": "28029", "Score": "0", "body": "I have used this code and there seems to be a problem when passing 0 values to it, they get converted to '' omitted, making it unreliable to pack 32bit floats to a 4 chars. Is there any solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T15:42:18.393", "Id": "28030", "Score": "0", "body": "@user1711738, this is the defined behavior and is not a problem. 0 gets converted to the `null` charater, which must of the time, does not have a representation. However, rest assured that something is there, and that you will be able to convert it back (just try `unpack(pack([0, 1, 2]))`)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-28T21:41:03.660", "Id": "41416", "Score": "0", "body": "Client aide byte encoding can be powerful, but I make sure its usable on the server too. But how do u pack/parse bytes using bitwise ops?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-07T13:58:24.807", "Id": "280523", "Score": "0", "body": "your code is beautiful :')" } ]
[ { "body": "<pre><code>function pack(bytes) {\n var str = \"\";\n// You could make it faster by reading bytes.length once.\n for(var i = 0; i &lt; bytes.length; i += 2) {\n// If you're using signed bytes, you probably need to mask here.\n var char = bytes[i] &lt;&lt; 8;\n// (undefined | 0) === 0 so you can save a test here by doing\n// var char = (bytes[i] &lt;&lt; 8) | (bytes[i + 1] &amp; 0xff);\n if (bytes[i + 1])\n char |= bytes[i + 1];\n// Instead of using string += you could push char onto an array\n// and take advantage of the fact that String.fromCharCode can\n// take any number of arguments to do\n// String.fromCharCode.apply(null, chars);\n str += String.fromCharCode(char);\n }\n return str;\n}\n\nfunction unpack(str) {\n var bytes = [];\n for(var i = 0; i &lt; str.length; i++) {\n var char = str.charCodeAt(i);\n// You can combine both these calls into one,\n// bytes.push(char &gt;&gt;&gt; 8, char &amp; 0xff);\n bytes.push(char &gt;&gt;&gt; 8);\n bytes.push(char &amp; 0xFF);\n }\n return bytes;\n}\n</code></pre>\n\n<p>so to put it all together</p>\n\n<pre><code>function pack(bytes) {\n var chars = [];\n for(var i = 0, n = bytes.length; i &lt; n;) {\n chars.push(((bytes[i++] &amp; 0xff) &lt;&lt; 8) | (bytes[i++] &amp; 0xff));\n }\n return String.fromCharCode.apply(null, chars);\n}\n\nfunction unpack(str) {\n var bytes = [];\n for(var i = 0, n = str.length; i &lt; n; i++) {\n var char = str.charCodeAt(i);\n bytes.push(char &gt;&gt;&gt; 8, char &amp; 0xFF);\n }\n return bytes;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-12T12:03:13.213", "Id": "15784", "Score": "4", "body": "Note that `String.fromCharCode.apply(null, chars);` will throw a \"RangeError: Maximum call stack size exceeded\" exception in browsers using JavaScriptCore (i.e. Safari) if `chars` has a length greater than 65536, and will lock up completely on arrays slightly smaller than that. A complete solution would either push the string directly into the array or use a chunked version of `fromCharCode`. I suspect the former is faster in Safari. See https://bugs.webkit.org/show_bug.cgi?id=80797" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T00:13:17.370", "Id": "3589", "ParentId": "3569", "Score": "17" } } ]
{ "AcceptedAnswerId": "3589", "CommentCount": "8", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-07-20T21:14:25.230", "Id": "3569", "Score": "31", "Tags": [ "javascript", "performance", "strings", "bitwise" ], "Title": "Pack and unpack bytes to strings" }
3569
<p>I've got a lexer written in C++ (Visual Studio 2010, so including lambdas and a few other C++0x tricks). This is my first lexing experience, the only other source code interpretation I ever did was trivial, didn't separate parsing and lexing, that sort of thing. The grammar closely resembles C++ without templates and the lexer should output appropriate tokens. </p> <p>Concerns:</p> <ul> <li>Unicode support- I absolutely want to support foreign-languages fully in this lexer.</li> <li>I also don't transmit any other content than the token type, and I'd also like to know how extensively I'd have to re-write to include them, for example, if I want to actually output an AST, I'll need to keep the identifiers instead of just deciding that they are and junking them.</li> <li>It's also been a long time since I wrote non-trivial C++ and I'd like to know how my comments are.</li> <li>In addition, I've used tools like ANTLR and flex and they generated massive lexers, and I'm concerned that I'm missing a trick here.</li> </ul> <p>Things that I'm definitely not missing:</p> <ul> <li>No string or character literals- I haven't implemented them yet.</li> <li>No const, volatile, or cast keywords</li> </ul> <p>That's pretty much it, I think. </p> <pre><code>class LexedFile { public: enum Token { // RESERVED WORDS (and identifier) // Taken care of by next() lambda. // They're inserted in order (except identifier) so shouldn't be too hard to verify Namespace, Identifier, For, While, Do, Switch, Case, Default, Try, Catch, Auto, Type, Break, Continue, Return, Static, Sizeof, Decltype, If, Else, // LOGICAL OPERATORS LogicalAnd, LogicalOr, LogicalNot, GreaterThan, GreaterThanOrEqual, LessThan, LessThanOrEqual, EqualComparison, NotEqualComparison, // BINARY OPERATORS AND, // Re-used for address-of, the lexer doesn't care ANDAssign, XOR, XORAssign, OR, ORAssign, NOT, NOTAssign, LeftShift, LeftShiftAssign, RightShift, RightShiftAssign, // ARITHMETIC OPERATORS Mul, MulAssign, Div, DivAssign, Mod, ModAssign, Plus, PlusPlus, PlusAssign, Sub, MinusMinus, // I dunno, SubSub just does't seem right. SubAssign, // LITERALS String, Float, Integral, Character, // SYNTACTIC ELEMENTS OpenParen, CloseParen, OpenSquare, CloseSquare, OpenCurlyParen, CloseCurlyParen, MemberAccess, Comma, Assign, Semicolon, Ellipses, PointerMemberAccess, Colon }; std::vector&lt;Token&gt; tokens; }; #pragma warning(disable : 4482) class InputFile { class StreamInput { public: std::vector&lt;wchar_t&gt;* ptr; int index; bool fail; StreamInput(std::vector&lt;wchar_t&gt;* ref) { ptr = ref; index = 0; fail = false; } operator bool() { return !fail; } void putback(wchar_t back) { index--; } StreamInput&amp; operator&gt;&gt;(wchar_t&amp; ref) { if (index == ptr-&gt;size()) { fail = true; return *this; } ref = (*ptr)[index]; index++; return *this; } }; std::wstring filename; public: InputFile(const std::wstring&amp; argfilename) : filename(argfilename) {} LexedFile Lex() { LexedFile l; auto FileHandle = CreateFile( filename.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0 ); std::vector&lt;wchar_t&gt; buffer; LARGE_INTEGER size; GetFileSizeEx(FileHandle, &amp;size); buffer.resize(size.QuadPart); DWORD read; ReadFile( FileHandle, &amp;buffer[0], size.QuadPart, &amp;read, nullptr ); CloseHandle(FileHandle); StreamInput input(&amp;buffer); //std::wifstream input(filename, std::ios::in); std::vector&lt;wchar_t&gt; stack; wchar_t current = 0; static const std::unordered_map&lt;std::wstring, LexedFile::Token&gt; reserved_words( []() -&gt; std::unordered_map&lt;std::wstring, LexedFile::Token&gt; { std::unordered_map&lt;std::wstring, LexedFile::Token&gt; retval; retval[L"namespace"] = LexedFile::Token::Namespace; retval[L"for"] = LexedFile::Token::For; retval[L"while"] = LexedFile::Token::While; retval[L"do"] = LexedFile::Token::Do; retval[L"switch"] = LexedFile::Token::Switch; retval[L"case"] = LexedFile::Token::Case; retval[L"default"] = LexedFile::Token::Default; retval[L"try"] = LexedFile::Token::Try; retval[L"catch"] = LexedFile::Token::Catch; retval[L"auto"] = LexedFile::Token::Auto; retval[L"type"] = LexedFile::Token::Type; retval[L"break"] = LexedFile::Token::Break; retval[L"continue"] = LexedFile::Token::Continue; retval[L"return"] = LexedFile::Token::Return; retval[L"static"] = LexedFile::Token::Static; retval[L"sizeof"] = LexedFile::Token::Sizeof; retval[L"decltype"] = LexedFile::Token::Decltype; retval[L"if"] = LexedFile::Token::If; retval[L"else"] = LexedFile::Token::Else; return retval; }() ); // Dumps the stack, looking for reserved words or identifiers. auto next_no_token = [&amp;] { if (stack.empty()) { return; } std::wstring token(stack.begin(), stack.end()); stack.clear(); if (reserved_words.find(token) != reserved_words.end()) { l.tokens.push_back(reserved_words.find(token)-&gt;second); return; } l.tokens.push_back(LexedFile::Identifier); }; auto next = [&amp;](Wide::LexedFile::Token t) { if (stack.empty()) { l.tokens.push_back(t); return; } std::wstring token(stack.begin(), stack.end()); stack.clear(); if (reserved_words.find(token) != reserved_words.end()) { l.tokens.push_back(reserved_words.find(token)-&gt;second); return; } l.tokens.push_back(LexedFile::Identifier); l.tokens.push_back(t); }; input &gt;&gt; current; if (current == 0xFEFF || current == 0xFFFE) { // BOM } else { input.putback(current); } while(input &gt;&gt; current) { // First we eliminate whitespace, when possible- including comments. // Then we define predicates to recognize tokens taking various forms. // Then they're called. // Then if none of them find anything, we put the character down as "identifier" in the stack and move on. // Whitespace if (current == L' ' || current == L'\n' || current == L'\t' || current == L'\r' ) { next_no_token(); continue; } // Comment - also div and div-equals if (current == L'/') { // Check for comments first- we'll look ahead input &gt;&gt; current; if (current == L'/') { // single-line comment // explicitly empty while loop while(input &gt;&gt; current &amp;&amp; current != L'\n'); next_no_token(); continue; } if (current == L'*') { // multi-line comment while(true) { // Wait until we find a terminator. while(input &gt;&gt; current &amp;&amp; current != L'*'); input &gt;&gt; current; if (current == L'/') { break; } // If we found a * for some other reason, like commented out code, then // just keep going again looking for one. } next_no_token(); continue; } // If we weren't a comment, check for /= if (current == L'=') { next(LexedFile::Token::DivAssign); continue; } // We don't have any more dual-character tokens to check for next(LexedFile::Token::Div); input.putback(current); // Put back the look-ahead token continue; } // Define predicates that will look for operators that occur in various groups. // Check for the operators that only exist on their own, and as assignment versions // "double_check" // ! != // ~ ~= // % %= // * *= auto check = [&amp;](wchar_t token, LexedFile::Token original, LexedFile::Token original_assign) -&gt; bool { if (current == token) { // Grab a look-ahead for *= input &gt;&gt; current; if (current == L'=') { next(original_assign); return true; } input.putback(current); next(original); return true; } return false; }; // For tokens that take the form (for example) // + ++ += // - -- -= // | || |= // &amp; &amp;&amp; &amp;= auto triple_check = [&amp;]( wchar_t token, LexedFile::Token original, LexedFile::Token original_original, LexedFile::Token original_equals) -&gt; bool { if (current == token) { input &gt;&gt; current; if (current == token) { next(original_original); return true; } if (current == L'=') { next(original_equals); return true; } input.putback(current); next(original); return true; } return false; }; // Written to handle &lt;, &lt;&lt;, &lt;=, &lt;&lt;= and &gt;, &gt;&gt;, &gt;=, &gt;&gt;= auto quadruple_check = [&amp;]( wchar_t token, LexedFile::Token original, LexedFile::Token original_original, LexedFile::Token original_equals, LexedFile::Token original_original_equals) -&gt; bool { if (current == token) { input &gt;&gt; current; if (current == L'=') { next(original_equals); return true; } if (current == token) { // We can put this back, and then just "check" for bitwise, which we know will succeed. check(token, original_original, original_original_equals); return true; } input.putback(current); next(original); return true; } return false; }; // Grab *, *=, %, %=, =, ==, !, !=, ~, ~= if (check(L'*', LexedFile::Token::Mul, LexedFile::Token::MulAssign)) continue; if (check(L'%', LexedFile::Token::Mod, LexedFile::Token::ModAssign)) continue; if (check(L'=', LexedFile::Token::Assign, LexedFile::Token::EqualComparison)) continue; if (check(L'!', LexedFile::Token::LogicalNot, LexedFile::Token::NotEqualComparison)) continue; if (check(L'~', LexedFile::Token::NOT, LexedFile::Token::NOTAssign)) continue; if (check(L'^', LexedFile::Token::XOR, LexedFile::Token::XORAssign)) continue; // Triple group: +, ++, +=, -, --, -=, |, ||, |=, &amp;, &amp;&amp;, &amp;= if (triple_check( L'+', LexedFile::Token::Plus, LexedFile::Token::PlusPlus, LexedFile::Token::PlusAssign )) continue; // Pointer member access operator // Handle the special case, then just move on if (current == L'-') { input &gt;&gt; current; if (current == L'&gt;') { next(LexedFile::Token::PointerMemberAccess); continue; } input.putback(current); current = L'-'; } if (triple_check( L'-', LexedFile::Token::Sub, LexedFile::Token::MinusMinus, LexedFile::Token::SubAssign )) continue; if (triple_check( L'|', LexedFile::Token::OR, LexedFile::Token::LogicalOr, LexedFile::Token::ORAssign )) continue; if (triple_check( L'&amp;', LexedFile::Token::AND, LexedFile::Token::LogicalAnd, LexedFile::Token::ANDAssign )) continue; // Pretty much only &lt;&lt;=, &lt;&lt;, &lt;=, &lt; and &gt;&gt;=, &gt;&gt;, &gt;=, &gt; fit into the quadruple group. if (quadruple_check( L'&lt;', LexedFile::Token::LessThan, LexedFile::Token::LeftShift, LexedFile::Token::LessThanOrEqual, LexedFile::Token::LeftShiftAssign )) continue; if (quadruple_check( L'&gt;', LexedFile::Token::GreaterThan, LexedFile::Token::RightShift, LexedFile::Token::GreaterThanOrEqual, LexedFile::Token::RightShiftAssign )) continue; // That's everything. Now on to the other syntactic elements // This lambda is of dubious value, mostly here just to be consistent // Elements of just one character auto syntactic = [&amp;](wchar_t token, LexedFile::Token original) -&gt; bool { if (current == token) { next(original); return true; } return false; }; if (syntactic(L'(', LexedFile::Token::OpenParen)) continue; if (syntactic(L')', LexedFile::Token::CloseParen)) continue; if (syntactic(L'[', LexedFile::Token::OpenSquare)) continue; if (syntactic(L']', LexedFile::Token::CloseSquare)) continue; if (syntactic(L':', LexedFile::Token::Colon)) continue; if (syntactic(L',', LexedFile::Token::Comma)) continue; if (syntactic(L';', LexedFile::Token::Semicolon)) continue; if (syntactic(L'}', LexedFile::Token::CloseCurlyParen)) continue; if (syntactic(L'{', LexedFile::Token::OpenCurlyParen)) continue; // Just dot, ellipses left, and then literal integers, floats, etc if (current == L'.') { input &gt;&gt; current; if (current == L'.') { // The only possible thing that can be here is another dot anyways input &gt;&gt; current; if (current == L'.') { next(LexedFile::Token::Ellipses); continue; } // Double dot illegal! throw std::runtime_error("Lexer failure: encountered '..'"); } input.putback(current); next(LexedFile::Token::MemberAccess); continue; } // Literals // If the stack is empty and we are a numeric character, then we begin a numeric literal. if (stack.empty() &amp;&amp; current &gt;= L'0' &amp;&amp; current &lt;= L'9') { // Consume until no more decimals while(input &gt;&gt; current &amp;&amp; current &gt;= L'0' &amp;&amp; current &lt;= L'9'); // If the next character is a dot, we're a floating-point literal if (current == L'.') { // Consume all the characters that make up the float while(input &gt;&gt; current &amp;&amp; current &gt;= L'0' &amp;&amp; current &lt;= L'9'); next(LexedFile::Token::Float); // Make "current" available for the next read as it's not part of the literal input.putback(current); continue; } next(LexedFile::Token::Integral); input.putback(current); continue; } // Skip string and character literals, and FP exponents for now // Not recognized, push and go again, and we don't want next() in this case. stack.push_back(current); } return l; } }; </code></pre> <p>Edit: I ran it through some test cases and fixed some bugs.</p>
[]
[ { "body": "<p>well....duplicated code is the first order</p>\n\n<pre><code> current &gt;= L'0' &amp;&amp; current &lt;= L'9'\n</code></pre>\n\n<p>might want to extract it out to isDigit or something. same with isWhitespace.....etc even if used one spot, it will help it be a lot more readable. </p>\n\n<p>In fact you might want to take various parts and extract into functions.</p>\n\n<p>I'm not a fan of while(true) loops. I think they could maybe be written better.</p>\n\n<p>I think maybe having more primitive functions to help you navigate the text would be useful skipTill, etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T03:46:35.240", "Id": "3574", "ParentId": "3573", "Score": "4" } }, { "body": "<p>Some things you can improve:</p>\n\n<ul>\n<li><p>The initialization of <code>reserved_words</code> is far too complex. You can use an initializer it to simplify it:</p>\n\n<pre><code>static const std::unordered_map&lt;std::wstring, LexedFile::Token&gt; reserved_words = { \n { L\"namespace\", LexedFile::Token::Namespace },\n { L\"for\", LexedFile::Token::For },\n { L\"while\", LexedFile::Token::While },\n { L\"do\", LexedFile::Token::Do },\n { L\"switch\", LexedFile::Token::Switch },\n { L\"case\", LexedFile::Token::Case },\n { L\"default\", LexedFile::Token::Default },\n { L\"try\", LexedFile::Token::Try },\n { L\"catch\", LexedFile::Token::Catch },\n { L\"auto\", LexedFile::Token::Auto },\n { L\"type\", LexedFile::Token::Type },\n { L\"break\", LexedFile::Token::Break },\n { L\"continue\", LexedFile::Token::Continue },\n { L\"return\", LexedFile::Token::Return },\n { L\"static\", LexedFile::Token::Static },\n { L\"sizeof\", LexedFile::Token::Sizeof },\n { L\"decltype\", LexedFile::Token::Decltype },\n { L\"if\", LexedFile::Token::If },\n { L\"else\", LexedFile::Token::Else }\n};\n</code></pre></li>\n<li><p>In <code>InputFile::StreamInput</code>, you probably want to have an <code>explicit operator bool()</code> instead of a bare one. It was prevent errors like <code>StreamInput stri = false;</code> which feels quite wrong. Also, it lacks a <code>const</code> qualification, it should be:</p>\n\n<pre><code>explicit operator bool() const {\n return !fail;\n}\n</code></pre></li>\n<li><p>The constructor of <code>StreamInput</code> should initialize the members via a constructor initialization list:</p>\n\n<pre><code>StreamInput(std::vector&lt;wchar_t&gt;* ref):\n ptr{ref},\n index{0},\n fail{false}\n{}\n</code></pre></li>\n<li><p>The parameter in <code>InputFile::StreamInput::putback</code> is unused. You can simply delete its name to avoid warnings if you really don't need it.</p></li>\n</ul>\n\n<p>I did not read the entire lexer (well, trying to find errors in a full lexer is quite hard), so I won't comment about its internal logic. I will leave this part to somebody else :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:31:09.993", "Id": "83364", "Score": "0", "body": "VS2010 doesn't have initializer lists or explicit operators. Also, you shoulda checked the date on the posting- I don't have anything like this anymore, because this is from three years ago." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T09:55:40.127", "Id": "83368", "Score": "0", "body": "@DeadMG Yeah, I realized the data after having posted this answer (for some reason, the quesiton was back on the main page). I realized that it was actually one of your questions when I came accross `Wide::`. But whatever." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-18T08:44:28.803", "Id": "47553", "ParentId": "3573", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T23:54:44.220", "Id": "3573", "Score": "7", "Tags": [ "c++", "c++11" ], "Title": "Lexer code in C++" }
3573
<p>I have written this method for converting a date time zone. How do i reduce the execution time of this method further.</p> <pre><code>public static Timestamp convertTimeZone(final Timestamp fromDate, final TimeZone fromTZ, final TimeZone toTZ ){ Long timeInDate = fromDate.getTime() ; int fromOffset = fromTZ.getOffset(timeInDate); int toOffset = toTZ.getOffset(timeInDate); Timestamp dateStamp = new Timestamp(fromDate.getTime()); if( fromOffset &gt;= 0){ int diff = 0; if( toOffset &gt; 0){ diff = ( fromOffset - toOffset); }else{ diff = ( fromOffset + Math.abs(toOffset)); } long date = fromDate.getTime() - diff; dateStamp.setTime( date ); }else{ int diff = 0; if( toOffset &gt; 0){ diff = ( Math.abs( fromOffset) + toOffset); }else{ diff = ( Math.abs( fromOffset) - Math.abs(toOffset)); } long date = fromDate.getTime() + diff; dateStamp.setTime( date ); } return dateStamp; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T08:14:13.563", "Id": "5375", "Score": "3", "body": "What is the ultimate purpose of this method? Dates a represented as milliseconds from the beginning of the epoch. For printing you can choose the timezone of the output using SimpleDateFormat. For persistence you could save the timezone along with the timestamp." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T12:02:31.903", "Id": "5382", "Score": "0", "body": "I get the value from database as timestamp, where i won't have any information of timezone. hence converting the timezone manually" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T13:28:15.503", "Id": "5389", "Score": "2", "body": "NB: Date and time handling isn't very well solved in Java. AFAIK there are several \"simplifications\" that can lead to problems. If you need reliable time handling have a look at the Joda Time library: http://joda-time.sourceforge.net/ . However I can't say if it will be faster than your code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T20:44:28.067", "Id": "5438", "Score": "0", "body": "Where does the `Timestamp` you are using come from? Is this a `java.security.Timestamp`? Do you need it it be one of those?" } ]
[ { "body": "<p>The method can be shortened a bit. It'll probably have some effect on perfomance as well.</p>\n\n<pre><code>public static Timestamp convertTimeZone(final Timestamp fromDate, final TimeZone fromTZ, final TimeZone toTZ ){\n\n // primitive long should be enough for his task\n final long timeInDate = fromDate.getTime();\n final int fromOffset = fromTZ.getOffset(timeInDate);\n final int toOffset = toTZ.getOffset(timeInDate);\n\n return new Timestamp(timeInDate + (toOffset - fromOffset));\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:04:05.023", "Id": "3584", "ParentId": "3575", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T06:04:45.303", "Id": "3575", "Score": "2", "Tags": [ "java" ], "Title": "Converting timezone for date using java" }
3575
<p>I am new to Python and had to create a schema parser to pull information on attributes and complex types, etc. and then convert data from flat files into the proper XML format. We are processing a lot of data and I've run into some issues once we pass around 1 millions processed records.</p> <p>I'm looking for any suggestions on code style, best python practices, etc. that will clean this up a bit and increase efficiency.</p> <p>Here is the part that pulls in the schema:</p> <pre><code>import csv, ConfigParser, re, datetime, time from lxml import etree elemdict = {} parser = etree.XMLParser() data = etree.parse(open("testschema.xsd"),parser) root = data.getroot() version = root.get("version") rootelement = root[0] elements = rootelement[0][0].getchildren() for e in elements: ename = e.get("name") elemdict[ename] = [] subelements = e[0][0].getchildren() for se in subelements: elemdict[ename].append(se.attrib) specials = root.getchildren()[1:] specialtypes = {} for sp in specials: sname = sp.get("name") specialtypes[sname] = {} specialtypes[sname]["type"] = sp.tag.split('}')[-1] #removes namespace to get either complex or simple type, another option here would be to use xpath('local-name()') or remove the first 34 characters from the tag, none of them really clean options typeelements = sp.getchildren()[0].getchildren() specialtypes[sname]["details"] = [] if specialtypes[sname]["type"] == "complexType": specialtypes[sname]["requireds"] = [] for t in typeelements: specialtypes[sname]["details"].append(t.get("name")) if (not "minOccurs" in t.attrib) or int(t.get("minOccurs"))&gt;0: specialtypes[sname]["requireds"].append(t.get("name")) else: for t in typeelements: specialtypes[sname]["details"].append(t.get("value")) </code></pre> <p>That pulls all information into two dictionaries, <code>elemdict</code> and <code>specialtypes</code>. Special types includes both enums and complex types.</p> <p>Here is the code that creates the XML elements and returns, where <code>d</code> is the root element, <code>datainput</code> is the line we are obtained from the file, <code>name</code> is the element name, and <code>requireds</code> is a list of required fields for the element:</p> <pre><code>def addData(d, datainput, name, requireds): try: datavals = dict((k.lower().replace(" ","_"),v) for k,v in datainput.iteritems()) #lower case all the keys for consistency except AttributeError: print "Invalid row, skipping: " + str(datainput) return for i in range(len(requireds)): rname = requireds[i]["name"] rtype = requireds[i]["type"] if rtype[0:3] != "xs:": #if no xs: prefix, element is a complex element of one of our types for j in range(len(specialtypes[rtype]["requireds"])): spname = specialtypes[rtype]["requireds"][j] if not((rname + "_" + spname) in datavals) or len(datavals[(rname + "_" + spname)])&lt;=0: print "missing attributes for complex element " + rname + " in values " + str(datavals) + ", returning" return elif not(rname in datavals) or len(datavals[rname])&lt;=0: print "no " + rname + " in values " + str(datavals) + ", returning" return element = etree.SubElement(d, name) element.set("id", datavals["id"]) for i in range(len(elemdict[name])): cname = elemdict[name][i]["name"] ctype = elemdict[name][i]["type"] if ctype[0:3] != "xs:" and specialtypes[ctype]["type"] == "complexType": #if the type does not start with and xml type and is a complex type specified by us validComplex = True for j in range(len(specialtypes[ctype]["requireds"])): spname = specialtypes[ctype]["requireds"][j] if not((cname + "_" + spname) in datavals) or len(datavals[(cname + "_" + spname)])&lt;=0: validComplex = False break if validComplex: temp = etree.SubElement(element, cname) for d in specialtypes[ctype]["details"]: if (cname + "_" + d) in datavals and len(datavals[(cname + "_" + d)]) &gt; 0: tempsubelem = etree.SubElement(temp, d) tempsubelem.text = datavals[(cname + "_" + d)] elif cname in datavals and len(datavals[cname]) &gt; 0: temp = etree.SubElement(element, cname) try: if ctype == "xs:date": temp.text = str(datetime.date(*time.strptime(datavals[cname],dateformat)[0:3])) else: temp.text = datavals[cname] except ValueError: temp.text = removeNonAscii(datavals[cname]) </code></pre>
[]
[ { "body": "<p>You might want to rethink your approach in a fundamental way if you want to create millions of rows of XML.</p>\n\n<ul>\n<li><p>Define Python classes to contain your actual data. These must be absolutely correct, based on ordinary Python processing. No XSD-based lookup or validation or range checking or anything. Just Python. Your application data must be in Plain Old Python Objects (POPO).</p></li>\n<li><p>Write a \"serializer\" that creates XML from your Plain Old Python Objects. Since the Python objects are already absolutely correct, the output XML will be absolutely correct.</p>\n\n<p>Or locate a seraializer. <a href=\"http://coder.cl/products/pyxser/\" rel=\"nofollow noreferrer\">http://coder.cl/products/pyxser/</a> Django has one. </p>\n\n<p><a href=\"https://stackoverflow.com/questions/1500575/python-xml-serializers\">https://stackoverflow.com/questions/1500575/python-xml-serializers</a></p></li>\n</ul>\n\n<p>Once you have this infrastructure of Python classes that produce XML in place, then you do the following.</p>\n\n<ul>\n<li>Rewrite your XSD parser so that it creates your Plain Old Python Object class definitions from the XSD. It's an XSD->Python translator.</li>\n</ul>\n\n<p>Now you do the bulk of your work in Python. Millions of rows in simple Python class definitions is easy. XML is merely serialized Python objects. Since the XSD is not used, this, too, is easy.</p>\n\n<p>Further (and most importantly) you do a <strong>one-time-only</strong> conversion of XSD to Python.</p>\n\n<p>Look at this Stackoverflow question for a direction to take. <a href=\"https://stackoverflow.com/questions/1072853/convert-xsd-to-python-class\">https://stackoverflow.com/questions/1072853/convert-xsd-to-python-class</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T15:05:01.007", "Id": "5415", "Score": "0", "body": "The XSD will periodically change as new versions are created (probably 2 or 3 new versions a year), which is whWould you suggest that I write my own class creator for better reuse?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T15:09:11.373", "Id": "5416", "Score": "0", "body": "@Mike J: \"Rewrite your XSD parser so that it creates your Plain Old Python Object class definitions from the XSD. It's an XSD->Python translator\". That is your \"class creator\". And you can reuse it, since it's a Python script that you wrote." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T15:13:14.700", "Id": "5418", "Score": "0", "body": "Sorry about that, I missed the obvious" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T21:38:16.840", "Id": "3586", "ParentId": "3580", "Score": "5" } } ]
{ "AcceptedAnswerId": "3586", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T16:50:21.340", "Id": "3580", "Score": "3", "Tags": [ "python", "beginner", "parsing", "xml" ], "Title": "XML schema parsing and XML creation from flat files" }
3580
<p>So I have this code in my program, and there are multiple variations of it. Just looking at it, I feel like there must be a way to make it more efficient, but I can't think of anything. Just looking at it, does anyone have any ideas?</p> <p>Essentially, what the code does is it determines which level of the text that it is currently parsing. If it it is in level 0, it adds that body of text to the <code>aMainSection</code> <code>ArrayList</code>.</p> <p>If it it in level 1, it adds that body of text to <code>aChildSection</code> of <code>aMainSection</code> (An <code>ArrayList</code> within the <code>aMainSection</code> <code>ArrayList</code>). Then it sets the <code>aMainSection</code> text to 'parent text' within a new <code>ArrayList</code>.</p> <p>etc.</p> <p>Notes:</p> <ul> <li><code>aMainSection</code> &amp; <code>aChildSection</code> are arrayLists of type <code>Section</code> (A custom class)</li> <li><code>levelCount</code> is just an array of type <code>int</code>, size 10 (abstract number)</li> </ul> <hr> <p><strong>Code</strong></p> <pre><code>// Adds the passed in heading text to the appropriate section public static void addSectionText(String text) { if (currentLevel == 0) { aMainSection.get(levelCount[0] - 1) .addSection(text); } else if (currentLevel == 1) { aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .addSection(text); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .getSection()); } else if (currentLevel == 2) { aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .addSection(text); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .getSection()); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .getSection()); } else if (currentLevel == 3) { aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .addSection(text); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .getSection()); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .getSection()); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .getSection()); } else if (currentLevel &gt;= 4) { aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .aChildSection.get(levelCount[4] - 1) .addSection(text); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .aChildSection.get(levelCount[4] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .getSection()); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .aChildSection.get(levelCount[4] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .getSection()); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .aChildSection.get(levelCount[4] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .getSection()); aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .aChildSection.get(levelCount[4] - 1) .addParentSection( aMainSection.get(levelCount[0] - 1) .aChildSection.get(levelCount[1] - 1) .aChildSection.get(levelCount[2] - 1) .aChildSection.get(levelCount[3] - 1) .getSection()); } } </code></pre> <p>Any help or thoughts would be appreciated.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T17:15:22.223", "Id": "5399", "Score": "0", "body": "I do not have time right now but what you need is a recursive function to call to dig into its child and call itself o dig into that child until there are no children. If I have a 15 minutes later and it hasnt been answered Ill try to write it for you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:12:17.693", "Id": "5402", "Score": "0", "body": "@Chad I was just wondering if you had time to post your recursive function? I would love to see a recursive implementation of this." } ]
[ { "body": "<p>That much repetition does have a <a href=\"http://en.wikipedia.org/wiki/Code_smell\" rel=\"nofollow\">smell</a> to it. Can you simplify it by saving and reusing intermediate values similar to what I've shown below?</p>\n\n<pre><code> else if (currentLevel == 3)\n {\n Section level0Section = aMainSection.get(levelCount[0] - 1);\n Section level1Section = level0Section.aChildSection.get(levelCount[1] - 1);\n Section level2Section = level1Section.aChildSection.get(levelCount[2] - 1);\n Section level3Section = level2Section.aChildSection.get(levelCount[3] - 1);\n level3Section.addSection(text);\n\n level3Section.addParentSection(level0Section.getSection());\n\n level3Section.addParentSection(level1Section.getSection());\n\n level3Section.addParentSection(level2Section.getSection());\n } \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:20:04.813", "Id": "5400", "Score": "0", "body": "Not just a smell, it stinks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:11:36.007", "Id": "5401", "Score": "0", "body": "@jimreed That definitely seems like a good way to go about it. Definitely cuts down on a good chunk of code. I just wonder if there is a more recursive alternative. Still, thank you very much for your help!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T03:16:22.383", "Id": "5406", "Score": "0", "body": "`level0Section`, `level1Section` in itself is a code smell, and it smells like an avoided array (or List): `level[0].section` and so on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T13:07:47.460", "Id": "5412", "Score": "0", "body": "@user unknown, what would be the benefit of making that change? Just changing level0Section...level3Section to level[0]....level[2] seems kind of unnecessarily tedious, as they both result in the exact same output." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T13:35:12.610", "Id": "5413", "Score": "0", "body": "There are repeated calls, which could be simplified to `setSectionAFromLevelBChildC (int a, int b, int c) { level[a].section = level[b].section.aChildSection.get (levelCount (c) - 1); }` and invocation {setSectionAFromLevelBChildC (1, 0, 1); }` and so on. Maybe I'm wrong, but a pattern can then more easily identified. The code is a bit long and missing too much information which I would have to mock up (are there side effects?), to test a suggestion for sure." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T17:28:42.667", "Id": "3582", "ParentId": "3581", "Score": "4" } } ]
{ "AcceptedAnswerId": "3582", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T16:53:24.570", "Id": "3581", "Score": "6", "Tags": [ "java", "optimization" ], "Title": "Determine which level of the text that it is currently parsing" }
3581
<p>I am using XMLReader and avoided SimpleXML because I must handle a huge file and for memory issues, SimpleXML is not the ideal solution. However, even I coded the below script in SimpleXML, it gives me the result really much faster.</p> <p>Because speed and memory is a must for this project, is there any way to speed up this code? What it does, it filters the books and show those that contains the word jQuery.</p> <pre><code>error_reporting(~0); $xml = &lt;&lt;&lt;EOD &lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; &lt;library&gt; &lt;book isbn="781"&gt; &lt;name&gt;SCJP 1.5&lt;/name&gt; &lt;info&gt;Sun Certified Java Programmer book&lt;/info&gt; &lt;/book&gt; &lt;book isbn="194"&gt; &lt;name&gt;jQuery is Awesome!&lt;/name&gt; &lt;info&gt;jQuery Reference Book&lt;/info&gt; &lt;/book&gt; &lt;book isbn="199"&gt; &lt;name&gt;jQuery 101&lt;/name&gt; &lt;info&gt;All you need to know about jQuery&lt;/info&gt; &lt;/book&gt; &lt;/library&gt; EOD; $file = 'data://text/plain;base64,'.base64_encode($xml); class XMLBookIterator implements iterator { private $file; private $reader; private $state; private $key = 0; private $book; private $valid; public function __construct($file) { $this-&gt;file = $file; } public function current() { return $this-&gt;book; } public function key() { return $this-&gt;key; } public function next() { $reader = $this-&gt;reader; while ($next = $reader-&gt;read()) { switch ($reader-&gt;nodeType) { case (XMLREADER::ELEMENT): $case = $reader-&gt;localName.'|'.$this-&gt;state; switch($case) { case 'library|0': break; case 'book|1': $this-&gt;book = new stdClass; $this-&gt;book-&gt;isbn = $reader-&gt;getAttribute('isbn'); break; case 'name|2': $this-&gt;book-&gt;name = $reader-&gt;readInnerXML(); break; case 'info|3': $this-&gt;book-&gt;info = $reader-&gt;readInnerXML(); $this-&gt;state=0; break; default: throw new Exception(sprintf('Invalid State: %s.', $case)); } $this-&gt;state++; if ($this-&gt;state === 1) break 2; } } $this-&gt;valid = $next; $this-&gt;key++; } public function rewind() { if ($this-&gt;reader) $this-&gt;reader-&gt;close(); $this-&gt;reader = new XMLReader(); $this-&gt;reader-&gt;open($this-&gt;file); $this-&gt;state = 0; $this-&gt;next(); // move to first element or invalidate if ($this-&gt;valid) $this-&gt;next(); // get first book $this-&gt;key = 0; } public function valid() { return $this-&gt;valid; } } class BookFilterIterator extends FilterIterator { private $term; public function __construct($iterator, $term) { parent::__construct($iterator); $this-&gt;term = $term; } public function accept() { $book = parent::current(); $name = $book-&gt;name; return false !== stripos($name, $this-&gt;term); } } // filtered books: $books = new XMLBookIterator($file); $filtered = new BookFilterIterator($books, 'jQuery'); foreach($filtered as $key =&gt; $book) { echo 'book (', $key, '):', "\n"; print_r($book); } </code></pre>
[]
[ { "body": "<p>Your code seems quite tidy and easy to understand, congratulations. But maybe you can check for built in functionality. XPath can search items for you:</p>\n\n<p><a href=\"http://www.php.net/manual/en/simplexmlelement.xpath.php\" rel=\"nofollow\">http://www.php.net/manual/en/simplexmlelement.xpath.php</a><br>\n<a href=\"http://www.w3schools.com/xpath/xpath_syntax.asp\" rel=\"nofollow\">http://www.w3schools.com/xpath/xpath_syntax.asp</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T19:54:17.660", "Id": "3621", "ParentId": "3585", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:09:41.640", "Id": "3585", "Score": "3", "Tags": [ "php", "xml" ], "Title": "In need to speed up this code that filters the data of XML using XMLReader" }
3585
<p>this code finds if there is the string 2004 in <code>&lt;date_iso&gt;&lt;/date_iso&gt;</code> and if it is so, I echo some data from that specific element that the search string was found.</p> <p>I was wondering if this is the best/fastest approach because my main concern is speed and the XML file is huge. Thank you for your ideas.</p> <p>this is a sample of the XML</p> <pre><code>&lt;entry ID="4406"&gt; &lt;id&gt;4406&lt;/id&gt; &lt;title&gt;Book Look Back at 2002&lt;/title&gt; &lt;link&gt;http://www.sebastian-bergmann.de/blog/archives/33_Book_Look_Back_at_2002.html&lt;/link&gt; &lt;description&gt;&lt;/description&gt; &lt;content_encoded&gt;&lt;/content_encoded&gt; &lt;dc_date&gt;20.1.2003, 07:11&lt;/dc_date&gt; &lt;date_iso&gt;2003-01-20T07:11&lt;/date_iso&gt; &lt;blog_link/&gt; &lt;blog_title/&gt; &lt;/entry&gt; </code></pre> <p>this is the code</p> <pre><code>&lt;?php $books = simplexml_load_file('planet.xml'); $search = '2004'; foreach ($books-&gt;entry as $entry) { if (preg_match('/' . preg_quote($search) . '/i', $entry-&gt;date_iso)) { echo $entry-&gt;dc_date; } } ?&gt; </code></pre>
[]
[ { "body": "<p>First of all, put up a timer so you know if things get better.</p>\n\n<p>You're repeating <code>'/' . preg_quote($search) . '/i'</code>for each book. You should create the search string only once or else you are wasting time:</p>\n\n<pre><code>&lt;?php\n$books = simplexml_load_file('planet.xml');\n$search = '2004';\n$regex = '/' . preg_quote($search) . '/i';\nforeach ($books-&gt;entry as $entry) {\n if (preg_match($regex, $entry-&gt;date_iso)) {\n echo $entry-&gt;dc_date;\n }\n}\n?&gt;\n</code></pre>\n\n<p>If you are only looking for 2004 or similar you might analyze if simpler functions would be faster e.g. <code>strpos</code>. </p>\n\n<p>Also the <code>/i</code> modifier might be unnecessary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T03:52:24.957", "Id": "3591", "ParentId": "3590", "Score": "2" } }, { "body": "<p>Be aware, that if you use <code>strpos</code> you should use the <code>!==</code> operator to check for an occurance of your haystack. If <code>2004</code> is at position 0 the <code>!=</code> will evaluate true.</p>\n\n<pre><code>&lt;?php\n$books = simplexml_load_file('planet.xml');\n$search = '2004';\nforeach ($books-&gt;entry as $entry) {\n if (strpos($entry-&gt;date_iso, $search) !== false) {\n echo $entry-&gt;dc_date;\n }\n}\n?&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T11:14:17.537", "Id": "3606", "ParentId": "3590", "Score": "2" } }, { "body": "<p>This might not exactly be an answer you're looking for, but I would imagine that the function <code>simplexml_load_file</code> is somewhat expensive on a large XML file since it creates a lot of objects containing information about the elements, attributes, values, contents, etc.</p>\n\n<p>For that reason I would try finding matching elements with <code>preg_match</code> first (match entire <code>entry</code> tags that contain 2004 in their respective <code>date_iso</code> tags), then either load just these matches with <code>simplexml_load_file</code> to extract the desired information, or (possibly even better) use <code>preg_match</code> to do the same thing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T06:46:00.390", "Id": "5648", "Score": "0", "body": "`simplexml` is *simple*, `preg_match` (in a loop!) is way more expensive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T15:11:34.923", "Id": "5724", "Score": "0", "body": "Are you sure about that? I would think it would depend on the XML and what exactly you're looking for in it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T14:41:27.073", "Id": "3644", "ParentId": "3590", "Score": "1" } } ]
{ "AcceptedAnswerId": "3591", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T03:17:31.633", "Id": "3590", "Score": "2", "Tags": [ "php", "xml" ], "Title": "Is there any faster way instead of using preg_match in the following code?" }
3590
<pre><code> IList&lt;WebSite&gt; wsl = new List&lt;WebSite&gt;(); login1 l = new login1(); string q = "select Id, DomainUrl, IsApproved, Date from website where UserId = @UserId"; using (MySqlConnection con = new MySqlConnection(WebConfigurationManager.ConnectionStrings["MySqlConnectionString"].ToString())) { using (MySqlCommand cmd = new MySqlCommand(q, con)) { cmd.Parameters.Add("@UserId", MySqlDbType.Int32).Value = userId; con.Open(); var reader = cmd.ExecuteReader(); while (reader.Read()) { var ws = new WebSite(); ws.Id = reader.GetInt32("Id"); ws.DomainUrl = reader.GetString("DomainUrl"); ws.IsApproved = reader.GetBoolean("IsApproved"); ws.User.Id = reader.GetInt32("UserId"); ws.Date = reader.GetDateTime("Date"); wsl.Add(ws); } reader.Close(); return wsl; } } </code></pre> <p>I want to make this code as elegant as possible.</p> <p>For this particular project I cannot use <code>NHibernate</code> as I have been instructed.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T06:36:41.493", "Id": "5407", "Score": "1", "body": "Two things: First, stop giving variables one-letter-names. Second, `using` the reader." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T08:08:46.300", "Id": "5408", "Score": "0", "body": "move the return wsl; to the end of the function" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T10:40:24.773", "Id": "5409", "Score": "0", "body": "@Bobby and Peer (cannot notify two additional persons) - these comments should probably be answers as they answer the question." } ]
[ { "body": "<p>I would </p>\n\n<ul>\n<li>reduce the visibility of the variable <code>wsl</code> as it's not required outside the seconds <code>using</code> scope (unless you listen to peer)</li>\n<li>reduce the visibility of the variable <code>q</code> as it's not required outside the first <code>using</code> scope</li>\n<li>better yet I'd probably externalize the query string altogether </li>\n<li>encapsulate the construction of the connection (<code>new MySqlConnection(WebConfigurationManager.ConnectionStrings[\"MySqlConnectionString\"].ToString())</code>) to a separate function <code>createConnection()</code> as the details of the process is not relevant in this context. The createConnection is then available for reuse and helps you to not repeat yourself</li>\n<li>define a builder for the WebSite instance especially if all the attributes are required e.g. 'WebSite.Builder().Id(reader.getInt32(\"ID\").DomainUrl(...)...build()'. This would make it easier for you to ensure that each WebSite is correctly formed. </li>\n<li>separate iterating over the reader and constructing of the <code>WebSite</code></li>\n<li>not set <code>ws.User.Id</code> as it seems somehow wrong to me. </li>\n</ul>\n\n<p>It might look something like this:</p>\n\n<pre><code> using (MySqlConnection con = Connect())\n {\n string q = \"select Id, DomainUrl, IsApproved, Date from website where UserId = @UserId\";\n using (MySqlCommand cmd = new MySqlCommand(q, con))\n {\n cmd.Parameters.Add(\"@UserId\", MySqlDbType.Int32).Value = userId;\n con.Open();\n\n IList&lt;WebSite&gt; wsl = new List&lt;WebSite&gt;();\n using(var reader = cmd.ExecuteReader()) {\n foreach (WebSite webSite in CreateWebSites(reader)) \n {\n wsl.Add(webSite);\n }\n }\n return wsl;\n }\n }\n\n private IEnumerable&lt;WebSite&gt; CreateWebSites(MySqlDataReader reader)\n {\n while (reader.Read())\n {\n yield CreateWebSite(reader);\n }\n }\n\n private MySQLConnection Connect() \n {\n return new MySqlConnection(\n WebConfigurationManager.ConnectionStrings[\"MySqlConnectionString\"].\n ToString());\n }\n\n private WebSite CreateWebSite(Reader reader) \n {\n return WebSite.Builder().\n Id(reader.GetInt32(\"Id\")).\n DomainUrl(reader.GetString(\"DomainUrl\")).\n IsApproved(reader.GetBoolean(\"IsApproved\")).\n User(reader.GetInt32(\"UserId\"))\n Date(reader.GetDateTime(\"Date\")).\n Build();\n }\n</code></pre>\n\n<p>Disclaimer: I don't know C# at all. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T14:40:17.163", "Id": "5414", "Score": "0", "body": "Wow..thats really good for not being familiar with c#. I going to take your advice" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T15:16:37.833", "Id": "5419", "Score": "0", "body": "Impressive for non-C# dev :). Just for the record: with .Net 4.0 there's no need of Builder, you can use var ws = new WebSite {Prop1 = x, Prop2=y};" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T15:34:49.497", "Id": "5421", "Score": "0", "body": "Good to know if I ever venture to the .net side. It's very tempting but I'd have to use Mono." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T11:05:22.257", "Id": "3594", "ParentId": "3592", "Score": "2" } }, { "body": "<p>This code is very tightly coupled with the specific database engine. That makes it hard to change if you decide to go with different database engine. And it's not possible to unit test it at all.</p>\n\n<p>Instead of using the specific MySql classes for connections, etc., change it to use the base interfaces, and then pass the connections and the queries from outside.</p>\n\n<p>Also, I generally avoid using \"return\" inside a code block like \"using\" and if/switch, if it does not make the code too clunky. That way the code path is much easier to follow.</p>\n\n<p>Bellow is an example of this particular method as part of some class, which can be reused in many different situations, incl web pages, services, etc. and with different databases, w/o changing the implementation of this class itself.</p>\n\n<pre><code>private IDatabaseProvider _dbProvider; //initialized in ctor, etc.\nprivate IConnectionStringProvider _connectionStringProvider;\nprivate IWebSiteMapper _mapper; //the db schema may change, or you may need to map from other source\n\npublic IList&lt;WebSite&gt; GetWebSitesForUser(int userId)\n{\n var wsl = new List&lt;WebSite&gt;();\n var con = _dbProvider.GetNewConnection(); //returns IDbConnection\n var cmd = _dbProvider.GetWebSiteListQueryCommand(con, userId); //IDbCommand, and addParam goes there\n\n conn.Open(); // no need of try/catch or using, as if this fails, no resources are leaked\n using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection)) //close con on reader.Close\n {\n while (reader.Read())\n {\n wsl.Add(_mapper.CreateFromReader(reader));\n }\n }\n\n return wsl;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T16:26:24.930", "Id": "5430", "Score": "0", "body": "I like this with the exception of using the reader. That cost you my +1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T17:13:36.493", "Id": "5431", "Score": "0", "body": "@Chad: I'm not about the score. Could you elaborate more on the \"reader\" part?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T17:17:30.037", "Id": "5432", "Score": "1", "body": "I dislike the reader because it keeps the connection open while doing processing. I prefer open connection - get data - close connecton - do processing. While reader works fine for small datasets, the processing time of a few milliseconds adds up when you get into thousands of records." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T00:21:35.973", "Id": "5631", "Score": "0", "body": "what alternative to the reader?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T13:07:43.837", "Id": "3595", "ParentId": "3592", "Score": "5" } } ]
{ "AcceptedAnswerId": "3595", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T06:21:25.703", "Id": "3592", "Score": "6", "Tags": [ "c#", "mysql", "sql" ], "Title": "Read from SQL database table, store in list of objects" }
3592
<p>For some time now, I've been using a pattern which I think could be done more elegantly. I have a lot of XML files that need to be represented in a Django views. My current approach is like this:</p> <p>I get a XML response from an API which gives me several documents.</p> <p>First I define a mock class like this:</p> <pre><code>class MockDocument: pass </code></pre> <p>Then I write an XPath expression that gives me a list of the document nodes:</p> <pre><code>from lxml import etree with open("xmlapiresponse.xml", "r") as doc: xml_response = doc.read() tree = etree.fromstring(xml_response) document_nodes = tree.xpath("//documents/item") </code></pre> <p>Now I iterate over the different documents and their fields using nested <code>for</code>-loops:</p> <pre><code># list for storing the objects document_objects = [] for document in document_nodes: # create a MockDocument for each item returned by the API document_object = MockDocument() for field in document: # store the corresponding fields as object attributes if field.tag == "something": document.something = field.text document_objects.append(document) </code></pre> <p>Now I can pass the list of mock objects to a Django view and represent them in the template in whichever way I want. Could this be done in a simpler fashion, though?</p>
[]
[ { "body": "<p>Using a generator function gives you some flexibility. You don't have to create a list.</p>\n\n<pre><code>def generate_documents( document_nodes ):\n\n for document in document_nodes:\n # create a MockDocument for each item returned by the API\n document_object = MockDocument() \n for field in document:\n # store the corresponding fields as object attributes\n if field.tag == \"something\":\n document.something = field.text\n yield document_object \n</code></pre>\n\n<p>You can do this of the list object is somehow important.</p>\n\n<pre><code>document_objects = list( generate_documents( document_nodes ) )\n</code></pre>\n\n<p>Or, more usefully, this</p>\n\n<pre><code>for d in generate_documents( document_nodes ):\n ... process the document ...\n</code></pre>\n\n<p>Which never actually creates a list object.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T15:24:44.153", "Id": "3596", "ParentId": "3593", "Score": "4" } } ]
{ "AcceptedAnswerId": "3596", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T10:48:16.397", "Id": "3593", "Score": "2", "Tags": [ "python", "xml", "django", "xpath" ], "Title": "Parsing and data presentation in Django" }
3593
<p>I am writing a simpel program that can basicly do the same as piping two linux commands can do. For example, <code>ls -l | grep vars.sh</code>, this can be done on the Linux console. I need to write a programm in C that can do the same. I think I got it working but I want to know if I am doing it rite and if there are some modifications I can do on my code.</p> <p>Here is my code:</p> <pre><code>#include &lt;stdio.h&gt; // Voor verschillende I/O's, macro's, declaraties. #include &lt;stdlib.h&gt; // Om de system call te activeren. #include &lt;unistd.h&gt; // Laden van constanten en types. int main() { pid_t pid; int pipefd[2]; pipe(pipefd); pid = fork(); if(pid==-1){ perror("pipe"); exit(EXIT_FAILURE); } if(pid&gt;0){ close(pipefd[0]); dup2(pipefd[1],1); execlp("ls","ls","-l",NULL); } else{ close(pipefd[1]); dup2(pipefd[0],0); execlp("grep","grep",".bashrc",NULL); exit(EXIT_FAILURE); } } </code></pre> <p>Any feedback,rewrites or modifications are welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T20:48:24.177", "Id": "5422", "Score": "0", "body": "Homework problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T20:49:33.000", "Id": "5423", "Score": "0", "body": "Code looks fine, not entirely clear what your question is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T20:50:21.937", "Id": "5424", "Score": "0", "body": "Looks like you are doing it rite :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T20:55:42.747", "Id": "5425", "Score": "1", "body": "Yea a homework problem :) I just want to be able to do `command | command` that works on Linux in a C program. The code works, but is there another way to do it by modifying the code? As in can this be done in a other way with C?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T22:20:55.820", "Id": "5426", "Score": "0", "body": "There are a [number of questions](http://stackoverflow.com/questions/tagged/pipe+c) for essentially the same problem (one of them yours from yesterday - though you have indubitably improved your question this time compared with that one; thank you), many with answers. Which of them did you review to see how your code differs from the working solutions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T22:24:46.417", "Id": "5427", "Score": "2", "body": "You don't do nearly enough plumbing; you need to close a lot more pipe file descriptors. If you `dup2()` a descriptor, you normally want to close the starting descriptor afterwards." } ]
[ { "body": "<p>The only other way that I could see this can be done in POSIX would be to use <code>popen()</code> rather than using raw pipes. It also returns a stream pointer that can be used with the C standard I/O functions like <code>fprintf()</code>, <code>fgets()</code>, etc. to read and/or write to the process on the other-side of the pipe created by <code>popen()</code>. According to the POSIX specification, with <code>popen()</code>, </p>\n\n<blockquote>\n <p>The environment of the executed\n command shall be as if a child process\n were created within the popen() call\n using the fork() function, and the\n child invoked the sh utility using the\n call:</p>\n \n <p>execl(shell path, \"sh\", \"-c\", command,\n (char *)0);</p>\n \n <p>where shell path is an unspecified\n pathname for the sh utility.</p>\n</blockquote>\n\n<p>So it's basically an easier, more straight-forward way to work with pipes rather than having to fork child processes yourself and close the un-used portions of the pipe so that you don't end up with accidental blocking reads or lost writes because there are still active file-descriptors on each end of the pipe that you've accidentally forgotten to close in either the parent or child process.</p>\n\n<p>With your example, using <code>popen()</code> would look like the following:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#define BUFFERSIZE 128\n\nFILE *ls_proc, *grep_proc;\nls_proc = popen(\"ls -l\", \"r\");\ngrep_proc = popen(\"grep .bashrc\", \"w\");\n\nchar buffer[BUFFERSIZE];\n\n//read from one child process and write to the other\nwhile (fgets(buffer, BUFFERSIZE, ls_proc) != NULL)\n fprintf(grep_proc, \"%s\", buffer);\n\npclose(ls_proc);\npclose(grep_proc); \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T05:09:09.477", "Id": "5428", "Score": "0", "body": "Thanks for the answer, though if I copy paste this in a main () function I get all sorts of errors when compiling. the FILE* gives an error and the fprintf statement gives a error" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-17T12:55:26.733", "Id": "5429", "Score": "0", "body": "Sorry, a small typo in the declaration of `grep_proc` where I forgot its `*` symbol because it's a pointer to a stream. You can copy and paste this code now and it should work." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-28T21:16:36.303", "Id": "432377", "Score": "0", "body": "This will not work with binary data that is passed through the pipe.`fgets` and `fprintf` only work on null terminal strings. Also, this requires the parent process to do the actual transfer of data in the `while` loop while the original example does not need a `while` loop to transfer data from one process to another (the system does the work for you)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T21:22:27.740", "Id": "3599", "ParentId": "3598", "Score": "1" } }, { "body": "<p>Your code looks fine to me. Since you're asking, I'd suggest one tiny thing; that you check the calls return values. pipe() and dup2() can fail too, you want to know when that happens.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-20T01:49:32.960", "Id": "3601", "ParentId": "3598", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-06-16T20:45:49.070", "Id": "3598", "Score": "5", "Tags": [ "c", "homework" ], "Title": "pipe 2 linux commands in C" }
3598
<p>I'm trying to learn scala. It's hard.</p> <p>I currently have a tree in the form</p> <pre><code>class Node(children:List[Node], value:Int){ } </code></pre> <p>I want to calculate a total cost defined by value + the sum of the totalcost of the children. My java background made me do this:</p> <pre><code>def totalCost() { var total = value for (child &lt;- children){ total = total+child.totalCost } return total } </code></pre> <p>now I know I should be folding or reducing, but it's not coming out. Could some of you frendly helpers give me a hand here?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T19:27:02.113", "Id": "5436", "Score": "0", "body": "I don't quite understand how this question is not within scope. @Michael K: Could you review your closure, and if it is in fact out of scope, explain how, so I won't be asking out of scope questions on this site again?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T19:33:06.057", "Id": "5437", "Score": "0", "body": "I would second that. The question was to review the given `totalCost` method, which works fine, but isn't very idiomatic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T09:50:44.523", "Id": "5440", "Score": "0", "body": "Probably it should be in stack overflow, it should be moved instead of getting closed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T03:07:11.737", "Id": "5485", "Score": "0", "body": "I apologize; this was flagged as OT and I didn't read the post closely enough. This does have working code and is on topic here." } ]
[ { "body": "<p>There is already a <code>sum</code> function:</p>\n\n<pre><code>def totalCost = value + children.map(_.totalCost).sum\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T09:59:00.953", "Id": "3605", "ParentId": "3602", "Score": "7" } }, { "body": "<p>A left-fold is an elegant solution too:</p>\n\n<pre><code>class Node (children:List[Node], value:Int) {\n def totalCost : Int = (value /: children) (_ + _.totalCost)\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-11-06T12:43:38.810", "Id": "495682", "Score": "0", "body": "Just a note for recent readers: `/:` is not used any more (it might even be deprecated, though I am not sure - see https://github.com/scala/bug/issues/9607). People write `foldLeft` instead." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T17:32:02.220", "Id": "3607", "ParentId": "3602", "Score": "2" } } ]
{ "AcceptedAnswerId": "3605", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T19:37:12.890", "Id": "3602", "Score": "2", "Tags": [ "scala" ], "Title": "Scala list folding" }
3602
<p>I implemented the algorithm by Pr. Chrystal described <a href="http://www.personal.kent.edu/~rmuhamma/Compgeometry/MyCG/CG-Applets/Center/centercli.htm" rel="nofollow">here</a> in Haskell so could someone please tell me: Do i have implemented this algorithm correctly?<br> Initial calling of findPoints takes the first and second point of convex hull and the list of points on convex hull. </p> <p>My second question is: I am trying to solve the problem on sphere online judge [link of problem in code below, because I can not post more than 2 links] using this algorithm but I'm getting the wrong answer.<br> The code for the problems is on <a href="http://ideone.com/perhE" rel="nofollow">ideone</a>. Why am I getting the wrong answer. </p> <pre><code>--http://www.spoj.pl/problems/QCJ4/ findAngle :: ( Num a , Ord a , Floating a ) =&gt; Point a -&gt; Point a -&gt; Point a -&gt; ( Point a , Point a , Point a , a ) findAngle u@(P x0 y0 ) v@(P x1 y1 ) t@(P x2 y2) | u == t || v == t = ( u , v , t , 10 * pi ) -- two points are same so set the angle more than pi | otherwise = ( u , v, t , ang ) where ang = acos ( ( b + c - a ) / ( 2 * sb * sc ) ) where b = ( x0 - x2 ) ^ 2 + ( y0 - y2 ) ^ 2 c = ( x1 - x2 ) ^ 2 + ( y1 - y2 ) ^ 2 a = ( x0 - x1 ) ^ 2 + ( y0 - y1 ) ^ 2 sb = sqrt b sc = sqrt c findPoints :: ( Num a , Ord a , Floating a ) =&gt; Point a -&gt; Point a -&gt; [ Point a ] -&gt; ( Point a , Point a , Point a , a ) findPoints u v xs | 2 * theta &gt;= pi = ( a , b , t , theta ) | and [ 2 * alpha &lt;= pi , 2 * beta &lt;= pi ] = ( a , b , t , theta ) | otherwise = if 2 * alpha &gt; pi then findPoints v t xs else findPoints u t xs where ( a , b , t , theta ) = minimumBy ( \(_,_,_, t1 ) ( _ , _ , _ ,t2 ) -&gt; compare t1 t2 ) . map ( findAngle u v ) $ xs ( _ , _ , _ , alpha ) = findAngle v t u --angle between v u t angle subtended at u by v t ( _ , _ , _ , beta ) = findAngle u t v -- angle between u v t angle subtended at v by u t </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T16:05:41.600", "Id": "5589", "Score": "0", "body": "I have solved this problem. Accepted code of problem QCJ4 [spoj](http://www.spoj.pl/problems/QCJ4) on [ideone](http://ideone.com/m9T82). I hope Mihai don't need to give away his reputation points as bounty to any one :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T07:30:52.973", "Id": "5750", "Score": "0", "body": "Can you post solution below? (I'll give you the bounty in this case)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T10:43:30.347", "Id": "5780", "Score": "0", "body": "@keep_learning: Now I got the bounty, which is not okay as I just posted some cosmetic changes, but AFAIK there is no way to give it back. If there is no other solution for that, at least I could start a 50 points bounty for a question of your choice..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T14:00:44.113", "Id": "5806", "Score": "0", "body": "@Mihai posted solution here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T14:02:19.073", "Id": "5807", "Score": "0", "body": "@Landel I think your code lead me to write more concise Haskell code so you can think of these bounties as taken from me :)" } ]
[ { "body": "<p>Not an answer, just a small improvement (not tested):</p>\n\n<pre><code>import Data.Function(on)\n\nfindAngle :: (Num a , Ord a , Floating a ) =&gt; Point a -&gt; Point a -&gt; Point a -&gt; ( Point a , Point a , Point a , a ) \nfindAngle u v t \n | u == t || v == t = (u , v , t , 10 * pi) -- two points are same so set the angle more than pi \n | otherwise = (u , v, t , ang) where\n ang = acos $ ( b + c - a ) / (2 * (sqrt $ b * c)) \n sqrDist (P x y) (P x' y') = ( x - x' ) ^ 2 + (y - y') ^ 2 \n [b, c, a] = map (uncurry sqrDist) [(u,t), (v,t), (u,v)]\n\nfindPoints :: ( Num a , Ord a , Floating a ) =&gt; Point a -&gt; Point a -&gt; [ Point a ] -&gt; ( Point a , Point a , Point a , a ) \nfindPoints u v xs \n | 2 * theta &gt;= pi = ( a , b , t , theta ) \n | and [ 2 * alpha &lt;= pi , 2 * beta &lt;= pi ] = (a , b , t , theta) \n | otherwise = if 2 * alpha &gt; pi then findPoints v t xs else findPoints u t xs \n where \n t4 (_ , _ , _ , t) = t \n (a , b , t , theta) = minimumBy (compare `on` t4) . map (findAngle u v) $ xs \n alpha = t4 $ findAngle v t u --angle between v u t angle subtended at u by v t\n beta = t4 $ findAngle u t v -- angle between u v t angle subtended at v by u t\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T09:39:56.907", "Id": "3604", "ParentId": "3603", "Score": "3" } }, { "body": "<p>As per request by Mihai , here is the accepted code of spoj problem . The only error in previous code was \" The minimal enclosing circle is determined by the diametric circle of S \". Instead of finding a circle passing through two points , i was calculating circle from three points. </p>\n\n<pre><code>import Data.List\nimport qualified Data.Sequence as DS \nimport Text.Printf\nimport Data.Function ( on ) \n\n\ndata Point a = P a a deriving ( Show , Ord , Eq ) \ndata Turn = S | L | R deriving ( Show , Eq , Ord , Enum ) -- straight left right \n\n\n--start of convex hull http://en.wikipedia.org/wiki/Graham_scan\n{--\ncompPoint :: ( Num a , Ord a ) =&gt; Point a -&gt; Point a -&gt; Ordering\ncompPoint ( P x1 y1 ) ( P x2 y2 )\n | compare x1 x2 == EQ = compare y1 y2\n | otherwise = compare x1 x2 \n\nfindMinx :: ( Num a , Ord a ) =&gt; [ Point a ] -&gt; [ Point a ]\nfindMinx xs = sortBy ( \\x y -&gt; compPoint x y ) xs\n\ncompAngle ::(Num a , Ord a ) =&gt; Point a -&gt; Point a -&gt; Point a -&gt; Ordering\ncompAngle ( P x1 y1 ) ( P x2 y2 ) ( P x0 y0 ) = compare ( ( y1 - y0 ) * ( x2 - x0 ) ) ( ( y2 - y0) * ( x1 - x0 ) )\n\nsortByangle :: ( Num a , Ord a ) =&gt; [ Point a ] -&gt; [ Point a ]\nsortByangle (z:xs) = z : sortBy ( \\x y -&gt; compAngle x y z ) xs \n\nconvexHull ::( Num a , Ord a ) =&gt; [ Point a ] -&gt; [ Point a ]\nconvexHull xs = reverse . findHull [y,x] $ ys where\n (x:y:ys) = sortByangle.findMinx $ xs \n\nfindTurn :: ( Num a , Ord a , Eq a ) =&gt; Point a -&gt; Point a -&gt; Point a -&gt; Turn\nfindTurn ( P x0 y0 ) ( P x1 y1 ) ( P x2 y2 )\n | ( y1 - y0 ) * ( x2- x0 ) &lt; ( y2 - y0 ) * ( x1 - x0 ) = L\n | ( y1 - y0 ) * ( x2- x0 ) == ( y2 - y0 ) * ( x1 - x0 ) = S\n | otherwise = R \n\nfindHull :: ( Num a , Ord a ) =&gt; [ Point a ] -&gt; [ Point a ] -&gt; [ Point a ]\nfindHull [x] ( z : ys ) = findHull [ z , x ] ys --incase of second point on line from x to z\nfindHull xs [] = xs\nfindHull ( y : x : xs ) ( z:ys )\n | findTurn x y z == R = findHull ( x : xs ) ( z:ys )\n | findTurn x y z == S = findHull ( x : xs ) ( z:ys )\n | otherwise = findHull ( z : y : x : xs ) ys\n--}\n\n--start of monotone hull give .04 sec lead over graham scan \n\ncompPoint :: ( Num a , Ord a ) =&gt; Point a -&gt; Point a -&gt; Ordering\ncompPoint ( P x1 y1 ) ( P x2 y2 )\n | compare x1 x2 == EQ = compare y1 y2\n | otherwise = compare x1 x2 \n\nsortPoint :: ( Num a , Ord a ) =&gt; [ Point a ] -&gt; [ Point a ]\nsortPoint xs = sortBy ( \\ x y -&gt; compPoint x y ) xs\n\n\nfindTurn :: ( Num a , Ord a , Eq a ) =&gt; Point a -&gt; Point a -&gt; Point a -&gt; Turn\nfindTurn ( P x0 y0 ) ( P x1 y1 ) ( P x2 y2 )\n | ( y1 - y0 ) * ( x2- x0 ) &lt; ( y2 - y0 ) * ( x1 - x0 ) = L\n | ( y1 - y0 ) * ( x2- x0 ) == ( y2 - y0 ) * ( x1 - x0 ) = S\n | otherwise = R \n\n\nhullComputation :: ( Num a , Ord a ) =&gt; [ Point a ] -&gt; [ Point a ] -&gt; [ Point a ]\nhullComputation [x] ( z:ys ) = hullComputation [z,x] ys\nhullComputation xs [] = xs\nhullComputation ( y : x : xs ) ( z : ys )\n | findTurn x y z == R = hullComputation ( x:xs ) ( z : ys )\n | findTurn x y z == S = hullComputation ( x:xs ) ( z : ys )\n | otherwise = hullComputation ( z : y : x : xs ) ys \n\n\nconvexHull :: ( Num a , Ord a ) =&gt; [ Point a ] -&gt; [ Point a ]\nconvexHull xs = final where\n txs = sortPoint xs\n ( x : y : ys ) = txs\n lhull = hullComputation [y,x] ys\n ( x': y' : xs' ) = reverse txs\n uhull = hullComputation [ y' , x' ] xs'\n final = ( init lhull ) ++ ( init uhull ) \n\n--end of convex hull \n--start of finding point algorithm http://www.personal.kent.edu/~rmuhamma/Compgeometry/MyCG/CG-Applets/Center/centercli.htm Applet’s Algorithm \n\n\nfindAngle :: ( Num a , Ord a , Floating a ) =&gt; Point a -&gt; Point a -&gt; Point a -&gt; ( Point a , Point a , Point a , a ) \nfindAngle u@(P x0 y0 ) v@(P x1 y1 ) t@(P x2 y2) \n | u == t || v == t = ( u , v , t , 10 * pi ) -- two points are same so set the angle more than pi \n | otherwise = ( u , v, t , ang ) where\n ang = acos $ ( b + c - a ) / ( 2.0 * ( sqrt $ b * c ) ) where\n sqrDist ( P x y ) ( P x' y' ) = ( x - x' ) ^ 2 + ( y - y' ) ^ 2 \n [ b , c , a ] = map ( uncurry sqrDist ) [ ( u , t ) , ( v , t ) , ( u , v ) ]\n\n\n\n findPoints :: ( Num a , Ord a , Floating a ) =&gt; Point a -&gt; Point a -&gt; [ Point a ] -&gt; ( Point a , a ) \n findPoints u v xs \n | 2 * theta &gt;= pi = circle2Points a b --( a , b , t , theta ) \n | and [ 2 * alpha &lt;= pi , 2 * beta &lt;= pi ] = circle3Points a b t --( a , b , t , theta ) \n | otherwise = if 2 * alpha &gt; pi then findPoints v t xs else findPoints u t xs \n where \n ( a , b , t , theta ) = minimumBy ( on compare fn ) . map ( findAngle u v ) $ xs \n fn ( _ , _ , _ , t ) = t \n ( _ , _ , _ , alpha ) = findAngle v t u --angle between v u t angle subtended at u by v t\n ( _ , _ , _ , beta ) = findAngle u t v -- angle between u v t angle subtended at v by u t\n\n\n\n--end of finding three points algorithm\n--find the circle through three points http://paulbourke.net/geometry/circlefrom3/ \n\n\ncircle2Points :: ( Num a , Ord a , Floating a ) =&gt; Point a -&gt; Point a -&gt; ( Point a , a ) \ncircle2Points ( P x0 y0 ) ( P x1 y1 ) = ( P x y , r ) where \n x = ( x0 + x1 ) / 2.0\n y = ( y0 + y1 ) / 2.0\n r = sqrt $ ( x0 - x1 ) ^ 2 + ( y0 - y1 ) ^ 2 \n\n\ncircle3Points :: ( Num a , Ord a , Floating a ) =&gt; Point a -&gt; Point a -&gt; Point a -&gt; ( Point a , a ) --( center , radius )\ncircle3Points u@(P x1 y1 ) v@(P x2 y2 ) t@(P x3 y3 ) \n | x2 == x1 = circle3Points u t v \n | x3 == x2 = circle3Points v u t \n | otherwise = ( P x y , 2 * r ) \n where \n m1 = ( y2 - y1 ) / ( x2 - x1 ) \n m2 = ( y3 - y2 ) / ( x3 - x2 ) \n x = ( m1 * m2 * ( y1 - y3 ) + m2 * ( x1 + x2 ) - m1 * ( x2 + x3 ) ) / ( 2 * ( m2 - m1 ) ) \n y = if y2 /= y1 \n then ( ( x1 + x2 - 2 * x ) / ( 2 * m1 ) ) + ( ( y1 + y2 ) / 2.0 ) \n else ( ( x2 + x3 - 2 * x ) / ( 2 * m2 ) ) + ( ( y2 + y3 ) / 2.0 ) \n r = sqrt $ ( x - x1 ) ^2 + ( y - y1 ) ^ 2 \n\n\n--start of SPOJ code \n\n\nformat::(Num a , Ord a ) =&gt; [[a]] -&gt; [Point a]\nformat xs = map (\\[x0 , y0] -&gt; P x0 y0 ) xs \n\n\nreadInt ::( Num a , Read a ) =&gt; String -&gt; a \nreadInt = read\n\n\nsolve :: ( Num a , Ord a , Floating a ) =&gt; [ Point a ] -&gt; ( Point a , a )\nsolve [ P x0 y0 ] = ( P x0 y0 , 0 ) --in case of one point\nsolve [ P x0 y0 , P x1 y1 ] = circle2Points ( P x0 y0 ) ( P x1 y1 ) -- in case of two points \nsolve xs = findPoints x y t where \n t@( x : y : ys ) = convexHull xs \n\n\nfinal :: ( Num a , Ord a , Floating a ) =&gt; ( Point a , a ) -&gt; a \nfinal ( t , w ) \n | w == 0 = 0\n | otherwise = w\n\n\nmain = interact $ ( printf \"%.2f\\n\" :: Double -&gt; String ) . final . solve . convexHull . format . map ( map readInt . words ) . tail . lines \n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T13:59:58.590", "Id": "3873", "ParentId": "3603", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T08:36:12.677", "Id": "3603", "Score": "5", "Tags": [ "haskell", "functional-programming" ], "Title": "Enclosing Circle Problem implementation in Haskell" }
3603
<p>So, I wrote this small library for fast DOM building with API tailored for CoffeeScript</p> <p>I feel like the code overall can be made better/smaller/faster.</p> <p>I am also not particularly happy about a few functions, namely:</p> <pre><code> # Parses out css classes and id from string like: # p#warning.big.yellow # =&gt; p # attr {"id": "warning", "class": ['big', 'yellow']} # #container # =&gt; div # attr {"id": "container"} # @returns node name (e.g. "span") dotHashRe = /[.#]/ parseElem = (elem, attr) -&gt; return elem unless dotHashRe.test elem attr['class'] ||= [] attr['class'] = [attr['class']] if typeof attr['class'] == 'string' elem = "div#{elem}" if dotHashRe.test(elem.charAt(0)) pieces = elem.split(dotHashRe) elemType = pieces.shift() pos = elemType.length classes = attr['class'] for piece in pieces if elem.charAt(pos) == '#' attr['id'] = piece else classes.push(piece) pos += piece.length + 1 delete attr['class'] unless attr['class'].length elemType </code></pre> <p>It is fast, but it looks like the code can be made a lot nicer</p> <p>The library (~100 LOC with comments): <a href="https://github.com/glebm/DOMBrew/blob/master/dombrew.js.coffee" rel="nofollow">https://github.com/glebm/DOMBrew/blob/master/dombrew.js.coffee</a></p> <p>Looking forward to the suggestions! :)</p>
[]
[ { "body": "<p>A bunch of random observations. I'd rethink the way you approach \"classes\". I'd start with something like</p>\n\n<pre><code>classes = attr['class'] || []\nclasses = [classes] if typeof classes == 'string'\n</code></pre>\n\n<p>And then write or delete it back at the end.</p>\n\n<p>Creating hashStartRe</p>\n\n<pre><code>hashStartRe = /^[.#]/\nelemType = if hashStartRe.test elem then \"div\" else pieces.shift()\n</code></pre>\n\n<p>Will probably be faster than the current rewriting and calling elem.charAt(0). It's definitely easier to read. However, it causes problems with \"pos\". (Solveable problems, but you do need to be careful.)</p>\n\n<p>At this point, the big question is whether you want to allow multiple ids or ids that aren't in the front position. If you restrict your attention to a#id.class1.class2 and don't process a.class1#id1#id2, you can simplify the for loop as well.</p>\n\n<p>A final performance point, since regular expressions are so fast on modern browsers, you may want to consider using the regular expression /(.#)([^.#)+)/ to do your parsing. But you'd need to sit down and do some proper analysis on what was faster. My gut tells me it will be.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T09:11:05.213", "Id": "3863", "ParentId": "3608", "Score": "3" } } ]
{ "AcceptedAnswerId": "3863", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T20:40:13.133", "Id": "3608", "Score": "3", "Tags": [ "library", "coffeescript" ], "Title": "A library written in CoffeeScript" }
3608
<p>I want to make figures of a rectangle and a circle. How can I make the code more elegant?</p> <pre><code>import java.awt.*; import java.awt.event.*; import javax.swing.*; class r extends JPanel { public int x1,x2,y1,y2; public static double SWITCH; public r() { setBackground(Color.WHITE); addMouseListener(new MouseAdapter() { public void mousePressed(MouseEvent m) { x1=m.getX(); y1=m.getY(); repaint(); } public void mouseReleased(MouseEvent m) { x2=m.getX(); y2=m.getY(); repaint(); } }); addMouseMotionListener(new MouseMotionAdapter() { public void mouseDragged(MouseEvent m) { x2=m.getX(); y2=m.getY(); repaint(); } }); } public void paintComponent(Graphics g) { super.paintComponent(g); if(SWITCH == 2) { g.drawRect(x1, y1, x2, y2); } else if (SWITCH == 3) { g.drawOval(x1,y1,x2,y2); } else { g.drawString("qwe", x1, y1); } } } public class q extends JFrame { public static void main(String[] args) { q window = new q(); window.setVisible(true); window.setSize(1024, 800); window.setDefaultCloseOperation(EXIT_ON_CLOSE); Container cont = window.getContentPane(); cont.setLayout(new GridLayout(2,2)); r panel = new r(); JPanel BPanel = new JPanel(); cont.add(panel); cont.add(BPanel); BPanel.setBackground(Color.blue); JButton button1,button2; button1 = new JButton("Rect"); button2 = new JButton("Oval"); BPanel.add(button1); BPanel.add(button2); button1.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { r.SWITCH = 2; } }); button2.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { r.SWITCH = 3; } }); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T11:53:54.680", "Id": "5470", "Score": "1", "body": "Why do you make `SWITCH` a `double`? If it were e.g. an `int` - or even better an `enum` with some meaningful states - you could use a `switch` statement in `paintComponent`. Just a thought: Maybe you could use `JRadioButton`s in a `ButtonGroup` instead of the two `JButton`s." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-27T17:21:58.487", "Id": "9835", "Score": "0", "body": "please learn java naming conventions and stick to them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T22:12:49.620", "Id": "78842", "Score": "0", "body": "I'd avoid alot of inner classes. I'd rather extract them." } ]
[ { "body": "<p>Just a few thoughts...</p>\n\n<p>You are using x and y coordinates. Why not take advantage of the <a href=\"http://download.oracle.com/javase/6/docs/api/java/awt/Point.html\"><code>Point</code> class</a>? The <a href=\"http://download.oracle.com/javase/6/docs/api/java/awt/event/MouseEvent.html\"><code>MouseEvent</code> class</a> has methods that return Point objects, and it would probably make your code more readable. x1 and y1 don't mean anything to me, but you could probably give meaningful names to the points represented by (x1, y1) and (x2, y2).</p>\n\n<p>The use of magic numbers (you storing 2 and 3 into <code>SWITCH</code>, for example) is a poor practice. Use constant <code>int</code>s or (as Landei suggested in the comments) an <code>enum</code>. It will allow you to improve the readable and understandability of the code - at a first read-through, I didn't get what you were doing.</p>\n\n<p>As per Java standards, a class name should begin with a capital letter. Your class is currently called <code>r</code>. You should give it a meaningful name. You might also want to look into other Java standards for code formatting in terms of brace placement, indentation, and so forth. To me, your code is just plain hard to read because of formatting.</p>\n\n<p>Rather than <code>if</code> and <code>switch</code>/<code>case</code> statements, consider leveraging polymorphism in order to draw different shapes. Move the logic to draw different shapes into concrete subclasses, while perhaps maintaining common logic in a superclass.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T12:52:04.620", "Id": "3618", "ParentId": "3609", "Score": "5" } }, { "body": "<p>A couple more thoughts.</p>\n\n<p>Use uppercase when naming a class.</p>\n\n<p>Separate your example into two classes, say DrawPanel for your class that creates the drawing panel and DrawObjects for the class that is creating the drawing objects.</p>\n\n<p>Add a few comments in your code explaining what you are trying to do and why.\nUse constructors to clean up your code and to make it more readable.</p>\n\n<p>I made a few improvements to the code and put in two classes below, take a look and ask questions.</p>\n\n<pre><code>import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\npublic class DrawPanel extends JFrame\n{\n private DrawObjects panel = new DrawObjects();\n private JPanel BPanel = new JPanel();\n private JFrame window = new JFrame();\n\n //constructor\n DrawPanel(){\n buildGUI(); \n }\n\n void buildGUI(){\n window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n window.setLayout(new GridLayout(2,2));\n window.add(panel);\n window.add(BPanel);\n BPanel.setBackground(Color.blue);\n\n //define buttons and add to panel\n JButton rect = new JButton(\"Rect\");\n JButton oval = new JButton(\"Oval\");\n BPanel.add(rect);\n BPanel.add(oval);\n\n rect.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e)\n {\n panel.setType(1);\n }\n });\n\n oval.addActionListener(new ActionListener() {\n public void actionPerformed(ActionEvent e)\n {\n panel.setType(2);\n }\n }); \n\n window.setVisible(true);\n window.setSize(1024, 800); \n}\n\n public static void main(String[] args)\n {\n //create this object\n new DrawPanel();\n }\n\n }//end class\n</code></pre>\n\n<p>class two</p>\n\n<pre><code>import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\n\nclass DrawObjects extends JPanel\n{\npublic int x1,x2,y1,y2;\npublic int type = 1;//default draw type\n\npublic DrawObjects()\n{\n init();\n}\n\npublic void init(){\n setBackground(Color.WHITE);\n addMouseListener(new MouseAdapter()\n {\n public void mousePressed(MouseEvent m)\n {\n x1 = m.getX();\n y1 = m.getY();\n repaint();\n }\n public void mouseReleased(MouseEvent m)\n {\n x2 = m.getX();\n y2 = m.getY();\n repaint();\n }\n });\n\n addMouseMotionListener(new MouseMotionAdapter()\n {\n public void mouseDragged(MouseEvent m)\n {\n x2 = m.getX();\n y2 = m.getY();\n repaint();\n }\n });\n}\n\npublic void setType(int arg){\n if(arg == 1){\n type = 1;\n }else if(arg == 2){\n type = 2;\n }\n}\n\n public void paintComponent(Graphics g)\n { \n super.paintComponent(g);\n if(type == 1)\n {\n g.drawRect(x1,y1,x2,y2);\n }\n else if (type == 2)\n {\n g.drawOval(x1,y1,x2,y2);\n }\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-13T20:33:57.407", "Id": "5351", "ParentId": "3609", "Score": "1" } } ]
{ "AcceptedAnswerId": "3618", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-23T21:15:46.383", "Id": "3609", "Score": "3", "Tags": [ "java", "swing" ], "Title": "Drawing simple shapes by mouse dragging" }
3609
<p>Provided <code>Object.prototype</code> hasn't been modified, will the following snippet work in major browsers?</p> <pre><code>var obj = {length:0}; var push = Array.prototype.push; push.call(obj,'1st value') push.call(obj,'2nd value'); </code></pre> <p>Many have responded that the above code is bad practice, but what makes code like this any better?</p> <pre><code>Array.prototype.slice(arguments,0) </code></pre> <p>Both are calling <code>Array.prototype</code>s on non <code>Array</code>s.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:48:56.393", "Id": "5441", "Score": "4", "body": "Huh? What are you talking about?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:49:44.127", "Id": "5442", "Score": "1", "body": "Interesting to see code like that. It's bad code but it works" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:50:00.813", "Id": "5443", "Score": "0", "body": "Is it cross browser..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:50:29.277", "Id": "5444", "Score": "0", "body": "@Tomalak it's a simple question. \"Does this work cross browser?\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:51:06.017", "Id": "5445", "Score": "0", "body": "Everything is cross-browser in some fashion. If you mean \"will it work universally\", probably not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:51:25.057", "Id": "5446", "Score": "0", "body": "@Raynos Changed titled.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:51:46.753", "Id": "5447", "Score": "2", "body": "I hope *you're* bulletproof if someone else has to maintain that eventually. Edit: great, makes no sense now due to title change :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:51:59.310", "Id": "5448", "Score": "2", "body": "@Raynos: at the time Tomalak posted his question, Lime hadn't yet said \"is it cross browser\". Look at the comment/answer timestamps before posting garbage like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:53:29.017", "Id": "5449", "Score": "0", "body": "@Raynos: It said only \"Is This Javascript BullefProof?\" at the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:55:21.887", "Id": "5450", "Score": "0", "body": "we've cleaned up the question. Was it really that much of a stretch to guess what people are saying. Be more tolerant of people who don't natively speak english." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:57:09.640", "Id": "5451", "Score": "0", "body": "@Raynos: I think it's pretty clear that \"Is This Javascript BullefProof?\" does not aptly describe what the OP wanted to know. That would be the case in _any_ language; let's stop wheeling out this \"but I'm not a native English speaker\" excuse at the first sign of failure. And please do not patronise me; I spend many hours here every day, guessing what people are saying. Usually successfully." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:58:03.790", "Id": "5452", "Score": "0", "body": "@Tomalak I've gotten used as translating garbage into coherent questions ;) You have a point though, I think I've made too many assumptions from jumping to his question to what it is now. And personally I interpret \"is this bulletproof\" as \"will this work\". I didn't meant to offend. Apologies." } ]
[ { "body": "<p>I'm going to say no, because this is an array. It works, but you are hammering a screw at this point. Simply use an array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:50:36.133", "Id": "5453", "Score": "0", "body": "+1 Like the analogy... People often extend `Array.prototype` so I was looking for an alternative that allowed me to loop through the properties/methods safely along with having array support" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:54:03.367", "Id": "5454", "Score": "0", "body": "But by making it an object, it allows you to add properties using the `.property` syntax, unlike arrays." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:56:16.103", "Id": "5455", "Score": "0", "body": "@Jcubed I think you meant if it was a function. Because adding properties to `Object.prototype` is absolutely forbidden. Well unless I misunderstood you..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:49:17.070", "Id": "3612", "ParentId": "3611", "Score": "4" } }, { "body": "<p>I'm not going to go into the depths of implementation detail with this one; I'm just going to say that you're invoking a single <code>Array</code> function on an object that is not an <code>Array</code>.</p>\n\n<p>It's like you're driving along the motorway in a box that <em>may</em> have any of: steering wheel, tyres, axle, floor, seats ... and you don't know which.</p>\n\n<p>Depending upon how <code>Array</code> is implemented on any given browser, this may completely not work at all. Breaking the API in this manner is a silly idea.</p>\n\n<p>So, <strong>no</strong>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:04:09.960", "Id": "5458", "Score": "0", "body": "Exactly...I'm trying not to break the API, that's why I asked if this is cross browser. There are lots of things that probably shouldn't work but definitely do work cross browser. For example: `0 == '' // true\n0 =='0' // true `" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:05:43.827", "Id": "5459", "Score": "0", "body": "@Lime: I believe that those examples are guaranteed to work by the Javascript standard. Messing about with `Array`'s internals is not. You _are_ breaking the API by the act of trying this; whether the resulting code \"works\" on your specific browser (or any other browser) is a different matter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:07:42.083", "Id": "5460", "Score": "0", "body": "Yeah and all the ECMAScript guarantees are always followed by all browsers. (IE cough...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:12:32.877", "Id": "5461", "Score": "0", "body": "I'm not really sure what your point is any more. I stand by my answer!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:15:32.227", "Id": "5462", "Score": "0", "body": "I totally agree that generally speaking it isn't a good idea,nor would I probably put this in code...but I've noticed `Array.prototype.slice.push(obj,0)` is often used on Objects like `arguments` for example. Is this also bad practice? Cause I'm kinda confused where the line is." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:16:44.407", "Id": "5463", "Score": "0", "body": "@Lime: Define \"often\". I've never seen that, and I'd not use any code that did that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T19:21:00.277", "Id": "5464", "Score": "0", "body": "Often is slightly vague, but considering jQuery, prototype, underscore.js and cofeescript all call `slice` on arguments I would argue it is definitely used fairly often." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T14:27:32.330", "Id": "5472", "Score": "0", "body": "@Lime: jQuery calls `Array.prototype.slice` on non-`Array` objects?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T22:14:36.337", "Id": "5477", "Score": "0", "body": "yeah jquery does 'slice.call(arguments)' it several different places." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T23:24:54.533", "Id": "5480", "Score": "0", "body": "@Lime: Maybe `arguments` is an `Array`." } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:55:29.250", "Id": "3614", "ParentId": "3611", "Score": "1" } }, { "body": "<p>It will work without crashing. The exact result will be the object with properties \"0\", \"1\" and the \"length\"==2. There is the scope replacement becasue of the \"call\" function using. However it's not very good practice to use this solution becasue of bad readability and maintainability. I suggest to do it excplicitly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T20:10:48.317", "Id": "3615", "ParentId": "3611", "Score": "-1" } }, { "body": "<p>Working with Javascript is like working with templates in C++. If it has what the function need it works. In this case length might not suffice for every browser. It is true that it is possible to use built-in functions like that but if that function tries to access a property which is not available in your object it will fail.</p>\n\n<p>Now coming to your second point. AFAIK, ECMA script standard does not push any internal operation and even if it does browsers do not use them as hard rules, they take it as guidelines. So it is possible that your code will not work on every browser, but arguments object is implemented by the browser as well, to be compatible with its array architecture. Therefore using Array.prototype.slice.push(arg, 0); is relatively safer than using your custom object with built in array functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T22:20:37.657", "Id": "5478", "Score": "0", "body": "What makes arguments compatible, because it definitely doesn't inherit form 'array.prototype'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T00:23:33.133", "Id": "5484", "Score": "0", "body": "It is supposed to be compatible, since it is basically an array of arguments, but as I said it is relatively safer. It is not a strongly typed language and you cannot be sure." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T19:44:56.220", "Id": "3620", "ParentId": "3611", "Score": "0" } }, { "body": "<p><kbd>Question 1:</kbd></p>\n<h3>What's the different between Code A and Code B?</h3>\n<p>Code A:</p>\n<pre><code>var obj = {length:0};\nvar push = Array.prototype.push;\npush.call(obj,'1st value')\npush.call(obj,'2nd value');\n</code></pre>\n<p>Code B:</p>\n<pre><code>Array.prototype.slice(arguments,0)\n</code></pre>\n<hr/>\n<p><kbd>Answer:</kbd></p>\n<p>First off, Code B is wrong and should be the following.</p>\n<p>Code B2:</p>\n<pre><code>function test(){\n var args = Array.prototype.slice.call(arguments,0);\n return args;\n}\n</code></pre>\n<p>Unless defined, <code>arguments</code> exist within the scope of a function. Basically <code>arguments</code> is an object literal with the initial state of <code>{length:0}</code>.\nWhen a function is called with an argument, the argument is stored in the object <code>arguments</code> by the index corresponding to the argument position.</p>\n<p>Example:</p>\n<pre><code>function getFirstArgument(){\n return arguments[0];\n}\nconsole.log( getFirstArgument(1,2,3) === 1 );\n</code></pre>\n<p>The purpose of Code B2 is to convert the <code>arguments</code> object into an array so you can get access to the array prototype functions easily.</p>\n<p>Example:</p>\n<pre><code>// returns the arguments as an array in reverse order.\nfunction reverseArguments(){\n return Array.prototype.slice.call(arguments).reverse();\n}\nconsole.log( reverseArguments(1,2,3).join(&quot;,&quot;) === &quot;3,2,1&quot; );\n</code></pre>\n<p>So as you can see, both <code>obj</code> in Code A and <code>arguments</code> in Code B are the same object initially.\nHowever, Code A is adding values to <code>obj</code>, while Code B2 is converting <code>arguments</code> to an array.</p>\n<p>More information here:</p>\n<p><a href=\"https://stackoverflow.com/questions/5145032/whats-the-use-of-array-prototype-slice-callarray-0\">What's the use of array.prototype.slice.call(arguments,0)</a></p>\n<p><a href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/slice\" rel=\"nofollow noreferrer\">MDN Array.slice</a></p>\n<p><kbd>Question 2:</kbd></p>\n<h2>Will &quot;Code A&quot; work in major browsers?</h2>\n<p><kbd>Answer:</kbd>\nMost likely. However, if you want to guarantee that it works, then rewrite the push fuction.</p>\n<pre><code>var push = function( obj, val ){\n if( typeof obj !== &quot;object&quot; ){\n return;\n }\n obj.length = obj.length || 0;\n obj[ obj.length ] = val;\n return ++obj.length;\n};\n</code></pre>\n<p>Usage:</p>\n<pre><code>var obj = {};\nconsole.log( push( obj, 1 ) === 1 );\nconsole.log( push( obj, 1 ) === 2 );\nconsole.log( JSON.stringify( obj ) === &quot;{&quot;0&quot;:1,&quot;1&quot;:1,&quot;length&quot;:2}&quot; );\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-28T01:49:48.887", "Id": "15999", "ParentId": "3611", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-21T18:47:25.320", "Id": "3611", "Score": "6", "Tags": [ "javascript" ], "Title": "Does this work cross browser?" }
3611
<p>I have a large namespace, but I don't want enum constants to be a part of it. In cases where an enum is related with a class, I coded enums inside the class so I can reach it using the class name. However, if an enum is related with namespace functions, what is the best way to do it?</p> <ol> <li><p>Use another namespace and put the enum inside, so from the outside it will be the same as others with different implementations?</p></li> <li><p>Continue and create a class with private constructors so it will be as same as others?</p></li> </ol> <p><strong>Classes:</strong></p> <pre><code>class A { public: enum Type { Aa, Ab }; Type GetType(); }; class B { public: enum Type { Ba, Bb }; private: B(); }; B::Type DoSomething(); </code></pre> <p><strong>Namespace:</strong></p> <pre><code>namespace B { enum Type { Ba, Bb }; } B::Type DoSomething(); </code></pre> <p>The first case seems to abuse classes, but it can be extended later to use same coding method as the others. I am in favor of namespace, but what are your opinions?</p>
[]
[ { "body": "<p>I like class. Not because its better or anything, but mainly because class is a nice unit for small amounts of information that's easy to work with. namespaces less so. Some tooling often helps you work with classes better to manipulate things. </p>\n\n<p>But in practice, it's not going to make a lot of difference the majority of the time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T08:36:59.773", "Id": "5490", "Score": "0", "body": "I can really understand what you mean, namespace feels like an overkill for the task." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T05:32:31.253", "Id": "3625", "ParentId": "3617", "Score": "2" } }, { "body": "<p>A class is a namespace + other stuff. You aren't going to use the other stuff, so use a namespace.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T10:06:14.113", "Id": "3638", "ParentId": "3617", "Score": "3" } }, { "body": "<p>I think you have to create a namespace e.g 'MyConst' and place into it all of your enums. Enums are in one place and easy to modify in the future.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T08:20:41.947", "Id": "5577", "Score": "0", "body": "Problem is duplicates. It is quite easy to have them. Almost every other enum has None or similar member." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T07:21:48.573", "Id": "3706", "ParentId": "3617", "Score": "0" } }, { "body": "<p>Do not use \"enum in class\" for public usage. You should use namespace for the purpose. (If your compiler supports C++0x, then use enum class.) </p>\n\n<p>The problem with \"enum in wrapper class\" is header dependency. When declaration code wants to use some \"enum in wrapper class\" type, then it should also references the whole class information. Because you cannot physically separate enumeration from the wrapper class (one definition rule), it'll introduces heavier header dependency.</p>\n\n<p>Moreover, because in C++, there can't be two separate definitions for one class so you cannot use forward declaration technique with \"enum in wrapper class\" like below.</p>\n\n<pre><code>// a.h\nnamespace A {\n enum Type {\n a,\n b\n };\n}\n\n// b.h\nnamespace A {\n enum Type; // forward declaration\n}\nA::Type function();\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T12:09:31.717", "Id": "5582", "Score": "0", "body": "Very good and solid statement. I replaced the answer with yours" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T08:47:17.710", "Id": "3707", "ParentId": "3617", "Score": "9" } } ]
{ "AcceptedAnswerId": "3707", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T10:32:26.763", "Id": "3617", "Score": "6", "Tags": [ "c++", "object-oriented", "enum" ], "Title": "C++ enums - which one is better?" }
3617
<p>I am progressing through the problems listed at projecteuler.com as I learn Scala (<a href="http://fromjavatoscala.blogspot.com" rel="nofollow">my blog where I am covering this experience</a>). I have written a function to produce all the Fibonacci numbers possible in an <code>Int</code> (it's only 47). However, the resulting function feels imperative (not functional).</p> <pre><code> val fibsAll = { //generate all 47 for an Int var fibs = 0 :: List() var current = fibs.head var next = 1 var continue = true while (continue) { current = fibs.head fibs = next :: fibs continue = ((0.0 + next + current) &lt;= Int.MaxValue) if (continue) next = next + current } fibs.reverse } </code></pre> <p>I am looking for feedback on this code: </p> <ol> <li>To what degree does the presence of even a single <code>var</code> (there are four here) indicate an erred approach from a functional standpoint?</li> <li>Given I want to return a <code>List[Int]</code>, what better way is there to do this recursively as opposed to my current (odd) "while loop" approach?</li> </ol> <p>I am finding the transition from imperative to functional thinking quite challenging.</p>
[]
[ { "body": "<pre><code>object Euler002 extends App{\n // Infinite List (Stream) of Fibonacci numbers \n def fib(a: Int = 0, b: Int = 1): Stream[Int] = Stream.cons(a, fib(b, a+b)) \n\n // Take how many numbers you want into a List \n val fibsAll = fib() takeWhile {_&gt;=0} toList\n fibsAll reverse \n}\n</code></pre>\n\n<p>Take a look at <a href=\"http://sites.google.com/a/ifrn.edu.br/leonardo/disciplinas/2011-1/plp/projeto-euler#TOC-Problema-2\" rel=\"nofollow\">this</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T20:42:14.783", "Id": "5473", "Score": "0", "body": "Tyvm for your answer. I had already found the \"sum the series\" answers. However, that solution doesn't work as I'm doing a modified version of the problems. So, I need the above function signature as-is; no parameters and returning all 47 values as a List[Int] in ascending order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T21:51:38.057", "Id": "5475", "Score": "0", "body": "I modified the code to convert the stream into a list" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T22:12:05.660", "Id": "5476", "Score": "0", "body": "LOL! Okay. That works. It still misses the point, though. I can't assume there are 47 values in the function (although I can in the test case validating the results).." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T22:51:49.353", "Id": "5479", "Score": "1", "body": "Use `takeWhile {_>0}` to get all numbers below `Int.MaxValue`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T23:25:54.040", "Id": "5481", "Score": "0", "body": "I will say I am immediately excited (and confused and dismayed) by the prospect of what you are implying. So, when two Int-s are added and the result is larger than Int.MaxValue, instead of generating a ValueOutOfRangeException, it returns the result rolling over the range (it basically forms a ring where 2147483647 is followed by -2147483648). That's why takeWhile works. I had assumed that I would get an exception and had to catch the terminating condition PRIOR to the range rollover. BTW, I need my sequence to include the (0, 1) start and not the projecteuler.com incorrect start of (1, 2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T23:37:13.903", "Id": "5482", "Score": "1", "body": "I prefer to use BigInt instead of Int. BigInt has no upper limit.\n\nYou could redefine `fibs` replacing `Int` with `BigInt`. `fibsAll` would look like: `val fibsAll = fib() takeWhile {_<Int.MaxValue} toList`" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T20:08:04.660", "Id": "3622", "ParentId": "3619", "Score": "6" } }, { "body": "<p>What you should seek in functional programming is <a href=\"http://en.wikipedia.org/wiki/Referential_transparency_%28computer_science%29\" rel=\"nofollow\">referential transparency</a>. That means you can replace something with its value, and the surrounding code will still work.</p>\n\n<p>For example:</p>\n\n<pre><code>var continue = true\nwhile (continue) {\n</code></pre>\n\n<p>So, <code>continue</code> is <code>true</code> (at least the first time this is executed). Can I replace, then, <code>while (continue)</code> with <code>while (true)</code> and have the rest of the code work as expected? The answer is no, of course.</p>\n\n<p>However, consider that this code generates a <code>fibsAll</code> which is a list of fibonacci numbers less than <code>Int.MaxInt</code>. If I replace the whole definition of <code>fibsAll</code> with that list, will the rest of the code act as expected? Yes, it will!</p>\n\n<p>So even though you lost referential transparency in the small, you still kept it in the large. If you need to compromise on FP, this is the kind of compromise you should seek.</p>\n\n<p>Having said that, there are many ways of getting around this. A <code>while</code> loop is often easily converted into recursion -- and, if tail recursive, recursion is as fast as, and sometimes faster than, <code>while</code> loops. For example:</p>\n\n<pre><code>import scala.annotation.tailrec // turns non-tail recursion into an error\nval fibsAll = {\n @tailrec def recurse(current: Int, next: Int, acc: List[Int]): List[Int] =\n if (next &gt;= current) recurse(next, next + current, current :: acc)\n else acc\n recurse(0, 1, Nil).reverse\n}\n</code></pre>\n\n<p>A non-tail recursive version of it is simpler, and since the list is pretty small, you are unlikely to get stack overflow errors.</p>\n\n<pre><code>val fibsAll = {\n def recurse(current: Int, next: Int): List[Int] =\n if (next &gt;= current) current :: recurse(next, next + current)\n else Nil\n recurse(0, 1)\n}\n</code></pre>\n\n<p>Another way of thinking of it is with <code>iterate</code>, which produces an element based on the previous one. For <code>Iterator</code> (not really a functional class) and <code>Stream</code>, it can be infinite. With other collections, such as <code>List</code>, you can define a number of elements. This solution uses a <code>Stream</code>, and then limit it as appropriate:</p>\n\n<pre><code>val fibsAll = (\n Stream.iterate(0 -&gt; 1){ case (a, b) =&gt; (b, a + b) }\n takeWhile { case (a, b) =&gt; b &gt;= a }\n map { case (a, b) =&gt; a }\n toList\n)\n</code></pre>\n\n<p>There's also <code>unfold</code>, which you can find on blogs and on the <a href=\"http://code.google.com/p/scalaz/\" rel=\"nofollow\">Scalaz</a> library. It combines <code>map</code>, <code>iterate</code> and <code>takeWhile</code> in a single function:</p>\n\n<pre><code>val fibsAll = (0, 1).unfold[List, Int]{ \n case (a, b) =&gt; \n if (a &gt; b) None \n else Some(a -&gt; (b, a + b))\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T12:41:37.920", "Id": "5521", "Score": "0", "body": "Fantastic! That was the principle I was trying to learn, but didn't know how to ask; referential transparency! And thank you for your being so detailed in your comments. It really helped me see what you are saying concretely. And to see that if/when a compromise is needed (say for performance reasons), encapsulating the referential transparency loss within a method is the best pathway for quality software engineering. Again, tysvm for your answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T19:46:00.590", "Id": "3630", "ParentId": "3619", "Score": "6" } } ]
{ "AcceptedAnswerId": "3622", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T17:56:29.523", "Id": "3619", "Score": "5", "Tags": [ "scala", "fibonacci-sequence" ], "Title": "Producing full list of Fibonacci numbers which fit in an Int" }
3619
<p>The basic requirement of my code is to accept a file input, parse it, convert it to a java type (A DTO essentially) for use in another component of the system.</p> <p>I should also note that I am not actually parsing a file from a filesystem, the FileParser will be used by a Message Driven Bean that has the contents of the file as a String already.</p> <p>I am looking for input and general design/code review, thanks for your time.</p> <p>I have 4 classes:</p> <ol> <li>FileParser </li> <li>Message </li> <li>MessageFactory </li> <li>MessageFieldTypes</li> </ol> <p>The format of the file is as follows:</p> <pre><code>FIELDONETYPE/FIELDONEVALUE FIELDTWOTYPE/FIELDTWOVALUE FIELDTHREETYPE/FIELDTHREEVALUE FIELDFOURTYPE/FIELDFOURVALUE FIELDFIVETYPE/FIELDFIVEVALUE </code></pre> <p>etc. </p> <p>There are roughly 20 fields.</p> <p>My initial thought was to parse the file into a hashmap and then create the object. Here is the code listing for the parser:</p> <pre><code>final public class FileParser { public static final Message parse(String text) { Map&lt;MessageFieldTypes, String&gt; map = new LinkedHashMap&lt;MessageFieldTypes, String&gt;(); for(String line : text.split(" *\n *")) { String[] keyValuePair = line.split(" */ *"); map.put(MessageFieldTypes.valueOf(keyValuePair[0]), keyValuePair.length == 1 ? "" : keyValuePair[1]); } return MessageFactory.createFromHashMap(map); } } </code></pre> <p>Here is the code listing for the factory:</p> <pre><code>public class MessageFactory { private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormat.forPattern("ddMMMyyyy"); public static Message createFromHashMap(Map&lt;MessageFieldTypes, String&gt; map) { Message message = new Message(); message.setFieldOne(new FieldOneType(map.get(MessageFieldTypes.FIELDONE), map.get(MessageFieldTypes.FIELDTWO), DATE_TIME_FORMATTER.parseDateTime(map.get(MessageFieldTypes.FIELDTHREE)).toLocalDate())); message.setFieldFour(new FieldFourType(map.get(MessageFieldTypes.FIELDFOUR))); message.setFieldFive(map.get(MessageFieldTypes.FIELDFIVE))); return message; } } </code></pre> <p>And the Enum:</p> <pre><code>public enum MessageFieldTypes { FIELDONE, FIELDTWO, FIELDTHREE, FIELDFOUR, FIELDFIVE } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T04:38:12.283", "Id": "5488", "Score": "0", "body": "Not a criticism, just curious - any special reason for using a `LinkedHashMap`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T04:55:05.287", "Id": "5489", "Score": "0", "body": "Yes, this I believe this is a mistake. I think initially I had thought about putting each value in an insertion ordered list (ArrayList or LinkedList) and just relying on the format of the message remaining constant to determine each field. The fact that this carried over to the map was probably just that the idea was in my mind." } ]
[ { "body": "<p>If you can change your file format slightly (to <code>type=value</code> or <code>type:value</code>) I'd suggest using the Java <a href=\"http://download.oracle.com/javase/6/docs/api/java/util/Properties.html\" rel=\"nofollow\">Properties</a> class. It can parse the file from a stream for you (Untested code):</p>\n\n<pre><code>final public class FileParser \n{\n public static final Message parse(String text) {\n text = text.replace(\"/\", \":\"); \n Properties typeValues = new Properties();\n typeValues.load(new StringReader(text));\n\n return MessageFactory.createFromHashTable(typeValues);\n }\n}\n</code></pre>\n\n<p>Note that <code>Properties</code> extends <code>HashTable</code>, not <code>HashMap</code>. They chose <code>HashTable</code> because <code>HashMap</code> is not thread-safe. They work pretty much the same way, though.</p>\n\n<p>On structure: I like the factory format, and it makes sense to use it here. You didn't mention whether the field types are known; if they are your factory code is fine. (It looks like they are, since you call several different constructors with fixed numbers of arguments.) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T04:00:47.683", "Id": "5486", "Score": "0", "body": "Thanks, that is very useful information. Unfortunately we do not have control over the format. We could pre-process it though and convert it to the properties format. Do you have any comments on the class structure? i.e. using a factory vs parsing inside the DTO itself etc." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T04:37:31.303", "Id": "5487", "Score": "0", "body": "I've updated the answer, also adding a simple \"/\" to \":\" replacement should you choose the properties route. I think your code structure is fine. The factory *could* be a simple instantiation, but I think the code is clearer with it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T03:35:41.957", "Id": "3624", "ParentId": "3623", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T02:28:16.177", "Id": "3623", "Score": "2", "Tags": [ "java" ], "Title": "File parser to Java type design" }
3623
<p>I'm trying to make an MVC3 application with an exchangeable data layer. I currently have this in a single file (Global.asax.cs) for brievity.</p> <p>It seems to be working as I want but as I'm new to DI I really would appreciate comments on this code.</p> <pre><code>public interface IDataLayer { dynamic GetItem(int id); dynamic SaveItem(dynamic item); } public class MockDataLayer : IDataLayer { public dynamic GetItem(int id) { dynamic item = new System.Dynamic.ExpandoObject(); item.Id = id; item.Name = "Some name"; return item; } public dynamic SaveItem(dynamic item) { return item; } } public class MainController : Controller { public ActionResult Display(int id = 0) { dynamic viewModel = Global.DataContext.GetItem(id); return View(viewModel); } } public class Global : System.Web.HttpApplication { public static IDataLayer dataContext; protected void Application_Start(object sender, EventArgs e) { IKernel kernel = new StandardKernel(); kernel.Bind&lt;IDataLayer&gt;().To&lt;MockDataLayer&gt;(); dataContext = kernel.Get&lt;IDataLayer&gt;(); RouteTable.Routes.MapRoute("", "{id}", new { controller = "Main", action = "Display", id = UrlParameter.Optional }); } } </code></pre>
[]
[ { "body": "<p>One tip I would give is to use the <a href=\"http://nuget.org/List/Packages/Ninject.MVC3\" rel=\"nofollow\">\"Ninject for ASP NET MVC 3\"</a> NuGet package. Install that package into your project. After doing this, you should find a file named \"NinjectMVC3.cs\" located in the \"App_Start\" folder. In this file, look for a method named <code>RegisterServices()</code>:</p>\n\n<pre><code>private static void RegisterServices(IKernel kernel)\n{\n kernel.Bind&lt;IDataLayer&gt;().To&lt;MockDataLayer&gt;().InRequestScope();\n} \n</code></pre>\n\n<p>This sets up a <code>MockDataLayer</code> to be returned for each separate web request. This ensures that <code>MockDataLayer</code> is disposed when the web request is completed. Now, when you want to create an instance of the data layer, use MVC's built-in <a href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.dependencyresolver%28v=vs.98%29.aspx\" rel=\"nofollow\"><code>DependencyResolver</code></a> class:</p>\n\n<pre><code>var dataContext = DependencyResolver.Current.GetService&lt;IDataLayer&gt;();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-07T21:18:57.667", "Id": "3948", "ParentId": "3627", "Score": "3" } } ]
{ "AcceptedAnswerId": "3948", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T15:12:12.947", "Id": "3627", "Score": "2", "Tags": [ "c#", ".net", "asp.net", "asp.net-mvc-3" ], "Title": "Use of Ninject and an injectable DataLayer in MVC3" }
3627
<p>Whenever a button is clicked, the following need to be performed:</p> <ol> <li>All siblings of the clicked button get toggled</li> <li>All <code>edit_button</code> get toggled, except for the <code>edit_button</code> within the same span as the clicked button (note: the excluded <code>edit_button</code> can be the same as the clicked button)</li> </ol> <p>The JavaScript is working in the way I want it to, but I am curious if there's another better way to achieve the second requirement.</p> <p>Note: <code>save_button</code> and <code>cancel_button</code> are hidden when first loaded.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>$(function() { $('.edit_button, .save_button, .cancel_button').click(function() { $(this).toggle(); $(this).siblings('button').toggle(); $('div#personal_info').find('button.edit_button').not($(this).parent().find('button.edit_button')).toggle(); }); });</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="personal_info"&gt; &lt;div id="section_1"&gt; &lt;span&gt;&lt;button class="edit_button"&gt;Edit&lt;/button&gt;&lt;button class="cancel_button"&gt;Cancel&lt;/button&gt;&lt;button class="save_button"&gt;Save Changes&lt;/button&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="section_2"&gt; &lt;span&gt;&lt;button class="edit_button"&gt;Edit&lt;/button&gt;&lt;button class="cancel_button"&gt;Cancel&lt;/button&gt;&lt;button class="save_button"&gt;Save Changes&lt;/button&gt;&lt;/span&gt; &lt;/div&gt; &lt;div id="section_3"&gt; &lt;span&gt;&lt;button class="edit_button"&gt;Edit&lt;/button&gt;&lt;button class="cancel_button"&gt;Cancel&lt;/button&gt;&lt;button class="save_button"&gt;Save Changes&lt;/button&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>The selector for all <code>edit_buttons</code> can be expressed as a single selector <code>$('div#personal_info button.edit_button')</code>. </p>\n\n<p>I am tempted to rewrite the code to use closure scope to cache the selector values e.g. </p>\n\n<pre><code>// Iterate using each to define cached values for selectors within a \n// closure scope \n$('.edit_button, .save_button, .cancel_button').each(function() {\n var button = $(this);\n // select all elements that need be toggled on click\n var toggled = $([\n button,\n button.siblings('button'),\n $('div#personal_info button.edit_button').\n not(button.parent().find('button.edit_button'))\n ]);\n // toggle each element separetely on click as the first element in a selector\n // defines the target visiblity of a no parameter .toggle()\n button.click(function() {\n toggled.each(\n function() {\n $(this).toggle();\n });\n });\n});\n</code></pre>\n\n<p>The benefit of it is that less traversing is needed. Unfortunately the toggle method didn't work quite as I imagined it would when there are both hidden and shown elements in the selector when using jQuery 1.6.2. </p>\n\n<p>The above <a href=\"http://jsfiddle.net/PZgEK/\" rel=\"nofollow\">code is available through jsFiddle</a></p>\n\n<p>From a maintenance/cleanliness point of view I'm a bit wary how this piece of code merges the concerns of </p>\n\n<ol>\n<li>Hiding all edit actions</li>\n<li>Showing all edit actions</li>\n<li>Displaying save and cancel actions for a specific edit action</li>\n<li>Hiding save and cancel actions for a specific edit action</li>\n</ol>\n\n<p>The result of all these goals leads to astonishment that is higher than the least possible. I don't really know what a good name for that function would be?</p>\n\n<p>Also how and where are the event handlers for onclick events of <code>.save_button</code> and <code>.cancel_button</code> defined? </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T17:02:50.730", "Id": "5508", "Score": "0", "body": "Aleksi - thx for spending your time to show and explain this alternative solution. I like the way you have outlined its pros and cons. I think I will stick with my solution plus the minor change mentioned in your first sentence. But your solution has definitely opened up my eyes to a different approach. Cheers!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T17:05:05.593", "Id": "5509", "Score": "0", "body": "Your solution helped me to learn the use of _.each_ and to get to know jsFiddle (I have been looking for a tool like this)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T19:52:45.043", "Id": "5513", "Score": "0", "body": "The sweetest words I've heard in all of stackexchange network. Thank you!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T07:11:34.567", "Id": "3637", "ParentId": "3634", "Score": "2" } } ]
{ "AcceptedAnswerId": "3637", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T23:59:41.740", "Id": "3634", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Toggling buttons on click" }
3634
<p>Just wondering if I could solicit some feedback on a stored procedure I'm running and whether there's a more efficient way of handling the scenario (I'm pretty sure there will be!).</p> <p>Basically I have a single SP that I call to return a list of records (Jobs) that may have one or more statuses and a sort order (I'm using RowNum for paging). At the moment I'm using WITH RECOMPILE because the variations on the statuses can change all the time (depending on user etc). There's also some filtering going on. </p> <p>I'm using an IF statement to essentially run the same bit of code with the only change being the sort order.</p> <p>I guess my questions are: Is there a better way of doing this (maybe different SP's for different statuses)? Am I overcomplicating things due to lack of knowledge (quite likely) Is the SP actually ok, but requires minor tweaks to reduce the number of lines?</p> <p>I've pasted a portion of the SP below - the only difference to the full code is the additional IF statements for the different sort orders...</p> <p>I'd appreciate any feedback.</p> <p>Thanks in advance!</p> <pre><code>CREATE PROCEDURE [dbo].[sp_Jobs] ( @PageNumber int, @PageSize int, @FilterExpression varchar(500), @OrderBy varchar(50), @CustomerID int, @ShowNotSet bit, @ShowPlaced bit, @ShowProofed bit, @ShowReProofed bit, @ShowApproved bit, @ShowOnTime bit, @ShowLate bit, @ShowProblem bit, @ShowCompleted bit, @ShowDispatched bit, @ShowUnapproved bit, @ShowClosed bit, @ShowReturned bit, @UserID int ) WITH RECOMPILE AS --JobNumber DESC if @OrderBy='JobNumberDESC' BEGIN WITH Keys AS (SELECT TOP (@PageNumber * @PageSize) ROW_NUMBER() OVER (ORDER BY JobNumber DESC) as rn,P1.jobNumber,P1.CustID,P1.DateIn,P1.DateDue,P1.DateOut,p1.client,p1.MasterJobStatusID,p1.MasterJobStatusTimestamp,p1.OwnerID FROM vw_Jobs_List P1 WITH (NOLOCK) WHERE (@CustomerID = 0 OR CustID = @CustomerID) AND (@UserID = 0 OR OwnerID = @UserID) AND ((@ShowNotSet = 1 AND MasterJobStatusID=1) OR (@ShowPlaced = 1 AND MasterJobStatusID=2) OR (@ShowProofed = 1 AND MasterJobStatusID=3) OR (@ShowReProofed = 1 AND MasterJobStatusID=4) OR (@ShowApproved = 1 AND MasterJobStatusID=5) OR (@ShowOnTime = 1 AND MasterJobStatusID=6) OR (@ShowLate = 1 AND MasterJobStatusID=7) OR (@ShowProblem = 1 AND MasterJobStatusID=8) OR (@ShowCompleted = 1 AND MasterJobStatusID=9) OR (@ShowDispatched = 1 AND MasterJobStatusID=10) OR (@ShowUnapproved = 1 AND MasterJobStatusID=11) OR (@ShowClosed = 1 AND MasterJobStatusID=12) OR (@ShowReturned = 1 AND MasterJobStatusID=13)) AND (Search LIKE '%'+@FilterExpression+'%') ORDER BY P1.JobNumber DESC ),SelectedKeys AS ( SELECT TOP (@PageSize)SK.rn,SK.JobNumber,SK.CustID,SK.DateIn,SK.DateDue,SK.DateOut FROM Keys SK WHERE SK.rn &gt; ((@PageNumber-1) * @PageSize) ORDER BY SK.JobNumber DESC) SELECT SK.rn,J.JobNumber,J.OwnerID,J.Description,J.Client,SK.CustID,OrderNumber, CAST(DateAdd(d, -2, CAST(isnull(SK.DateIn,0) AS DateTime)) AS nvarchar) AS DateIn, CAST(DateAdd(d, -2, CAST(isnull(SK.DateDue,0) AS DateTime)) AS nvarchar) AS DateDue,CAST(DateAdd(d, -2, CAST(isnull(SK.DateOut,0) AS DateTime)) AS nvarchar) AS DateOut, Del_Method,Ticket#, InvoiceEmailed, InvoicePrinted, InvoiceExported, InvoiceComplete, JobStatus,j.MasterJobStatusID,j.MasterJobStatusTimestamp,js.MasterJobStatus FROM SelectedKeys SK JOIN vw_Jobs_List J WITH (NOLOCK) ON j.JobNumber=SK.JobNumber JOIN tbl_SYSTEM_MasterJobStatus js WITH (NOLOCK) ON j.MasterJobStatusID=js.MasterJobStatusID ORDER BY SK.JobNumber DESC END </code></pre> <p>--ELSE IF for other column sorting</p>
[]
[ { "body": "<p>You can use <code>CASE</code> statements in the <code>ORDER BY</code> clauses to decide which sort order to use:</p>\n\n<pre><code> SELECT (...)\nORDER BY CASE @OrderBy\n WHEN 'JobNumberDESC' THEN sk.jobnumber\n WHEN (etc.)\n END DESC,\n CASE @OrderBy\n WHEN 'JobNumberASC' THEN sk.jobnumber\n WHEN (etc.)\n END ASC;\n</code></pre>\n\n<p>(You would have to split up the ascending and descending sort options like that)</p>\n\n<p>One issue with that approach, though, is that in your original statement, I count four places where the <code>ORDER BY</code> statement occurs. That would mean repeating the long <code>CASE</code> statement a lot. I think we can fix that, though.</p>\n\n<p>First off, sorting in a subquery usually doesn't make much sense. I don't see any reason to have <code>keys</code> and <code>selectedkeys</code> sorted, so let's remove those <code>ORDER BY</code> statements.</p>\n\n<p>Now we're left with two <code>ORDER BY</code>s: the one used in the <code>ROW_NUMBER</code> function and the final sort. No matter what, you need to include the <code>ORDER BY</code> in the <code>ROW_NUMBER</code> function to make sure your paging works correctly, but here's the thing: now you can use that row number to sort the final result (i.e., change the final <code>ORDER BY sk.jobnumber DESC</code> to <code>ORDER BY sk.rn</code>). Now there's only one place where you need the dynamic <code>ORDER BY</code> clause, which is a lot better than four!</p>\n\n<p>Disclaimer: I haven't tested these ideas; just brainstorming.</p>\n\n<hr>\n\n<p>Another option would be to use <a href=\"http://www.sommarskog.se/dynamic_sql.html\" rel=\"nofollow\">dynamic SQL</a>. Then you'd have something like this:</p>\n\n<pre><code>DECLARE @OrderByClause varchar(500),\n @sql varchar(max);\n\nSET @OrderByClause =\n CASE @OrderBy\n WHEN 'JobNumberDESC' THEN 'sk.jobnumber DESC'\n WHEN (etc)\n END;\n\nSET @sql = 'WITH keys\n AS (SELECT TOP (@PageNumber * @PageSize)\n ROW_NUMBER() OVER (ORDER BY ' + @OrderByClause + ') AS rn' +\n (etc.);\n\nEXEC sp_executesql @sql, (etc.);\n</code></pre>\n\n<p>Just make sure you pay attention to the SQL injection threat.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-31T19:17:24.477", "Id": "6752", "Score": "1", "body": "Remove WITH RECOMPILE as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T06:01:18.533", "Id": "3704", "ParentId": "3636", "Score": "1" } } ]
{ "AcceptedAnswerId": "3704", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T01:16:14.367", "Id": "3636", "Score": "2", "Tags": [ "sql", "sql-server" ], "Title": "Recommendations for stored procedure" }
3636
<p>I have some code which looks like this:</p> <pre><code>do { hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched); if (hr == S_FALSE) { break; } llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace; } while (hr != S_FALSE); </code></pre> <p>It is bad because <code>hr == S_FALSE</code> is checked twice on every iteration.</p> <p>I could write it like this:</p> <pre><code>while (true) { hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched); if (hr == S_FALSE) { break; } llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace; }; </code></pre> <p>It is bad because it gives the impression that there exists no loop invariant (i.e. it could be an infinite loop, which would be a programmer error).</p> <p>Finally, I could write it with <code>goto</code>s, but that is bad because <code>goto</code>s are <em>considered harmful</em>. Also, it gets really hard to check the correctness of the loop.</p> <p>How would you write this loop and why?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T23:13:42.850", "Id": "5533", "Score": "2", "body": "I would go with the `while (true)`: all alternatives have some duplicated code somewhere." } ]
[ { "body": "<p>You could combine your loop condition and the hr assignment in one line, like this:</p>\n\n<pre><code>while ((hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched)) != S_FALSE) {\n llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T12:22:12.677", "Id": "3640", "ParentId": "3639", "Score": "4" } }, { "body": "<p>My initial thought is to simply lose the break. While they have their place in switch-case statements, it is generally best to avoid them in loops unless they're used at the top of a loop and truly help improve readability. Even then, I tend to look for alternatives.</p>\n\n<pre><code>do {\n hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched);\n if (hr != S_FALSE) { \n llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;\n }\n} while (hr != S_FALSE);\n</code></pre>\n\n<p>Alternatively, you could just initialize hr prior to the while loop and avoid the extra check against S_FALSE every loop.</p>\n\n<pre><code>hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched);\nwhile (hr != S_FALSE) {\n llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;\n hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched);\n}\n</code></pre>\n\n<p>I don't like the following style of while loop as it utilizes a side-effect.</p>\n\n<pre><code>while ((hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched)) != S_FALSE) {\n llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;\n}\n</code></pre>\n\n<p>Lastly, it may be worthwhile to consider a for loop here. I like the look of this because it cleanly separates the looping from the updates to llCbStorage.</p>\n\n<pre><code>for (hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched);\n hr != S_FALSE;\n hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched)) \n{\n llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T15:55:17.133", "Id": "5504", "Score": "0", "body": "I went for the `for` loop, it is brilliant -- looks very clear and does exactly what it should with minimal code replication." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T22:01:54.200", "Id": "5516", "Score": "1", "body": "I tend to like the while loop, while it uses a side-effect, it is idiomatic c/c++" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T14:58:30.747", "Id": "19131", "Score": "0", "body": "My preference is the while loop with side-effecting condition. That's a pretty common C idiom, and it avoids duplication, and it cleanly separates condition from body. The one change I'd make is to have it say `while (S_FALSE != (hr = pEnumMgmt->Next(1, &mgmtObjProp, &ulFetched)))`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T13:22:08.937", "Id": "3642", "ParentId": "3639", "Score": "10" } }, { "body": "<p>COM is like a zombie -- the only way to be safe with it around is to lock it in a box from which it can't escape, then bury it as deeply as possible, just to be sure.</p>\n\n<p>Since (in this case) you're iterating over a COM pseudo-collection, to make this into decent C++, you want to lock the COM zombie-iteration inside a real iterator, something like this:</p>\n\n<pre><code>template &lt;class T&gt;\nclass COM_iterator { \n HRESULT current;\n unsigned long fetched;\n XXX mgmtObject; // not sure of the correct type here.\n T enumerator;\n\n COM_iterator next() {\n current = enumerator-&gt;Next(1, &amp;mgmtObject, &amp;fetched);\n return *this;\n }\npublic:\n COM_iterator() : current(S_FALSE) {}\n\n COM_iterator(T enum) : enumerator(enum) {\n next();\n }\n\n COM_iterator &amp;operator++() { return next(); }\n\n unsigned long long operator*() {\n return mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace; \n }\n\n bool operator!=(COM_iterator const &amp;other) {\n return current != other.current;\n }\n};\n</code></pre>\n\n<p>We then want to bury that ugliness in a header file. Using it, however, we can not merely produce a prettier loop, but in fact eliminate the loop itself entirely, and instead use an idiomatic C++ algorithm:</p>\n\n<pre><code>#include &lt;numeric&gt;\n#include \"com_iterator\"\n\nlong long total_bytes = \n std::accumulate(COM_iterator&lt;your_COM_type&gt;(pEnumMgmt),\n COM_iterator&lt;your_COM_type&gt;(),\n 0LL);\n</code></pre>\n\n<p>As it stands, this code does have one real problem: it's only suitable for looking at one particular property of the data you're looking at. To clean that up, it should probably have the code to access the specific data involved (<code>mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace</code>, in this case) encapsulated in a separate policy-like class that's passed as a template parameter to the iterator. This allows separation between the COM iteration code, and the code to access the internals of the specific object you care about. Alternatively, the COM_iterator could return <code>mgmtProp</code>, and leave it to the client code to figure out what data to use from each item being iterated over.</p>\n\n<p>Edit: Using the \"policy-like\" extractor class, you'd start by creating a small class to extract and return the data of interest:</p>\n\n<pre><code>class extract_AllocatedDiffSpace { \n XXX mgmtObject;\npublic:\n extact_AllocatedDiffSpace(XXX init) : mgmtObject(init) {}\n operator long long() { return mgmtObject[0].Obj.DiffArea.m_llAllocatedDiffSpace; }\n};\n</code></pre>\n\n<p>... and then you'd add a template parameter for that type:</p>\n\n<pre><code>template &lt;class T, class U&gt;\nclass COM_iterator { \n// ...\n};\n</code></pre>\n\n<p>and rewrite <code>operator *</code> something like this:</p>\n\n<pre><code>U operator *() { \n return U(mgmtProp);\n}\n</code></pre>\n\n<p>Then the extractor object would be returned by <code>operator *</code>, and when <code>std::accumulate</code> tried to add that to <code>long long</code>, it would convert from the <code>extract_whatever</code> object to <code>long long</code> using your <code>operator long long</code>, which (in turn) would extract and return the right field.</p>\n\n<p>You do need/want to treat this with a bit of care -- the <code>extract_xxx</code> class should generally have only a ctor and one cast operator, to prevent it from accidentally being used in unintended ways. If, for example, you already have a class that acts as a front-end for an mgmtObject in other ways, you probably do <em>not</em> want to just add the <code>operator long long</code> to it -- that makes it much too easy for that conversion to be used in other contexts where it's not appropriate.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T23:57:45.273", "Id": "5534", "Score": "0", "body": "I really like this solution although I have not implemented it yet. Could you give me a hint on how you would write the *policy-like class*? Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:31:59.767", "Id": "5618", "Score": "0", "body": "+1 Nice approach. How would you handle something like E_FAIL being returned from Next? Throw an exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:52:51.530", "Id": "5620", "Score": "0", "body": "@Adrian: Yes, probably. E_FAIL, E_ABORT, E_POINTER, and probably a few more, look/feel a lot like exceptions to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-20T15:03:29.567", "Id": "19132", "Score": "0", "body": "That sounds really nice (honestly, I mean this), but it exhibits why some people think C++ is ridiculous and elephantine amazingly well. A 3 line loop is being replaced with 10s of lines of code, including 2 classes (one of them templated), and *no loop*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T00:26:23.860", "Id": "19150", "Score": "0", "body": "@Novelocrat: First, by my count, the original loop is 5 lines, not three. Second, that 10s of lines of other code is *only written once*. That lets you use all the normal C++ algorithms, so most \"loops\" end up as a line apiece. For anything but the *most* trivial program, the code ends up both shorter *and* much more readable for anybody accustomed to using algorithms/iterators in other code (looking only at length, the break-even point is about 7 loops)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T00:33:59.200", "Id": "19151", "Score": "0", "body": "Ultimately, It's mostly a question of the scale of program for which you design. If your typical program is 100 lines or less, and has no more than two or three loops, then this would indeed be a silly waste of time. If you're accustomed to writing programs that are tens of thousands or lines (or more) this doing a little extra work up front to save a lot more later starts to make a great deal more sense." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T16:02:15.320", "Id": "3647", "ParentId": "3639", "Score": "10" } }, { "body": "<pre><code>while( (hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched)) != S_FALSE ) {\n llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;\n}\n</code></pre>\n\n<p>the above is in my opinion the cleaner way to do what you want.. I don't like the following way because it's more long than necessary:</p>\n\n<pre><code> for (hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched);\n hr != S_FALSE;\n hr = pEnumMgmt-&gt;Next(1, &amp;mgmtObjProp, &amp;ulFetched)) \n {\n llCbStorage += mgmtObjProp[0].Obj.DiffArea.m_llAllocatedDiffSpace;\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T23:48:42.360", "Id": "3728", "ParentId": "3639", "Score": "0" } } ]
{ "AcceptedAnswerId": "3642", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T11:38:51.817", "Id": "3639", "Score": "4", "Tags": [ "c++" ], "Title": "Most elegant way to write this loop" }
3639
<p>Is there any different in performance for the following 2 queries. I'm just wondering what is the better of the two:</p> <pre><code>var res1 = (from a in _ctx.DataContext.Actions join e in _ctx.DataContext.Events on a.EventId equals e.EventId select a).Single(a =&gt; a.ActionId == actionId); </code></pre> <p>or</p> <pre><code>var res2 = (from a in _ctx.DataContext.Actions join e in _ctx.DataContext.Events on a.EventId equals e.EventId where a.ActionId == actionId select a).Single(); </code></pre>
[]
[ { "body": "<p>There should not be any performance difference that is a result of the syntax used. The query syntax is just eye candy that gets converted to the same underlying code. The difference between the two is really just</p>\n\n<pre><code>_ctx.DataContext.Actions\n.Join(_ctx.DataContext.Events, blah, blah, blah)\n.Single(a=&gt;a.ActionId == actionId);\n</code></pre>\n\n<p>vs.</p>\n\n<pre><code>_ctx.DataContext.Actions\n.Join(_ctx.DataContext.Events, blah, blah, blah)\n.Where(a=&gt;a.ActionId == actionId)\n.Single();\n</code></pre>\n\n<p>If there's a performance difference, I'd be very surprised. The only way to really tell is to run some tests. I personally prefer your second method or my first; as I do not like mixing query syntax with imperative syntax.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T16:02:59.750", "Id": "5506", "Score": "1", "body": "I agree, I think it is better to use consistent syntax. I prefer expression syntax for joins too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T15:53:49.540", "Id": "3646", "ParentId": "3645", "Score": "6" } } ]
{ "AcceptedAnswerId": "3646", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T15:40:42.047", "Id": "3645", "Score": "4", "Tags": [ "c#", ".net", "linq" ], "Title": "Is there any loss in performance converting a 'where' clause to a lambda?" }
3645
<p>Before I start working on a quite <strong>JavaScript</strong> heavy application I would like you to review my JS MVC approach.</p> <ul> <li>How can it be improved?</li> <li>Are there any mistakes/issues I should be aware of?</li> </ul> <p>Since the entire app will have multiple modules I would like to split the code into standalone modules that can be loaded as required (any suggestions how to do this?)</p> <p><strong>html</strong></p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;input type="button" id="button" value="world"/&gt; &lt;div id="message"&gt;&lt;/div&gt; &lt;/div&gt; &lt;script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="project.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="utils.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><strong>project.js</strong></p> <pre><code>var GLOBAL = {} || GLOBAL; GLOBAL.SETTINGS = function($) { var global = { fontColor:"red" } return { MODEL : { text : "Text Inside The Containter" }, VIEW : { container: $(".container") }, CONTROLLER : { style : function() { GLOBAL.SETTINGS.VIEW.container.css("color",global.fontColor).append("&lt;h2&gt;" + GLOBAL.SETTINGS.MODEL.text + "&lt;h2&gt;"); } }, init : function() { GLOBAL.SETTINGS.CONTROLLER.style(); } } }(jQuery); GLOBAL.SETTINGS.init(); </code></pre> <p><strong>utils.js</strong></p> <pre><code>GLOBAL.UTILS = function($) { var text = "SOMETHING"; //local return { MODEL : { text : "World" }, VIEW : { button : $("#button"), container: $("#message") }, CONTROLLER : { hello : function(msg) { GLOBAL.UTILS.VIEW.container.append( "Hello " + GLOBAL.UTILS.MODEL.text + "&lt;br/&gt;" ); } }, EVENTS : function() { GLOBAL.UTILS.VIEW.button.click( function() { GLOBAL.UTILS.CONTROLLER.hello(); }); }, init : function() { GLOBAL.UTILS.EVENTS(); } } }(jQuery); GLOBAL.UTILS.init(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T19:55:08.880", "Id": "5514", "Score": "1", "body": "I dont know where to start. Why is everything global :S" } ]
[ { "body": "<blockquote>\n <p>Since the entire app will have multiple modules I would like to split\n the code into standalone modules that can be loaded as required (any\n suggestions how to do this?)</p>\n</blockquote>\n\n<p>Use a dynamic module loader such as <a href=\"http://requirejs.org/\" rel=\"nofollow\">requireJS</a>. You can use it to load modules dynamically using AJAX, and it features an optimization tool to combine your scripts into a single file to reduce the number of HTTP requests on production server.</p>\n\n<blockquote>\n <p>How can it be improved?</p>\n</blockquote>\n\n<p>Stick to shared conventions for the naming of variables. Do not use all-uppercase for regular variables, only when you wish to indicate a constant value.</p>\n\n<p>Use a name specific to your appliation/website, organization or company instead of GLOBAL for the global variable referencing the root of your library, if any: it is no longer needed using <a href=\"http://wiki.commonjs.org/wiki/Modules/AsynchronousDefinition\" rel=\"nofollow\">Asynchronous Module Definition</a> with requireJS.</p>\n\n<blockquote>\n <p>Are there any mistakes/issues I should be aware of?</p>\n</blockquote>\n\n<p>You should think about the way you wish to handle the communication between modules. The latest trend is to abstract and decouple the communication using publish/subscribe pattern.</p>\n\n<p>You can find more details in The <a href=\"http://www.slideshare.net/nzakas/scalable-javascript-application-architecture\" rel=\"nofollow\">Scalable JavaScript Application Architecture presentation</a> by Nicholas C. Zakas, and you may be interested in <a href=\"https://github.com/eric-brechemier/lb_js_scalableApp\" rel=\"nofollow\">the open-source framework that I developed based on this approach</a>, which I <a href=\"https://github.com/eric-brechemier/introduction_to_lb_js_scalableApp\" rel=\"nofollow\">presented recently</a> in Paris JavaScript user group.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-17T15:36:45.183", "Id": "95135", "Score": "0", "body": "In JavaScript all-uppercase variables are [advocated when used for objects that serve as global namespaces](http://javascript.crockford.com/code.html#names). However, I would pick something other than GLOBAL, and nothing within the global \"namespace\" should be all-uppercase." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T13:27:06.800", "Id": "3694", "ParentId": "3648", "Score": "2" } }, { "body": "<p>I'd highly recommend you to take a look at <a href=\"http://maccman.github.com/spine/\" rel=\"nofollow\">Spine.js</a>. It is a tiny library developed by Alex McCaw.</p>\n\n<p>To fully understand his approach (which is similar to the one of Backbone.js), you should also look at his book \"Developing JavaScript Web Applications\" where he highly emphasizes the usage of the MVC pattern.</p>\n\n<p>An example app where Spine has been used can be found here:\n<a href=\"http://maccman-holla.heroku.com/\" rel=\"nofollow\">http://maccman-holla.heroku.com/</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T15:24:25.203", "Id": "3697", "ParentId": "3648", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T18:55:46.853", "Id": "3648", "Score": "3", "Tags": [ "javascript", "design-patterns" ], "Title": "JavaScript MVC - review and suggestions" }
3648
<p>I was wondering if this code can be coded better in terms of semantics or design. Should I return the LOS as numbers? should I have the constants be read from the db in case the user or I want to change them in the future?</p> <pre><code>def get_LOS(headway = None, frequency = None, veh_per_hr = None): if frequency != None and headway = veh_per_hr == None: headway = 1 / frequency if headway!= None or veh_per_hr != None: if headway 10 &lt; or veh_per_hr &gt; 6: return 'A' elif 10 &lt;= headway &lt; 15 or 5 &lt; veh_per_hr &lt;= 6: return 'B' elif 15 &lt;= headway &lt; 20 or 3 &lt; veh_per_hr &lt;= 5: return 'C' elif 20 &lt;= headway &lt; 31 or 2 &lt; veh_per_hr &lt;= 3: return 'D' elif 31 &lt;= headway &lt; 60 or 1 &lt;= veh_per_hr &lt; 2: return 'E' elif headway &gt;= 60 or veh_per_hr &lt; 1: return 'F' else: return 'Error' </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T21:20:47.117", "Id": "5515", "Score": "1", "body": "Edit so that the code is readable and correct. Also you might want to explain a little more about what get_LOS is actually trying to accomplish and what the values 'A' - 'F' mean." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T21:20:59.290", "Id": "5530", "Score": "2", "body": "This code can't run in this form. `headway = veh_per_hr == None` is illegal as is `headway 10 <`. Please be sure that code you want reviewed has a small chance of actually running. And if it doesn't run, please use StackOverflow to find and fix the problems." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-04T09:29:19.120", "Id": "376989", "Score": "0", "body": "The current question title 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." } ]
[ { "body": "<pre><code>def get_LOS(headway = None, frequency = None, veh_per_hr = None):\n</code></pre>\n\n<p>You have no docstring. That would helpful in explaining what the parameters are doing.</p>\n\n<pre><code> if frequency != None and headway = veh_per_hr == None:\n</code></pre>\n\n<p>When checking wheter something is none it is best to use <code>is None</code> or <code>is not None</code></p>\n\n<pre><code> headway = 1 / frequency\n</code></pre>\n\n<p>The problem is that if someone passes frequency along with one of the other parameters, this function will go merrily onwards and probably not even produce an error. I recommend having a get_LOS_from_frequency function which takes the frequency and then calls this function.</p>\n\n<pre><code> if headway!= None or veh_per_hr != None:\n if headway 10 &lt; or veh_per_hr &gt; 6:\n</code></pre>\n\n<p>I'm pretty sure that won't compile</p>\n\n<pre><code> return 'A'\n elif 10 &lt;= headway &lt; 15 or 5 &lt; veh_per_hr &lt;= 6:\n return 'B'\n elif 15 &lt;= headway &lt; 20 or 3 &lt; veh_per_hr &lt;= 5:\n return 'C'\n elif 20 &lt;= headway &lt; 31 or 2 &lt; veh_per_hr &lt;= 3:\n return 'D'\n elif 31 &lt;= headway &lt; 60 or 1 &lt;= veh_per_hr &lt; 2:\n return 'E'\n elif headway &gt;= 60 or veh_per_hr &lt; 1:\n return 'F'\n</code></pre>\n\n<p>I'd store these values in a list which makes it easy to pull them from configuration at a later date if neccesary.</p>\n\n<pre><code> else:\n return 'Error'\n</code></pre>\n\n<p>Don't report error by returning strings. Throw an exception, or at least assert False.</p>\n\n<p>How I'd do this:</p>\n\n<pre><code>import bisect\ndef get_los_from_frequency(frequency):\n return get_los(1 / frequency)\n\nHEADWAY_LIMITS = [10, 15, 20, 31, 60]\nVEH_PER_HR_LIMITS = [1,2,3,5,6]\nGRADES = \"ABCDEF\"\n\ndef get_los(headway = None, veh_per_hr = None):\n if headway is None:\n headway_score = len(GRADES)\n else:\n headway_score = bisect.bisect_left(HEADWAY_LIMITS, headway)\n\n if veh_pr_hr is None:\n veh_pr_hr_score = len(GRADES)\n else:\n veh_pr_hr_score = len(GRADES) - bisect.bisect_left(VEH_PR_HR_LIMITS, veh_pr_hr)\n\n return GRADES[min(headway_score, veh_pr_hr_score)]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T11:31:03.267", "Id": "5519", "Score": "0", "body": "This was very helpful especially with the bisect and lists :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T04:02:37.330", "Id": "3654", "ParentId": "3650", "Score": "8" } }, { "body": "<p>Rather than:</p>\n\n<pre><code>if frequency != None and headway = veh_per_hr == None:\n headway = 1 / frequency\n</code></pre>\n\n<p>You should move the assignment out of the if statement:</p>\n\n<pre><code>if frequency is not None:\n headway = veh_per_hr\n if veh_per_hr is None:\n headway = 1 / frequency\n</code></pre>\n\n<p>This will make it more clear what you're doing without making a future reader do a double-take when they see the assignment embedded in the middle of an if statement. It also might point out that this might be better written as:</p>\n\n<pre><code>headway = veh_per_hr\nif veh_per_hr is None and frequency is not None:\n headway = 1 / frequency\n</code></pre>\n\n<p>As an aside, if you want to know why to use <code>is None</code> or <code>is not None</code> instead of <code>== None</code> or <code>!= None</code>, one reason is:</p>\n\n<pre><code>&gt;&gt;&gt; import timeit\n&gt;&gt;&gt; timeit.Timer('x=1; x != None').timeit()\n0: 0.18491316633818045\n&gt;&gt;&gt; timeit.Timer('x=1; x is not None').timeit()\n1: 0.17909091797979926\n</code></pre>\n\n<p>Another could be the fact that it's much easier to accidentally type <code>=</code> instead of <code>==</code> and have an unnoticed assignment slip by in your conditional (which is another argument for never doing that on purpose as a later maintainer might mistake that for a typo).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T15:03:20.767", "Id": "3662", "ParentId": "3650", "Score": "2" } } ]
{ "AcceptedAnswerId": "3654", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T19:46:56.183", "Id": "3650", "Score": "3", "Tags": [ "python" ], "Title": "Simple Function in python" }
3650
<p>I'm learning a little Scala by writing a little card game. What I want to do here is check that the <code>Traversable[Team]</code> supplied has the same number of team members for each team.</p> <p>How can I clean this up?</p> <pre><code>val teamSizes = teams.map(_.members.size) require(teamSizes.foldLeft((true, teamSizes.head)) { (tuple, lastSize) =&gt; val (b, size) = tuple (b &amp;&amp; size == lastSize, lastSize) }._1) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T14:04:30.110", "Id": "5522", "Score": "2", "body": "The `forall` solution seems like the optimal solution to me." } ]
[ { "body": "<p>An alternative approach is:</p>\n\n<pre><code>require (teamSizes.min == teamSizes.max)\n</code></pre>\n\n<p>but ỳour <code>forall</code>-solution expresses better the idea, that all members share the same size.</p>\n\n<p>And without measuring it, or trying to investigate my assumption, I guess that my approach traverses the collection twice, which could be a drawback for bigger collections or if performed million of times. So less so in this example.</p>\n\n<p>But maybe it is possible to model the constraint into your design, so that all teams get the right size from the beginning?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T01:26:04.633", "Id": "3674", "ParentId": "3651", "Score": "5" } }, { "body": "<p>I've come up with an alternative, which is nice and compact:</p>\n\n<pre><code>val teamSizes = teams.map(_.members.size)\nrequire(teamSizes.forall(_ == teamSizes.head))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T06:08:47.960", "Id": "3684", "ParentId": "3651", "Score": "4" } } ]
{ "AcceptedAnswerId": "3684", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T20:37:05.350", "Id": "3651", "Score": "5", "Tags": [ "scala" ], "Title": "Checking a collection of Ints" }
3651
<p>How can I improve up this code?<br> Is it ok to write code using <code>Invoke</code> and <code>Action</code> so liberally or is this bad? </p> <p><em>Performance is not an issue as I'm not using <code>Invoke</code> 50,000x in a a row (a lot of other things will be done in-between, making the performance hit null).</em></p> <p>The primary goal is to run my list of tasks either by Item first or task first. The secondary goal is to NOT write a massively long method where each method is written out in each way they can be completed. Doing so makes adding new tasks later much easier.</p> <p><strong>Code:</strong> <em>(Updated with pseudo extras)</em> </p> <pre><code>public class TaskObject { public bool RunPerItem = true; //PLACEHOLDER, normally derived externally from view model public bool RunPerTask = false; //PLACEHOLDER, normally derived externally from view model public Dictionary&lt;string, Item&gt;() TaskItems = new Dictionary&lt;string, Item&gt;() { { "ItemA", new Item() {} }, { "ItemB", new Item() {} }, { "ItemC", new Item() {} }, } private List&lt;Action&lt;TaskObject, Item&gt;&gt; Tasks = new List&lt;Action&lt;TaskObject, Item&gt;&gt;() { (TO, I) =&gt; { TO.TaskA(I); }, (TO, I) =&gt; { TO.TaskB(I); }, (TO, I) =&gt; { TO.TaskC(I); } }; public void RunTasks() { //RunPerItem &amp; RunPerTask are type `bool` if (this.RunPerItem) { foreach (var I in this.TaskItems) { foreach (var T in this.Tasks) { T.Invoke(this, I.Value); } } } else if (this.RunPerTask) { foreach (var T in this.Tasks) { foreach (var I in this.TaskItems) { T.Invoke(this, I.Value); } } } } public void TaskA(Item I) { /*...*/ } public void TaskB(Item I) { /*...*/ } public void TaskC(Item I) { /*...*/ } } public class Item { public string ItemName { get; set; } } </code></pre> <p>Thanks for any advice/help!!!</p> <p><strong>Edit/Clarification/Extra Details:</strong> </p> <p>The above code describes 2 different loops with different orders of task completion. </p> <p><strong>Example Orders:</strong><br> <code>this.RunPerItem</code><br> ItemA<br> -TaskA<br> -TaskB<br> -TaskC </p> <p>ItemB<br> -TaskA<br> -TaskB<br> -TaskC </p> <p><code>this.RunPerTask</code><br> ItemA<br> -TaskA </p> <p>ItemB<br> -TaskA </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T18:37:06.647", "Id": "5529", "Score": "0", "body": "Let me check if I understand the idea. You have 2 concepts: tasks and items. You say \"This task should be done against this item\". The relations between tasks and items are many-to-many. Single task can be applied to multiple items and single item can be processed by multiple tasks. Depending on some conditions, you either say \"I want all the tasks required for this item to be ran\" or \"I want this task to process all the items it should\". Is that correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T21:29:52.900", "Id": "5531", "Score": "0", "body": "This code isn't even close to a compileable state. I'm not sure what the \"this\" object refers to in the T.Invoke() calls. Is the RunTasks() method actually on a TaskObject?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T00:25:15.583", "Id": "5535", "Score": "0", "body": "@John Kraft It's not suppose to be. I'm just asking for suggestions on refactoring the loop using different approaches. Not my entire code. `this` refers to the object that contains `RunTasks()`. I didn't include the entire object as it's pointless to my example. I'll update my code with some extra pseudo code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T00:38:14.240", "Id": "5536", "Score": "0", "body": "@loki2302 You have it kinda right. The 2 loops only change the order in which tasks are done on each item. The number of items and tasks is irrelevant. In my example, it will either run task A on each item, then move to B, C, etc.. or do all tasks on 1 item (A, B, C, etc..) and then move to the next item and repeat. As you can see in my example code, the second set of `foreach` statements are ordered the opposite of the first set ((foreach item -> foreach task), (foreach task -> foreach item)), and the task always processes the item the same way in the end (`T.Invoke(this, I.Value);`)." } ]
[ { "body": "<p>Instead of calling your delegates by using <code>Invoke</code> you can call them using the following easier formatting:</p>\n\n<pre><code>Action someAction = () =&gt; {};\nsomeAction();\n</code></pre>\n\n<p>Delegate invocations aren't that much slower than ordinary method calls. No need to worry about performance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T01:05:43.520", "Id": "5538", "Score": "0", "body": "This sounds cool, but is a bit above me right now. How do I apply this to the current `List` of `Action`s I currently have in the code above? From what I understand of your example code, I would have to make them all fields which would kill the looping over them idea as far as I can see/understand. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T11:41:38.253", "Id": "5555", "Score": "0", "body": "`T( this, I.Value );` ... Why would there be any difference? ;p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T12:00:52.730", "Id": "5556", "Score": "0", "body": "Ahhh cool.. I didn't know you could do that.. interesting... Is this syntactic sugar or does it behave slightly different than using `T.Invoke(..`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T13:59:58.220", "Id": "5560", "Score": "0", "body": "I'm pretty certain [it's syntactic sugar](http://msdn.microsoft.com/en-us/library/aa288459(v=vs.71).aspx). When you want to call the delegate asynchronously however, you can use `BeginInvoke` and `EndInvoke`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T00:36:01.127", "Id": "3671", "ParentId": "3652", "Score": "1" } }, { "body": "<p>Simple thing I see is for readability i'd place the inside of each top ifs into a seperate method with an explicit name. And I always like returning immediately (often times the method itself) then you don't need the else (your second if).</p>\n\n<pre><code>public void RunTasks()\n{\n if (this.RunPerItem) \n {\n return RunTasksForEachItem();\n }\n\n return RunEachTask();\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T01:00:27.157", "Id": "5537", "Score": "0", "body": "Good idea with the explicit method idea. I'll look into the return idea. I'm not sure it'll work with my real code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T20:01:05.123", "Id": "5568", "Score": "0", "body": "Ahh... I see now. I implemented the method separation idea, but the return idea would break the rest of my code (interaction with my view, which isn't in the code above)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T00:46:22.443", "Id": "3672", "ParentId": "3652", "Score": "0" } }, { "body": "<p>I don't know if you can, depending on your real world needs... but if you can convert the TaskItems Dictionary to a List of KeyValuePairs like this...</p>\n\n<pre><code>public List&lt;KeyValuePair&lt;string, Item&gt;&gt; TaskItems = new List&lt;KeyValuePair&lt;string, Item&gt;&gt;\n{\n new KeyValuePair&lt;string, Item&gt;( \"ItemA\", new Item() {} ),\n new KeyValuePair&lt;string, Item&gt;( \"ItemB\", new Item() {} ), \n new KeyValuePair&lt;string, Item&gt;( \"ItemC\", new Item() {} ), \n};\n</code></pre>\n\n<p>Then you can use the ForEach() exstension method to reduce the loop code to...</p>\n\n<pre><code>if (this.RunPerItem) \n{\n TaskItems.ForEach(I =&gt; Tasks.ForEach(T =&gt; T(this, I.Value))); \n}\nelse if (this.RunPerTask)\n{\n Tasks.ForEach(T =&gt; TaskItems.ForEach(I =&gt; T(this, I.Value)));\n}\n</code></pre>\n\n<p>If you couple that with @Steven Jueris' idea of splitting them into their own methods, your code will be very clean.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T20:03:07.837", "Id": "5569", "Score": "0", "body": "That is beautiful! I thought there was some fancy linq/lambda/extension method way of doing this. I just couldn't think of it. I still have trouble thinking of my code in that manner as I've been writing out all my code the long way like above for years. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T20:07:06.647", "Id": "5570", "Score": "0", "body": "I think I could extend the dictionary class to support the ForEach extension method too.. That should be easy to find on google." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T20:10:48.063", "Id": "5571", "Score": "0", "body": "Yes. There's a gazillion implementations of it on the net. The only difference between the list and dictionary, the way you are using it, is that the dictionary won't allow you to add the same key/value pair twice. It's a good measure of protection if you cannot control what gets put into the collection. However, if you have full control over the collection and don't have to worry about that, then there's no harm in using the list and the built in method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T20:16:50.607", "Id": "5572", "Score": "1", "body": "Personally, I'd stay away from using the `List<T>.ForEach()` method. It doesn't really make a `foreach` looping construct look much cleaner. In some ways, it unnecessarily complicates it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T20:27:33.680", "Id": "5573", "Score": "0", "body": "@Jeff Mercado - normally I would agree. In more complicated usage, it can complicate the code, as well as, cause difficulty debugging. However, IMO, this simple usage lends itself well to the construct." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T13:47:57.860", "Id": "3695", "ParentId": "3652", "Score": "4" } } ]
{ "AcceptedAnswerId": "3695", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T00:15:03.510", "Id": "3652", "Score": "4", "Tags": [ "c#", "delegates" ], "Title": "Improve my Task Loops" }
3652
<p>jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.</p> <blockquote> <p>jQuery is designed to change the way that you write JavaScript.</p> </blockquote> <p><strong>Useful links:</strong></p> <ul> <li><p><a href="http://jquery.com/" rel="nofollow">Official website</a></p></li> <li><p><a href="http://docs.jquery.com/Main_Page" rel="nofollow">Official documentation</a></p></li> <li><p><a href="http://api.jquery.com/" rel="nofollow">Official API reference</a></p></li> <li><p><a href="http://blog.jquery.com/" rel="nofollow">Official Blog</a></p></li> <li><p><a href="http://jqfundamentals.com/" rel="nofollow">jQuery Fundamentals</a></p></li> <li><p><a href="http://www.learningjquery.com/" rel="nofollow">Learning jQuery - Tips, Techniques, Tutorials</a></p></li> </ul> <p><strong>Books</strong></p> <ul> <li><p><a href="http://jqueryenlightenment.com/" rel="nofollow">jQuery Enlightenment</a></p></li> <li><p><a href="http://www.manning.com/bibeault2/" rel="nofollow">jQuery in Action, Second Edition</a></p></li> <li><p><a href="http://book.learningjquery.com/" rel="nofollow">Learning jQuery, Third Edition</a></p></li> </ul> <p><strong>What to know more:</strong></p> <ul> <li>Read <a href="http://ejohn.org/about/" rel="nofollow">about John Resig</a>, creator of the jQuery JavaScript library.</li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T06:19:25.427", "Id": "3655", "Score": "1", "Tags": null, "Title": null }
3655
A JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T06:19:25.427", "Id": "3656", "Score": "1", "Tags": null, "Title": null }
3656
<p>I'm working on set of methods that locate DVR surveillance footage, based on timestaps.</p> <p>The files are in the following format: </p> <p><code>&lt;drive&gt;\&lt;year&gt;\&lt;month&gt;\&lt;day&gt;\&lt;camera&gt;\&lt;hour&gt;-&lt;minute&gt;-&lt;second&gt;.&lt;extension&gt;</code></p> <p>Example: Z:\2011\07\02\000001\00-13-15.mkv through Z:\2011\07\02\000001\23-45-13.mkv</p> <p>The videos are in 15ish minute increments, that start <em>roughly</em> around the turn of the hour. The edge case, as you could imagine, is around that turn of the hour mark. I have come up with two methods that get the job done, but are extremely convoluted, and frankly ugly.</p> <p>Can any one think of a less complex way to do this?</p> <p><strong>EDIT:</strong> After some thought, I refactored it into three methods. Splitting out the path building as I had with the file name. It's better, but I still feel it can be simpler. This also resolves the 'change of day' issue I had mentioned below.</p> <pre><code> public static string GetSecurityFootage(DateTime timeStamp, Camera camera) { string storageLoc = Initialization.DvrStorageLocation; // Just bail if we don't have a valid storage location. if (!Directory.Exists(storageLoc)) { return ""; } // Get path and file name based on timestamp. string path = GetVideoPath(timeStamp, camera, storageLoc); string fileName = GetVideo(timeStamp, path.ToString()); if (fileName != "" &amp;&amp; File.Exists(path + fileName)) { path = path + fileName; } // Try the end of the last hour/day. else { // Subtract from time minutes +1 to set time to last hour. timeStamp = timeStamp.AddMinutes(-(timeStamp.Minute + 1)); path = GetVideoPath(timeStamp, camera, storageLoc); fileName = GetVideo(timeStamp, path.ToString()); if (fileName != "" &amp;&amp; File.Exists(path + fileName)) { path = path + fileName; } else { // If it's not it the last hour, we do not have footage. return ""; } } return path; } private static string GetVideoPath(DateTime timeStamp, Camera camera, string storageLoc) { string pathSep = Path.DirectorySeparatorChar.ToString(); string cameraPath = ""; string year = timeStamp.Year.ToString(); string month = timeStamp.Month.ToString(); string day = timeStamp.Day.ToString(); StringBuilder path = new StringBuilder(); // Paths are preceded by 0. if (day.Length == 1) { day = "0" + day; } if (month.Length == 1) { month = "0" + month; } switch (camera) { case Camera.Patio: cameraPath = "000001"; break; case Camera.Counter: cameraPath = "000002"; break; case Camera.Shed: cameraPath = "000003"; break; case Camera.Cafe: cameraPath = "000004"; break; case Camera.Lobby: cameraPath = "000005"; break; default: cameraPath = "000002"; //default to counter. break; } // Path to video. path.Append(storageLoc); if (!storageLoc.Trim().EndsWith(pathSep)) { path.Append(pathSep); } path.Append(year); path.Append(pathSep); path.Append(month); path.Append(pathSep); path.Append(day); path.Append(pathSep); path.Append(cameraPath); path.Append(pathSep); // The path doesn't exist, we will not have footage. if (!Directory.Exists(path.ToString())) { return ""; } return path.ToString(); } private static string GetVideo(DateTime timeStamp, string path) { string hour = timeStamp.Hour.ToString(); int minute = timeStamp.Minute; //leave as int for comparison. string fileName = ""; if (hour.Length == 1) { hour = "0" + hour; } // Get all the files in the dir, but just the file names. var files = Directory.GetFiles(path.ToString()).Select(f =&gt; Path.GetFileName(f)); // All files that start with the correct hour. var q = from f in files where f.Trim().StartsWith(hour) orderby f select f; // Now, loop the files for the higest that is still less than the minute we're looking for. foreach (var file in q) { int min = 0; int.TryParse(file.Substring(3, 2), out min); // Set file name for each loop; when done the highest should always be the last one set. if (min &lt;= minute) { fileName = file; } } return fileName; } </code></pre> <p>I guess there is no strike-through... disregard the following:</p> <p><em>One thing that is noticeable is that for the change of day, it will fail to find the footage. This isn't a huge deal, this is only a convenience feature for our POS. In this case, the user will just have to browse to the video manually. The change of hour is important, otherwise this feature is useless 1/4 of the time.</em></p>
[]
[ { "body": "<p>String.IsnullOrEmpty instead of blank string comparisons. Also return immediately in your if and remove the else, put the else contents in a seperate explicitely named method which you return directly.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T13:31:05.143", "Id": "5559", "Score": "0", "body": "Good call on returning after from the first if. The nested if statement was really bugging. But, what benefit would it be to add another method after the if? If it returns on the first if, I could leave the second hour check under it without calling fourth method." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T01:06:35.000", "Id": "3673", "ParentId": "3659", "Score": "1" } }, { "body": "<p>Looking at how you try to solve this problem, you try to guess the expected file name of \nthis point in time. Allow me to suggest another approach which is more natural and simpler IMHO.</p>\n\n<p>If all these videos are sorted, a footage is in a video if it's timestamp is within the time of this video, e.g. if you have a video <code>Z:\\2011\\07\\02\\000001\\13-45-13.mkv</code> and the next video is <code>Z:\\2011\\07\\02\\000001\\14-00-32.mkv</code>, and you are looking for the footage at 2011-07-02 13:52:07, you know that the footage it's in the first one. </p>\n\n<p>To do this, you need to </p>\n\n<ol>\n<li>Sort the videos by their starting date (which you will get by parsing the name).</li>\n<li>Search for the video containing this footage timestamp.</li>\n</ol>\n\n<p>This also handles all your edge cases :).</p>\n\n<p>But I still have some comments about your code.</p>\n\n<ol>\n<li>Don't do <code>path.ToString()</code> when <code>path</code> is <em>already</em> a string.</li>\n<li><code>String.format</code> is more readable than <code>StringBuilder</code> in your case.</li>\n<li>What if you add another camera? You will have to modify and recompile your code. Consider defining cameras externally.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T13:31:00.153", "Id": "5558", "Score": "0", "body": "Thanks for all the helpful feedback. I noticed the path.ToString() after I edited, it was just left over. I used StringBuilder because of the if in the middle of it, but I moved that check up, and changed to string.Format, now I only need one pathSep. The choice to build the cameras as a enum was one of security; so there is not some cameras.xml that a user could delete." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T02:20:22.947", "Id": "3675", "ParentId": "3659", "Score": "6" } }, { "body": "<p>Just break the method in a smaller ones and move all of them in a separate class that will be used only for creating a path to a file. It might be the builder as a loki2302 said or just a provider</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T05:48:16.673", "Id": "3703", "ParentId": "3659", "Score": "0" } } ]
{ "AcceptedAnswerId": "3675", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T14:54:16.697", "Id": "3659", "Score": "2", "Tags": [ "c#" ], "Title": "Any suggestions on how to clean up this convoluted file look-up method?" }
3659
<p>I am a C# developer, dont know much about vc++ or c++, never used it, for some reasons i have decided to use a c++ dll in my app for downloading content from the web.</p> <p>I dont want to use WebClient.</p> <p>I want it to download html content by providing Url of the resource, the dll will return the string response.</p> <p>this is the code i have till now, <a href="http://www.zedwood.com/article/113/cpp-winsock-basic-http-connection" rel="nofollow">source</a></p> <pre><code>#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;stdlib.h&gt; #include &lt;winsock.h&gt;//dont forget to add wsock32.lib to linker dependencies using namespace std; #define BUFFERSIZE 1024 void die_with_error(char *errorMessage); void die_with_wserror(char *errorMessage); int main(int argc, char *argv[]) { string request; string response; int resp_leng; char buffer[BUFFERSIZE]; struct sockaddr_in serveraddr; int sock; WSADATA wsaData; char *ipaddress = "208.109.181.178"; int port = 80; request+="GET /test.html HTTP/1.0\r\n"; request+="Host: www.zedwood.com\r\n"; request+="\r\n"; //init winsock if (WSAStartup(MAKEWORD(2, 0), &amp;wsaData) != 0) die_with_wserror("WSAStartup() failed"); //open socket if ((sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) &lt; 0) die_with_wserror("socket() failed"); //connect memset(&amp;serveraddr, 0, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = inet_addr(ipaddress); serveraddr.sin_port = htons((unsigned short) port); if (connect(sock, (struct sockaddr *) &amp;serveraddr, sizeof(serveraddr)) &lt; 0) die_with_wserror("connect() failed"); //send request if (send(sock, request.c_str(), request.length(), 0) != request.length()) die_with_wserror("send() sent a different number of bytes than expected"); //get response response = ""; resp_leng= BUFFERSIZE; while (resp_leng == BUFFERSIZE) { resp_leng= recv(sock, (char*)&amp;buffer, BUFFERSIZE, 0); if (resp_leng&gt;0) response+= string(buffer).substr(0,resp_leng); //note: download lag is not handled in this code } //display response cout &lt;&lt; response &lt;&lt; endl; //disconnect closesocket(sock); //cleanup WSACleanup(); return 0; } void die_with_error(char *errorMessage) { cerr &lt;&lt; errorMessage &lt;&lt; endl; exit(1); } void die_with_wserror(char *errorMessage) { cerr &lt;&lt; errorMessage &lt;&lt; ": " &lt;&lt; WSAGetLastError() &lt;&lt; endl; exit(1); } </code></pre> <p>The instructions with the code says, code will end an http download 'early' if the download is anything slower than instant. </p> <p><strong>Please suggest better code, or modifications, which can be perfect for use in a Fast Crawler.</strong></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T04:36:47.350", "Id": "5523", "Score": "7", "body": "Your implementation is completely broken with respect to HTTP compliance. You might be lucky if it works in more than one case. Implementing HTTP is not trivial. Use WebClient or any other well-tested HTTP library. Furthermore, your performance will not magically increase by switching from C# to C++." } ]
[ { "body": "<p>The above implementation has little to no chance of working. The HTTP protocol is quite complex, and none of that complexity is contemplated.</p>\n\n<p>My advice is, don't waste time and energy in this. Use a high-level library.</p>\n\n<p>Also, using low-level code will <strong>NOT</strong> improve the performance of fetching a document via HTTP -- even if your implementation was blazing-fast 100% polished assembly code, you'd still have to wait centuries (from the CPU point of view) for the data to arrive from the network.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T06:29:39.207", "Id": "3661", "ParentId": "3660", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T04:05:21.340", "Id": "3660", "Score": "1", "Tags": [ "c#", "c++" ], "Title": "VC++ Fast Http Download" }
3660
<p>Rather than doing what is essentially a large switch statement for every possible type, is there a better more generic way of converting to a specific type with reflection? I've looked up TypeConverter but don't understand the documentation.</p> <pre><code>if (header.Property.PropertyType == typeof(Int32)) { header.Property.SetValue(instanceOfTrade, value.ToInt(), null); } else if (header.Property.PropertyType == typeof(decimal)) { header.Property.SetValue(instanceOfTrade, value.ToDecimal(), null); } else if (header.Property.PropertyType == typeof(DateTime)) { header.Property.SetValue(instanceOfTrade, value.TryToDateTime(), null); } else { header.Property.SetValue(instanceOfTrade, value.ToString(), null); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T17:11:17.780", "Id": "5525", "Score": "0", "body": "Maybe you mean \"with reflection\"? Is reflection mandatory approach? Could you post how does your code's consumer look like?" } ]
[ { "body": "<p>You could use an extension method (if this is common), or a regular generic method with a &quot;<a href=\"http://msdn.microsoft.com/en-us/library/system.iconvertible.aspx\" rel=\"noreferrer\">IConvertible</a>&quot; constraint on the desired value then call &quot;<a href=\"http://msdn.microsoft.com/en-us/library/system.convert.changetype.aspx\" rel=\"noreferrer\">Convert.ChangeType</a>&quot; in your SetValue call.</p>\n<pre><code>static class ObjectExtensions\n{\n public static void SetPropertyValue&lt;T&gt;(this object obj, string propertyName, T propertyValue)\n where T : IConvertible\n {\n PropertyInfo pi = obj.GetType().GetProperty( propertyName );\n \n if( pi != null &amp;&amp; pi.CanWrite )\n {\n pi.SetValue\n (\n obj,\n Convert.ChangeType(propertyValue, pi.PropertyType),\n null\n );\n }\n }\n}\n\nclass TestObject\n{\n public string Property1 { get; set; }\n public int Property2 { get; set; }\n}\n\nvoid Main()\n{\n TestObject o = new TestObject();\n \n // Propery1 == null, Property2 == 0\n o.SetPropertyValue( &quot;Property1&quot;, 1 );\n o.SetPropertyValue( &quot;Property2&quot;, &quot;123&quot; );\n // Propery1 == 1, Property2 == 123\n}\n</code></pre>\n<p>Obviously no error handling and this is assuming you want it available on all types, so I just threw it in an &quot;ObjectExtensions&quot; class so it'll be visible on all types.</p>\n<p>Just adjust the constraints to fit your exact needs, or just throw it in a regular class if you don't want to use extensions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T15:53:55.703", "Id": "3664", "ParentId": "3663", "Score": "6" } } ]
{ "AcceptedAnswerId": "3664", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T15:14:48.000", "Id": "3663", "Score": "6", "Tags": [ "c#", "reflection" ], "Title": "Is there a better way to convert to a specific type with reflection?" }
3663
<p>I've been researching various patterns for structuring my business logic &amp; data access, particular in the context of C# and the Entity Framework. I've come up with a basic idea of how I <em>think</em> I'd like to do it, based on several SO answers:</p> <ul> <li><p><a href="https://stackoverflow.com/questions/1169188/ef-objectcontext-service-and-repositry-managing-context-lifetime">https://stackoverflow.com/questions/1169188/ef-objectcontext-service-and-repositry-managing-context-lifetime</a></p></li> <li><p><a href="https://stackoverflow.com/questions/678922/using-transactions-with-business-processes-and-the-repository-pattern">https://stackoverflow.com/questions/678922/using-transactions-with-business-processes-and-the-repository-pattern</a></p></li> </ul> <p>I envision a <code>UnitOfWork</code> that encapsulates an <code>IObjectContext</code> (abstract so I can swap out contexts for testing), and exposes a repository of <code>IQueryable&lt;TEntity&gt;</code>.</p> <pre><code>interface IUnitOfWork { private IObjectContext _context; public void SetupContext(); // Create object context here IQueryable&lt;TEntity&gt; Repository&lt;TEntity&gt;() where TEntity : class, IEntityWithKey; } </code></pre> <p>I intend to write service classes that contain my business logic, and follow this structure:</p> <pre><code>class MyService : IService { public DoWork() { // Same as nesting one using within the other using( IUnitOfWork unitOfWork = unitOfWorkFactory.Create() ) using( TransactionScope tScope = new TransactionScope() ) { var repository = unitOfWork.Repository&lt;TEntity&gt;(); /* Do some work with repository */ unitOfWork.Commit(); // Save changes tScope.Complete(); // End transaction } } } </code></pre> <p>Am I going crazy with design patterns? Is there a better way to do this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T23:37:56.957", "Id": "5628", "Score": "0", "body": "This looks a little too generic to really comment on, you need a bit of a problem spec before anyone can speak to implementation details at this level. Given this is architectural, the problem scope is the whole domain which is a little too broad and you give no context of the domain anyhow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T00:24:42.553", "Id": "5700", "Score": "0", "body": "It may be architectural, but I think there's plenty of context. I'm looking feedback on this code's use of design patterns in regards to EF. I realize it's general, but I expected a general response; Ladislav's answer is exactly what I was looking for." } ]
[ { "body": "<p>By reviewing this I have two general comments to your code:</p>\n\n<h2>Transaction</h2>\n\n<p>Is there any reason to use explicit transaction scope? When you call <code>SaveChanges</code> on the context it already uses transaction. It either uses ambient transaction or create a new one database transaction. So unless you are using multiple transactional resources (multiple database connections, MSMQ, etc.) or calling <code>SaveChanges</code> multiple times you don't need to create transaction explicitly. It is point of unit of work to save changes as one atomic unit. Also one side note: Default transaction used in SaveChanges uses default (or current) isolation level configured on database connection. Default for SQL Server is <code>ReadCommitted</code>. Default isolation level for <code>TransactionScope</code> is <code>Serializable</code>.</p>\n\n<h2>Testing</h2>\n\n<p>You mentioned that you want to make this abstraction to be able to replace context for testing. If you mean unit testing you can stop and go back to redesign your interfaces. You cannot unit test your business layer code if it uses <code>IQueryable</code> (Linq-to-entities) exposed by your data access layer. There is currently no provider which can simulate linq-to-entities behaviour for your unit tests. Once you use same in memory collection to mock <code>IQueryable</code> you will use linq-to-objects in your unit tests instead. That means you will test different code. </p>\n\n<p>The only correct way is either:</p>\n\n<ul>\n<li>Not expose <code>IQueryable</code> from your DAL. Keep all linq-to-entities queries as internal implementation of your repositories (= you must materialize result in repositories by for example calling <code>.ToList</code>).</li>\n<li>Use integration tests against real test database instead of using unit tests with mocked data access layer</li>\n</ul>\n\n<p>I wrote several answers about this problematic on Stack Overflow:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/6766478/unit-testing-dbcontext\">Unit testing DbContext</a></li>\n<li><a href=\"https://stackoverflow.com/questions/6051145/using-the-repository-pattern-to-support-multiple-providers\">Using the repository pattern to support multiple providers</a></li>\n</ul>\n\n<p>Check also linked answers in those questions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T19:37:22.100", "Id": "5736", "Score": "0", "body": "One concern I have about exposing `IList<T>` instead of `IQueryable<T>` for my repository is that it means I will sometimes be returning large lists and filtering them in memory with LINQ-to-Objects, which is not desirable when I have a short-lived `UnitOfWork` creating the repository. Are integration tests the only way, then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T21:18:02.463", "Id": "5739", "Score": "0", "body": "@Rob: That is not true. I don't say that you should always return all entities to your application and run filtering in memory. Your DAL can still do filtering. You just need to construct queries in DAL and don't let upper layer to construct them if you want to mock / fake DAL. Upper layer can only pass parameters for your queries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T21:56:12.930", "Id": "5745", "Score": "0", "body": "@Ladislav: Seems I was misunderstanding the repository pattern; I wasn't going to expose it to the business layer at all, but instead encapsulate it inside a DAO. In that sense, my business logic would have never touched IQueryable. Thanks for your clarification." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T10:38:40.337", "Id": "3760", "ParentId": "3667", "Score": "3" } } ]
{ "AcceptedAnswerId": "3760", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T18:21:21.353", "Id": "3667", "Score": "2", "Tags": [ "c#", "design-patterns", "entity-framework" ], "Title": "Advice on approach to organizing my business logic & data access?" }
3667
<p>I have a requirement where I need to build a grid with dynamic columns. I am dealing with a large dataset so I would like to use server-side paging, sorting, filtering logic so that I render only a page-size. I think I got the basic functionality working but just wanted to get my approach reviewed.</p> <p>An action route will be the JSON datasource for the <code>jqgrid</code>.</p> <p><a href="https://stackoverflow.com/questions/5111653/problem-showing-jqgrid-with-dynamic-column-binding">Reference</a></p> <p>My approach:</p> <ol> <li>First make an ajax call to get the dynamic col model and other grid params (<code>rows</code>, <code>page</code> etc.) except data.</li> <li>Update grid params (<code>url</code>, <code>datatype</code> and <code>mtype</code>) to enable server-side paging, sorting etc.</li> </ol> <p>I am using a flag in the query string to determine if I need the col model (or) the data.</p> <p>Note: I set the async flag to false for the AJAX requests to make sure I do not run into timing issues.</p> <p>As you can see, I need to make two requests to set up the grid. One to get the col model and another one to get data and to update it to enable server-side interaction for subsequent requests. Is this ok?</p> <pre><code>$.ajax({ url: firstFetchURL, //will hit an asp.net mvc action on a controller that returns json dataType: "json", type: 'POST', async: false, success: function (result) { if (result) { if (!result.Error) { var colD = result.data; var colM = result.colModelList; var colN = result.columnNames; $("#myGrid").jqGrid('GridUnload'); $("#myGrid").jqGrid({ datatype: 'local', colModel: colM, colNames: colN, data: colD, height: "auto", rowNum: 10, sortname: viewOptionText, sortorder: "desc", pager: '#myGridPager', caption: "Side-by-Side View", viewrecords: true, gridview: true }); //Update grid params so that subsequent interactions with the grid for sorting,paging etc. will be server-side $("#myGrid").jqGrid('setGridParam', { url: secondFetchURL, datatype: 'json', mtype: 'POST' }).trigger('reloadGrid'); } } }, error: function (xhr, ajaxOptions, thrownError) { if (xhr &amp;&amp; thrownError) { alert('Status: ' + xhr.status + ' Error: ' + thrownError); } }, complete: function () { $("#loadingDiv").hide(); } }); </code></pre> <p>I saw a related post <a href="https://stackoverflow.com/questions/2277962/jqgrid-and-dynamic-column-binding">here</a>, but I am looking for some direction from experienced JQGrid users.</p>
[]
[ { "body": "<p>Small recommendations:</p>\n\n<ol>\n<li>It seems to me that you can remove <code>async: false</code> parameter for the <code>$.ajax</code> call.</li>\n<li>You can remove <code>result.data</code> from the data returned by the ajax call. (After that you should and the line with <code>var colD = result.data</code>). The data will be not really used because you call <code>trigger('reloadGrid');</code> immediately.</li>\n<li>On the other side the values for <code>sortname</code> and <code>sortorder</code> parameters should be included in the data model (as the properties of <code>result</code>).</li>\n<li>You can use <code>url: secondFetchURL, datatype: 'json', mtype: 'POST'</code> parameters directly in the jqGrid definition ( in <code>$(\"#myGrid\").jqGrid({/*here*/});</code>. No <code>trigger('reloadGrid')</code> will be needed.</li>\n</ol>\n\n<p><strong>UPDATED</strong>: Look at <a href=\"https://stackoverflow.com/questions/5383847/is-it-possible-to-modify-the-colmodel-after-data-has-loaded-with-jqgrid/5408195#5408195\">this</a> and <a href=\"https://stackoverflow.com/questions/5387179/jqgrid-several-questions-matrix-display/5409356#5409356\">this</a> answers. Probably the approach is what you need from the dynamic columns.</p>\n\n<p>You can take a look in <a href=\"https://stackoverflow.com/questions/5171617/how-to-add-custom-formatter-for-jqgrid-with-dynamic-column-binding/5175127#5175127\">the answer</a> in case if you will need to use <a href=\"http://www.trirand.com/jqgridwiki/doku.php?id=wiki:custom_formatter\" rel=\"nofollow noreferrer\">custom formatters</a>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T14:30:17.910", "Id": "5561", "Score": "0", "body": "One issue with my approach is I need to make two requests to set up the grid the first time, one to get the col model and another for the data. Is it possible to extend the Json reader so that we can the col model server-side like the other parameters. { total: xxx, \npage: yyy, \nrecords: zzz, \nrows: [ ...],\ncolModel: {....}, // is it possible to support this in jqgrid\ncolNames: {....} // is it possible to support this in jqgrid\n}" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T14:46:35.983", "Id": "5562", "Score": "0", "body": "@StudentForever: It is not possible because many parts of grid are currently not dynamic. I have the same opinion as you in the subject. Some time before I made [the feature request](http://www.trirand.com/blog/?page_id=393/feature-request/filling-jqgrid-parameters-like-colmodel-per-ajax/#p22758) which was stayed unanswered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T14:53:53.927", "Id": "5563", "Score": "0", "body": "Very interesting , Thanks. Any final thoughts on my approach on making two requests to initialize the dynamic jqgrid based on my requirement. Thanks a lot for your time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T15:34:56.377", "Id": "5564", "Score": "0", "body": "@StudentForever: You are welcome! If you have common (general) grid settings the usage of two asynchronous `ajax` calls (one inside of the `success` handler of another) I find the logical consequence from the possibilities which you has. It is clear enough and easy to understand and to manage. One additional tip: try to use not so much jqGrid settings in the `colModel` which you save in the database. Instead of that you can consider to use [column templates](http://stackoverflow.com/questions/6044047/stopping-columns-resizable-in-jqgrid/6047856#6047856)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T15:54:38.430", "Id": "5565", "Score": "0", "body": "Ok, Thanks. Will look into the column templates option. Thanks again for all your inputs." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T15:56:21.180", "Id": "5566", "Score": "0", "body": "@StudentForever: You are welcome!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T22:55:01.660", "Id": "3669", "ParentId": "3668", "Score": "5" } } ]
{ "AcceptedAnswerId": "3669", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T21:53:44.453", "Id": "3668", "Score": "3", "Tags": [ "javascript", "jquery", "ajax", "asp.net-mvc", "url-routing" ], "Title": "JQGrid with dynamic columns and server-side functionality" }
3668
<p>I've built a <a href="http://en.wikipedia.org/wiki/Discrete_event_simulation" rel="nofollow">discrete event simulation system</a>, similar to the bank problem presented on the wikipedia page but with a key difference.</p> <p>Let's say, that a <code>TELLER</code> can service two <code>CUSTOMERS</code> at the same time, and that the <code>CUSTOMER-DEPARTURE</code> time depends upon the number of <code>CUSTOMERS</code> a <code>TELLER</code> is servicing concurrently; I need to manage the dynamic <code>CUSTOMER-DEPARTURE</code> event scheduling when the number of concurrently served <code>CUSTOMERS</code> changes.</p> <p>Consider the following example, where the servicing time for a single customer is of 4 time intervals and is doubled when the teller is servicing two customers at the same time:</p> <pre><code>t=0 CUSTOMER-ARRIVAL (1) t=1 TELLER-BEGINS-SERVICE (1) --&gt; schedules CUSTOMER-DEPARTURE (1) at t_a=5 ... t=3 CUSTOMER-ARRIVAL (2) t=4 TELLER-BEGINS-SERVICE (1) --&gt; teller is now servicing two customers: - reschedule CUSTOMER-DEPARTURE (1) to t_b=6 - schedule CUSTOMER-DEPARTURE (2) at t_c=12 ... t=6 CUSTOMER-DEPARTURE (1) --&gt; teller is now servicing only one customer: - reschedule CUSTOMER-DEPARTURE (2) at t_d=9 ... t=9 CUSTOMER-DEPARTURE (2) </code></pre> <p>The times are calculated using this formula:</p> <pre><code>t = t_current + (4 - completed) * customer_count </code></pre> <p>Which gives these results for the values used above:</p> <ol> <li>t_a = 1 + (4 - 0) * 1 = 5</li> <li>t_b = 4 + (4 - 3) * 2 = 6</li> <li>t_c = 4 + (4 - 0) * 2 = 12</li> <li>t_d = 6 + (4 - 1) * 1 = 9</li> </ol> <p>I came up with the following code in Python; is there something you would have done differently?</p> <pre><code>import heapq class Simulator(object): def __init__(self): self.queue = [] self.time = 0 def schedule(self, time, callback, *args, **kwargs): """ Schedules an event to be executed at a later point in time. ``callback`` is a callable which executed the event-specific behavior; the optional ``args`` and ``kwargs`` arguments will be passed to the event callback at invocation time. Returns an object which can be used to reschedule the event. """ assert time &gt; self.time event = [time, True, callback, args, kwargs] heapq.heappush(self.queue, event) return event def reschedule(self, event, time): """ Reschedules ``event`` to take place at a different point in time """ assert time &gt; self.time rescheduled = list(event) event[1] = False rescheduled[0] = time heapq.heappush(self.queue, rescheduled) return rescheduled def run(self): """ Simple simulation function to test the behavior """ while self.queue: time, valid, callback, args, kwargs = heapq.heappop(self.queue) if not valid: continue self.time = time callback(*args, **kwargs) def event(id, simulator, scheduled, rescheduled=None): if rescheduled is None: print "Event #{0}: scheduled at {1} and fired at {2}".format(id, scheduled, simulator.time) else: print "Event #{0}: scheduled at {1}, rescheduled at {2} and fired " \ "at {3}".format(id, scheduled, rescheduled, simulator.time) s = Simulator() e1 = s.schedule(5, event, 1, s, 5) e2 = s.schedule(7, event, 2, s, 7, 12) e3 = s.schedule(9, event, 3, s, 9) s.reschedule(e2, 12) s.run() </code></pre> <hr>
[]
[ { "body": "<p>Event is some kind of stateful object being modeled as a list. Often a bad idea.</p>\n\n<pre><code>class Event( object ):\n def __init__( self, time, callback, *args, **kwargs ):\n self.time= time\n self.live= True\n self.callback= callback\n self.args= args\n self.kwargs= kwargs\n def invalidate( self ):\n self.live= False\n def __call__( self ):\n if self.live: \n self.callback( self.*args, **self.kwargs )\n</code></pre>\n\n<p>This may be better than a list. A list where the order of the arguments is critical is a bad thing waiting to happen.</p>\n\n<p>Code like <code>event[1] = False</code> is utterly opaque. It should be replaced with <code>event.invalidate()</code> so that the meaning is obvious.</p>\n\n<p>Also, once you have an <code>Event</code> class, your separate <code>event</code> function becomes needless. You can subclass <code>event</code> like this.</p>\n\n<pre><code>class MyEvent( Event ):\n def __call__( self, id, simulator, scheduled, rescheduled=None ):\n if rescheduled is None:\n print \"Event #{0}: scheduled at {1} and fired at {2}\".format(id,\n scheduled, simulator.time)\n else:\n print \"Event #{0}: scheduled at {1}, rescheduled at {2} and fired \" \\\n \"at {3}\".format(id, scheduled, rescheduled, simulator.time)\n</code></pre>\n\n<p>Avoid trying to build a \"mutable tuple\" as a fixed-length list. </p>\n\n<p>Either use immutable named tuples or a proper class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T04:07:41.900", "Id": "5643", "Score": "1", "body": "Thanks for taking the time to reply, but this does not address at all my question (actually not true, after the edit to add the code, but this is a long story ;-) ). The problem I have is with the rescheduling part of the priority queue and I'm asking more for *design* aspects rather than for *implementation* details (and yes, although I completely agree with your opinions, if you ask me, using an object or a list, is merely an implementation detail; the client never accesses the data in the list or in the object)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T11:05:06.163", "Id": "5718", "Score": "0", "body": "\"I'm asking more for design aspects rather than for implementation details\". You posted code. That means you're asking for implementation details. I can't find a design question. If you want to ask a design question, then you need to (1) actually identify the design issue, and (2) consider posting on Stack Overflow. This is code review. That means implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T15:50:20.210", "Id": "5728", "Score": "0", "body": "If you take a look at the question, before it was edited and before it was migrated from programmers (not by me!), the question was: \"Which is the best way to—at t=4 and t=6—reschedule the already scheduled events?\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T15:57:43.383", "Id": "5729", "Score": "1", "body": "If someone has to spend more than a few seconds looking at the question, there's a small possibility that the question could stand to have better organization. Not everyone is capable of reading and parsing lots and lots of words and coming to a full understanding. **TL;DR**: If folks don't get your question, consider fixing it. Second. This is code review. Therefore, claiming you don't want a review of the code is going to be confusing to us who read the questions, expecting to find code and code reviews. If you want **design** review, you need to use Stack Overflow to discuss design." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T16:01:34.317", "Id": "5730", "Score": "0", "body": "You're probably right, but as I said before, I posted the question on http://programmers.stackexchange.com/ and ins FAQ you can find these three items: \"Algorithm and data structure concepts, Design patterns, Architecture\" so I posted to the right site... again I didn't migrate it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T17:40:46.923", "Id": "5731", "Score": "0", "body": "As I said before, you should consider posting it on StackOverflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T17:45:42.573", "Id": "5732", "Score": "0", "body": "I think we are going nowhere here (and I think that you're not reading my comments at all too)... I continue to believe that the right place for this is programmers.stackexchange.com, as I wanted a **design** advice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T17:53:11.323", "Id": "5733", "Score": "0", "body": "@GaretJax: \"I continue to believe\". Clearly. I'll say it one last time because you won't get any help on CodeReview or on Programmers. You can continue to hope for a miracle. Or you can try StackOverflow. I think it's good to actually take action because you might get help. However, you're free to simply respond that you disagree with the idea of taking action to get help. I understand your reasoning." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T17:54:18.430", "Id": "5734", "Score": "0", "body": "@S.Lott let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/964/discussion-between-garetjax-and-s-lott)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T00:29:32.197", "Id": "3729", "ParentId": "3670", "Score": "0" } }, { "body": "<p>Given the problem scope as I understand it (need to execute events in particular sequence, with ability to rearrange sequence at any point) I think the design seems clean and direct. I caveat that with: I don't know python, and I seem to be missing the part where you are ensuring sequence of your queue by the event's time member. I understand the event.time needs to be the sequencing key for your queue, or else the reschedule will have erratic behavior as self.time goes forward and backward if the queue isn't in order</p>\n\n<p>The design wholesale seems clean though, to my eyes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T19:43:28.507", "Id": "5688", "Score": "1", "body": "Python orders tuples by ordering them by their first member, in case of conflicts, it uses the second and so on; the heapq module can be used as a prioritized queue, where the element returned by `heapq.heappop(queue)` function always equals `sorted(queue)[0]`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T00:07:47.017", "Id": "3751", "ParentId": "3670", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-27T21:15:15.647", "Id": "3670", "Score": "5", "Tags": [ "python", "simulation" ], "Title": "Discrete event simulation with variable intervals" }
3670
<p>The below code works fine with no errors and no problems.</p> <p>However, I think that it is too long, and I want to refactor it by separating the three parts (as commented on the code) by creating a new method for each of them, so that I can reuse them later.</p> <p>I tried to separate Part 2 and created a method which takes an <code>IQuerayble&lt;anonymous&gt;</code> as its parameter, and called it with <code>makbuzQuery</code> as that parameter. However, when it is in a separate method, <code>foreach</code> does not see what is inside the <code>IQueryable&lt;anonymous&gt;</code>.</p> <p>How can I refactor this code by creating separate methods for Part 1, Part 2 and Part 3?</p> <pre><code>public static IEnumerable MakbuzOlustur(int islemId) { //id si verilen tahsilat işleminin bilgilerini çekiyorm //Part 1 var makbuzQuery = from islem in db.TBLP1ISLEMs where islem.ID == islemId select new { islem.ID, CARIFIRMABIREYADI = islem.TBLP1CARI.K_FIRMAADI == null || islem.TBLP1CARI.K_FIRMAADI == "" ? islem.TBLP1CARI.B_ADSOYAD : islem.TBLP1CARI.K_FIRMAADI,//SAYIN CARIADRESI = CariAdresAyarla(islem.TBLP1CARI.ID), MAKBUZTARIHI = DateTime.Now.ToShortDateString(), islem.BELGENO, islem.GENELTOPLAM, CARININPARABIRIMI = islem.TBLP1CARI.LISTEPARABIRIMI, islem.PARABIRIMI, YAZIYLA = BAL.para.DataFormat.tutar_to_yazi(DAL.Format.ParaDuzenle.ParaFormatDuzenle(islem.GENELTOPLAM.ToString())), islem.ACIKLAMA, PERSONELADI = BirIsleminPersoneliniBul(islem.ID) }; //Part 2 List&lt;Makbuz&gt; makbuzListesi = new List&lt;Makbuz&gt;(); foreach (var makbuz in makbuzQuery) { Makbuz makbuzObjesi = new Makbuz(); //eğer işlemin kuru varsa çekiyorum decimal isleminKuru = DovizTuruVerilenBirIsleminDovizKurunuCek(makbuz.ID, makbuz.PARABIRIMI); makbuzObjesi.IslemId = makbuz.ID; makbuzObjesi.FirmaBireyAdi = makbuz.CARIFIRMABIREYADI; makbuzObjesi.Adres = makbuz.CARIADRESI; makbuzObjesi.MakbuzTarihi = makbuz.MAKBUZTARIHI; makbuzObjesi.BelgeNo = makbuz.BELGENO; //carinin para birimi TL ise kur ile çarpmaya gerek yok if (makbuz.CARININPARABIRIMI == "TL") { makbuzObjesi.GenelToplam = makbuz.GENELTOPLAM.Value; } else { makbuzObjesi.GenelToplam = (makbuz.GENELTOPLAM * isleminKuru).Value; } makbuzObjesi.ParaBirimi = "TL"; makbuzObjesi.Yaziyla = BAL.para.DataFormat.tutar_to_yazi(DAL.Format.ParaDuzenle.ParaFormatDuzenle(makbuzObjesi.GenelToplam.ToString().Replace(',','.'))); makbuzObjesi.Aciklama = makbuz.ACIKLAMA; makbuzListesi.Add(makbuzObjesi); makbuzObjesi.PersonelAdi = makbuz.PERSONELADI; } //Part 3 var toReport = from makbuzSon in makbuzListesi select new { ID = makbuzSon.IslemId, FIRMABIREYADI = makbuzSon.FirmaBireyAdi, ADRES = makbuzSon.Adres, MAKBUZTARIHI = makbuzSon.MakbuzTarihi, BELGENO = makbuzSon.BelgeNo, GENELTOPLAM = DAL.Format.ParaDuzenle.ParaFormatDuzenle(makbuzSon.GenelToplam.ToString()) + " TL", PARABIRIMI =makbuzSon.ParaBirimi, YAZIYLA = makbuzSon.Yaziyla, ACIKLAMA = makbuzSon.Aciklama, PERSONELADI = makbuzSon.PersonelAdi }; return toReport; } </code></pre> <p>This is the referred class</p> <pre><code>public class Makbuz { public int IslemId { get; set; } public string FirmaBireyAdi { get; set; } public string Adres { get; set; } public string MakbuzTarihi { get; set; } public string BelgeNo { get; set; } public decimal GenelToplam { get; set; } public string ParaBirimi { get; set; } public string Yaziyla { get; set; } public string Aciklama { get; set; } public string PersonelAdi { get; set; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T21:08:40.623", "Id": "5540", "Score": "0", "body": "@M. Tibbits I didn't know that site Mr.Tibbits thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-28T14:26:31.397", "Id": "104556", "Score": "0", "body": "`islem.TBLP1CARI.K_FIRMAADI == null || islem.TBLP1CARI.K_FIRMAADI == \"\"` looks like it should be able to be replaced with `string.IsNullOrEmpty(islem.TBLP1CARI.K_FIRMAADI)`." } ]
[ { "body": "<p>Well this jumped out at me as a relatively easy thing to break out. EDIT: not sure what the data type is on the makbuzQuery type -- hence the data type of the parameter of the new function</p>\n\n<pre><code>//Part 2 -- change to\nList&lt;Makbuz&gt; makbuzListesi = getMakbuzList(makbuzQuery);\n\n\n//new function\nList&lt;Makbuz&gt; getMakbuzList(makbuzQueryType makbuzQuery)\n{\n List&lt;Makbuz&gt; makbuzListesi = new List&lt;Makbuz&gt;(); \n foreach (var makbuz in makbuzQuery)\n {\n Makbuz makbuzObjesi = new Makbuz();\n //eğer işlemin kuru varsa çekiyorum\n decimal isleminKuru = DovizTuruVerilenBirIsleminDovizKurunuCek(makbuz.ID, makbuz.PARABIRIMI);\n\n makbuzObjesi.IslemId = makbuz.ID;\n makbuzObjesi.FirmaBireyAdi = makbuz.CARIFIRMABIREYADI;\n makbuzObjesi.Adres = makbuz.CARIADRESI;\n makbuzObjesi.MakbuzTarihi = makbuz.MAKBUZTARIHI;\n makbuzObjesi.BelgeNo = makbuz.BELGENO;\n //carinin para birimi TL ise kur ile çarpmaya gerek yok\n if (makbuz.CARININPARABIRIMI == \"TL\")\n {\n makbuzObjesi.GenelToplam = makbuz.GENELTOPLAM.Value;\n }\n else\n {\n makbuzObjesi.GenelToplam = (makbuz.GENELTOPLAM * isleminKuru).Value;\n }\n makbuzObjesi.ParaBirimi = \"TL\";\n makbuzObjesi.Yaziyla =\n BAL.para.DataFormat.tutar_to_yazi(DAL.Format.ParaDuzenle.ParaFormatDuzenle(makbuzObjesi.GenelToplam.ToString().Replace(',','.')));\n makbuzObjesi.Aciklama = makbuz.ACIKLAMA;\n makbuzListesi.Add(makbuzObjesi);\n makbuzObjesi.PersonelAdi = makbuz.PERSONELADI;\n\n }\n return makbuzListesi;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T07:12:25.667", "Id": "5541", "Score": "0", "body": "Thank you Mr.Cortright that was the first thing I also tried but as I mentioned in my question because the query type is `IQueryable<anonymous>` I think that's why in the `foreach` loop `makbuz.` does not give the inner properties of `makbuzQuery`, it gives error." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T07:07:55.747", "Id": "3678", "ParentId": "3677", "Score": "2" } }, { "body": "<p>Here you go with your division of 1 big method into 3 parts as you wanted :</p>\n\n<pre><code>public static IEnumerable MakbuzOlustur(int islemId) \n {\nvar makbuzQuery = CreateMakbuzQuery(islemId); // You got your makbuzQuery created and stored\nList&lt;Makbuz&gt; makbuzListesi = CreateList(makbuzQuery);\nvar toReport = CreateReport(makbuzListesi);\n }\n\n // Part 1\n private static CreateMakbuzQuery(int islemId) {\nvar makbuzQuery = from islem in db.TBLP1ISLEMs where islem.ID == islemId\n select new {\n islem.ID, CARIFIRMABIREYADI = islem.TBLP1CARI.K_FIRMAADI == null \n || islem.TBLP1CARI.K_FIRMAADI == \"\" ? \n islem.TBLP1CARI.B_ADSOYAD : islem.TBLP1CARI.K_FIRMAADI,//SAYIN \n CARIADRESI = CariAdresAyarla(islem.TBLP1CARI.ID), MAKBUZTARIHI = \n DateTime.Now.ToShortDateString(), islem.BELGENO, islem.GENELTOPLAM, CARININPARABIRIMI \n = islem.TBLP1CARI.LISTEPARABIRIMI, islem.PARABIRIMI, YAZIYLA = \n BAL.para.DataFormat.tutar_to_yazi(DAL.Format.ParaDuzenle.ParaFormatDuzenle\n (islem.GENELTOPLAM.ToString())), islem.ACIKLAMA, PERSONELADI = BirIsleminPersoneliniBul\n (islem.ID) \n };\n\nreturn makbuzQuery;\n }\n\n // Part 2\n private static CreateList(var makbuzQuery) {\n List&lt;Makbuz&gt; makbuzListesi = new List&lt;Makbuz&gt;(); \nforeach (var makbuz in makbuzQuery) { \n Makbuz makbuzObjesi = new Makbuz(); \n //e?er i?lemin kuru varsa çekiyorum \n decimal isleminKuru = DovizTuruVerilenBirIsleminDovizKurunuCek(makbuz.ID, \n makbuz.PARABIRIMI); \n makbuzObjesi.IslemId = makbuz.ID; \n makbuzObjesi.FirmaBireyAdi = makbuz.CARIFIRMABIREYADI;\n makbuzObjesi.Adres = makbuz.CARIADRESI;\n makbuzObjesi.MakbuzTarihi = makbuz.MAKBUZTARIHI; \n makbuzObjesi.BelgeNo = makbuz.BELGENO;\n //carinin para birimi TL ise kur ile çarpmaya gerek yok \n if (makbuz.CARININPARABIRIMI == \"TL\") {\n makbuzObjesi.GenelToplam = makbuz.GENELTOPLAM.Value; \n } else {\n makbuzObjesi.GenelToplam = (makbuz.GENELTOPLAM * isleminKuru).Value;\n }\n makbuzObjesi.ParaBirimi = \"TL\";\n makbuzObjesi.Yaziyla = BAL.para.DataFormat.tutar_to_yazi(DAL.Format.ParaDuzenle.ParaFormatDuzenle(makbuzObjesi.GenelToplam.ToString().Replace(',','.')));\n makbuzObjesi.Aciklama = makbuz.ACIKLAMA;\n makbuzListesi.Add(makbuzObjesi);\n makbuzObjesi.PersonelAdi = makbuz.PERSONELADI;\n }\nreturn makbuzListesi;\n }\n\n// PArt 3\nprivate static CreateReport(List&lt;Makbuz&gt; makbuzListesi) {\nvar toReport = from makbuzSon in makbuzListesi \n select new \n {\n ID = makbuzSon.IslemId,\n FIRMABIREYADI = makbuzSon.FirmaBireyAdi\n ADRES = makbuzSon.Adres, \n MAKBUZTARIHI = makbuzSon.MakbuzTarihi,\n BELGENO = makbuzSon.BelgeNo, \n GENELTOPLAM = DAL.Format.ParaDuzenle.ParaFormatDuzenle\n (makbuzSon.GenelToplam.ToString()) + \" TL\", PARABIRIMI \n =makbuzSon.ParaBirimi, YAZIYLA = makbuzSon.Yaziyla, ACIKLAMA = \n makbuzSon.Aciklama, PERSONELADI = makbuzSon.PersonelAdi \n};\n\n return toReport;\n }\n</code></pre>\n\n<p>Hopefully this does your work. Kindly check your query, to make sure that while formatting nothing is lost.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T09:11:13.567", "Id": "5542", "Score": "0", "body": "Thanks I will try this and feedback as soon as possible, I hope I don't get that anonymous IQueryable problem with this code too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T10:54:09.540", "Id": "5543", "Score": "0", "body": "Errors I had with your code are like this var cannot be used as a parameter type, and some method needed a return type.I handled those but the same problem I mentioned in my question remains with your CreateList method.Thanks for your time." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T09:01:09.063", "Id": "3679", "ParentId": "3677", "Score": "1" } }, { "body": "<p>Why not using Makbuz class as </p>\n\n<pre><code>select new Makbuz() \n{ \n //Assign all your properties here \n}\n</code></pre>\n\n<p>instead of using that anonymous type?</p>\n\n<p>And you could make all those queries into a single one if you really want.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T07:45:21.117", "Id": "5544", "Score": "0", "body": "I will try it and feedback as soon as possible, thanks for the idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T07:54:38.540", "Id": "5545", "Score": "1", "body": "I see that what you are basically doing there is pulling some data from a source, formatting a bit some properties, and then returning the data via IEnumerable. If I were you and if you afford it, I'd give more power to that Makbuz class. I'd do one method to return IEnumerable<Makbuz> from db.TBLP1ISLEMs in one query based on that ID parameter. The all that extra bits of processing, I would sepparate them in different small methods, and I will call those methods inside \"select new Makbuz() { // Assign properties and call those methods here }." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T08:12:38.767", "Id": "5546", "Score": "0", "body": "I used to call the methods in select part however, I got `could not translate expression into sql` error a couple times like this one [could not translate expression into sql](http://stackoverflow.com/questions/5755873/could-not-translate-expression-into-sql); that is why I started to use more queries.Also I think not calling the methods in the select part is much readable and never causes error, even if they do tracking them is easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T08:34:36.323", "Id": "5547", "Score": "0", "body": "Could you post which method that you are calling inside the selector produces that exception? That error of yours generally happens when you try processing data using the variables pulled directly from the DB (like your islem there from the first line of code). You should do a simple select in first place, then call AsEnumerable() on that query, and then do the processing that you need (by your new methods) client side." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T08:52:20.993", "Id": "5548", "Score": "0", "body": "The method is in another question I asked and solved.I linked it on my previous comment, thanks for your interest." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-22T07:23:02.027", "Id": "3680", "ParentId": "3677", "Score": "1" } }, { "body": "<p>Not a direct answer, but check out the Resharper refactor stuff. Pretty neat. Highlight a section of code and select the menu ReSharper / Refactor / Move.. (Ctrl+RO) It will copy the code to a method of your choice <em>and</em> wire in the correct parameters to keep it working.</p>\n\n<p>I find that when I ecounter these situations that they are less of a headache now as a result of this little option. Like you can just try stuff to see what it looks like and if you don't like it, just hit Ctrl+Z to undo.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T16:38:22.517", "Id": "5549", "Score": "0", "body": "thanks sgtz, what reshaper says is `create a method chain` which is my idea also, however when I click `create chan method` I get those errors, too." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-24T16:23:02.750", "Id": "3681", "ParentId": "3677", "Score": "1" } }, { "body": "<p>Simplest thing will be, using Visual Studio, and let VS do the magic. Select part of the code, right click and select <strong>Extract Method</strong>, this will give you dialog box where you can give appropriate name of the Method. Passing parameter and return value all will be taken care by visual studio only. No, need to do it manually. </p>\n\n<p>But yes, if you have time then go through site <a href=\"http://www.dofactory.com\" rel=\"nofollow\">http://www.dofactory.com</a> and check out which design pattern is suitable to your code. Restructure your code accordingly.</p>\n\n<p>I always go with some what faster way, whenever I feel that I have to copy paste some logic will extract method from that, and if I need it in different class, I make that method public, this thing works in small projects and obviously if you are running out of time. Otherwise I personally prefer structural coding for greater re-useability.</p>\n\n<p>Please let me know, if you need further help or information.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T13:41:33.367", "Id": "5550", "Score": "0", "body": "nice link, nice information thank you, I will try those and feedback." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T06:56:10.930", "Id": "5551", "Score": "0", "body": "Please select answer as correct answer if answer has solved your problem." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-25T12:59:47.190", "Id": "3682", "ParentId": "3677", "Score": "1" } }, { "body": "<p>I think you are running into a fundamental problem I often have with anonymous types: they are anonymous. C++0x has some interesting extensions for getting types back from anonymous types, though I am not sure they would help here.</p>\n\n<p>I suggest creating an explicit type to replace the anonymous type. This may cause early evaluation of your query.</p>\n\n<pre><code>public class MakbuzQT\n{\n public int ID;\n public string CARIFIRMABIREYADI;\n public string CARIADRESI;\n public string MAKBUZTARIHI;\n public string BELGENO;\n public decimal GENELTOPLAM;\n public string CARININPARABIRIMI;\n public string PARABIRIMI;\n public string YAZIYLA;\n public string ACIKLAMA;\n public string PERSONELADI;\n}\n</code></pre>\n\n<p>Now you can use the explicit type to refactor the query out:</p>\n\n<pre><code> public static IEnumerable&lt;MakbuzQT&gt; Part1(int islemId) {\n //id si verilen tahsilat işleminin bilgilerini çekiyorm\n var makbuzQuery = from islem in db.TBLP1ISLEMs\n where islem.ID == islemId\n select new MakbuzQT {\n ID = islem.ID,\n CARIFIRMABIREYADI = islem.TBLP1CARI.K_FIRMAADI == null ||\n islem.TBLP1CARI.K_FIRMAADI == \"\" ?\n islem.TBLP1CARI.B_ADSOYAD :\n islem.TBLP1CARI.K_FIRMAADI,//SAYIN\n CARIADRESI = CariAdresAyarla(islem.TBLP1CARI.ID),\n MAKBUZTARIHI = DateTime.Now.ToShortDateString(),\n BELGENO = islem.BELGENO,\n GENELTOPLAM = islem.GENELTOPLAM,\n CARININPARABIRIMI = islem.TBLP1CARI.LISTEPARABIRIMI,\n PARABIRIMI = islem.PARABIRIMI,\n YAZIYLA = BAL.para.DataFormat.tutar_to_yazi(DAL.Format.ParaDuzenle.ParaFormatDuzenle(islem.GENELTOPLAM.ToString())),\n ACIKLAMA = islem.ACIKLAMA,\n PERSONELADI = BirIsleminPersoneliniBul(islem.ID)\n };\n\n return makbuzQuery;\n }\n\n public static List&lt;Makbuz&gt; Part2(IEnumerable&lt;MakbuzQT&gt; q) {\n var ans = new List&lt;Makbuz&gt;();\n\n foreach (var makbuz in q) {\n Makbuz makbuzObjesi = new Makbuz();\n //eğer işlemin kuru varsa çekiyorum\n decimal isleminKuru = DovizTuruVerilenBirIsleminDovizKurunuCek(makbuz.ID, makbuz.PARABIRIMI);\n\n makbuzObjesi.IslemId = makbuz.ID;\n makbuzObjesi.FirmaBireyAdi = makbuz.CARIFIRMABIREYADI;\n makbuzObjesi.Adres = makbuz.CARIADRESI;\n makbuzObjesi.MakbuzTarihi = makbuz.MAKBUZTARIHI;\n makbuzObjesi.BelgeNo = makbuz.BELGENO;\n //carinin para birimi TL ise kur ile çarpmaya gerek yok\n if (makbuz.CARININPARABIRIMI == \"TL\") {\n makbuzObjesi.GenelToplam = makbuz.GENELTOPLAM;\n }\n else {\n makbuzObjesi.GenelToplam = (makbuz.GENELTOPLAM * isleminKuru);\n }\n makbuzObjesi.ParaBirimi = \"TL\";\n makbuzObjesi.Yaziyla = BAL.para.DataFormat.tutar_to_yazi(DAL.Format.ParaDuzenle.ParaFormatDuzenle(makbuzObjesi.GenelToplam.ToString().Replace(',', '.')));\n makbuzObjesi.Aciklama = makbuz.ACIKLAMA;\n makbuzObjesi.PersonelAdi = makbuz.PERSONELADI;\n\n ans.Add(makbuzObjesi);\n }\n\n return ans;\n }\n\n public static IEnumerable MakbuzOlustur(int islemId) {\n List&lt;Makbuz&gt; makbuzListesi = Part2(Part1(islemId));\n\n //Part 3\n var toReport = from makbuzSon in makbuzListesi\n select new {\n ID = makbuzSon.IslemId,\n FIRMABIREYADI = makbuzSon.FirmaBireyAdi,\n ADRES = makbuzSon.Adres,\n MAKBUZTARIHI = makbuzSon.MakbuzTarihi,\n BELGENO = makbuzSon.BelgeNo,\n GENELTOPLAM = DAL.Format.ParaDuzenle.ParaFormatDuzenle(makbuzSon.GenelToplam.ToString()) + \" TL\",\n PARABIRIMI = makbuzSon.ParaBirimi,\n YAZIYLA = makbuzSon.Yaziyla,\n ACIKLAMA = makbuzSon.Aciklama,\n PERSONELADI = makbuzSon.PersonelAdi\n };\n\n return toReport;\n }\n</code></pre>\n\n<p>Part3 will have the same issue and you can create an explicit type if you want to refactor out the query into another method in the same way as part 2.</p>\n\n<p>I run into this quite a bit and have yet to find what I think is a satisfactory solution, so I end up creating explicit types instead.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T01:10:38.773", "Id": "5552", "Score": "0", "body": "PS I also find it annoying that C# requires you name the fields explicitly when you using an explicit type in a query, rather than matching the field names for you when it will create the same field names for anonymous types." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-26T01:08:04.793", "Id": "3683", "ParentId": "3677", "Score": "7" } } ]
{ "AcceptedAnswerId": "3683", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-07T06:59:02.100", "Id": "3677", "Score": "2", "Tags": [ "c#" ], "Title": "Refactoring and creating separate methods" }
3677
<p>I have a method to parse <code>strings</code>. It can be used to parse a <code>float</code> using a specific <code>culture</code> and then get a new <code>string</code> with a specific out-<code>culture</code>. The same applies to <code>ints</code>, <code>doubles</code> and <code>decimals</code>. </p> <p>The code that I've written is quite repetitive for each of the different parse methods which makes it hard to maintain (especially as I am just about to make the method a lot more complex).</p> <p>Is it possible to make this code less repetitive? </p> <pre><code>if (mapping.ParseDecimal) { decimal i; if (decimal.TryParse(value, numberStyle, inCulture, out i)) { return i.ToString(outCulture); } else { if (logger.IsDebugEnabled) logger.DebugFormat("Could not parse value \"{0\" to a decimal using the culture \"{1}\".", value, inCulture); } } else if (mapping.ParseDouble) { double i; if (double.TryParse(value, numberStyle, inCulture, out i)) { return i.ToString(outCulture); } else { if (logger.IsDebugEnabled) logger.DebugFormat("Could not parse value \"{0\" to a double using the culture \"{1}\".", value, inCulture); } } else if (mapping.ParseFloat) { float i; if (float.TryParse(value, numberStyle, inCulture, out i)) { return i.ToString(outCulture); } else { if (logger.IsDebugEnabled) logger.DebugFormat("Could not parse value \"{0\" to a float using the culture \"{1}\".", value, inCulture); } } else if (mapping.ParseInt) { int i; if (int.TryParse(value, numberStyle, inCulture, out i)) { return i.ToString(outCulture); } else { if (logger.IsDebugEnabled) logger.DebugFormat("Could not parse value \"{0\" to a int using the culture \"{1}\".", value, inCulture); } } </code></pre>
[]
[ { "body": "<p>I have a method that does something similar in that it takes a string and converts it to a given primitive type. It uses generics so there's less code.</p>\n\n<pre><code> public static T ReadConfigItem&lt;T&gt;(string strValue, IFormatProvider formatProvider) where T : struct\n {\n T result;\n\n if (string.IsNullOrEmpty(strValue))\n { \n result = (T)(Convert.ChangeType(false, typeof(T), formatProvider));\n }\n else\n {\n result = (T)(Convert.ChangeType(strValue, typeof(T), formatProvider));\n }\n\n return result;\n }\n</code></pre>\n\n<p>It can then be used like this:</p>\n\n<pre><code> System.Globalization.CultureInfo c = new System.Globalization.CultureInfo(\"fr-FR\");\n Console.WriteLine(ReadConfigItem&lt;double&gt;(\"90,99\", c));\n Console.WriteLine(ReadConfigItem&lt;double&gt;(\"9\", c));\n Console.WriteLine(ReadConfigItem&lt;int&gt;(\"6\", c));\n Console.WriteLine(ReadConfigItem&lt;double&gt;(null, c));\n Console.WriteLine(ReadConfigItem&lt;int&gt;(null, c));\n Console.WriteLine(ReadConfigItem&lt;bool&gt;(\"true\", c));\n Console.WriteLine(ReadConfigItem&lt;bool&gt;(\"True\", c));\n Console.WriteLine(ReadConfigItem&lt;bool&gt;(null, c));\n</code></pre>\n\n<p>I'm in the UK and the output I get is:</p>\n\n<pre><code>90.99\n9\n6\n0\n0\nTrue\nTrue\nFalse\n</code></pre>\n\n<p>If you wanted you could change this to an extension method on the string class.</p>\n\n<p>Example of extension class:</p>\n\n<pre><code>public static class ConvertExtensions\n {\n public static T ConvertTo&lt;T&gt;(this string strValue, IFormatProvider formatProvider) where T : struct\n {\n T result;\n\n if (string.IsNullOrEmpty(strValue))\n {\n result = (T)(Convert.ChangeType(false, typeof(T), formatProvider));\n }\n else\n {\n result = (T)(Convert.ChangeType(strValue, typeof(T), formatProvider));\n }\n\n return result;\n }\n }\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>CultureInfo c = new CultureInfo(\"fr-FR\"); \nConsole.WriteLine(\"\".ConvertTo&lt;double&gt;(c));\nConsole.WriteLine(\"True\".ConvertTo&lt;bool&gt;(c));\nConsole.WriteLine(\"true\".ConvertTo&lt;bool&gt;(c));\nConsole.WriteLine(\"\".ConvertTo&lt;bool&gt;(c));\nConsole.WriteLine(\"\".ConvertTo&lt;decimal&gt;(c));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T12:17:01.887", "Id": "5557", "Score": "0", "body": "This would have been the best method if I didn't have to use the Parse version :) +1 though for a really nice solution" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T10:00:12.893", "Id": "3688", "ParentId": "3686", "Score": "5" } }, { "body": "<p>If repetition is your primary concern, you could try doing something like this:</p>\n\n<pre><code>public delegate string ParserMethod(string value, NumberStyles numberStyle, CultureInfo inCulture, CultureInfo outCulture);\n\npublic static class NumericParser\n{\n public static readonly ParserMethod ParseInt = Create&lt;int&gt;(int.TryParse);\n public static readonly ParserMethod ParseFloat = Create&lt;float&gt;(float.TryParse);\n public static readonly ParserMethod ParseDouble = Create&lt;double&gt;(double.TryParse);\n public static readonly ParserMethod ParseDecimal = Create&lt;decimal&gt;(decimal.TryParse);\n\n public static Logger Logger { get; set; }\n\n delegate bool TryParseMethod&lt;T&gt;(string s, NumberStyles style, IFormatProvider provider, out T result);\n static ParserMethod Create&lt;T&gt;(TryParseMethod&lt;T&gt; tryParse) where T : IFormattable\n {\n return (value, numberStyle, inCulture, outCulture) =&gt;\n {\n T result;\n if (tryParse(value, numberStyle, inCulture, out result))\n {\n return result.ToString(null, outCulture);\n }\n else\n {\n if (Logger != null &amp;&amp; Logger.IsDebugEnabled)\n Logger.DebugFormat(\"Could not parse value \\\"{0}\\\" to a {1} using the culture \\\"{2}\\\".\", value, typeof(T).Name, inCulture);\n return \"\";\n }\n };\n }\n}\n</code></pre>\n\n<p>This way, you only have to pass around the appropriate <code>ParserMethod</code> you want to use. In your case, you could map your different mapping values to the appropriate <code>ParserMethod</code>. And call it when needed.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:42:12.180", "Id": "5608", "Score": "0", "body": "Create<int>(int.TryParse); in what namespace is Create located?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:46:26.923", "Id": "5610", "Score": "0", "body": "`Create<T>()` is the static method that you see at the end of the class. ;) I needed a nice way to create the `ParserMethod`s and a factory fit the bill." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:49:08.100", "Id": "5612", "Score": "0", "body": "ahhh...I see it now, thanks. thanks for the quick answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T10:42:12.143", "Id": "3691", "ParentId": "3686", "Score": "15" } } ]
{ "AcceptedAnswerId": "3691", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T09:35:07.750", "Id": "3686", "Score": "9", "Tags": [ "c#", "parsing" ], "Title": "Same code to parse int, float, decimal?" }
3686
<p>So, consider the following code:</p> <pre><code>public class OneConcreteTypeOfOutputFormat { private Dictionary&lt;Type, IEntityWriter&gt; writers; public Dispatcher() { this.writers = new Dictionary&lt;string, IEntityWriter(); CreateWriters(writers); } private void CreateWriters(Dictionary&lt;string, IEntityWriter&gt; writers) { string nspace = typeof(OneConcreteWriter).Namespace; Assembly assembly = Assembly.GetExecutingAssembly(); foreach (var writer in assembly.GetAllFromNamespace&lt;IEntityWriter&gt;(nspace)) writers.Add(writer.EntityType.FullName, writer); } private bool HasWriterForAllPropTypes(IEnumerable&lt;Entity&gt; data) { return data.All(ent =&gt; writers.ContainsKey(ent.GetType().FullName)); } public void WriteEntities(IEnumerable&lt;Entity&gt; entities) { Require.That(() =&gt; HasWriterForAllPropTypes(outputData)); foreach(Entity entity in entities) writers[entity.GetType().FullName].Write(entity); } } </code></pre> <p>Here, I am using the actual type of the Entity (which is a baseclass) to write it. I've heard that it's considered inelegant to use type-checking to perform operations, but I really don't want each Entity to write itself. This is a very easy and comfortable way to match something like this up. Do you find this clashing with the tenets of object-oriented programming? Sadly, each writer need to cast to it's specific type in the Write method.</p> <p><strong>UPDATE</strong></p> <p>Note that the code above is completely updated - changes include:</p> <ul> <li><p>Added writer initialization code. It is delegated to a unit-tested extension method.</p></li> <li><p>Changed the name of the class to reflect that it is only one of different types of output formats - so it would require more than just creating one writer for each Entity.</p></li> <li><p>Added a little bit of the validation code.</p></li> </ul>
[]
[ { "body": "<p>I don't know if it will be useful for you, but here is one variant:<br>\nAdd to your Entity base class a method called GetWriter. This method should return IEntityWriter.\nThis IEntityWriter should have method Write() without parameters.</p>\n\n<p>Then an implementation of an Entity would be something like: </p>\n\n<pre><code>class XXXEntity: Entity\n{\n public override IEntityWriter GetWriter()\n {\n return new XXXEntityWriter(this);\n }\n}\n</code></pre>\n\n<p>And then the method WriteEntities in your example would be</p>\n\n<pre><code>public void WriteEntities(IEnumerable&lt;Entity&gt; entities)\n{\n foreach(Entity entity in entities)\n entity.GetWriter().Write();\n}\n</code></pre>\n\n<p>The 'mappings' approach (no matter if it is in the code or in the xml file) have a couple of problems:<br>\n1. It's easy to do wrong configuration of mappings. You can map a XXXEntity to YYYEntityWriter.<br>\n2. It's easy to forget to add an EntityWriter when you add new Entity or you can forget to add the mapping. And this is a real problem.</p>\n\n<p>By the way. Judging from the description of the task, a concrete EntityWriter have to know about a concrete Entity.\nSo mapping is not as flexible as it seems, because of this explicit connection between EntityWriter and Entity.\nIt's not a problem to use GetType(). The problem here is to separate (hide) connections between classes that should work together.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T11:06:07.393", "Id": "5580", "Score": "0", "body": "Thanks for the answer. Yes, this is indeed one idea, thanks. Mappings approach: Actually, I simplified the code above a bit - in reality IEntityWriter has a property GetEntityType, which is used to put them in the map, and the Writers are dynamically instantiated using reflection. Will consider it a bit more, thanks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T13:45:29.070", "Id": "5588", "Score": "0", "body": "+1: Scrap 'problem' 1 though, it's not like using your suggestion makes it less likely to match the wrong writer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:09:51.570", "Id": "5614", "Score": "0", "body": "@Steven Jeuris: Actually, it is. In my approach, if you create a concrete EntityWriter it will work with a concrete Entity. So if you create XXXEntityWriter it will work with XXXEntity only. And every time you create a concrete Entity, you'll have to create a corresponding EntityWriter for this Entity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:58:44.403", "Id": "5625", "Score": "0", "body": "@Max you really want to do it this way. This is the correct design approach.. Even if there's reflection instantiation, put that code in the individual concrete classes to reflection instantiate the correct writer on each individual entity basis. Make a base class that will do the common reflection code if you care (or use a proper DI framework instead) and each implementor class will utilize that common reflection code to get the writer *it* wants" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T10:33:09.117", "Id": "5680", "Score": "0", "body": "@Jimmy Separation of concern was what I was going for - if each Entity should know how to write itself, then the same can be said for alot more. Another problem that I havn't clarified is that there will be different *types* of writers - dammit, I've asked this question all wrong - let me update it with a bit more real code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T16:22:25.320", "Id": "5685", "Score": "0", "body": "Now, the task is more clear. I think that it can not be resolved by means of pure OOP. You'll have to use the reflection in one way or another and your solution is pretty good." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T13:13:21.603", "Id": "3693", "ParentId": "3689", "Score": "6" } }, { "body": "<p>I have no idea why you have words \"strategy pattern\" in your subject, but what you want is called \"polymorphic behavior\". There are 2 ways that considered fine:</p>\n\n<ol>\n<li>Adding required interface method to Entity and overriding/implementing it in all descendants.</li>\n<li>Using Visitor design pattern. The idea is almost the same as in p.1, but in this case it would be quite easy to add more methods like <code>Write()</code> without need of changing interface <code>Entity</code> interface.</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T03:36:48.923", "Id": "3701", "ParentId": "3689", "Score": "1" } }, { "body": "<p>Described solutions are really nice, but sometimes you just don't want Entity class to know anything about EntityWriter. Moreover, sometimes it might even be impossible if these classes are put in a different assemblies. And the only thing you need is a mapping table in a client class (Dispatcher) of which EntityWriter to use based on Entity type.</p>\n\n<p>The only bad thing I can see in your code is that Dispatcher knows about all possible types of Entity and EntityWriter. I don't see any problems with using GetType () or typeof in my code. But it is surely better to get rid of specific classes from the Dispatcher code.</p>\n\n<p>The simplest thing is to use a little bit of reflection and Activator class:</p>\n\n<ol>\n<li>Create an xml file that contains mapping of entity types to writer types</li>\n<li>Create IDictionary field in Dispatcher and fill it with the data from xml file on startup where Entity writer instance is got by using Activator class</li>\n<li>On the runtime just use the same code as you have in WriteEntries, but change the signature to get entity type FullName: entity.GetType().FullName</li>\n</ol>\n\n<p>Hope it helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T11:08:14.367", "Id": "5581", "Score": "0", "body": "actually, this is what I am doing (but instead of using an XML file, I get all writers from their specific namespace). I wanted to simplify the code before I posted, but as usual that is not a good idea. Thanks for coming up with the same solution though, makes me a bit more secure if I end up choosing this one! :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:49:33.950", "Id": "5624", "Score": "1", "body": "I disagree, when reflection is necessitated by the design to maintain loose coupling, you may want to take a step back from the design- or rely on some late binding or proxy framework (i.e. ninject, MEF, WCF) that abstracts this in an industry standard way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T08:11:36.087", "Id": "5649", "Score": "0", "body": "Afaik, Ninject, MEF and WCF will allow you to create an instance of an interface, but there is no way to instruct them which specific class should be instantiated based on a provided instance of Entity at the runtime. I highly agree that we should use standart proxy frameworks, but I can't see how they will help in that case. Can you elaborate your solution?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T04:55:20.003", "Id": "3702", "ParentId": "3689", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T10:22:55.930", "Id": "3689", "Score": "3", "Tags": [ "c#" ], "Title": "Type checking to perform a variation of the strategy pattern" }
3689
<p>I often use jQuery plugins for front-end functionality in web applications. This requires me to write code like this, where I am assigning a function to an object property:</p> <pre><code>var trainingDiary = $("#training_diary").fullCalendar({ dayClick: function(date, allDay, jsEvent, view) { var title = prompt('Event Title:'); var dayObj = $(this); //console.log($(this)); if (title) { $.ajax({ url: "/app_dev.php/addtrainingday", global: false, type: "POST", data: "dayNo=" + date.getDate(), //returns day of month. getDay() returns day of week async:true, success: function(msg) { trainingDiary.fullCalendar('renderEvent', { title: title, start: date, allDay: allDay, backgroundColor:'#cccccc' }, true // make the event "stick" across calendar pages ) dayObj.css({'background-color':'#339933','background-image':'url()'}) console.log(msg.valueOf()); } //end ajax success }) } else { trainingDiary.fullCalendar('unselect'); } }, theme: true, header: {left:'title', center: '', right: 'today prev next'}, firstDay:1 }); </code></pre> <p>The code becomes hard to read and maintain as there is now a success function within an Ajax function within yet another function. How can I improve the code so that <code>dayClick: function(...)</code> can call a function defined outside of the <code>fullCalendar</code> call? In this case, <code>fullCalendar</code> is a jQuery plugin.</p>
[]
[ { "body": "<p>You should use the <a href=\"http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth\" rel=\"nofollow\">JavaScript Module Pattern</a> to create a private scope for your function declarations:</p>\n\n<pre><code>// Directives for JSLint\n/*global console, prompt, $ */ // declaration of global variables used\n/*jslint unparam: true, sloppy: true, white: true */ // disable less useful checks\n\n// create a closure for private scope\n(function(){\n\n // Private declarations\n\n var calendarOptions, // object, options for calendar diary\n trainingDiary; // object, training diary using jQuery plugin fullCalendar()\n\n function onDayClick(date, allDay, jsEvent, view) {\n // Function: onDayClick(day, allDay, jsEvent, view)\n // Callback for the selection of a day in the calendar.\n //\n // Parameters:\n // date - type?, description?\n // allDay - type?, description?\n // jsEvent - type?, description?\n // view - type?, description?\n\n // single var declaration\n var title, // string, event title, input by user\n dayObj, // object, jQuerified DOM element\n ajaxOptions; // object, options for AJAX call to addtrainingday script\n\n // this declaration must be nested to access date, allDay... in closure scope\n function onAjaxSuccess(msg) {\n // Function: onAjaxSuccess(msg)\n // Callback for a successful AJAX call to server-side addtrainingday script.\n //\n // Parameter:\n // msg - string, message received from server, for logging purpose \n\n var event = {\n title: title,\n start: date,\n allDay: allDay,\n backgroundColor:'#cccccc'\n };\n\n trainingDiary.fullCalendar(\n 'renderEvent',\n event,\n true // make the event \"stick\" across calendar pages\n ); // added missing semicolon\n\n dayObj.css({\n 'background-color':'#339933',\n 'background-image':'url()'\n }); // added missing semicolon\n\n console.log(msg.valueOf());\n\n } // end of onAjaxSuccess declaration\n\n // Init\n title = prompt('Event Title:');\n dayObj = $(this);\n ajaxOptions = {\n url: \"/app_dev.php/addtrainingday\",\n global: false,\n type: \"POST\",\n // getDate() returns day of month. getDay() returns day of week\n data: \"dayNo=\" + date.getDate(),\n async: true,\n success: onAjaxSuccess\n };\n\n //console.log($(this));\n if (title) {\n $.ajax(ajaxOptions); // added missing semicolon\n } else {\n trainingDiary.fullCalendar('unselect');\n }\n\n } // end of onDayClick declaration\n\n // Initialization code\n\n calendarOptions = {\n dayClick: onDayClick,\n theme: true,\n header: {\n left: 'title',\n center: '',\n right: 'today prev next'\n },\n firstDay: 1\n };\n\n trainingDiary = $(\"#training_diary\").fullCalendar(calendarOptions);\n\n}()); // the function is called immediately to make the declarations effective\n</code></pre>\n\n<p>I also created extra variables to hold options objects, to enhance readability, and I added comments to describe the intent and parameters of functions declared.</p>\n\n<p>Note that trainingDiary is now declared in the private scope as well. If you need to access it in the global scope, you will need to export it to the global object by assigning it to global this or window:</p>\n\n<pre><code>(function(){\n\n // Private declarations\n (...)\n\n // Init\n (...)\n\n // Public declarations\n this.trainingDiary = trainingDiary;\n}());\n</code></pre>\n\n<p>I checked the code with latest <a href=\"http://jslint.com/\" rel=\"nofollow\">JSLint</a>; it is a useful tool once you know what to expect from it, e.g. by reading \"JavaScript: The Good Parts\" from its author Douglas Crockford. It would definitely help you to spot the missing semicolons, which can cause unexpected issues when you minify your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T05:10:18.917", "Id": "5647", "Score": "0", "body": "Wow - thanks so much for such a comprehensive answer. I will take a look into this approach and report back. Can you explain how one would '[assign it to] global this'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T12:21:42.530", "Id": "5653", "Score": "1", "body": "This is shown in second example: this.trainingDiary = trainingDiary; A classic alternative would be to assign to window, which only works in a browser environment: window.trainingDiary = trainingDiary;" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T16:48:10.500", "Id": "5660", "Score": "0", "body": "yep - my bad. I realised this after I read through your answer again and the link on closures. I've updated my question with the latest code. JSLint complains about ROOT_URL - this is defined in another file." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T17:06:28.270", "Id": "5661", "Score": "0", "body": "my bad again - just realised I can alert JSLint to an additional global declaration and you had already done this for jquery" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T13:09:13.257", "Id": "3692", "ParentId": "3690", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T10:32:27.653", "Id": "3690", "Score": "3", "Tags": [ "javascript", "datetime" ], "Title": "Training diary calendar" }
3690
<p>I have roughly 40 or 50 functions that are similar to the one provided by the code below.</p> <p>I kept all the common calculations between multiple functions separate such as <code>service_coverage_area</code> . I then kept all the specific calculations that are not repeated or needed by any other functions in the function that needs those calculations such as calculating f_sc. </p> <p>My question is: Am I doing this right? as in is this the best practice to code utility functions? should I be separating all the mini calculations into separate functions but then have to deal with 200 functions instead of the current 50?</p> <p><strong>Note</strong> that the self is there cause this code is part of a class. I just copy and pasted 2 functions into this paste</p> <pre><code>import bisect def service_coverage_area(self, mode): #simplified for codereview return 1 def some_calc(self, mode, street_type, grade, elderly_proportion, f_px): """ where: r = r_0 * f_sc * f_s * f_pop * f_px r_0 = ideal transit stop service radius 400m for bus and 800m for rail / express bus and commuter needed variable: mode f_sc = street connectivity factor {'grid':1, 'hybrid':0.85, 'cul_de_sac':0.45} needed variable: street connectivity tye f_s = grade fator 0.00 to 0.05 -&gt; 1.00 0.06 to 0.08 -&gt; 0.95 0.09 to 0.11 -&gt; 0.80 0.12 to 0.15 -&gt; 0.65 needed variable: grade f_pop population factor 1 for normal population 0.85 of 20% is elderly population needed variable:elderly_proportion f_px pedestrian crossing factor provided by another calculation """ #calculate r_0 r_0 = self.service_coverage_area(mode) #calculate f_sc if street_type == 'grid': f_sc = 1 elif street_type == 'hybrid': f_sc = 0.85 elif street_type == 'cul_de_sac': f_sc = 0.45 #calculate f_s grades = [0.05, 0.08, 0.11] f_s_values = [1.00, 0.85, 0.80, 0.65] f_s_score = bisect.bisect(grades, grade) f_s = f_s_values[f_s_score] #calculate f_pop if elderly_proportion &lt;= 0.2: f_pop = 1 else: f_pop = 0.85 return r_0 * f_sc * f_s * f_pop * f_px </code></pre>
[]
[ { "body": "<blockquote>\n <p>Am I doing this right?</p>\n</blockquote>\n\n<p>Almost.</p>\n\n<blockquote>\n <p>as in is this the best practice to code utility functions? </p>\n</blockquote>\n\n<p>These aren't \"utility\" functions. They appear to be central to your app. There are rarely \"utility\" functions in any app. </p>\n\n<p>What we used to call \"utility\" functions are almost always part of a standard library. </p>\n\n<blockquote>\n <p>should I be separating all the mini calculations into separate functions</p>\n</blockquote>\n\n<p>Yes.</p>\n\n<blockquote>\n <p>but then have to deal with 200 functions instead of the current 50?</p>\n</blockquote>\n\n<p>You still have the calculations. You're just giving them names and keeping them separate. Giving them separate names makes them more reusable, easier to test and easier to find.</p>\n\n<p>The most important thing here is to avoid creating a (nearly) useless class who's only job is to contain a bunch of functions.</p>\n\n<p>Your code uses no instance variables and simply uses another function that happens to be in the class. Both of these could be <code>@staticmethod</code> method functions.</p>\n\n<p>There's no reason -- in Python -- to create a class unless you have instance variables and a change in state of some kind.</p>\n\n<p>[In Java, you must often create \"all-static\" classes because there's no other place to put stateless math like this.]</p>\n\n<p>You can simply put these functions into a simple module and avoid the class definitions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T10:52:13.797", "Id": "5578", "Score": "0", "body": "Seems to me quite a few python programmers forget that not everything needs to be a full fledged class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T10:56:16.547", "Id": "5579", "Score": "0", "body": "@Daniel Goldberg: Bonus. I had someone on Stack Overflow who had a super-complex bit of `staticmethod` coding. When I suggested it was just a function, they insisted that using a bare function violated some OO principle or other." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T12:21:03.027", "Id": "5583", "Score": "0", "body": "Thanks a lot for the advice, I spent the better half of the evening splitting the file into multiple modules. Still working on the tests and all; however, time will tell on how my ability to maintain these modules. Thanks for the reply though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T12:21:36.410", "Id": "5584", "Score": "0", "body": "I agree about your comment on classes; therefore, I won't be using classes or @staticmethods" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T12:23:06.940", "Id": "5585", "Score": "1", "body": "\"multiple modules\"? Why waste time on that? They're all related, right? If you thought they belonged in one class, then they definitely belong in one module." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T02:46:53.847", "Id": "5640", "Score": "0", "body": "@DanielGoldberg -- a lot of *other* languages use the class as the organizing principle of the language. You get in the habit." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T23:52:47.463", "Id": "3700", "ParentId": "3696", "Score": "5" } }, { "body": "<pre><code>#calculate r_0\nr_0 = self.service_coverage_area(mode)\n</code></pre>\n\n<p>I recommend a more descriptive variable name then r_0 (some for all your variables)</p>\n\n<pre><code>#calculate f_sc\nif street_type == 'grid':\n f_sc = 1\nelif street_type == 'hybrid':\n f_sc = 0.85\nelif street_type == 'cul_de_sac':\n f_sc = 0.45\n</code></pre>\n\n<p>Use a dictionary f_sc = MYDICT[street_type]</p>\n\n<pre><code>#calculate f_s\ngrades = [0.05, 0.08, 0.11]\nf_s_values = [1.00, 0.85, 0.80, 0.65]\n</code></pre>\n\n<p>constants are better placed at the global/class level rather than inside the function.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T13:41:16.373", "Id": "5587", "Score": "0", "body": "Concerning the first point: I defined r_0 in the doc string, with respect to the code r_0 is usually known. I agree and thanks about the dict. With respect to teh constants, those will eventually move into the db. I have a #TODO on top of each one to remind me to move them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:20:25.997", "Id": "5623", "Score": "0", "body": "@dassouki, yes you define it. I'd still give it a better name." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T13:38:30.513", "Id": "3710", "ParentId": "3696", "Score": "1" } } ]
{ "AcceptedAnswerId": "3700", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-28T14:51:05.573", "Id": "3696", "Score": "3", "Tags": [ "python" ], "Title": "A large number of math type equations and functions in a python module" }
3696
<p>Should the following be considered wtf code?</p> <pre><code>abstract class BaseCat { public virtual void SayMiau() { Console.WriteLine("MIAU!"); } } class StrangeCat : BaseCat { private readonly bool _canMiau; public StrangeCat(bool canMiau) { _canMiau = canMiau; } public override void SayMiau() { if (_canMiau) { base.SayMiau(); } } } </code></pre> <p>What's the right approach here? <a href="http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Non-Virtual_Interface" rel="nofollow">Non-virtual interfaces</a> (NVI)?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T13:11:41.360", "Id": "5586", "Score": "0", "body": "Relevant discussion: http://stackoverflow.com/questions/2340487/is-the-non-virtual-interface-nvi-idiom-as-useful-in-c-as-in-c" } ]
[ { "body": "<p>Yes, it should.<br>\nIt breaks the Liskov substitution principle.</p>\n\n<p>I don't know what is the NVI, but I think that the right approach in this particular case would be\nto create a sub class NormalCat: BaseCat and move the method SayMiau() to this class.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T10:22:35.323", "Id": "3708", "ParentId": "3705", "Score": "1" } }, { "body": "<p>The example you show has no rationale for the BaseCat being abstract, make it non-abstract and your example makes perfect sense. Though I would make a strong case that your BaseCat may want to implement the structure of StrangeCat. Then have StrangeCat merely implement a change to the _canMiau if valid.</p>\n\n<pre><code>public class BaseCat\n{\n protected bool _canMiau;\n\n // if you wanted abstract so BaseCat could not be constructed make the constructor protected\n protected BaseCat(bool canMiau) { _canMiau = canMiau; }\n\n public virtual void SayMiau()\n {\n if (_canMiau)\n {\n Console.WriteLine(\"MIAU!\");\n }\n }\n}\n\npublic class StrangeCat : BaseCat\n{\n public StrangeCat(bool canMiau) : base(canMiau) { }\n}\n\npublic class MuteCat : BaseCat\n{\n public MuteCat() : base(false) { }\n}\n\npublic class LoudCat : BaseCat\n{\n public LoudCat() : base(true) { }\n}\n</code></pre>\n\n<p>Then when you kick the cat, it will respond appropriately with minimal duplication of logic. I would avoid an abstract class unless the inheritors are going to implement significant logic differences, your example doesn't show that (though your real situation may have that). </p>\n\n<pre><code>public void KickCat(BaseCat)\n{\n Foot.StraightTowardsCat(BaseCat, Anatomy.Rear);\n BaseCat.SayMiau();\n}\n\n...\n\nKickCat(new MuteCat()); // I love this cat, it's like it doesn't even care!\nKickCat(new LoudCat()); // Whines, blah.\nKickCat(new StrangeCat(true)); // Whines this time.\nKickCat(new StrangeCat(false)); // Doesn't whine this time! Woot!\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T14:03:24.863", "Id": "3711", "ParentId": "3705", "Score": "2" } } ]
{ "AcceptedAnswerId": "3711", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T07:09:15.673", "Id": "3705", "Score": "3", "Tags": [ "c#", ".net" ], "Title": "Subclassing, NVI" }
3705
<p>For a little background, I'm a contributor to SquishIt and decided that I should start cleaning up the mess of unit tests (<a href="https://github.com/Akkuma/SquishIt/blob/master/SquishIt.Tests/JavaScriptBundleTests.cs" rel="nofollow">my updated version of one set of tests</a> vs. <a href="https://github.com/jetheredge/SquishIt/blob/master/SquishIt.Tests/JavaScriptBundleTests.cs" rel="nofollow">original set of tests</a>). After tackling only part of the "rewrite", I figured it would be a good opportunity to learn, try, and understand BDD style testing to hopefully help improve the unit tests being written and ran. I decided to go with NSpec after taking a look at some of the choices out there. </p> <p>My problem is simply trying to break the tests down into the appropriate "groupings" that logically make sense and "conform" to xSpec. Here is what I've done so far and passes all tests as expected:</p> <pre><code>using NSpec; using SquishIt.Framework; using SquishIt.Framework.JavaScript; namespace SquishIt.Tests { class describe_JavaScriptBundle : nspec { public JavaScriptBundle bundle; public void AddTest1JS() { bundle.Add("test.js"); } } class when_I_create_a_bundle : describe_JavaScriptBundle { void before_each() { if (bundle == null) { bundle = Bundle.JavaScript(); } } void and_add_no_files() { it["GroupBundles containskey default"] = () =&gt; bundle.GroupBundles.ContainsKey("default").is_true(); it["has no Assets"] = () =&gt; bundle.GroupBundles["default"].Assets.Count.Is(0); } } class then_I_add_a_file : when_I_create_a_bundle { void before_each() { AddTest1JS(); } void it_should_contain_only_one_file() { bundle.GroupBundles["default"].Assets.Count.Is(1); } } class then_I_add_the_same_file : then_I_add_a_file { void it_should_still_contain_only_one_file() { bundle.GroupBundles["default"].Assets.Count.Is(1); } } } </code></pre> <p>How can I improve this or am I already on the right track?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T18:49:55.267", "Id": "5947", "Score": "1", "body": "I usually shy away from inheritance until I have significant nesting inside of my method contexts. Your tests communicate intent and test behavior. That's really all that matters in a good test suite :-)" } ]
[ { "body": "<p>I've just started out using NSpec myself last night. I really like how expressive it can be, though I see how easy it is to get into a bit of a class inheritance mess (I certainly did last night! :).</p>\n\n<p>Here's my suggested way of coding your test:</p>\n\n<pre><code>public class describe_JavaScriptBundle : nspec\n{\n protected JavaScriptBundle bundle;\n\n private void CreateBundle()\n {\n if (bundle == null)\n {\n bundle = Bundle.JavaScript();\n }\n }\n\n private void after_each()\n {\n bundle = null;\n }\n\n public void Bundle_Contains_No_Files()\n {\n it[\"When I create a new bundle\"] = this.CreateBundle;\n it[\"And bundle contains no files\"] = () =&gt; { };\n it[\"Then bundle will contain default key\"] = () =&gt; { };\n it[\"And bundle will have no assets\"] = () =&gt; { };\n }\n\n public void Bundle_Contains_One_File()\n {\n it[\"When I create a new bundle\"] = this.CreateBundle;\n it[\"And bundle contains one file\"] = () =&gt; bundle.Add(\"test.js\");\n it[\"Then bundle should have one asset\"] = () =&gt; { };\n }\n\n public void Add_Same_File_To_Bundle()\n {\n it[\"When I create a new bundle\"] = this.CreateBundle;\n it[\"And bundle contains one file\"] = () =&gt; bundle.Add(\"test.js\");\n it[\"When I add the same file to the bundle\"] = () =&gt; bundle.Add(\"test.js\");\n it[\"Then bundle should have one asset\"] = () =&gt; { };\n }\n}\n</code></pre>\n\n<p>The key here is the output you get:</p>\n\n<pre><code>describe JavaScriptBundle &lt;- Feature\n Bundle Contains No Files &lt;- Scenario\n When I create a new bundle\n And bundle contains no files\n Then bundle will contain default key\n And bundle will have no assets\n Bundle Contains One File &lt;- Scenario\n When I create a new bundle\n And bundle contains one file\n Then bundle should have one asset\n Add Same File To Bundle &lt;- Scenario\n When I create a new bundle\n And bundle contains one file\n When I add the same file to the bundle\n Then bundle should have one asset\n</code></pre>\n\n<p>Notice how I try to describe the feature and then each scenario. This way I'm able to visually see how each scenario it tested. By no means am I saying that having inheritance in wrong, it's just in your case I don't think the tests are complicated enough to warrant this.</p>\n\n<p>So fill in the blanks for the tests and give it a whirl. Let me know if it works out for you.</p>\n\n<p>Cheers.\nJas.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T18:44:10.143", "Id": "5946", "Score": "0", "body": "NSpec is geared toward Context/Specification. While you can do Gherkin style testing in NSpec, it's better suited for nesting context. I've added an example that shows how you can nest context, hopefully it doesn't hurt the readability of the specification." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T18:55:51.230", "Id": "5948", "Score": "1", "body": "On a side note, it's worth noting that NSpec doesn't guarantee that you'll get the same instance of the NSpec test across \"it\" blocks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-10T20:29:41.517", "Id": "6016", "Score": "0", "body": "Thanks for the tips. In your second comment, is there documentation which explains this further? What is meant by \"....same instance of the NSpec test...\"? Cheers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-16T18:44:17.070", "Id": "6198", "Score": "0", "body": "NSpec manages an instance of your test class per specify/it. In context/spec, \"it\" and \"specify\" blocks are meant to only assert the given state of a system (not change it). Manipulating state in those blocks is not recommended. As Matt and I tighten down on isolating specification blocks, it'll cause any state defined in these blocks to be reset. Also, there is no guarantee that it and specify blocks will run in the order they have been defined." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-07T21:00:41.163", "Id": "3947", "ParentId": "3712", "Score": "1" } }, { "body": "<p>Here is how I've written most of my NSpec tests, I usually start a context out with an act. This dry's up the specification. If I find myself doing too many \"acts\", I end up breaking it up into separate specifications.</p>\n\n<pre><code>class describe_JavaScriptBundle : nspec\n{\n JavaScriptBundle bundle;\n\n void AddTest1JS()\n {\n bundle.Add(\"test.js\");\n }\n\n void before_each()\n {\n bundle = Bundle.JavaScript();\n }\n\n void adding_a_bundle()\n {\n context[\"no files added\"] = () =&gt;\n {\n it[\"GroupBundle contains default key\"] = () =&gt;\n bundle.GroupBundles.ContainsKey(\"default\").is_true();\n\n it[\"has no Assets\"] () =&gt; \n bundle.GroupBundles[\"default\"].Assets.Count.Is(0);\n };\n\n context[\"adding one file\"] = () =&gt;\n {\n act = () =&gt; AddTest1JS();\n\n it[\"contains the file\"] = () =&gt; \n bundle.GroupBundles[\"default\"].Assets.Count.Is(1);\n\n context[\"adding the same file again\"] = () =&gt;\n {\n act = () =&gt; AddTest1JS();\n\n it[\"should still only contain one file\"] = () =&gt; \n bundle.GroupBundles[\"default\"].Assets.Count.Is(1);\n };\n };\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T18:39:38.870", "Id": "3970", "ParentId": "3712", "Score": "4" } } ]
{ "AcceptedAnswerId": "3970", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T15:19:43.323", "Id": "3712", "Score": "4", "Tags": [ "c#", "unit-testing" ], "Title": "Unit tests for the SquishIt framework" }
3712
<p>I'm trying to optimize performance for recursive directory listing with some exceptions:</p> <pre><code>function listdir($basedir) { global $root, $ignore_dirs, $ignore_files, $filetypes, $ignore_starts_with; if ($handle = @opendir($basedir)) { while (false !== ($fn = readdir($handle))) { if ($fn != '.' &amp;&amp; $fn != '..') { $s = true; foreach ($ignore_starts_with as $pre) if (strpos($fn, $pre) === 0) $s = false; $dir = $basedir."/".$fn; if ($s &amp;&amp; is_dir($dir) &amp;&amp; !in_array($fn, $ignore_dirs)) { listdir($dir); } else { if ($s &amp;&amp; !in_array($fn,$ignore_files) &amp;&amp; preg_match("/[^.\/].+\.($filetypes)$/",$dir,$fname)) printlink($fname[0]); } } } closedir($handle); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T17:51:06.583", "Id": "5594", "Score": "3", "body": "Optimize how? Where is the bottleneck? What have your profiling results shown?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:27:12.860", "Id": "5596", "Score": "0", "body": "im not shire about foreach construction, and many if's" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:39:49.460", "Id": "5598", "Score": "3", "body": "Well, I would prove that is actually a bottleneck before potentially wasting time optimizing them out (if that's even possible). For example, if 98% of your time is spent doing I/O then removing an if statement or a loop is pointless. That said, your `$s` variable will only hold the *last* assignment, so you may as well just break out of it the first time that condition is met." } ]
[ { "body": "<p>First of all, I'd use <a href=\"http://www.php.net/~helly/php/ext/spl/classRecursiveDirectoryIterator.html\" rel=\"nofollow\">RecursiveDirectoryIterator</a>, removed globals and corrected formatting.</p>\n\n<p>Then used Xdebug + CacheGrind to try different versions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T06:41:10.767", "Id": "3741", "ParentId": "3713", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T16:18:32.857", "Id": "3713", "Score": "2", "Tags": [ "php", "recursion", "file-system" ], "Title": "Recursive directory listing" }
3713
<p>A short while ago, I have submitted a coding exercise to a potential employer. The response came back the next morning and you can guess what it was from the subject of this post. </p> <p>I am not totally at loss, but I need another programmer's perspective. Is there anything that jumps out?</p> <p>The idea of the exercise is simple: I'm given an input file with names of cars, one per line, possibly repeated and in no particular order. </p> <p>The program should output the same names, except with no repetitions, the number of occurrences listed next to each car, and in order of decreasing repetitions. </p> <p>Example:</p> <p><code>Honda\n Audi\n Honda\n</code> -> <code>Honda 2 \n Audi 1\n</code></p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;string&gt; #include &lt;map&gt; #include &lt;algorithm&gt; #include &lt;cctype&gt; using namespace std; // helper functions /////////////////////////////////////// // reads lines from instream void collect_lines(istream &amp;in, map&lt;string, int&gt; &amp;lines); // given lines-&gt;num_occurs map, reverses mapping void reorg_by_count(map&lt;string, int&gt; &amp;lines, multimap&lt;int, string&gt; &amp;bycount); /////////////////////////////////////////////////////////// int main(int ac, char* av[]) { istream *in; map&lt;string, int&gt; *lines = new map&lt;string, int&gt;(); multimap&lt;int, string&gt; *lines_by_count = new multimap&lt;int, string&gt;(); if (ac &lt; 2) { in = &amp;cin; } else { in = new ifstream(av[1]); } if (!in-&gt;good()) return 1; collect_lines(*in, *lines); reorg_by_count(*lines, *lines_by_count); if (in != &amp;cin) { ((ifstream *)in)-&gt;close(); delete in; } cout &lt;&lt; "=====================\n\n"; multimap&lt;int, string&gt;::reverse_iterator it = lines_by_count-&gt;rbegin(); for (; it != lines_by_count-&gt;rend(); it++) { cout &lt;&lt; it-&gt;second &lt;&lt; " " &lt;&lt; it-&gt;first &lt;&lt; '\n'; } delete lines; delete lines_by_count; return 0; } // Read the instream line by line, until EOF. // Trim initial space. Empty lines skipped void collect_lines(istream &amp;in, map&lt;string, int&gt; &amp;lines) { string tmp; while (in.good()) { getline(in, tmp); int i = 0; // trim initial space (also skips empty strings) for (i = 0; i &lt; tmp.length() &amp;&amp; !isalnum(tmp[i]); i++); if (i &gt;= tmp.length()) continue; tmp = tmp.substr(i); for (i = 0; i &lt; tmp.length(); i++) { if (!isalnum(tmp[i])) { tmp[i] = ' '; } // thus, HoNdA == Honda if (i == 0) { tmp[i] = toupper(tmp[i]); } else { tmp[i] = tolower(tmp[i]); } } // and record the counts if (lines.count(tmp) == 0) { lines[tmp] = 0; } lines[tmp]++; } } // given lines-&gt;num_occurs map, reverses mapping void reorg_by_count(map&lt;string, int&gt; &amp;lines, multimap&lt;int, string&gt; &amp;bycount) { map&lt;string, int&gt;::iterator it = lines.begin(); for (; it != lines.end(); it++) { bycount.insert(pair&lt;int, string&gt;(it-&gt;second, it-&gt;first)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T16:51:50.873", "Id": "5591", "Score": "9", "body": "I think the question is simple and you have put much more coding efforts. I believe in 3 kind of optimizations; `\"time, space, text\"`; \"text\" optimization is called *readability*. You could have solved this problem with probably 10 lines of code. I won't be able to provide code now; may be tomorrow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:59:02.463", "Id": "5602", "Score": "3", "body": "Its a good C answer. But its not C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T00:32:29.933", "Id": "5632", "Score": "0", "body": "Huh? I see references and STL use..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T00:56:01.663", "Id": "5634", "Score": "9", "body": "@trinithis: C++ is a style. The code may have been using C++ types but the style was C like (not C++ like). The trouble is people think that because both languages have the same basic syntax that moving from one to the other is trivial. I find that converting C programmers to C++ is really difficult because you have to move them past the whole C mindset. Hence I would not consider the above code to be C++. Some people use the term \"C with classes\" as a distinct language the lies somewhere between C and C++, here people use C++ features but still code with a C style." } ]
[ { "body": "<p>You're doing manual memory management. That's not a good idea. In fact, that's something that you don't need to do at all in modern C++. You either use automatic objects, or use use smart pointers to dynamically allocated objects.</p>\n\n<p>In your case, there's no need to do dynamic allocation at all. Instead of:</p>\n\n<pre><code>map&lt;string, int&gt; *lines = new map&lt;string, int&gt;();\nmultimap&lt;int, string&gt; *lines_by_count = new multimap&lt;int, string&gt;();\n// more things\ndelete lines;\ndelete lines_by_count;\n</code></pre>\n\n<p>You should have just used automatic objects:</p>\n\n<pre><code>map&lt;string, int&gt; lines;\nmultimap&lt;int, string&gt; lines_by_count;\n// things\n</code></pre>\n\n<p>The same goes for the <code>ifstream</code> you used. This clearly shows you don't understand one of the most important facets of C++.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:36:08.800", "Id": "5597", "Score": "9", "body": "I think this is probably the biggest one. If their prospective employer is looking for C++ skills, using pointers and `new` all the time shows exactly the opposite." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:58:48.283", "Id": "5601", "Score": "22", "body": "Agreed. Having been the interviewer, I'll share my thoughts with you. When I see this kind of code, I think \"This person doesn't understand stack vs heap, references, or memory management in general. They probably learned Java first, and then tried to jump into C/C++.\" (Note that I don't hate Java, I just speculate on *why* this code was written this way). Based on the code, I assume large gaps in the coder's knowledge, and move on. Since you posted here, asking what's wrong, I assume you actually want to learn, which is a very good quality in a coder. Good luck to you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:01:31.543", "Id": "5603", "Score": "4", "body": "oh, and your for loop. You declared the iterator before the loop and left the first part of the `for` blank, when there was no need to do that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:41:31.617", "Id": "5607", "Score": "7", "body": "@Tim: There's no NEED to put the iterator declaration inside the for loop control region either, and this way the lines are shorter and easier to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T01:59:56.573", "Id": "5639", "Score": "0", "body": "@Tim I read it the opposite way: rather than learning java first, it sounds more like he learned C first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T20:03:45.697", "Id": "5689", "Score": "0", "body": "@Joel Yes, I have started with C, then C++ THEN Java." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T08:56:40.663", "Id": "5717", "Score": "5", "body": "@Ben: You can insert line breaks inside the `for` statement. And the needlessly extended scope of the iterator is far worse than any long line could ever be" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T17:04:43.763", "Id": "3715", "ParentId": "3714", "Score": "50" } }, { "body": "<p>I assume it works, but didn't try it. I would consider it not finished. In an interview situation, they will want you to do your best, and it's more about proving that you are aware of things like checking return status, and doing the right thing, even though the problem at hand is small, and can be dashed off quickly, they probably still want to see a complete program.</p>\n\n<p>Here's what stood out to me:</p>\n\n<ul>\n<li>Should use 'argc', 'argv' names for familiarity.</li>\n<li>lines and lines_by_count are constructed on the heap for no reason - should just use the stack.</li>\n<li>No allocations are checked.</li>\n<li>Processes command line arguments, doesn't either (a) complain about excess arguments or (b) use them.</li>\n<li>No usage or '-help' support.</li>\n<li>Code contains assumptions about ASCII input, but doesn't declare that.</li>\n<li>Error handling just quits with no message.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T17:25:33.170", "Id": "5592", "Score": "15", "body": "\"*No allocations are checked*\" `new` throws, there's nothing to check. Of course, he shouldn't be using `new`..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:04:54.360", "Id": "5621", "Score": "3", "body": "This is kinda a tangent and I'll probably get flamed for my heretic view but I would say in most programs (including this) checking allocations is not necessary. It's an extremely rare occurrence that they fail, and when they do in 99.9% of cases you want to crash. In 99.9% of cases (excluding absurd implementations of undefined behavior) the difference is simply crashing with or without an error message. If the computer is out of memory, a lot of applications will crash at the same time, most with segfault-like error messages, so it should be clear to the user what's going on" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:06:20.867", "Id": "5622", "Score": "0", "body": "Also don't misunderstand what I said; for big applications an allocation failure check in the application's global allocation manager is certainly a good idea. I'm just saying that for small applications like this it's just overkill." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T01:19:57.400", "Id": "5636", "Score": "1", "body": "For small applications, yes, it is overkill, I agree. But for an interview question? You do it by the book." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T21:33:26.217", "Id": "5666", "Score": "3", "body": "@Andreas: \"If the computer is out of memory, a lot of applications will crash at the same time, most with segfault-like error messages, so it should be clear to the user what's going on\" <- The idea that **the computer** is out of memory when allocations fail for \"out of memory\" is bogus. Because an application does not have enough free contiguous memory in its address space it doesn't mean no one else has." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-10-19T01:34:30.750", "Id": "397092", "Score": "0", "body": "@PaulBeckingham \"no allocations are checked\". What do you mean? Whether `new` has succeeded? (sorry native language isn't english and I'm not sure I understand some things, especially phrases/expressions..) If so then, as other commentators said then yes It is overkill. A good point though. Nice answer. + 1" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T17:07:29.003", "Id": "3716", "ParentId": "3714", "Score": "15" } }, { "body": "<p>Here are problems that I detected : </p>\n\n<ul>\n<li>do not use raw pointers. There is rarely a need for a raw pointer in c++. If you must, use smart pointers. </li>\n<li>what is the point of multimap? You could that map variable that you defined. </li>\n<li>use of c casts is bad (in this line : <code>((ifstream *)in)-&gt;close();</code>) </li>\n<li>the collect_lines function is too complex and does too much. </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:06:40.583", "Id": "5595", "Score": "0", "body": "More importantly, there's no reason to use pointers at all in this code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:44:29.443", "Id": "5600", "Score": "0", "body": "@Brendan: Actually, since the stream is polymorphic, pointers are helpful. But dynamic allocation is still not needed." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T17:22:22.910", "Id": "3717", "ParentId": "3714", "Score": "8" } }, { "body": "<p>Yes to everything that was said so far. One additional thing which I saw is:</p>\n\n<pre><code>// and record the counts\nif (lines.count(tmp) == 0)\n{\n lines[tmp] = 0;\n}\nlines[tmp]++;\n</code></pre>\n\n<p>Everything except the last line is unnecessary. When lines[tmp] is accessed for the first time, the key tmp is automatically created in lines, and initialized with the default-constructed value of int (which happens to be 0). See <a href=\"http://en.cppreference.com/w/cpp/container/map/operator_at\">http://en.cppreference.com/w/cpp/container/map/operator_at</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T17:23:40.753", "Id": "3718", "ParentId": "3714", "Score": "7" } }, { "body": "<p>As one of the commenter I believe this could be done in a few, say 10 lines, of code. Writing to long methods is often a sign that one is doing something wrong. </p>\n\n<p>My point is that the sheer size will make the interviewer say it's not good enough. I imagine they want a short clean piece of code that does what they asked for, and not every trick in the book to show off. </p>\n\n<p><strong>on @Martinho suggestion I add my example here</strong></p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;list&gt;\n#include &lt;map&gt;\n\nusing namespace std;\n\nbool my_pair_compare(pair&lt;string,int&gt; &amp;a, pair&lt;string,int&gt; &amp;b) { \n return a.second &gt; b.second; \n}\n\nvoid my_pair_output(pair&lt;string,int&gt; &amp;p) { \n cout &lt;&lt; p.first &lt;&lt; \" \" &lt;&lt; p.second &lt;&lt; endl; \n}\n\nint main() {\n map&lt;string,int&gt; cars;\n\n while (1) {\n string name;\n cin &gt;&gt; name;\n if (cin.eof()) break;\n cars[name]++;\n }\n\n list&lt;pair&lt;string,int&gt; &gt; names;\n\n map&lt;string,int&gt;::iterator citer = cars.begin();\n while (citer != cars.end()) \n names.push_back(*citer++);\n\n names.sort(my_pair_compare);\n for_each(names.begin(), names.end(), my_pair_output);\n\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:10:43.090", "Id": "5605", "Score": "0", "body": "Here is a [gist](https://gist.github.com/1114501) (35 lines total, ~10 active lines)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:16:26.820", "Id": "5615", "Score": "0", "body": "@epatel: post the gist in the answer!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T19:39:26.580", "Id": "5664", "Score": "2", "body": "The `list` would be better replaced with a `vector`, then `std::sort()` instead of `.sort()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T00:31:50.753", "Id": "8585", "Score": "1", "body": "If you use `vector` like Jon Purdy adviced, it has a constructor that takes a begin/end pair so you don't need the while loop. Just write: `vector<pair<string,int> > names(cars.begin(), cars.end());` Another 3 lines (and one empty line) gone!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T17:26:37.877", "Id": "3719", "ParentId": "3714", "Score": "17" } }, { "body": "<p>Why do these return void?</p>\n\n<pre><code>// reads lines from instream\nvoid collect_lines(istream &amp;in, map&lt;string, int&gt; &amp;lines);\n\n// given lines-&gt;num_occurs map, reverses mapping\nvoid reorg_by_count(map&lt;string, int&gt; &amp;lines, \n multimap&lt;int, string&gt; &amp;bycount);\n</code></pre>\n\n<p>There's no need to pass by reference in this case, just do this:</p>\n\n<pre><code>// reads lines from instream\nmap&lt;string, int&gt; collect_lines(istream &amp;in);\n\n// given lines-&gt;num_occurs map, reverses mapping\nmultimap&lt;int, string&gt; reorg_by_count(map&lt;string, int&gt; &amp;lines);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:43:17.603", "Id": "5599", "Score": "0", "body": "pre-C++0x, the pass-by-reference versions will save an expensive copy" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:06:31.123", "Id": "5604", "Score": "0", "body": "@BenVoigt: I don't think so. RVO and NRVO will likely kick in on functions where the return logic is non-complex." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:22:15.257", "Id": "5606", "Score": "0", "body": "Oh, and in addition, that's quite premature optimization, I'd go for clarity first. In addition, you can \"swaptimize\" the return value too, if you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:43:36.437", "Id": "5609", "Score": "1", "body": "@DeadMG: Do many compiler even consider RVO and NRVO on functions that aren't inlined? Being defined after use, and fairly long, I'm doubtful that inlining would occur here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T11:08:39.743", "Id": "5652", "Score": "0", "body": "@Ben Voigt: Modern compilers inline across translation units. A function defined later in the same TU is child's play in comparison. Plus, my points about premature optimization and swaptimization still apply." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T18:34:36.430", "Id": "3721", "ParentId": "3714", "Score": "4" } }, { "body": "<p>@Martinho's comments are on target (as is usual for him), but I think there's more to it than just that. @iammilind and @epatel may have a bit ambitious hoping for 10 lines of code, but based on code I posted in a <a href=\"https://stackoverflow.com/questions/3301684/map-operationsfind-most-occurence-element/3302118#3302118\">previous answer</a> meeting similar requirements, I'd guess around 15 to 20 could be fairly reasonable.</p>\n\n<p>I'm also less than enthused about how you've organized your code. In particular, I dislike having <code>collect_lines</code> not only reading input and putting it into the map, but also trimming leading white space and doing name-style capitalization. Absent a specific requirement to do so, I'd probably skip those for an interview question, but if they are required they should be in separate functions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:48:57.033", "Id": "5611", "Score": "0", "body": "10 or 15, think we are in the same ballpark at least ;) got a question of what I was thinking of so made a [gist](https://gist.github.com/1114501) (35 lines total, ~10-15 active lines)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:34:08.643", "Id": "3722", "ParentId": "3714", "Score": "5" } }, { "body": "<h3>Problems I see:</h3>\n<p>My problem with your code is that you are newing a lot of stuff that should just be objects.</p>\n<pre><code>map&lt;string, int&gt; *lines = new map&lt;string, int&gt;();\nmultimap&lt;int, string&gt; *lines_by_count = new multimap&lt;int, string&gt;();\n</code></pre>\n<p>Both of these should just be plain objects.</p>\n<pre><code>map&lt;string, int&gt; lines;\nmultimap&lt;int, string&gt; lines_by_count;\n</code></pre>\n<p>This one fact would have caused you to be rejected. I would have seen this and I would not have read any-further into your code straight onto the reject pile. This fundamental flaw in your style shows that you are not a C++ programmer.</p>\n<p>Next the objects you new are stored in RAW pointers. This is a dead give away that you are not an experienced C++ programmer. There should practically never be any pointers in your code. (All pointers should be managed by an object). Even though you manually do delete these two it is not done in an exception safe way (so they can still potentially leak).</p>\n<p>You are reading a file incorrectly.</p>\n<pre><code>while (in.good())\n{\n getline(in, tmp);\n</code></pre>\n<p>This is the standard anti-pattern for reading a file (even in C). The problem with your version is that the last successful read will read upto <strong>but</strong> not past the EOF. Thus the state of the file is still good but there is now no content left. So you re-enter the loop and the first read operation <code>getline()</code> will then fail. Even though it can fail you do not test for that.</p>\n<p>I would expect to see this:</p>\n<pre><code>while (getline(in, tmp))\n{\n // Line read successfully\n // Now I can processes it\n}\n</code></pre>\n<p>Next you are showing a fundamental misunderstanding of how maps work:</p>\n<pre><code> if (lines.count(tmp) == 0)\n {\n lines[tmp] = 0;\n }\n lines[tmp]++;\n</code></pre>\n<p>If you use the operator[] on a map it always returns a reference to an internal value. This means if the value does not exist one will be inserted. So there is no need to do this check. Just increment the value. If it is not their a value will be inserted and initialized for you (thus integers will be zero). Though not a big problem its usually preferable to use pre-increment. (For those that are going to say it does not matter. On integer types it does not matter. But you have to plan fro the future where somebody may change the type to a class object. This way you future proof your code against change and maintenance problems. So prefer pre-increment).</p>\n<p>You are doing extra work you don't need to:</p>\n<pre><code>// trim initial space (also skips empty strings)\nfor (i = 0; i &lt; tmp.length() &amp;&amp; !isalnum(tmp[i]); i++);\n</code></pre>\n<p>The streams library already discards spaces when used correctly. Also the ';' at the end of the for. This is considered bad practice. It is really hard to spot and any maintainer is going to ask did he really mean that. When you have an empty body it is always best to use the {} and put a comment in their <code>{/*Deliberately empty*/}</code></p>\n<p>Here you are basically lower casing the string.</p>\n<pre><code> for (i = 0; i &lt; tmp.length(); i++)\n {\n if (!isalnum(tmp[i]))\n {\n tmp[i] = ' ';\n }\n</code></pre>\n<p>You could use the C++ algorithms library to do stuff like this:</p>\n<pre><code>std::transform(tmp.begin(), tmp.end(), tmp.begin(), ::tolower());\n // ^^^^^^^^^^^ or a custom \n // functor to do the task\n</code></pre>\n<p>Const correctness.</p>\n<pre><code>void reorg_by_count(map&lt;string, int&gt; &amp;lines, multimap&lt;int, string&gt; &amp;bycount)\n</code></pre>\n<p>The parameter <code>lines</code> is not mutated by the function nor should it be. I would expect it to be passed as a const reference as part of the documentation of the function that you are not going to mutate it. This also helps in future maintenance as it stops people from accidentally mutating the object in a way that later code would not expect.</p>\n<p>My final thing is I did not see any encapsulation of the concept of a car. You treated it all as lines of text. If you had invented a car object you can define how cars are read from a stream and written to a stream etc. Thus you encapsulate the concept in a single location.</p>\n<p>I would have done something like this:<br />\nProbably still overkill.</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iterator&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n#include &lt;map&gt;\n#include &lt;cctype&gt;\n\nclass Car\n{\n public:\n bool operator&lt;(Car const&amp; rhs) const {return name &lt; rhs.name;}\n friend std::istream&amp; operator&gt;&gt;(std::istream&amp; stream, Car&amp; self)\n {\n std::string line;\n std::getline(stream, line);\n\n std::stringstream linestream(line);\n linestream &gt;&gt; self.name; // This strips white space\n\n // Lowercase the name\n std::transform(self.name.begin(), self.name.end(), self.name.begin(), ::tolower);\n // Uppercase first letter because most are proper nouns\n self.name[0] = ::toupper(self.name[0]);\n return stream;\n }\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, Car const&amp; self)\n {\n return stream &lt;&lt; self.name &lt;&lt; &quot;\\n&quot;;\n }\n private:\n std::string name;\n};\n\nint main(int argc, char* argv[])\n{\n if (argc &lt; 2)\n { exit(1);\n }\n std::ifstream cars(argv[1]);\n std::map&lt;Car,int&gt; count;\n\n Car nextCar;\n while(cars &gt;&gt; nextCar)\n {\n ++count[nextCar];\n }\n\n // PS deliberately left the sorting by inverse order as an exercise.\n for(auto const&amp; car: count) {\n std::cout &lt;&lt; car.first &lt;&lt; &quot;: &quot; &lt;&lt; car.second &lt;&lt; &quot;\\n&quot;;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:16:54.547", "Id": "5616", "Score": "13", "body": "+1 Many good points, like const correctness. Creating a Car object, however, is--in my mind--overkill." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T23:02:01.230", "Id": "5627", "Score": "4", "body": "@Adrian McCarthy: I like the `Car` object as it lets me do this: `while(cars >> nextCar)` which is very intuitive to read. (If this was a bigger program) then it also it centralized the code where we read a car from a stream. So if we modify the representation of a car we only have to modify one piece of code and all loops will still work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T20:38:52.093", "Id": "5691", "Score": "0", "body": "@Martin Thanks for a generously informative answer. (BTW, EVERYONE, thanks for your time). Martin, in my \"defense\" (well, not really) I've seen a lot of raw pointers in production code :) Or should I say :(" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T22:24:38.553", "Id": "5696", "Score": "2", "body": "@Jozin S Bazin: There is a lot of C code that pretends to be C++ (AKA C with classes)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T00:34:23.053", "Id": "5746", "Score": "0", "body": "If exception safety is the reason why people use smart pointers, I'll start using them I guess. I'd been thinking it was just because people wanted to be smug and make everything different from C just so they could tell the difference between old-school and new school programmers. And like Jozin, all the production code I've seen uses \"raw\" pointers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T14:23:24.777", "Id": "5754", "Score": "3", "body": "@Seth Carnegie: Find an article on RAII. In my opinion this is the **MOST** important concept in C++ that must be learned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T18:01:57.113", "Id": "5786", "Score": "0", "body": "@Martin, I'm already familiar with RAII, I've just been a slow adopter. _Really_ slow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-21T17:51:43.820", "Id": "349054", "Score": "1", "body": "You missed the `using namespace` antipattern to add to the list!" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:48:41.457", "Id": "3723", "ParentId": "3714", "Score": "96" } }, { "body": "<p>Here's what I would answer:</p>\n\n<pre class=\"lang-python prettyprint-override\"><code>def countCars(fname):\n carCount = {}\n with open(fname, 'r') as f:\n for car in f:\n car = car.strip()\n carCount[car] = 1 + carCount.get(car, 0)\n return carCount\n\ndef printCount(carCount):\n items = carCount.items()\n items.sort(lambda a,b:b[1]-a[1])\n for item in items:\n print \"%s %d\" % item\n\nif __name__ == \"__main__\":\n import sys\n printCount(countCars(sys.argv[1]))\n</code></pre>\n\n<p>And then they'd say \"That isn't C++\" and I'd say \"C++ really isn't appropriate for this kind of work, which is an order of magnitude faster to write in higher-level language and runs IO-bound anyway.\" and then they wouldn't hire me and I'd go work at a company that uses languages that <em>aren't</em> old enough to rent a car.</p>\n\n<p>Go ahead, flame away, what do I care...</p>\n\n<p><em>Later:</em>\nThe thought occurs, maybe the hiring company didn't specify the language and that was the OP's mistake, choosing a Reagan-era hold-over like C++.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T04:39:32.787", "Id": "5646", "Score": "1", "body": "Python? Pshaw! Nobody's even heard of the Web when that old language was invented. You should be using Clojure, or Go. They're so much *newer*! Never mind [relevance in the real world](http://langpop.com/), amirite?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T14:14:57.080", "Id": "5655", "Score": "0", "body": "@Mud -- in (some degree of) seriousness, I wouldn't defend Python as *young*, I attended the first world-wide Python conference back in 1996 (there were maybe 30 people there) because I was writing a platform for Internet retail, in Python. The next year, I sold it to Microsoft and mind-bogglingly [they're still selling it](http://www.microsoft.com/commerceserver/en/us/roadmap.aspx)! Clojure and Go aren't *bad* choices for this problem (although I would argue, no better than Python), and although Mud is sarcastically correct, popularity matters, technical innovation does too. No chars left!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T22:53:46.457", "Id": "5667", "Score": "4", "body": "@Malvolio: it's a coding exercise, what did you expect? They have to give some simple task... About higher-level languages: There are zillions of usages of c/C++ where python (and most other languages) would fail: compilers, modern 3d games, audio and video processing, device drivers, desktop apps (your browser, movie player, chat, ...), embedded devices and almost all the implementation of other languages (including python). Ranting about how easier is to solve a simple task like this in a higher-language shows your ignorance and it is alone enough reason not to hire you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T10:05:19.000", "Id": "5678", "Score": "0", "body": "@yi_H -- What did I expect? Well, call me ignorant but I expect that an exercise in a job interview is relevant to the actual job. So, if the company is writing device drivers or video processing or whatever C++ shines in, then a string processing function is a poor choice of exercises. In my uninformed opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T00:46:59.863", "Id": "8588", "Score": "1", "body": "@Malvolio The task apparently was good enough to weed out those that don't know C++ well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-21T17:48:35.530", "Id": "349053", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-21T22:30:07.030", "Id": "349088", "Score": "0", "body": "@TobySpeight -- you know that was 6 and a half years ago, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-22T08:57:48.093", "Id": "349120", "Score": "0", "body": "I didn't actually notice the date. The answer still isn't a review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-22T16:41:57.597", "Id": "349198", "Score": "0", "body": "@TobySpeight -- my review is \"C++ really isn't appropriate for this kind of work.\" I don't really speak C++, having stopped using it _in 1991_. I had a newborn at the time; she is now older than I was at the time." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T02:43:18.233", "Id": "3732", "ParentId": "3714", "Score": "-7" } }, { "body": "<p>Following @Malvolio idea I guess this task might have been done in <a href=\"http://en.wikipedia.org/wiki/AWK\" rel=\"nofollow\">AWK</a>.</p>\n\n<p>AWK is made for programs of this kind. It is event driven, for axample it has event handlers for each line and end of file. It also has map data structure and can print to stdout.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T18:06:40.497", "Id": "5663", "Score": "0", "body": "Or shell script. `sort cars.txt | uniq -c | sort -rn`, and relax." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T17:18:44.533", "Id": "5813", "Score": "0", "body": "Yes, this! Add find for unbridled power." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T03:53:16.193", "Id": "3736", "ParentId": "3714", "Score": "3" } }, { "body": "<blockquote>\n <p>I'd be grateful for any brutally honest feedback.</p>\n</blockquote>\n\n<p>The code is 5 times longer than it needs to be, thanks in part to superfluous code which does things that weren't called for in the specification.</p>\n\n<p>You need 3 or 4 lines of code to read the lines into a map. You use 40 doing things like... recapitalizing, but only the first word in each brand name, for no apparent reason, without explanation. You also strip out any non-alphanumeric characters, which will <em>break</em> brand names like Mercedes-Benz or Rolls-Royce, again without explanation.</p>\n\n<p>The comments are somewhat poor/inconsistent. Comments should tell the reader something the code doesn't. For instance, you explain that you're stripping leading space from each line (something the code already tells us), but don't explain why you aren't stripping trailing space (something we can't read in the code).</p>\n\n<p>Variable names like <code>tmp</code> are also poor (with a few exceptions, like perhaps a swap routine). We <em>know</em> the variable is temporary because of it's scope. The name should tell us what it's <em>for</em>. In this case, it contains the line we're reading, so a name like <code>line</code> would have been better.</p>\n\n<p>As others have pointed out, you're also allocating objects on the heap for no apparent reason. You delete them at the end of main, but not in your early return, which is a huge red flag (given that this is a major source of headaches in C++).</p>\n\n<p>You also have some code that shows you're unfamiliar without how standard library classes work (like assigning 0 to a map entry which is already 0).</p>\n\n<hr>\n\n<p>As soon as I read the problem description, I alt-tabbed to my editor and wrote this program. I ended up with almost exactly what <code>epatel</code> posted (although his code is broken for multi-word auto names). I haven't been a C++ programmer in nearly 10 years, so I don't know if there's some new fangled stuff I don't know about (lamdas would help here), but the company was probably looking for something straightforward and succinct.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T05:29:47.100", "Id": "3740", "ParentId": "3714", "Score": "10" } }, { "body": "<p>This is an interesting exercise.</p>\n\n<p>It's interesting because no sensible person would solve this problem in C++. For the very simple reason that the solution in shell script is:</p>\n\n<pre><code>sort cars.txt | uniq -c | sort -rn\n</code></pre>\n\n<p>Or, if you insist on counts following names:</p>\n\n<pre><code>sort cars.txt | uniq -c | sort -rn | sed 's/ *\\([0-9]*\\) \\(.*\\)$/\\2 \\1/'\n</code></pre>\n\n<p>Platforms that aren't unix will have other tools that could be used to solve it.</p>\n\n<p>So, were they trying to see if you'd come up with a sensible non-C++ solution, or was this a pointless task that was being used purely to see what sort of code you write?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T23:13:15.647", "Id": "5668", "Score": "4", "body": "An answer like this definitely deserves some extra points (if you also give a c++ solution) but you have to understand it's a small exercise. Can you come up with a good task that doesn't take to much time to code and can be used to measure your coding skills, yet it's only solvable with C++ and not with shell script, python or ruby? Can you come up with something that's not a pointless task?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T17:00:15.923", "Id": "5687", "Score": "1", "body": "Fair point. The test we give people at my company (in Java) involves a small but realistic already-existing class that's part of an imaginary web application - a registration handler, in fact, which takes a username and password and creates an account. We ask interviewees to add some more features to it. I don't think that's pointless (perhaps only because J2EE doesn't provide this out of the box, but should!)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T18:12:23.953", "Id": "3747", "ParentId": "3714", "Score": "8" } }, { "body": "<p>Just to throw out a thought that nobody else mentioned, everybody here is using a map (which as I'm a C# dev I'm imagining that's more or less a dictionary/hashtable of sorts), I would have thought of doing this as a heapsort on a filled in string array from the file, then iterate over it just counting dupes and outputting the previous member with it's count everytime a member doesn't match the previous.</p>\n\n<p>sorry for my lack of C++ but it would be something like, after reading the file or stdin into the array and heapifying it (you may need to implement your own text comparer, not sure on that in C++)</p>\n\n<pre><code>string previousCar = sortedArray[0];\nint numberOfConsecutiveDupes = 0;\nfor(int i = 0; i &lt; length(sortedArray); i++) // Don't know if this is how to retrieve array length in C++ sorry :(\n{\n if (sortedArray[i] == previousCar)\n {\n numberOfConsecutiveDupes++;\n continue; // don't know if continue exists in C++?\n }\n\n SendYourOutputToFileOrWhereverYouWantTo(previousCar + \" \" + itoa(numberOfConsecutiveDupes)); // itoa, I know this is wrong, I really don't know C++\n previousCar = sortedArray[i];\n numberOfConsecutiveDupes = 1;\n}\n</code></pre>\n\n<p>I realize this would <em>not</em> get anyone the job, I'm just trying to propose a different solution strategy given that they did know C++ syntax/STL/etc (which I def do not)..</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-10-29T00:43:12.520", "Id": "8587", "Score": "1", "body": "Everyone is using `std::map` because it is the textbook example for `std::map`! An easy `while(cin >> name) map[name]++;` is enough to read words and count them. Not using a std::map is a clear signal one is not known with C++." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T22:27:31.193", "Id": "3748", "ParentId": "3714", "Score": "-2" } }, { "body": "<p>Considering that others have already corrected your code I'd like to propose a somehow different approach to the problem.</p>\n\n<p>I think that we can get rid of the extra pass of sorting an auxiliary map/multimap at the end to preserve the decreasing order.</p>\n\n<p>In order to do that we can use a vector that holds car frequency information and a map that links the car name to that vector.</p>\n\n<p>It's much easier to express this in code so here it goes: </p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;map&gt;\n#include &lt;set&gt;\n#include &lt;vector&gt;\n\nusing namespace std;\n\nint main( int numberOfArguments, char** arguments )\n{\n typedef map&lt; string, unsigned int &gt; CarEntryMap;\n\n typedef pair&lt; unsigned int, CarEntryMap::iterator &gt; CarFrequency;\n\n typedef vector&lt; CarFrequency &gt; CarFrequencyVector;\n\n fstream file( \"C:\\\\Cars.txt\" );\n\n if( !file.is_open() )\n {\n return 0;\n }\n\n CarEntryMap carEntries;\n\n CarFrequencyVector carFrequencies;\n\n string carName = \"\";\n\n while( getline( file, carName ) )\n {\n CarEntryMap::iterator it = carEntries.find( carName );\n\n if( it == carEntries.end() )\n {\n CarEntryMap::iterator entry = carEntries.insert( it, pair&lt; string, unsigned int &gt;( carName, carFrequencies.size() ) );\n\n carFrequencies.push_back( CarFrequency( 1, entry ) );\n }\n else\n {\n unsigned int index = it-&gt;second;\n\n pair&lt; unsigned int, CarEntryMap::iterator &gt;&amp; currentEntry = carFrequencies[ index ];\n\n currentEntry.first++;\n\n if( index != 0 )\n {\n unsigned int updatedIndex = index;\n\n for( int i = index - 1; i &gt;= 0; i-- )\n {\n if( currentEntry.first &lt;= carFrequencies[i].first )\n {\n break;\n }\n\n updatedIndex = i;\n }\n\n if( index != updatedIndex )\n {\n carFrequencies[ updatedIndex ].second-&gt;second = index;\n\n currentEntry.second-&gt;second = updatedIndex;\n\n swap( carFrequencies[ updatedIndex ], currentEntry );\n }\n }\n }\n }\n\n for( CarFrequencyVector::iterator it = carFrequencies.begin(); it != carFrequencies.end(); ++it )\n {\n cout &lt;&lt; it-&gt;second-&gt;first &lt;&lt; \" \" &lt;&lt; it-&gt;first &lt;&lt; endl;\n }\n\n return 0;\n}\n</code></pre>\n\n<p>This way, instead of sorting at the end we only swap two entries in vector when the car frequency order changes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T02:30:35.897", "Id": "3771", "ParentId": "3714", "Score": "2" } }, { "body": "<p>Here is my improvement over epatel's answer.</p>\n\n<ul>\n<li>It uses a <code>map</code> instead of a <code>list</code>, as suggested in one of the comments.</li>\n<li>It uses the standard <code>copy</code> algorithm instead of doing that manually.</li>\n<li>It imports every name from the <code>std</code> namespace explicitly, to avoid importing unrelated names.</li>\n<li>The functions <code>my_pair_less</code> and <code>my_pair_output</code> don't modify the pairs, so they get an extra <code>const</code> qualifier for their arguments.</li>\n<li>The file is read in line by line, which saves a few lines of code and also allows car names that consist of multiple words.</li>\n</ul>\n\n<p>And here's the code:</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;map&gt;\n#include &lt;vector&gt;\n\nusing std::cin;\nusing std::cout;\nusing std::map;\nusing std::pair;\nusing std::string;\nusing std::vector;\n\nbool my_pair_less(const pair&lt;string, int&gt; &amp;a, const pair&lt;string, int&gt; &amp;b) {\n return b.second &lt; a.second;\n}\n\nvoid my_pair_output(const pair&lt;string, int&gt; &amp;p) {\n cout &lt;&lt; p.first \" \" &lt;&lt; p.second &lt;&lt; \"\\n\";\n}\n\nint main() {\n map&lt;string, int&gt; cars;\n\n string name;\n while (getline(cin, name)) {\n cars[name]++;\n }\n\n vector&lt;pair&lt;string, int&gt; &gt; names;\n copy(cars.begin(), cars.end(), back_inserter(names));\n sort(names.begin(), names.end(), my_pair_less);\n\n for_each(names.begin(), names.end(), my_pair_output);\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-20T06:08:41.183", "Id": "4254", "ParentId": "3714", "Score": "4" } }, { "body": "<p>This is my take on this. I used a map and multiset and a sort predicate.</p>\n\n<pre><code>struct sort_pred {\n bool operator()(const std::pair&lt;string,int&gt; &amp;left, const std::pair&lt;string,int&gt; &amp;right) {\n return left.second &gt; right.second;\n }\n};\n\nint main()\n{\n multiset&lt; pair&lt;string,int&gt; ,sort_pred &gt; myset;\n map&lt;string,int&gt; mymap;\n readfile(mymap);\n for(map&lt;string,int&gt;::iterator it=mymap.begin();it!=mymap.end();it++)\n {\n myset.insert(make_pair&lt;string,int&gt;(it-&gt;first,it-&gt;second));\n }\n cout&lt;&lt;\"Elements in the set:\"&lt;&lt;endl;\n for(multiset&lt;pair&lt;string,int&gt;,sort_pred &gt;::iterator it=myset.begin();it!=myset.end();it++)\n cout&lt;&lt;it-&gt;first&lt;&lt;\" \"&lt;&lt;it-&gt;second&lt;&lt;endl;\n return 0;\n}\n\nvoid readfile(map&lt;string,int&gt; &amp;t)\n{\n string filename=\"temp.txt\";\n ifstream file;\n file.open(filename.c_str());\n\n if(!file.is_open())\n {\n cerr&lt;&lt;\"Error opening file : \"&lt;&lt;filename.c_str()&lt;&lt;endl;\n exit(0);\n }\n\n string line;\n while(getline(file,line))\n {\n if(t.find(line)!=t.end())\n t[line]++;\n else\n t.insert(std::make_pair(line,1));\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-12-21T17:47:21.230", "Id": "349051", "Score": "0", "body": "You have presented an alternative solution, but haven't reviewed the code. Please [edit] it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-29T07:18:14.447", "Id": "51971", "ParentId": "3714", "Score": "-1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T16:45:50.490", "Id": "3714", "Score": "94", "Tags": [ "c++", "interview-questions" ], "Title": "Outputting the names of cars, without repetitions, with the number of occurrences in order of decreasing repetitions" }
3714
<p>I have a method with too many parameters. </p> <p>How would you refactor it?</p> <p>Things I considered so far:</p> <ul> <li>pass an array to the object and check for required keys (no code hint, phpdoc, programmer doesn't know which are required)</li> <li>pass an object (silly method with getters and setters, programmer still doesn't know which are required)</li> </ul> <p>Here's the method:</p> <pre><code>public function doDirectPayment( $amount, $credit_card_type, $credit_card_number, $expiration_month, $expiration_year, $cvv2, $first_name, $last_name, $address1, $address2, $city, $state, $zip, $country, $currency_code, $ip_address, $payment_action = 'Sale' ) { $client = $this-&gt;getClient(); $client-&gt;setParameterGet('METHOD', 'DoDirectPayment'); $month = str_pad(ltrim((string)$expiration_month, 0), 2, '0', STR_PAD_LEFT); $expiration_date = $month . $expiration_year; $client-&gt;setParameterGet('PAYMENTACTION', urlencode($payment_action)); $client-&gt;setParameterGet('AMT', urlencode($amount)); $client-&gt;setParameterGet('CREDITCARDTYPE', urlencode($credit_card_type)); $client-&gt;setParameterGet('ACCT', urlencode($credit_card_number)); $client-&gt;setParameterGet('EXPDATE', urlencode($expiration_date)); $client-&gt;setParameterGet('CVV2', urlencode($cvv2)); $client-&gt;setParameterGet('FIRSTNAME', urlencode($first_name)); $client-&gt;setParameterGet('LASTNAME', urlencode($last_name)); $client-&gt;setParameterGet('STREET', urlencode($address1)); if (!empty($address2)) { $client-&gt;setParameterGet('STREET2', urlencode($address2)); } $client-&gt;setParameterGet('CITY', urlencode($city)); $client-&gt;setParameterGet('STATE', urlencode($state)); $client-&gt;setParameterGet('ZIP', urlencode($zip)); $client-&gt;setParameterGet('COUNTRYCODE', urlencode($country)); $client-&gt;setParameterGet('CURRENCYCODE', urlencode($currency_code)); $client-&gt;setParameterGet('IPADDRESS', urlencode($ip_address)); $response = $client-&gt;request(Zend_Http_Client::GET); return $response; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:52:16.140", "Id": "5641", "Score": "3", "body": "biggest argument list I've ever seen :)" } ]
[ { "body": "<p>Passing an object (class name 'Payment' perhaps?) is not that silly actually. You can add public method <code>validate()</code> to it, that could be called from <code>doDirectPayment()</code> in order to check if all required fields have been filled. </p>\n\n<p>You will probably want to make it as <a href=\"http://www.phpfreaks.com/tutorial/design-patterns---value-object\" rel=\"nofollow\">value object</a> so as to avoid unexpected side effects.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:30:55.257", "Id": "5642", "Score": "0", "body": "also, if you use an object, return $this from the setters so function calls can be chained. But the array solution is equally fine, I guess it's a matter of taste.." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:11:04.180", "Id": "3734", "ParentId": "3733", "Score": "5" } }, { "body": "<p>I'd group the parameters:</p>\n\n<pre><code>doDirectPayment(CreditCard $card, User $user, array $options = array())\n</code></pre>\n\n<p>But this doesn't solve all problems. </p>\n\n<p>To mark something required you'd use interface, but the interface can only force the existence of the methods, not the properties.</p>\n\n<p>So the best option seems to be forcing the params in the constructor:</p>\n\n<pre><code>class CreditCard {\n public function __construct($required1, $required2 /*, etc*/);\n}\n</code></pre>\n\n<p>But this way you can't instantiate the object without providing options (no fluent interface).</p>\n\n<p>You may mark the params optional and provide some validation method. The problem is, how to automatically call this method. Maybe some SPL interface may help here.</p>\n\n<hr>\n\n<p>From Fowler's Refactoring:</p>\n\n<blockquote>\n <p>Long Parameter Lists</p>\n \n <p>Too many parameters. Functionality is wrong, or not enough use of\n fields</p>\n \n <p>Hinders: comprehension, use, adding parameters</p>\n \n <p>Main Refactoring: Replace Parameter with Method, Preserve Whole Object, Introduce Parameter Object</p>\n</blockquote>\n\n<hr>\n\n<p>Looks like most of those params will come from the user filled form, so you could simply do:</p>\n\n<pre><code>doDirectPayment(PaymentForm $form, array $otherOptions = array()) {\n // ...\n foreach ($form-&gt;getValues() as $name =&gt; $value) {\n $client-&gt;setParameterGet(strtoupper($name), urlencode($value));\n }\n // ...\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T23:48:37.020", "Id": "5670", "Score": "0", "body": "+1 the constructor of the data object that will be the parameter causes required fields, then privatizing the setters on those ensures relative immutability so they can't be replaced with nulls. This is exactly the correct approach from my experience." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:21:59.533", "Id": "3735", "ParentId": "3733", "Score": "8" } }, { "body": "<p>I'm not entirely sure if this is feasible in PHP, but a class-seperated builder pattern is a nice way to alleviate long parameter lists.</p>\n\n<p>You can have each builder return the next component as required.</p>\n\n<p>ie:</p>\n\n<pre><code>CreditCardInfo.Build(credit_card_type, _number, month, year) // Returns NameInfo Builder class\n.Build(first_name, last_name) //Returns AddressInfo Builder class\n.Build(address1, address2, city, state, zip, country) //Returns TransactionInfo Builder class\n.Build(ip_address) //Returns Payment class\n.DoDirectPayment();\n</code></pre>\n\n<p>Each of the builder classes { <em>CreditCardInfo, NameInfo, AddressInfo, TransactionInfo</em> } have a <em>Build</em> method that returns the next Builder class in order. The final one returned, <strong>Payment</strong>, will contain the DoDirectDeposit action. </p>\n\n<p>This helps show the intent of each of the parameters, and gives a clear API as to how each parameter grouping contributes to the requirements of the function call.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T04:09:04.780", "Id": "3772", "ParentId": "3733", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:04:34.570", "Id": "3733", "Score": "7", "Tags": [ "php" ], "Title": "Payment function with too many parameters" }
3733
<p>I'm hoping some folks can take a few minutes to review some code I was working on today.</p> <p><a href="https://gist.github.com/1115202" rel="nofollow">https://gist.github.com/1115202</a></p> <p>Essentially, I'm doing a lot of work in Node.js at the moment and I'm a big fan of Promises.</p> <p>Since 99% of the work that I'm doing involves performing several asynchronous actions and then parsing the results, I wanted something a little simpler and more light-weight that some of the other Promise/Deferred/Futures libraries that are out there.</p> <p>My aim with this is to have a simple when().then() format without having to instantiate a new Promise inside each function.</p> <p>The usage is like this:</p> <pre><code>when( function(){ this.pass(1); }, function(){ this.pass(2); } ) .then(function(results){ console.log( results ); }); </code></pre> <p>In the Github gist I've linked to above, there are use cases near the bottom. Test case 1 uses timeouts, the 2nd test case uses several async http requests in Node.js and logs the total results at the end when all 3 have finished.</p> <p>I'd love to hear any opinions good or bad, recommendations on how to make it better, etc. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T13:01:51.340", "Id": "5654", "Score": "0", "body": "I use [After](https://gist.github.com/1115502) instead of when/then. I don't think you can get much lighter then that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T15:27:49.727", "Id": "5656", "Score": "0", "body": "@Raynos how do you prevent the same function from calling `after` return value twice, or is that not a worry? I mean the scenario of that happening is highly unlikely." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T15:37:03.247", "Id": "5657", "Score": "0", "body": "@Lime if you use `after` in a buggy manner then that's a _bug_ you should fix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T15:58:20.067", "Id": "5659", "Score": "0", "body": "In terms of shortening, I think you can replace the switch statement with a ternary function, unless I've missed something. https://gist.github.com/1115658" } ]
[ { "body": "<p>I made The following edits:</p>\n\n<ol>\n<li>Prevent the same <code>when</code> function from calling <code>pass</code> twice(therefore invalidating results)</li>\n<li>Sends <code>pass</code> function as 1st argument to avoid <code>var that = this</code></li>\n<li>It stores the first pass arg only for simplicity instead of all <code>arguments</code> in results(easily switched)</li>\n<li>Then <code>function</code> can't be called more then one</li>\n<li>I removed the need for <code>When</code> and <code>when</code> functions(you could leave the separate functions for clarity if you wanted)</li>\n<li>There is now only one method <code>then</code> and prop <code>funcs</code></li>\n</ol>\n\n<p><a href=\"https://gist.github.com/1115319\" rel=\"nofollow\">https://gist.github.com/1115319</a></p>\n\n<p>Usage</p>\n\n<pre><code>when(\n function(pass){setTimeout(pass,3000)},\n function(pass){pass('2nd');}\n)\n.then(function(results){\n console.log(results);\n})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T23:28:48.433", "Id": "5669", "Score": "0", "body": "Thanks for the tips Lime. Here's the updated gist https://gist.github.com/1115202/f9453b0fa0279c136e88ff2ba419043d1868419f. I adopted a few of your changes, including using instanceof to instantiate a new when() and having then() redefine itself. I also liked your method of passing pass() into each function as an argument, so I adopted that as well. I ended up more or less using the same style I started with, since its a bit easier for me to read through and understand the code when I need to go back to it, and hopefully others as well. What do you think of the updates?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T04:20:53.823", "Id": "5673", "Score": "1", "body": "It doesn't have some of the security/safety checks implemented above, but otherwise it looks good to me :D" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T08:00:08.183", "Id": "3744", "ParentId": "3739", "Score": "3" } } ]
{ "AcceptedAnswerId": "3744", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T05:14:28.303", "Id": "3739", "Score": "2", "Tags": [ "javascript", "node.js" ], "Title": "Please review my implementation of a simple When/Then (pseudo Promise) in javascript" }
3739
<p>I am new to erlang (2 days to be honest) and I would highly appreciate some peer review. I am doing <a href="http://www.erlang.org/course/exercises.html">these exercises</a> and was a bit stuck at this point:</p> <blockquote> <p>2) Write a function which starts N processes in a ring, and sends a message M times around all the processes in the ring. After the messages have been sent the processes should terminate gracefully.</p> </blockquote> <p>With some help from SO, I came up with a working solution, but I am not sure about its quality in any aspect: Language comprehension, Coding style, Efficiency, etc.</p> <p>I will be grateful for any comment you have.</p> <pre><code>-module (concur). -export ( [pingCircle/3, pingCircle/2] ). pingCircle (Names, Message, TTL) -&gt; Processes = lists:map (fun (Name) -&gt; spawn (?MODULE, pingCircle, [Name, nobody] ) end, Names), ProcessPairs = lists:zip (Processes, rot1 (Processes) ), lists:map (fun ( {Process, Recipient} ) -&gt; Process ! {setRecipient, Recipient} end, ProcessPairs), Circle = lists:map (fun ( {Process, _} ) -&gt; Process end, ProcessPairs), hd (Circle) ! {Message, TTL - 1, lists:last (Circle) }. rot1 ( [] ) -&gt; []; rot1 ( [Head | Tail] ) -&gt; Tail ++ [Head]. pingCircle (Name, Recipient) -&gt; receive {setRecipient, NewRecipient} -&gt; pingCircle (Name, NewRecipient); {Message, 0, Originator} -&gt; io:format ("~s received ~p with TTL 0 and dying.~n", [Name, Message] ), if Originator == self () -&gt; io:format ("All dead.~n"); true -&gt; Recipient ! {Message, 0, Originator} end; {Message, TTL, Originator} -&gt; io:format ("~s received ~p with TTL ~p.~n", [Name, Message, TTL] ), if Originator == self () -&gt; Recipient ! {Message, TTL - 1, Originator}; true -&gt; Recipient ! {Message, TTL, Originator} end, pingCircle (Name, Recipient) end. </code></pre>
[]
[ { "body": "<pre><code>lists:map (fun ( {Process, Recipient} ) -&gt; Process ! {setRecipient, Recipient} end, ProcessPairs)\n</code></pre>\n\n<p>Whenever you use <code>lists:map</code> and don't use its return values, you almost certainly want to be using <code>lists:foreach</code> instead. <code>map</code> will not only build up a list that you never use, it also does not guarantee that the elements will be processed in any specific order.</p>\n\n<hr>\n\n<pre><code>Circle = lists:map (fun ( {Process, _} ) -&gt; Process end, ProcessPairs),\n</code></pre>\n\n<p>Unless I'm missing something here, the list you'll get back from <code>map</code> will be the same as your original <code>Processes</code> list, which you built <code>ProcessPairs</code> from. So you can just use <code>Processes</code> and get rid of <code>Circle</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-09T12:35:16.520", "Id": "4705", "ParentId": "3745", "Score": "4" } }, { "body": "<p>You can replace </p>\n\n<pre><code>spawn (?MODULE, pingCircle, [Name, nobody] )\n</code></pre>\n\n<p>with</p>\n\n<pre><code>spawn (fun() -&gt; pingCircle(Name, nobody) end)\n</code></pre>\n\n<p>This action allows do not export <code>pingCircle/2</code> from the module.\nIt is also recommended to use <code>spawn_link</code> instead of <code>spawn</code>, because it helps to avoid lost processes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T18:35:13.697", "Id": "18553", "ParentId": "3745", "Score": "5" } }, { "body": "<p>I'm reading Erlang Programming by Cesarini and Thompson, which poses essentially the same question. I tried it a couple different ways, and ended up with the code below. Essentially it creates the ring from tail (self()) to head (FirstNode) then injects user messages into FirstNode, followed by a quit message. The test() function creates a ring of a million threads and sends a thousand messages.</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Modified to wait before sending the quit, and display a count of messages that passed the master node. Note that in Erlang Programming, the problem doesn't specify that messages should stop at the originator, nor that messages start at any nodes other than the first node.</p>\n\n<pre><code>-module(ring2).\n-export([test/0, test_race/0, start/3, node_loop/2, fire_quit_later/1]).\n\ntest() -&gt; ring2:start(2, 1000000, \"Hey\").\n\nstart(NumMsgs, NumProcs, Message) -&gt;\n FirstNode = send_messages(create_node(NumProcs, self()), NumMsgs, Message),\n spawn(ring2, fire_quit_later, [FirstNode]),\n MessageCount = node_loop(FirstNode, 0),\n io:format(\"Done at ~p. Master node processed ~p messages.~n\", [calendar:local_time(), MessageCount]).\n\nfire_quit_later(FirstNode) -&gt;\n receive\n after 20000 -&gt; io:format(\"Firing quit at ~p~n\", [calendar:local_time()]), FirstNode ! quit\n end.\n\nsend_messages(FirstNode, 0, _) -&gt; FirstNode;\nsend_messages(FirstNode, NumMsgs, Message) -&gt;\n FirstNode ! Message,\n send_messages(FirstNode, NumMsgs - 1, Message).\n\ncreate_node(0, NextNode) -&gt; NextNode;\ncreate_node(NodeNumber, NextNode) -&gt; create_node(NodeNumber - 1, spawn(ring2, node_loop, [NextNode, 0])).\n\nnode_loop(NextNode, MessageCount) -&gt;\n receive\n quit -&gt; NextNode ! quit, MessageCount;\n Message -&gt; NextNode ! Message, node_loop(NextNode, MessageCount + 1)\n end.\n\ntest_race() -&gt;\n self() ! quit,\n receive\n quit -&gt; done\n after 1000 -&gt; {error, no_message}\n end.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-02T15:36:22.243", "Id": "32142", "ParentId": "3745", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-30T14:10:37.717", "Id": "3745", "Score": "10", "Tags": [ "erlang" ], "Title": "Erlang concurrency in circles" }
3745
<p>I was told this is the place to come for input/feedback on your programming. I am always looking to improve either by personal review or outside opinion/help. Would the community here be willing to provide positive criticism of my script below?</p> <pre><code>/******************************************************************** * Author: Mattew Hoggan * Description: Write a client program that uses the data type point. * Read a sequence of points (pairs of floating-point numbers) from * standard input, and find the one that is closest to the first. * *****************************************************************/ #include &lt;math.h&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;istream&gt; #include &lt;iterator&gt; #include &lt;algorithm&gt; #include &lt;limits.h&gt; using namespace std; typedef struct point { float x; float y; } point; float calc_distance( const point *a, const point *b ) { return sqrt( pow( a-&gt;x-b-&gt;x, 2.0 ) + pow( a-&gt;y-b-&gt;y, 2.0 ) ); } void print_point( point *a ) { cout &lt;&lt; "(" &lt;&lt; a-&gt;x &lt;&lt; ", " &lt;&lt; a-&gt;y &lt;&lt; ") "; } void delet_point( point *a ) { delete a; } vector&lt;point*&gt;* form_pairs( vector&lt;float&gt; &amp;num ) { vector&lt;point*&gt; *points=NULL; if( ( num.size( ) &amp; 1 ) == 1 ) { cerr &lt;&lt; "ERROR: You input: " &lt;&lt; num.size( ) &lt;&lt; " which is odd, failed to build vector " &lt;&lt; endl; return points; } else { cout &lt;&lt; "Going to build points" &lt;&lt; endl; points = new vector&lt;point*&gt;; for( vector&lt;float&gt;::iterator vit=num.begin( ); vit!=num.end( ); vit+=2 ) { point *in = new point( ); in-&gt;x = *(vit); in-&gt;y = *(vit+1); points-&gt;push_back( in ); } return points; } } void pop_front( vector&lt;point*&gt; *pairs ) { reverse( pairs-&gt;begin( ), pairs-&gt;end( ) ); pairs-&gt;pop_back( ); reverse( pairs-&gt;begin( ), pairs-&gt;end( ) ); } void min_euclidean_distance( vector&lt;point*&gt; *pairs ) { if( pairs-&gt;size( ) == 1 ) { cerr &lt;&lt; "You already know the answer to this" &lt;&lt; endl; return; } point *first = pairs-&gt;front( ); pop_front( pairs ); point *second = pairs-&gt;front( ); pop_front( pairs ); for_each( pairs-&gt;begin( ),pairs-&gt;end( ),print_point ); cout &lt;&lt; endl; point *p_min = second; float f_min = calc_distance( first,second ); for( vector&lt;point*&gt;::iterator pit = pairs-&gt;begin( ); pit != pairs-&gt;end( ); pit++ ) { float tmp = calc_distance( first,(*pit) ); if( tmp &lt; f_min ) { f_min = tmp; p_min = (*pit); } } cout &lt;&lt; "The closest node to "; print_point( first ); cout &lt;&lt; " is "; print_point( p_min ); cout &lt;&lt; " at " &lt;&lt; f_min &lt;&lt; " units away " &lt;&lt; endl; delete first; delete second; } int main( int arc, char **arv ) { vector&lt;float&gt; num; cout &lt;&lt; "Please, input even number of floats: "; for( istream_iterator&lt;float&gt; iit (cin); iit!=istream_iterator&lt;float&gt;( );iit++ ) { num.push_back( (*iit) ); } vector&lt;point*&gt;* pairs = form_pairs( num ); if( pairs ) { min_euclidean_distance( pairs ); for_each( pairs-&gt;begin( ),pairs-&gt;end( ),delet_point ); delete pairs; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-20T19:03:46.217", "Id": "58178", "Score": "0", "body": "I learned [something new](http://stackoverflow.com/a/6321226/1157100) today: `pow(x, 2)` performs the same as `x * x` with optimization on." } ]
[ { "body": "<p>A couple of comments.</p>\n\n<p>1) Why is this a free standing function and not a member?</p>\n\n<pre><code>float calc_distance( const point *a, const point *b )\n</code></pre>\n\n<p>It access members that should potentially be private. Best to make it a member.<br>\nAlso why are you passing by pointer. Best to pass by const reference. </p>\n\n<p>2) You use pointers where you should use objects. </p>\n\n<pre><code>vector&lt;point*&gt;* form_pairs( vector&lt;float&gt; &amp;num )\n</code></pre>\n\n<p>RAW pointers have no ownership semantics associated with them. Thus it is not clear who should clean them up. In this case you do clean then up, <strong>BUT</strong> not in an exception safe way. In C++ code it is generally a mistake to have any pointers in the code (pointers should be wrapped up in smart pointers or containers).</p>\n\n<p>In this case you should just have a simple vector of objects and you should return a reference. I know it looks expensive to copy back a vector but RVO and NRVO will take care of that and usually the vector is constructed in place at the destination and no copy is required.</p>\n\n<p>As the num vector is not changed. You should pass it by const reference.</p>\n\n<pre><code>std::vector&lt;point&gt; form_pairs(vector&lt;float&gt; const&amp; num)\n</code></pre>\n\n<p>3) What are you trying to acieve here?</p>\n\n<pre><code>if( ( num.size( ) &amp; 1 ) == 1 )\n</code></pre>\n\n<p>You are trying to validate that the input has an even number of floats as input.<br>\nWhy are you trying to make that fact cryptic. If you must do this then make a comment on you intent. Code is going to be in maintenance a lot longer than it takes to develop. Make sure you make it easy to understand.</p>\n\n<p>5) You are doing too much work here:</p>\n\n<pre><code> for( vector&lt;float&gt;::iterator vit=num.begin( );\n vit!=num.end( ); vit+=2 )\n</code></pre>\n\n<p>Here you could have used a standard algorithm. I would have used <code>std::copy()</code>. Also by using <code>+= 2</code> you are limiting yourself to <code>random access iterators</code> ie vectors. You are code should try and be neutral on the type of container. Thus limit yourself to the ++ operator.</p>\n\n<p>6) Dynamically allocating the pointer.</p>\n\n<pre><code> point *in = new point( );\n</code></pre>\n\n<p>a) Why not have a constructor that takes the two parameters to do the initialization.<br>\nb) Who owns the object. The owner is the person responsible for deleting the object.<br>\nc) If you had stored normal point objects in the vector this would not have been an issue.</p>\n\n<p>7) This is just a tad nit picky:</p>\n\n<pre><code>int main( int arc, char **arv )\n</code></pre>\n\n<p>Technically argv should be declared <code>char* argv[]</code>. </p>\n\n<p>8) Again too much work:</p>\n\n<pre><code>vector&lt;float&gt; num;\nfor( istream_iterator&lt;float&gt; iit (cin);\n iit!=istream_iterator&lt;float&gt;( );iit++ ) {\n num.push_back( (*iit) );\n}\n</code></pre>\n\n<p>This can be achieved with:</p>\n\n<pre><code>std::copy(std::istream_iterator&lt;float&gt;(std::cin),\n std::istream_iterator&lt;float&gt;(),\n std::back_inserter(num));\n</code></pre>\n\n<p>I would write it like this:<br>\nSimplicity is key!</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;fstream&gt;\n#include &lt;cmath&gt;\n\nclass Point\n{\n public:\n float distance(Point const&amp; rhs) const\n {\n float dx = x - rhs.x;\n float dy = y - rhs.y;\n\n return sqrt( dx * dx + dy * dy);\n }\n private:\n float x;\n float y;\n friend std::istream&amp; operator&gt;&gt;(std::istream&amp; stream, Point&amp; point);\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, Point const&amp; point);\n};\n</code></pre>\n\n<h3>Edit</h3>\n\n<p>Added comments on how stream operators work based on comments below.</p>\n\n<pre><code>// This function reads a point from a stream\n// It returns the stream object thus allowing chaining.\n// std::cin &gt;&gt; p1 &gt;&gt; p2 &gt;&gt; p3 &gt;&gt; etc;\n//\n// The side affect of returning the stream is that it can also\n// be used in conditionals. The stream will auto covert into a tyep\n// that can be used in a boolean context which is `true` if the stream\n// is still in a good state and `false` if the read failed.\n// while(std::cin &gt;&gt; point)\n// {\n// // Successfully read a point from the stream.\n// }\n//\nstd::istream&amp; operator&gt;&gt;(std::istream&amp; stream, Point&amp; point)\n{\n return stream &gt;&gt; point.x &gt;&gt; point.y;\n}\n\n// This function writes a point to a stream\n// This just returns the stream object\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, Point const&amp; point)\n{\n return stream &lt;&lt; point.x &lt;&lt; \" \" &lt;&lt; point.y &lt;&lt; \" \";\n\n // The above is just a shorthand way of writting this:\n stream &lt;&lt; point.x &lt;&lt; \" \" &lt;&lt; point.y &lt;&lt; \" \";\n return stream;\n\n // This is because the result of the operator &gt;&gt; and operator &lt;&lt;\n // Is always the stream passed as the first parameter.\n // Or historically this is what you are supposed to return to prevent confusion.\n}\n</code></pre>\n\n<p>This makes the main loop very easy to write:</p>\n\n<pre><code>int main()\n{\n std::ifstream data(\"Plop\");\n\n // Trying to find the closest point to this.\n Point first;\n data &gt;&gt; first;\n\n // The next point is the closest until we find a better one\n Point closest;\n data &gt;&gt; closest;\n\n float bestDistance = first.distance(closest);\n\n Point next;\n while(data &gt;&gt; next) // read a point. If if fails loop not entered.\n {\n float nextDistance = first.distance(next);\n if (nextDistance &lt; bestDistance)\n {\n bestDistance = nextDistance;\n closest = next;\n }\n }\n\n std::cout &lt;&lt; \"First(\" &lt;&lt; first &lt;&lt; \") Closest(\" &lt;&lt; closest &lt;&lt; \")\\n\";\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T06:10:13.083", "Id": "5675", "Score": "0", "body": "could you please explain the friend member functions. I don't really understand the return type. What is being returned exactly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T12:04:00.493", "Id": "5681", "Score": "1", "body": "One good idea is to have a `distance_squared` function that doesn't take the square root. Note that `sqrt(a * a) > sqrt(b * b)` is true if and only if `a > b`, so you can avoid the (expensive) `sqrt` call if you only need to see which one is largest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T17:00:09.967", "Id": "5686", "Score": "0", "body": "@Matthew: I have moved the friend functions to a more traditional location outside the class and written comments. Defining them inside the class is a little trick that I sometimes use when writing simple applications." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T21:29:26.760", "Id": "5692", "Score": "0", "body": "@Martin: Your expertise and willingness to share it is greatly appreciated. Thank you so much for your time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T09:13:30.090", "Id": "32776", "Score": "0", "body": "@LokiAstari: why should argv technically be declared char* argv[]?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-13T19:05:17.790", "Id": "32815", "Score": "1", "body": "@Xploit: Its probably overemphasis as char** is just as valid. But argv is an array of pointers. Declaring it as such helps others read it correctly. Using char** is just a pointer to a pointer it does not convey the semantics of an array. Thus the idea of using `char* argv[]` is to pass as much information to the reader of the code as possible." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T05:18:27.103", "Id": "3755", "ParentId": "3754", "Score": "5" } } ]
{ "AcceptedAnswerId": "3755", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T04:33:30.377", "Id": "3754", "Score": "2", "Tags": [ "c++", "stl" ], "Title": "Reading a sequence of points and finding the closest one to the first" }
3754
<p>I am trying to get in a lot of practice for interviews so I am trying to write as much code as possible, and getting feed back from excellent programmers like "you". Can I get some general feed back on this small bit of code? Any recommendations on style, good practice, etc. is greatly appreciated.</p> <p>Normally I would put the class declarations in their own header files, and the definitions in a .cpp file, write a make file and build using make. However, this is a small program so I just place everything inside one module.</p> <pre><code>/******************************************************************** * Define a data type for triangles in the unit square, including a * function that computes the area of a triangle. Then write a client * program that generates random triples of pairs of floats between 0 * and 1 and computes the average area of the triangles generated. * *****************************************************************/ #include &lt;iostream&gt; #include &lt;math.h&gt; #include &lt;time.h&gt; #include &lt;stdlib.h&gt; using namespace std; class Point { public: Point( ) { ;} Point( float x, float y ) : x( x ), y( y ){ ;} float getX( ) { return x; } float getY( ) { return y; } void setX( float X ) { x = X; } void setY( float Y ) { y = Y; } void print( ) { cout &lt;&lt; "("&lt;&lt;x&lt;&lt;", "&lt;&lt;y&lt;&lt;") "&lt;&lt;endl; } private: float x; float y; }; class Line { public: Line( Point a, Point b ) : a( a ), b( b ){ ;} void mid_point( Point &amp;mid ); float length( ); Point getA( ) { return a; } Point getB( ) { return b; } void print( ) { a.print( ); b.print( ); } private: Point a; Point b; }; void Line::mid_point( Point &amp;mid ) { mid.setX( (a.getX( )+b.getX( ))/2.0 ); mid.setY( (a.getY( )+b.getY( ))/2.0 ); } float Line::length( ) { return sqrt( pow( a.getX( )-b.getX( ),2.0 ) + pow( a.getY( )-b.getY( ),2.0 ) ); } class Triangle { public: Triangle( Line A,Line B,Line C ) : A( A ), B( B ), C( C ){ ;} float calc_area( ); void print( ) { cout &lt;&lt; "Line A formed from points\n"; A.print( ); cout &lt;&lt; "Line B formed from points\n"; B.print( ); cout &lt;&lt; "Line C formed from points\n"; C.print( ); } private: Line A; Line B; Line C; }; float Triangle::calc_area( ) { Point mid; C.mid_point( mid ); Line height( mid, A.getB( ) ); return 0.5*C.length( )*height.length( ); } int main( int argc, char *argv[ ] ) { srand( time( NULL ) ); //Calculate area of 10 triangles; for( int i=0;i&lt;10;i++ ) { Point p1( (rand( )%10)/10.0,(rand( )%10)/10.0 ); Point p2( (rand( )%10)/10.0,(rand( )%10)/10.0 ); Point p3( (rand( )%10)/10.0,(rand( )%10)/10.0 ); Line l1( p1,p2 ); Line l2( p2,p3 ); Line l3( p3,p1 ); Triangle t( l1,l2,l3 ); t.print( ); cout &lt;&lt; "Area = " &lt;&lt; t.calc_area( ) &lt;&lt; endl &lt;&lt; endl; } } </code></pre> <p>Output: (in the case you don't want to copy and pasted the code)</p> <pre><code>[mehoggan@desktop triangle]$ ./tri_area Line A formed from points (0.4, 0.2) (0.6, 0.4) Line B formed from points (0.6, 0.4) (0.8, 0.6) Line C formed from points (0.8, 0.6) (0.4, 0.2) Area = 0 Line A formed from points (0.5, 0.2) (0.6, 0.3) Line B formed from points (0.6, 0.3) (0.5, 0.9) Line C formed from points (0.5, 0.9) (0.5, 0.2) Area = 0.0942404 Line A formed from points (0.5, 0.9) (0.5, 0.8) Line B formed from points (0.5, 0.8) (0.1, 0.2) Line C formed from points (0.1, 0.2) (0.5, 0.9) Area = 0.129059 Line A formed from points (0.3, 0.1) (0.7, 0.2) Line B formed from points (0.7, 0.2) (0.5, 0.4) Line C formed from points (0.5, 0.4) (0.3, 0.1) Area = 0.0548293 Line A formed from points (0.8, 0.1) (0.2, 0.5) Line B formed from points (0.2, 0.5) (0.8, 0.3) Line C formed from points (0.8, 0.3) (0.8, 0.1) Area = 0.067082 Line A formed from points (0.5, 0.8) (0.2, 0.2) Line B formed from points (0.2, 0.2) (0.8, 0.3) Line C formed from points (0.8, 0.3) (0.5, 0.8) Area = 0.166208 Line A formed from points (0.6, 0.2) (0.8, 0.5) Line B formed from points (0.8, 0.5) (0.4, 0.2) Line C formed from points (0.4, 0.2) (0.6, 0.2) Area = 0.0424264 Line A formed from points (0.1, 0.3) (0.1, 0) Line B formed from points (0.1, 0) (0.4, 0.9) Line C formed from points (0.4, 0.9) (0.1, 0.3) Area = 0.20744 Line A formed from points (0.2, 0.4) (0.6, 0.9) Line B formed from points (0.6, 0.9) (0.3, 0.9) Line C formed from points (0.3, 0.9) (0.2, 0.4) Area = 0.109659 Line A formed from points (0.1, 0.4) (0.1, 0.3) Line B formed from points (0.1, 0.3) (0.8, 0.5) Line C formed from points (0.8, 0.5) (0.1, 0.4) Area = 0.134629 </code></pre>
[]
[ { "body": "<p>I am not an expert on modern c++ but this is a hint I would include:</p>\n\n<p>Instead of having the method print that always prints to cout, I would also include a method where it receives the stream to print to.\nSomething like this for point (not tested):</p>\n\n<pre><code>void print(std::ostream &amp;s){ s &lt;&lt; \"(\"&lt;&lt;x&lt;&lt;\", \"&lt;&lt;y&lt;&lt;\") \"&lt;&lt;endl;}\n</code></pre>\n\n<p>and for line:</p>\n\n<pre><code>void print(std::ostream &amp;s){ a.print(s); b.print(s);}\n</code></pre>\n\n<p>So in this way you can print to cout, cerr or a file if you want :)</p>\n\n<p>Hope this helps</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T09:10:40.100", "Id": "5676", "Score": "0", "body": "This seems like a trick that most people are showing me. I will adopt it into my style to make things more C++ like. Thanks -matt" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T22:30:23.057", "Id": "5697", "Score": "1", "body": "@Matthew: I would go a step further and do it the C++ way by defining the operator<< for your types." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T22:40:00.617", "Id": "5698", "Score": "0", "body": "@Martin: Yes, I thought about that later on." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T08:58:34.623", "Id": "3758", "ParentId": "3757", "Score": "1" } }, { "body": "<p>Reviewed and edited under Windows 7, compiles in VS10 SP1. Take the comments and changes with a grain of salt and use what you deem are good changes :) </p>\n\n<pre><code>/********************************************************************\n * Define a data type for triangles in the unit square, including a\n * function that computes the area of a triangle. Then write a client\n * program that generates random triples of pairs of floats between 0\n * and 1 and computes the average area of the triangles generated.\n * *****************************************************************/\n // .h headers are deprecated, use the headers with the \"c\" prefix like so.\n#include &lt;iostream&gt;\n#include &lt;cmath&gt;\n#include &lt;ctime&gt;\n#include &lt;ostream&gt;\n\n// No using namespace std. Since this is a .cpp this is acceptable, but \n// here is a rule of thumb I found useful that lets me avoid namespace std\n// even in .cpp files:\n// - Write \"using std::xxx\" locally if you are using xxx more than three times.\n// - Write \"using std::xxx\" globally if many functions are using xxx.\n// - Write \"using namespace std\" locally if you are using 3 or more std:: functions more than three times.\n// - Write \"using namespace std\" globally if you are lazy :D\n\n// Reviewing your class design, I would like to stress some things:\n// You are using the space R^2 (two dimensions, real numbers).\n// I do not see this constraint in your problem definition above. Consider how you would expand this class\n// to multiple dimensions as well as the realm of complex numbers (for which the length and other functions is slightly\n// different).\n\n// You did not define any operator overloads for things such as addition, subtraction, etc.\n// Consider if it's worth implementing these functions, especially with vectors.\n\nclass Point {\npublic:\n // You could default-initialize the second ctor and remove the need for the first one.\n Point( float x = 0, float y = 0 ) \n : x_( x ), y_( y )\n { } // You do not need semicolons inside an empty function body.\n\n // C++ usually doesn't prefix getters with \"get\". Again, depends on the style guide and personal preference.\n float x( ) const \n { return x_; } // Getters do not mutate your members, make it const!\n\n float y( ) const \n { return y_; } \n\n void setX( float x ) { x_ = x; } // Parameters are usually lower-case in C++.\n void setY( float y ) { y_ = y; }\n\n // Personal preference, but give me a space between all those symbols! Otherwise it's hard to read.\n void print( ) const \n { } \n\nprivate:\n float x_; // Members are usually of the form m_X, m_x, or x_ to distinguish them from local or parameter variables.\n float y_;\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, Point const&amp; point)\n{\n os &lt;&lt; \"(\" &lt;&lt; point.x() &lt;&lt; \", \" &lt;&lt; point.y() &lt;&lt; \") \" &lt;&lt; std::endl;\n return os;\n}\n\nclass Line {\npublic:\n // Consider a default constructor. \n // We would then have, essentially, a line of length zero, or a point.\n Line( Point a = Point(), Point b = Point() ) \n : a_( a ), b_( b )\n { }\n\n // Why is this function outside the class body whereas all others are inside? \n // You are mutating mid, something a user of your library might not be aware of.\n // I recommend giving this function a return value of the midpoint instead.\n Point midpoint( ) const\n {\n return Point ((a_.x( ) + b_.x( )) / 2.0,\n (a_.y( ) + b_.y( )) / 2.0);\n }\n\n // Again, why have this function outside the class and not the others?\n float length( ) const\n {\n // Length of a line is of the form:\n // sqrt( (P2_x - P1_x)^2 + (P2_y - P1_y)^2 + ... + (P2_n - P1_n)^2 )\n // where n is the number of coordinates of the point.\n // I mention this because you are using only two dimensions, but many more are possible and used.\n\n // This will not work, think about arithmetic operators for your Point class.\n // return sqrt((a - b) * (a - b));\n\n // (P2_x - P1_x)^2 = (P2_x - P1_x) * (P2_x - P1_x)\n // Do not use pow in this case. We are using integers and pow() uses doubles or floats.\n\n // sqrt uses doubles or floats. Depending on the accuracy, you want to change the cast (and the program) to a double.\n return sqrt (static_cast&lt;float&gt;((b_.x() - a_.x()) * (b_.x() - a_.x()) + \n (b_.y() - a_.y()) * (b_.y() - a_.y())));\n }\n\n Point const&amp; a( ) const\n { return a_; }\n\n Point const&amp; b( ) const\n { return b_; }\n\nprivate:\n Point a_;\n Point b_;\n};\n\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, Line const&amp; line)\n{\n os &lt;&lt; line.a() &lt;&lt; line.b();\n return os;\n}\n\nclass Triangle {\npublic:\n // Triangle of size zero? :D\n Triangle( Line a = Line(), Line b = Line(), Line c = Line() ) \n : a_( a ), b_( b ), c_( c )\n { }\n\n // Since the area of a triangle is just called \"area\" in mathematics, \n // why not call the function the same?\n float area( ) {\n // We are not modifying mid or height past the initialization.\n // Might as well const it.\n // I also changed the ctor call for height, this prevents the \"most vexing parse\" problem\n // as well as me being able to align the \"=\" :3\n const Point mid = c_.midpoint();\n const Line height = Line( mid, a_.b( ) );\n\n return static_cast&lt;float&gt;(0.5 * c_.length( ) * height.length( ));\n }\n\n // You used accessors for Line and Point, but why not for Triangle?\n Line const&amp; a() const { return a_; }\n Line const&amp; b() const { return b_; }\n Line const&amp; c() const { return c_; }\n\nprivate:\n Line a_;\n Line b_;\n Line c_;\n};\n\n// Non-member non-friend for greatest encapsulation power :3\n// Using an operator&lt;&lt; allows us to not just write to console, but moar! D:\nstd::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, Triangle const&amp; triangle)\n{\n os &lt;&lt; \"Line A formed from points\\n\" &lt;&lt; triangle.a() \n &lt;&lt; \"Line B formed from points\\n\" &lt;&lt; triangle.b()\n &lt;&lt; \"Line C formed from points\\n\" &lt;&lt; triangle.c();\n\n return os;\n}\n\nint main( int argc, char *argv[ ] ) {\n srand( time( NULL ) );\n\n // Calculate area of 10 triangles;\n // For non-pod types (e.g. iterators), it is better to use post-increment (++i).\n // I like to use it even on POD types just so I'm in the habit of using post-increment.\n for( int i = 0; i &lt; 10; ++i ) {\n // Remember that this is a non-uniform distribution that gets worse as you\n // increase the range of the rand (unless you remove the modulo division, of course).\n // With such small numbers and for the intents of your program, this is negligible.\n Point p1( (rand( ) % 10) / 10.0,(rand( ) % 10) / 10.0 );\n Point p2( (rand( ) % 10) / 10.0,(rand( ) % 10) / 10.0 );\n Point p3( (rand( ) % 10) / 10.0,(rand( ) % 10) / 10.0 );\n\n Line l1( p1,p2 );\n Line l2( p2,p3 );\n Line l3( p3,p1 );\n\n Triangle t( l1,l2,l3 );\n std::cout &lt;&lt; t;\n\n std::cout &lt;&lt; \"Area = \" &lt;&lt; t.area( ) &lt;&lt; \"\\n\\n\";\n }\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T12:58:34.653", "Id": "3761", "ParentId": "3757", "Score": "5" } }, { "body": "<p><code>using namespace std;</code> is almost always a bad idea. Even in small programs I would avoid it.</p>\n\n<p>Your algorithm for <code>calc_area</code> is just plain wrong. The area of a triangle is half the length of a side multiplied by the perpendicular distance from the third vertex to the base line, <em>not</em> the distance from the vertex to the mid-point of the base. (Think of a triangle with vertices at (-1,0), (1,0) and (1, 1). The area of this triangle should be 1, not sqrt(2).)</p>\n\n<p>Reviewing your <code>Point</code> class, the default constructor doesn't initialized the member variables. This may be acceptable for performance reasons - for example - if you deliberately want to be able to create large arrays of uninitialized <code>Points</code> but it's often safer to explicitly initialize all class members in a constructor.</p>\n\n<p>Having both getters and setters for <code>x</code> and <code>y</code> effectively makes them public data members. The only functionality that <code>Point</code> has is <code>print</code> but this can be provided as a non-member function. Once you've done this your class provides no functionality that a simple <code>struct</code> doesn't. In addition, you can use aggregate initialization for a <code>struct</code> which can be useful.</p>\n\n<p>E.g.</p>\n\n<pre><code>struct Point\n{\n float x;\n float y;\n};\n\n// print functionality\nstd::ostream&amp; operator( std::ostream&amp; os, const Point&amp; point )\n{\n os &lt;&lt; \"(\" &lt;&lt; point.x &lt;&lt; \", \" &lt;&lt; point.y &lt;&lt; \") \" &lt;&lt; std::endl;\n}\n</code></pre>\n\n<p>This is a lot simpler, although you would have to change initializations.</p>\n\n<pre><code>// Point p( p1, p2 );\nPoint p = { p1, p2 };\n</code></pre>\n\n<p>One disadvantage is that you can't easily construct a temporary <code>Point</code> with explicit initial values. If you need to do this you could consider a helper function analogous to <code>std::make_pair</code>.</p>\n\n<p>E.g.</p>\n\n<pre><code>inline Point MakePoint( int px, int py )\n{\n Point p = { px, py };\n return p;\n}\n\nint main()\n{\n // FunctionTakingPoint( Point( 1, 2 ) );\n FunctionTakingPoint( MakePoint( 1, 2 ) );\n}\n</code></pre>\n\n<p>Being a trivial POD-struct, most compilers will have little difficulty in eliding most of the implied copies.</p>\n\n<p>There is some argument that <code>Line</code> deserves to be a class as you have no setters for its members, but given that it has little behaviour and the behaviour it has can be provided by free functions I would keep it as a POD <code>struct</code>. Clients can choose to make a <code>const</code> instance should they so choose.</p>\n\n<p>Also, I don't see any need to make <code>mid_point</code> take a reference to a <code>struct</code>. It can return by value for more readable code.</p>\n\n<pre><code>struct Line\n{\n Point a;\n Point b;\n};\n\nPoint mid_point( const Line&amp; line )\n{\n Point p = { ( line.a.x + line.b.x ) / 2.0,\n ( line.a.y + line.b.y ) / 2.0 };\n return p;\n}\n\ndouble length( const Line&amp; line )\n{\n double xdiff = line.b.x - line.a.x;\n double ydiff = line.b.y - line.a.y;\n return sqrt( xdiff * xdiff + ydiff * ydiff );\n}\n\nstd::ostream&amp; operator&lt;&lt;( std::ostream&amp; os, const Line&amp; line )\n{\n os &lt;&lt; line.a &lt;&lt; line.b;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T21:47:03.280", "Id": "5693", "Score": "0", "body": "A of triangle = 1/2*base*height, I understand my mistake about taking the midpoint because if the triangle is acute then the midpoint to the top point is not the perpendicular height. If you have a triangle that is not orthogonal to the coordinate axis how do you get the point co-linear to the base that would give you the height of the triangle?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T21:57:58.170", "Id": "5695", "Score": "0", "body": "It's simplest not to. The simplest formula for the area of the triangle when you have cartesian co-ordinates for its vertices is to use the half magnitude of the cross product of the vectors along two of its sides. In this case it is simply half of the absolute value of `(x2 - x1)(y3 - y1) - (y2 - y1)(x3 - x1)`. See here: http://en.wikipedia.org/wiki/Triangle#Using_vectors" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-11T17:59:27.447", "Id": "12090", "Score": "0", "body": "In the first bit of code, `operator(` should be `operator<<(`." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T14:29:44.897", "Id": "3764", "ParentId": "3757", "Score": "8" } }, { "body": "<p>A couple of points:</p>\n\n<pre><code>#include &lt;math.h&gt;\n#include &lt;time.h&gt;\n#include &lt;stdlib.h&gt;\n</code></pre>\n\n<p>There are C++ versions of these headers:</p>\n\n<pre><code>#include &lt;cmath&gt;\n#include &lt;ctime&gt;\n#include &lt;cstdlib&gt;\n</code></pre>\n\n<p>I know every beginners guide in the world says:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>Don't do it. If you want to import something specific use:</p>\n\n<pre><code>using std::cin;\nusing std::cout; // or whatever you to import.\n</code></pre>\n\n<p>If you are going to do this then try and scope the <code>using</code> to the closes scope that makes sense. But there is no real reason even to do this. Just prefix stuff with <code>std::</code>.</p>\n\n<pre><code>std::cout &lt;&lt; \"Print a line\\n\";\n</code></pre>\n\n<p>Don't break encapsulation with get/set</p>\n\n<pre><code>float getX( ) { return x; }\nfloat getY( ) { return y; }\nvoid setX( float X ) { x = X; }\nvoid setY( float Y ) { y = Y; }\n</code></pre>\n\n<p>This is just a bad idea. I know it looks like you are protecting encapsulation, but you are not. What you are actually doing is binding your implementation to an expectation of what it needs to provide. What you should be doing is providing methods that use the internal members (that's what encapsulation is about).</p>\n\n<p>Is a triangle really 3 lines?</p>\n\n<pre><code>Triangle( Line A,Line B,Line C ) : A( A ), B( B ), C( C ){ ;}\n</code></pre>\n\n<p>I think a triangle is really better represented as 3 points. What if A and B are parallel!<br>\nThis also makes several of the other methods easier to write. It seems like you be able to get the distance between two points by subtracting them or a distance method (thus you don't need to expose their internal representation with getX() and getY()).</p>\n\n<p>It's OK to write a print method. But you should proably also provide the output stream operator.</p>\n\n<pre><code>void print( ) { cout &lt;&lt; \"(\"&lt;&lt;x&lt;&lt;\", \"&lt;&lt;y&lt;&lt;\") \"&lt;&lt;endl; }\n</code></pre>\n\n<p>I would do this:</p>\n\n<pre><code>class Point\n{\n public:\n void print(std::ostream&amp; str) const // Notice the cost\n { \n str &lt;&lt; \"(\" &lt;&lt; x &lt;&lt; \", \" &lt;&lt; y &lt;&lt; \") \" &lt;&lt; std::endl;\n }\n};\nstd::ostream&amp; operator(std::ostream&amp; str, Point const&amp; data)\n{\n data.print(str);\n return str;\n}\n</code></pre>\n\n<p>PS. This is not correct:</p>\n\n<pre><code>float Triangle::calc_area( ) {\n Point mid;\n C.mid_point( mid );\n Line height( mid, A.getB( ) );\n return 0.5*C.length( )*height.length( );\n}\n</code></pre>\n\n<p>The height line must be perpendicular to the C-Line.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T22:47:58.530", "Id": "3766", "ParentId": "3757", "Score": "2" } } ]
{ "AcceptedAnswerId": "3764", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-31T08:03:52.740", "Id": "3757", "Score": "6", "Tags": [ "c++", "mathematics", "graph" ], "Title": "Compute random triplets of float pairs and average area of generated triangles" }
3757
<p>I'm writing a BitTorrent client. Part of the protocol is an exchange of length-prefixed messages between peers. The forms of these messages are described in the <a href="http://www.bittorrent.org/beps/bep_0003.html#all-non-keepalive-messages-start-with-a-single-byte-which-gives-their-type">official specification</a> and also in the <a href="http://wiki.theory.org/BitTorrentSpecification#Messages">unofficial specification</a> that is maintained by the community. This is my code for writing out this messages into a stream. I'm currently using C++11 as supported by GCC 4.6.</p> <p>I have a header file:</p> <pre><code>#ifndef MESSAGE_HPP #define MESSAGE_HPP #include &lt;ostream&gt; #include &lt;string&gt; #include &lt;type_traits&gt; namespace greed { // This type defines all the message types and the matching codes // It uses C++11's ability to define an enum's underlying type enum message_type : signed char { // this keep_alive as negative is a hack I'm not too happy with keep_alive = -1, choke = 0, unchoke = 1, interested = 2, not_interested = 3, have = 4, bitfield = 5, request = 6, piece = 7, cancel = 8 }; // There are three basic kinds of messages // These three basic templates are used in CRTP below // - messages with no payload: these contain only the length // and the type code template &lt;message_type Type&gt; struct no_payload_message { std::ostream&amp; put(std::ostream&amp; os) const; }; // - messages with a fixed-length payload: these contain the length, // the type code, and a payload of a fixed-length, that is // determined by the message type. template &lt;typename Message&gt; struct fixed_payload_message { std::ostream&amp; put(std::ostream&amp; os) const; }; // - messages with a payload of variable length: these contain the length, // the type code, and the payload. template &lt;typename Message&gt; struct variable_payload_message { std::ostream&amp; put(std::ostream&amp; os) const; }; // A template definition for messages, templated on the message type. template &lt;message_type Type&gt; struct message {}; // A specialization for keep-alives, which are special messages that // consist of a single zero byte. template&lt;&gt; struct message&lt;keep_alive&gt; { public: std::ostream&amp; put(std::ostream&amp; os) const; }; // Specializations for the no-payload messages types // The only difference between these is the message type. template &lt;&gt; struct message&lt;choke&gt; : public no_payload_message&lt;choke&gt; {}; template &lt;&gt; struct message&lt;unchoke&gt; : public no_payload_message&lt;unchoke&gt; {}; template &lt;&gt; struct message&lt;interested&gt; : public no_payload_message&lt;interested&gt; {}; template &lt;&gt; struct message&lt;not_interested&gt; : public no_payload_message&lt;not_interested&gt; {}; // The specializations for fixed-length payload messages contain: // - appropriate constructors // - a type that defines the format of the message (data_type) // - a function that returns the data (data) // These are used by the fixed_payload_message template template&lt;&gt; struct message&lt;have&gt; : public fixed_payload_message&lt;message&lt;have&gt;&gt; { public: message() = delete; explicit message(unsigned index); struct data_type; data_type data() const; private: unsigned index; }; // The specializations for variable-length payload messages contain: // - appropriate constructors // - a type that defines the format of the message (data_type) // - a function that returns the variable payload (payload) // - a function that writes out the parts of the message that are not variable (init) // These are used by the variable_payload_message template template&lt;&gt; struct message&lt;bitfield&gt; : public variable_payload_message&lt;message&lt;bitfield&gt;&gt; { public: message() = delete; explicit message(std::string bits); const std::string payload() const; struct data_type; void init(char* ptr) const; private: std::string bits; }; template&lt;&gt; struct message&lt;request&gt; : public fixed_payload_message&lt;message&lt;request&gt;&gt; { public: message() = delete; message(unsigned index, unsigned begin, unsigned length); struct data_type; data_type data() const; private: unsigned index; unsigned begin; unsigned length; }; template&lt;&gt; struct message&lt;piece&gt; : public variable_payload_message&lt;message&lt;piece&gt;&gt; { public: static const message_type id = piece; message() = delete; message(unsigned index, unsigned begin, std::string block); const std::string payload() const; struct data_type; void init(char* ptr) const; private: unsigned index; unsigned begin; std::string block; }; template&lt;&gt; struct message&lt;cancel&gt; : public fixed_payload_message&lt;message&lt;cancel&gt;&gt; { public: message() = delete; message(unsigned index, unsigned begin, unsigned length); struct data_type; data_type data() const; private: unsigned index; unsigned begin; unsigned length; }; // A simple type trait that determines if a type is a message type template &lt;typename NonMesssage&gt; struct is_message : std::false_type {}; template &lt;message_type Type&gt; struct is_message&lt;message&lt;Type&gt;&gt; : std::true_type {}; // Implementation of operator&lt;&lt; for all message types // This requires the put member function template &lt;typename Message&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, typename std::enable_if&lt;is_message&lt;Message&gt;::value,const Message&amp;&gt;::type message); } #endif </code></pre> <p>And an implementation file:</p> <pre><code>#include "message.hpp" // this header contains the hton function #include "util.hpp" #include &lt;memory&gt; #include &lt;new&gt; namespace greed { // simple implementation of operator&lt;&lt; for messages template &lt;typename Message&gt; std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const Message&amp; message) { return message.put(os); } // implementation of no-payload message base class template &lt;message_type Type&gt; std::ostream&amp; no_payload_message&lt;Type&gt;::put(std::ostream&amp; os) const { // make sure this struct is not padded or anything // this is a gcc attribute, I'll change this when there is // support for the C++11 attribute alignas struct __attribute__ ((packed)) data_type { unsigned len; message_type type; }; // hton is a function that converts from host-endianness to network-endianness data_type buffer = { hton(sizeof(data_type)-sizeof(data_type::len)), Type }; // lay out the length and the message type return os.write(reinterpret_cast&lt;char*&gt;(&amp;buffer), sizeof(data_type)); // write it } // implementation of fixed-length payload message base class template &lt;typename Message&gt; std::ostream&amp; fixed_payload_message&lt;Message&gt;::put(std::ostream&amp; os) const { auto buffer = static_cast&lt;const Message*&gt;(this)-&gt;data(); // get the data from the derived class return os.write(reinterpret_cast&lt;char*&gt;(&amp;buffer), sizeof(buffer)); // write it } // implementation of variable-length payload message base class template &lt;typename Message&gt; std::ostream&amp; variable_payload_message&lt;Message&gt;::put(std::ostream&amp; os) const { typedef typename Message::data_type header_type; auto m = static_cast&lt;const Message*&gt;(this); const auto payload = m-&gt;payload(); // get the payload const auto data_type_size = sizeof(header_type)+payload.size(); // get the total size std::unique_ptr&lt;char[]&gt; mem(new char[data_type_size]); // allocate a buffer for it m-&gt;init(mem.get()); // write out the fixed-length portion std::copy(payload.begin(), payload.end(), mem.get()+sizeof(header_type)); // copy the payload to the buffer return os.write(mem.get(), data_type_size); // write it } std::ostream&amp; message&lt;keep_alive&gt;::put(std::ostream&amp; os) const { return os.put(0); // keep-alives are just a simple zero byte } message&lt;have&gt;::message(unsigned index) : index(index) {} struct __attribute__ ((packed)) message&lt;have&gt;::data_type{ unsigned len; message_type type; unsigned index; }; // have message data message&lt;have&gt;::data_type message&lt;have&gt;::data() const { return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), have, hton(index) }; } message&lt;bitfield&gt;::message(std::string bits) : bits(bits) {} struct __attribute__ ((packed)) message&lt;bitfield&gt;::data_type { unsigned len; message_type type; }; // bitfield message payload const std::string message&lt;bitfield&gt;::payload() const { return bits; } void message&lt;bitfield&gt;::init(char* ptr) const { // construct a new message&lt;bitfield&gt;::data_type in place new(ptr) data_type{ hton(sizeof(data_type)-sizeof(data_type::len)+bits.size()), bitfield }; } message&lt;request&gt;::message(unsigned index, unsigned begin, unsigned length) : index(index), begin(begin), length(length) {} struct __attribute__ ((packed)) message&lt;request&gt;::data_type { unsigned len; message_type type; unsigned index; unsigned begin; unsigned length; }; // request message data message&lt;request&gt;::data_type message&lt;request&gt;::data() const { return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), request, hton(index), hton(begin), hton(length) }; } message&lt;piece&gt;::message(unsigned index, unsigned begin, std::string block) : index(index), begin(begin), block(block) {} struct __attribute__ ((packed)) message&lt;piece&gt;::data_type { unsigned len; message_type type; unsigned index; unsigned begin; }; const std::string message&lt;piece&gt;::payload() const { return block; } void message&lt;piece&gt;::init(void* ptr) const { // construct a new message&lt;piece&gt;::data_type in place new(ptr) data_type{ hton(sizeof(data_type)-sizeof(data_type::len)+block.size()), piece, index, begin }; } message&lt;cancel&gt;::message(unsigned index, unsigned begin, unsigned length) : index(index), begin(begin), length(length) {} struct __attribute__ ((packed)) message&lt;cancel&gt;::data_type { unsigned len; message_type type; unsigned index; unsigned begin; unsigned length; }; // cancel message data message&lt;cancel&gt;::data_type message&lt;cancel&gt;::data() const { return data_type{ hton(sizeof(data_type)-sizeof(data_type::len)), cancel, hton(index), hton(begin), hton(length) }; } // explicit template instantiations for all message types template struct message&lt;keep_alive&gt;; template struct message&lt;choke&gt;; template struct message&lt;unchoke&gt;; template struct message&lt;interested&gt;; template struct message&lt;not_interested&gt;; template struct message&lt;have&gt;; template struct message&lt;bitfield&gt;; template struct message&lt;request&gt;; template struct message&lt;piece&gt;; template struct message&lt;cancel&gt;; template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;keep_alive&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;choke&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;unchoke&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;interested&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;not_interested&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;have&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;bitfield&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;request&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;piece&gt;&amp; message); template std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const message&lt;cancel&gt;&amp; message); } </code></pre> <p>I'm a bit unsure about how I dealt with the variable-length messages, especially the usage of placement new, without calling the destructor.</p> <p>So, opinions?</p>
[]
[ { "body": "<p>Can't really complain about most of it.</p>\n\n<p>The only thing I dislike is the abuse of auto:</p>\n\n<pre><code> auto m = static_cast&lt;const Message*&gt;(this);\n const auto payload = m-&gt;payload(); // get the payload\n const auto data_type_size = sizeof(header_type)+payload.size(); // get the total size\n</code></pre>\n\n<p>You know what the types are so why not be specific (personally I think that will make the code easier to read). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T13:33:00.870", "Id": "5721", "Score": "0", "body": "If that's an abuse of the auto keyword, whats the intended use?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T14:44:50.077", "Id": "5722", "Score": "0", "body": "Its intend use is places where the type is a really complex template and you dont actually need or want to know. Like iterators or functrs retrieved from complex template objects: `for(auto it = plop.being(); it != plop.end(); ++it){}` Here all you need to know is that it is an iterator the exact type is not important. Above the exact type is 1) important 2) Easy to deduce. `m` is a message and being used as one. `data_type_size` is a `size_t`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T14:49:37.000", "Id": "5723", "Score": "2", "body": "I disagree that code sprinkled with types is easier to read. Type inference is a good thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T15:18:01.850", "Id": "5726", "Score": "1", "body": "@Cat: At this point me advice is just a personal opinion. Thats why I dislike rather than saying there is anything wrong. But please chime into this conversation: http://stackoverflow.com/q/6900459/14065" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T15:37:27.830", "Id": "5727", "Score": "0", "body": "@Martin The intent of templates is to allow generic containers. So please don’t abuse templates for metaprogramming." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T05:17:11.437", "Id": "3781", "ParentId": "3770", "Score": "0" } }, { "body": "<pre><code> enum message_type : signed char\n</code></pre>\n\n<p>Do you have a specific reason (e.g. protocol requirements?) that this be signed? Bit-level stuff usually involves unsigned types. The protocol specs also explicity mention the size of the message type field: a single byte. So I recommend <code>std::uint8_t</code> here.</p>\n\n<pre><code> // A template definition for messages, templated on the message type.\n template &lt;message_type Type&gt;\n struct message {};\n</code></pre>\n\n<p>If only the specializations are meant to be used (I couldn't tell from looking at your code), I usually 'forbid' the base template to catch mistakes early. Errors about how <code>message&lt;...&gt;</code> has no <code>put</code> member are confusing and not necessarily near the code that instantiated the template. The simplest way to do it is to leave the template undefined but lately I've been using a trick: <code>static_assert( dependent_false&lt;Type&gt;::value, \"Only specializations should be used\" );</code>, where <code>dependent_false&lt;T&gt;::value</code> is always <code>false</code> but won't trigger the assert until instantiation (whereas <code>static_assert( false, ... )</code> always triggers and won't let you compile, ever.)</p>\n\n<pre><code> template&lt;&gt;\n struct message&lt;bitfield&gt; : public variable_payload_message&lt;message&lt;bitfield&gt;&gt;\n {\n public:\n message() = delete;\n explicit message(std::string bits);\n\n const std::string payload() const;\n</code></pre>\n\n<p>I'd prefer returning <code>std::string</code> here. (Ditto for <code>message&lt;piege&gt;::payload</code>.)</p>\n\n<pre><code> // A simple type trait that determines if a type is a message type\n template &lt;typename NonMesssage&gt;\n struct is_message : std::false_type {};\n template &lt;message_type Type&gt;\n struct is_message&lt;message&lt;Type&gt;&gt; : std::true_type {};\n</code></pre>\n\n<p>Lately I've been making my traits more convenient to use by adding forwarding specializations: <code>template&lt;typename T&gt; struct is_message&lt;T&amp;&gt;: is_message&lt;T&gt; {};</code>, and another one for <code>const</code>. They help with perfect forwarding because if you have e.g. <code>template&lt;typename M&gt; void perfectly_forwarded(M&amp;&amp;);</code> then <code>M</code> might be <code>T const&amp;</code> for some <code>T</code>. Since you're not doing that in your code I don't think you need it -- just a head's up.</p>\n\n<pre><code> // Implementation of operator&lt;&lt; for all message types\n // This requires the put member function\n template &lt;typename Message&gt;\n std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, typename std::enable_if&lt;is_message&lt;Message&gt;::value,const Message&amp;&gt;::type message);\n</code></pre>\n\n<p>Deduction can't work here. C++03-style code uses <code>enable_if</code> at the return type, or when there is no return type (e.g. constructors) as a default argument. Maybe you tried to 'collapse' the default argument with the actual, interesting parameter, but you can't do that. C++0x-style code can put <code>enable_if</code> as a defaulted template parameters but that's moot since you really want (credit to CatPlusPlus):</p>\n\n<pre><code>template&lt;message_type M&gt;\nstd::ostream&amp;\noperator&lt;&lt;(std::ostream&amp; os, message&lt;M&gt; const&amp; m);\n</code></pre>\n\n<hr>\n\n<pre><code> // simple implementation of operator&lt;&lt; for messages\n</code></pre>\n\n<p>Change definition to match previous declaration.</p>\n\n<pre><code> // implementation of no-payload message base class\n template &lt;message_type Type&gt;\n std::ostream&amp; no_payload_message&lt;Type&gt;::put(std::ostream&amp; os) const {\n // make sure this struct is not padded or anything\n // this is a gcc attribute, I'll change this when there is\n // support for the C++11 attribute alignas\n struct __attribute__ ((packed)) data_type {\n unsigned len;\n message_type type;\n };\n // hton is a function that converts from host-endianness to network-endianness\n data_type buffer = { hton(sizeof(data_type)-sizeof(data_type::len)), Type }; // lay out the length and the message type\n return os.write(static_cast&lt;char*&gt;(&amp;buffer), sizeof(data_type)); // write it\n }\n</code></pre>\n\n<p>Again, following protocol specs, I'd make <code>len</code> a <code>std::uint32_t</code>. The unofficial spec use <code>1</code> as the length, I'm not sure what you're computing here. Minor note: I always write <code>os.write(static_cast&lt;char*&gt;(&amp;buffer), sizeof buffer)</code> to future-proof (unlikely to matter here but still).</p>\n\n<pre><code> // implementation of fixed-length payload message base class\n template &lt;typename Message&gt;\n std::ostream&amp; fixed_payload_message&lt;Message&gt;::put(std::ostream&amp; os) const {\n auto buffer = static_cast&lt;const Message*&gt;(this)-&gt;data(); // get the data from the derived class\n return os.write(static_cast&lt;char*&gt;(&amp;buffer), sizeof(buffer)); // write it\n }\n</code></pre>\n\n<p>And in fact here you do take the size of the object!</p>\n\n<pre><code> // implementation of variable-length payload message base class\n template &lt;typename Message&gt;\n std::ostream&amp; variable_payload_message&lt;Message&gt;::put(std::ostream&amp; os) const {\n typedef typename Message::data_type header_type;\n\n auto m = static_cast&lt;const Message*&gt;(this);\n const auto payload = m-&gt;payload(); // get the payload\n const auto data_type_size = sizeof(header_type)+payload.size(); // get the total size\n std::unique_ptr&lt;char[]&gt; mem(new char[data_type_size]); // allocate a buffer for it\n m-&gt;init(mem.get()); // write out the fixed-length portion\n std::copy(payload.begin(), payload.end(), mem.get()+sizeof(header_type)); // copy the payload to the buffer\n return os.write(mem.get(), data_type_size); // write it\n }\n</code></pre>\n\n<p>I don't see the need to copy the final message into a buffer. Why not use two calls to <code>ostream::write</code>? You could replace the <code>init</code> members (which you already dislike) with a <code>data</code> member like the fixed-length messages.</p>\n\n<pre><code>// Lots of definitions/instantiations\n</code></pre>\n\n<p>Again, I didn't check conformance to the specs. I also already mentioned to you how most of the explicit instantiations aren't needed.</p>\n\n<p>I'd also write <code>sizeof field0 + sizeof field1 + ...</code> for computing the various sizes that you need rather than subtracting from the total size. I'd do that for clarity and I don't think it's a correctness issue however.</p>\n\n<hr>\n\n<p>Final remarks on the general design:</p>\n\n<p>I think you're somewhat abusing specializations here: there's is no need (IMO) for a <code>message</code> catch-all template since the three kinds of messages are not similar in use. This really shows I think with the constructors that aren't compatible: you can't write a generic <code>message&lt;M&gt; m(arguments go here);</code>. Personally I'd have used overloaded function templates to return those three types.</p>\n\n<p>Also I personally typically use <code>std::vector&lt;unsigned char&gt;</code> for binary stuff rather than <code>std::string</code> but I don't think that really matters (plus you may have a use for some <code>std::string</code>-specific stuff that is not in the code you presented).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T12:55:20.157", "Id": "3786", "ParentId": "3770", "Score": "6" } } ]
{ "AcceptedAnswerId": "3786", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T01:25:47.383", "Id": "3770", "Score": "8", "Tags": [ "c++", "c++11", "memory-management", "networking" ], "Title": "BitTorrent peer protocol messages" }
3770
<p>I found the following two types of exception-handling in Business Logic Layer. </p> <p><a href="http://rads.stackoverflow.com/amzn/click/0470396865" rel="nofollow noreferrer">ASP.NET 3.5 Enterprise Application Development</a> uses a similar method like the first one (I read it few years ago).</p> <p>I also found <a href="https://stackoverflow.com/questions/523875/where-to-put-try-catch">this</a> on Stack Overflow, but it doesn't answer my question.</p> <p>I'm wondering which one is better design and efficiency.</p> <p><strong>Method 1 - in Business Logic Layer</strong></p> <pre><code>private int InsertUser(string firstname, string lastname, ref List&lt;string&gt; errors) { if (!string.IsNullOrEmpty(firstname)) errors.Add("First name is required."); if (!string.IsNullOrEmpty(lastname)) errors.Add("Last name is required."); if (errors.Count &gt; 0) return -1; int userId = -1; try { // Insert user and return userId } catch (Exception ex) { // Log error to database errors.Add("Error occurs. Please contact customer service."); } return userId; } </code></pre> <p><strong>Method 2 - in Business Logic Layer</strong></p> <pre><code>private int InsertUser(string firstname, string lastname) { if (!string.IsNullOrEmpty(firstname)) throw new ArgumentNullException(firstname); if (!string.IsNullOrEmpty(lastname)) throw new ArgumentNullException(lastname); int userId = -1; // Insert user and return userId. Let user handle the exception in UI. return userId; } </code></pre> <p>The disadvantage of Method 2 is that the UI has to filter out what to display/not display the error depending on the exception. For instance, you might not want to display a <code>System.Data.Entity</code> exception to the user.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T20:32:57.117", "Id": "5703", "Score": "1", "body": "As an aside, you don't have to pass a `List<string>` as a `ref` argument. `List<T>`, like all classes, is a reference type, so changes made to `errors` by `InsertUser()` will always be reflected in the original object (*assignment* to `errors` would not be reflected without `ref`)." } ]
[ { "body": "<p>My approach is to catch and log/report errors at the highest point in the call stack possible, unless I have a way of actually <em>handling</em> them (ie I can take steps to allow the app to continue processing)in which case I'll add a try/catch at the appropriate point. </p>\n\n<p>Since it looks like all you are going to do with the error is log it, I'd use Method 2 in this particular instance.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:36:22.110", "Id": "5704", "Score": "0", "body": "Thank you for your comment. Now, I lean more towards method 2 - UI handling exceptions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:20:03.510", "Id": "3774", "ParentId": "3773", "Score": "3" } }, { "body": "<p>It can be interesting to convey more information about the error to the end user, but it doesn't mean the UI layer has to be the only one to handle the exception.</p>\n\n<p>You can both log the error into your database from the business layer and relay it to the UI layer if you rethrow the exception:</p>\n\n<pre><code>try {\n // Insert user and return userId...\n} catch (Exception ex) {\n // Log error to database...\n throw; // Relay error to UI layer.\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:29:35.743", "Id": "5705", "Score": "0", "body": "Thank you for the comment. Will there be multiple entries in database if each layer logs the same error to DB? In addition, we do not want to display somethign like System.Data.Entity to user. Therefore, UI have to somehow figure what to display/not display the error." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:32:19.470", "Id": "5706", "Score": "1", "body": "@Win, I was under the impression that the UI layer could not log anything to the database, mostly because it was using the business layer as an abstraction instead of hitting the DB directly. Was I wrong?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:42:43.283", "Id": "5707", "Score": "0", "body": "@Frédéric - It is also true. My main concern is that UI have to somehow filter what to display/not display the error. I do not want to display to user something like System.Data.Entity." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:52:51.020", "Id": "5708", "Score": "4", "body": "@Win, you do not seem comfortable with the UI layer deciding what to display to the end user. *Why?* The *entire purpose* of the UI layer is to query the business layer and format that information in a appropriate manner for the end user. The business layer can indeed do that job and pass, say, prerendered markup to the UI layer, but why would it do so? After all, its entire purpose it to abstract the data source *in a UI-independent way*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:59:28.997", "Id": "5709", "Score": "0", "body": "@Frédéric - Good point! I'll definitely keep in mind that. Thank you!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:20:54.700", "Id": "3775", "ParentId": "3773", "Score": "9" } }, { "body": "<p>It can be more work for someone using method 1 to catch the errors thrown by null arguments. Also, if they can't see your code then it would be a downright pain in the ass. Other than that, it is your choice. Typically, people just put stuff into a try catch and expect the lib to throw exceptions. I don't recommend having two ways of reporting errors.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:21:05.443", "Id": "3776", "ParentId": "3773", "Score": "0" } }, { "body": "<p>I have heard strong arguments that it should be handled in both, because the business layer needs to ensure the integrity of the data being stored. In particular, if the business layer is being used from multiple front end applications, then it is important that the errors are handled within the buisness layer so that you can be certain of integrity wherever the data comes from.</p>\n\n<p>Additionally, they need to be handled in the UI, becasue the user needs as much information as you can provide ( in an appriate way ) about why data is wrong. It is important that I as the user am told that the data I have entered is wrong and why - it may be invalid data, or duplicate, and I need to know which.</p>\n\n<p>Having said that, I don't really agree with this view. In particular, if you have a single UI working with a buisness layer, I would be tempted to put the validation in the UI, to provide the best feedback to the user about what has gone wrong. This might involve picking up exceptions from the business layer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:29:39.683", "Id": "3777", "ParentId": "3773", "Score": "0" } }, { "body": "<p>Event though try/catch is slower I would prefer it for following reasons.</p>\n\n<ul>\n<li>Using if/List method requires every method that call this\nmethod check for errors, not only that but it requires everybody\nremember to check for errors, and if somebody forget, then they will\nhave error </li>\n<li>You can have Application level exception handler that will\nrecord all exceptions to the repository storage </li>\n<li>You can catch all exceptions in one place (WCF service, Application) so less code is\nrequired for dealing with individual error. </li>\n<li>Much easier on the caller side to implement call just wrap call in try/catch. More readable code.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:31:08.880", "Id": "3778", "ParentId": "3773", "Score": "1" } }, { "body": "<p>You should separate two different tasks: Business rules validation and error handling.\nIn general, business rules validations should be processed with Method 1. If you are working on a new project, you even may create a special set of classes for business rules validation. Then your example can be modified like this:</p>\n\n<pre><code>class User\n{\n [Required]\n public string FirstName { get; set; }\n\n [Required]\n public string LastName { get; set; }\n}\n\nstatic class Validator\n{\n public static List&lt;string&gt; Validate(object objectToValidate)\n {\n List&lt;string&gt; result = new List&lt;string&gt;();\n //Get all properties with \"Required\" attribute\n //For each property\n //If this property is empty\n //Add to result\n //Return result\n }\n}\n</code></pre>\n\n<p>Then, your UI code will be like:</p>\n\n<pre><code>var validationErrors = Validator.Validate(user);\nif (validationErrors.Count == 0)\n{\n UsersService.Insert(user); \n}\nelse\n{\n private DisplayErrors(validationErrors );\n}\n</code></pre>\n\n<p>And UsersService.Insert code:</p>\n\n<pre><code>var validationErrors = Validator.Validate(user);\nif (validationErrors.Count == 0)\n{\n Repository.Insert(user); \n}\nelse\n{\n throw new Exception(\"Some details about validation errors.\");\n}\n</code></pre>\n\n<p>Of course, it is a very simplified example and there are hundreds of variants, but the idea is to separate the validation and the error handling. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T16:02:28.173", "Id": "5755", "Score": "0", "body": "Interesting approach! Thank you for your comment" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T12:03:59.277", "Id": "3785", "ParentId": "3773", "Score": "3" } } ]
{ "AcceptedAnswerId": "3775", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T19:14:57.720", "Id": "3773", "Score": "8", "Tags": [ "c#", ".net", "comparative-review", "error-handling", "asp.net" ], "Title": "Place try/catch in business logic or user interface" }
3773
<p>I guess I might use delegates. But I'm not certain if I can apply for it. </p> <p>Sorry if the code is a mess. I'm a beginner and am still learning. For that reason, I need a little of help to improve this code. It's not finished.</p> <p>I'm creating a Math quiz system. And there are many questions as you will be able to see in it, they're so different and I have a difficult moment to create the classes.</p> <pre><code> private int[] Generate_Fraction(int li1, int ls1, int li2, int ls2) { int numerator = randomizer.Next(li1, ls1); int denominator = randomizer.Next(li2, ls2); int[] fraction = new int[2]; fraction[0] = numerator; fraction[1] = denominator; return fraction; } // Decimals private double[] GeneratePattern5(double[][] limits) { double[] decimals = new double[limits.Length]; for (int i = 0; i &lt; limits.Length; i++) { bool flag; double decTemp; do { flag = false; decTemp = GetDoubleBetween(limits[i][0], limits[i][1], (int)limits[i][2]); if (Exists(decimals, decTemp, i)) { flag = true; } } while (flag); decimals[i] = decTemp; } return decimals; } // Fractions like: 6/60 private int[][] GeneratePattern7(int[][] arrayLimits) { int[][] fractions = new int[arrayLimits.Length][]; for (int i = 0; i &lt; arrayLimits.Length; i++) { bool flag; int[] fracTemp = new int[2]; do { flag = false; fracTemp = Generate_Fraction(arrayLimits[i][0], arrayLimits[i][1], arrayLimits[i][2], arrayLimits[i][3]); fracTemp[1] *= fracTemp[0]; if (Exists(fractions, fracTemp, i)) { flag = true; } } while (flag); fractions[i] = fracTemp; } return fractions; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:13:37.660", "Id": "5710", "Score": "3", "body": "I think you mean generics, not delegates?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:14:07.037", "Id": "5711", "Score": "1", "body": "Can you be more specific, which part of the code do you think is verbose?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:16:07.770", "Id": "5712", "Score": "0", "body": "The return types and methods of generating the values differ greatly, so I don't see any obvious way to do it. What do you think is wrong with the way you have it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:19:05.660", "Id": "5713", "Score": "0", "body": "Well, that's an example code from my solution. I've got to generate many patterns, if you see the subroutines GeneratePattern5 and GeneratePattern7, they're doing the same thing, only verify if the data exists in the list.\n\nDo you get me?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:23:55.867", "Id": "5714", "Score": "0", "body": "Well, 7 is a lucky number. How the number of toes on your foot figures into this is pretty unguessable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:28:12.197", "Id": "5715", "Score": "0", "body": "Oscar, if you post your patterns functions again and ask how to use generics and delegates to make a single function from the two, I will post an answer with code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T21:13:24.573", "Id": "5737", "Score": "0", "body": "There's a lot of issues with your code. Don't use arrays to hold different data. Create a type for that or use a [`Tuple`](http://msdn.microsoft.com/en-us/library/system.tuple.aspx). What does `GetDoubleBetween()` and `Exists()` methods do? What are the arguments for? You don't provide those implementations and the arguments themselves tells us nothing about what they _could_ be (made worse by the use of arrays). We can make some guesses but they'll only be guesses, you should make it very clear what they are and what they do." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T21:25:07.747", "Id": "5742", "Score": "0", "body": "Anyway, I uploaded the code below. I know that there's a lot of issue Jeff. Do you think I should use that data structure?\n\nPlease read the lastest post." } ]
[ { "body": "<p>You can remove duplication from this code. There are a couple of ways to do this but as a result you'll get really complicated code. I think you should leave it as it is now. There are situations when it's better to have some duplication than to have complicated code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T10:54:08.630", "Id": "3784", "ParentId": "3780", "Score": "0" } }, { "body": "<p>Unless I'm missing something, you can move the Exists inside the condition and remove the flag variable. This will change the loop to...</p>\n\n<pre><code> double decTemp;\n\n do\n {\n decTemp = GetDoubleBetween(limits[i][0], limits[i][1], (int)limits[i][2]);\n } while (Exists(decimals, decTemp, i));\n</code></pre>\n\n<p>I believe that this is more semantically in line with what you are trying to accomplish. You could do the same thing inside the GeneratePattern7 method as well. Doing so will reduce a lot of clutter.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T15:35:31.213", "Id": "3788", "ParentId": "3780", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-07-29T21:09:37.860", "Id": "3780", "Score": "-2", "Tags": [ "c#", "beginner", "wpf" ], "Title": "Can I improve this code using delegates?" }
3780
<p>I'm just looking for more feedback on style/approach regarding this small problem. Also, if you have tips to make it more readable or C++-like, please let me know.</p> <p>Also, why is the problem asking for the sum and mean of each name and all names, while the sum of a single element is itself? Am I missing anything in terms of answering the question?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;map&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; /******************************************************************** * Read a sequence of possibly whitespace-separated (name,value) * pairs, where the name is a single whitespace-separated word and * the value is an integer or floating-point value. Compute and print * the sum and mean for each name and the sum and mean for all names * ******************************************************************/ using namespace std; std::multimap&lt;string,float&gt; _map; istream&amp; operator&gt;&gt;(istream&amp; stream, pair&lt;string,float&gt; &amp;in ) { return stream &gt;&gt; in.first &gt;&gt; in.second; } ostream&amp; operator&lt;&lt;(ostream&amp; stream, pair&lt;string,float&gt; &amp;out ) { return stream &lt;&lt; "(" &lt;&lt; out.first &lt;&lt; ", " &lt;&lt; out.second &lt;&lt; ")" &lt;&lt; endl; } int main( int argc, char *argv[ ] ) { istream *is = &amp;cin; do { pair&lt;string,float&gt; input; (*is) &gt;&gt; input; _map.insert(input); } while( is-&gt;peek( ) != EOF ); ostream *os = &amp;cout; multimap&lt;string,float&gt;::iterator mit = _map.begin( ); float sum = 0.0; while( mit != _map.end( ) ) { pair&lt;string,float&gt; p_pair = (*mit); (*os) &lt;&lt; p_pair; sum+=p_pair.second; mit++; } float mean = static_cast&lt;float&gt;( sum/_map.size( ) ); (*os) &lt;&lt; "Sum: " &lt;&lt; sum &lt;&lt; " Mean: " &lt;&lt; mean &lt;&lt; endl; } </code></pre>
[]
[ { "body": "<p>Comments:</p>\n\n<p>At the file scope all words beginning with underscore are reserved.<br>\nSee: <a href=\"https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797\">https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier/228797#228797</a></p>\n\n<pre><code>std::multimap&lt;string,float&gt; _map;\n</code></pre>\n\n<p>The aexct rules are a pain to remember (I had to go and check to make sure it was reserved). So I never prefix an identifier with '_'.</p>\n\n<p>I would not define stream operators for standard types.</p>\n\n<pre><code>istream&amp; operator&gt;&gt;(istream&amp; stream, pair&lt;string,float&gt; &amp;in ) \nostream&amp; operator&lt;&lt;(ostream&amp; stream, pair&lt;string,float&gt; &amp;out )\n</code></pre>\n\n<p>The trouble with doing this is that you may (in larger projects) clash with other people doing the same or with standard operators. (I though this would already work for std::pair without any work (obviously I was wrong)) I would only ever write stream operators fro my own types.</p>\n\n<p>References are your friend:</p>\n\n<pre><code>istream *is = &amp;cin;\n</code></pre>\n\n<p>Why take the address of a stream. Create a reference:</p>\n\n<pre><code>istream&amp; is = &amp;cin;\n</code></pre>\n\n<p>This is almost certainly wrong:</p>\n\n<pre><code> (*is) &gt;&gt; input;\n _map.insert(input);\n</code></pre>\n\n<p>What happens if the input operator fails?</p>\n\n<pre><code> while(is &gt;&gt; input)\n {\n // Do until the input fails.\n }\n</code></pre>\n\n<p>So rewriting your loop:</p>\n\n<pre><code>pair&lt;string,float&gt; input;\nwhile(is &gt;&gt; input)\n{\n // Is not the whole point that a name may appear multiple times.\n // Otherwise why compute the sum and average for each name\n // Thus you need to increment the count.\n myMap[input.first] += input.second;\n}\n</code></pre>\n\n<p>Not a big deal with a small object but I would get in the habit of using references.</p>\n\n<pre><code>pair&lt;string,float&gt; p_pair = (*mit); // This makes a copy.\n\npair&lt;string,float&gt; const&amp; p_pair = (*mit); // This is an alias to the object.\n</code></pre>\n\n<p>Here is what I would do:</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;memory&gt;\n#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n\n// Simple formatter used to \n// Print the data in a particular way. This formatter is tied to the particular storage format.\nstruct OutputFormater\n{\n std::map&lt;std::string, std::pair&lt;int, int&gt; &gt;::value_type const&amp; data;\n\n OutputFormater(std::map&lt;std::string, std::pair&lt;int, int&gt; &gt;::value_type const&amp; d)\n : data(d)\n {}\n\n friend std::ostream&amp; operator&lt;&lt;(std::ostream&amp; stream, OutputFormater const&amp; value)\n {\n std::string const&amp; name = value.data.first;\n int const&amp; count = value.data.second.first;\n int const&amp; sum = value.data.second.second;\n\n return stream &lt;&lt; name &lt;&lt; \": \" &lt;&lt; sum &lt;&lt; \": \" &lt;&lt; (sum/count) &lt;&lt; \" \";\n }\n};\n</code></pre>\n\n<p>This I hope makes main very east to read.</p>\n\n<pre><code>int main()\n{\n std::map&lt;std::string, std::pair&lt;int, int&gt; &gt; data;\n std::string name;\n int count;\n\n int totalCount = 0;\n int totalSum = 0;\n\n // Read in the data\n while(std::cin &gt;&gt; name &gt;&gt; count)\n {\n totalCount++;\n totalSum += count;\n data[name].first++; // increment the count;\n data[name].second += count; // increment the sum of counts;\n }\n\n // Copy the container to a stream using a formatter.\n std::copy(data.begin(), data.end(), std::ostream_iterator&lt;OutputFormater&gt;(std::cout, \"\\n\"));\n if (totalCount &gt; 0)\n {\n std::cout &lt;&lt; totalSum &lt;&lt; \": \" &lt;&lt; totalSum/totalCount &lt;&lt; \"\\n\";\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T19:37:15.250", "Id": "3792", "ParentId": "3783", "Score": "2" } }, { "body": "<p>Although it might be a bit longer (I haven't bothered to count lines), I think I'd prefer something on this order:</p>\n\n<pre><code>#include &lt;map&gt;\n#include &lt;string&gt;\n#include &lt;numeric&gt;\n#include &lt;iostream&gt;\n#include &lt;utility&gt;\n#include &lt;iterator&gt;\n#include &lt;algorithm&gt;\n\ntypedef std::multimap&lt;std::string, float&gt; vtype;\ntypedef std::pair&lt;std::string, float&gt; ptype;\n\nnamespace std { \nstd::istream &amp;operator&gt;&gt;(std::istream &amp;is, ptype &amp;v) { \n return is &gt;&gt; v.first &gt;&gt; v.second;\n}\n}\n\nfloat add_second(float a, vtype::value_type b) { \n return a + b.second;\n}\n\ntemplate &lt;class FwdIt&gt;\nfloat average(FwdIt start, FwdIt end) { \n float total = std::accumulate(start, end, 0.0f, add_second);\n return total / std::distance(start, end);\n}\n\nint main() {\n vtype values((std::istream_iterator&lt;ptype&gt;(std::cin)), \n std::istream_iterator&lt;ptype&gt;());\n\n vtype::iterator start, end;\n\n for (start = values.begin(); start != values.end(); start=end) {\n end = values.upper_bound(start-&gt;first);\n std::cout &lt;&lt; start-&gt;first &lt;&lt; \": \" &lt;&lt; average(start, end) &lt;&lt; \"\\n\"; \n }\n std::cout &lt;&lt; \"Overall: \" &lt;&lt; average(values.begin(), values.end()) &lt;&lt; \"\\n\";\n return 0;\n}\n</code></pre>\n\n<p>If you preferred, you could use an <code>std::vector</code> instead of an <code>std::multimap</code>. That would require some minor changes to the code (e.g., using <code>std::upper_bound</code> instead of <code>std::multimap::upper_bound</code>, and adding a call to <code>std::sort</code> after reading the data, but would otherwise be pretty similar. It would, however, probably be a bit more efficient (less CPU time and memory).</p>\n\n<p>While I suppose others might disagree, I prefer this for the simple reason that I find it easier to understand. We start by reading in all the data. We then find each run of identical keys, and compute the average for that run and print it out. When we reach the end of the data, we do the same for the overall average.</p>\n\n<p>In fairness, if you were working with <em>huge</em> amounts of data, this probably wouldn't be the best way do do things. It does spend more time walking through the same data than is strictly necessary. At the same time, unless you're going to rewrite the code to overlap reading the data with computing the result, it's unlikely to make much real difference -- almost regardless of how you do the computation, that I/O will almost certainly occupy the vast majority of the overall time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T21:17:06.333", "Id": "5738", "Score": "0", "body": "I went looking for this function on the sgi website, which is what I have been using for my on-line resource. But I can't seem to find this function \nvalues((std::istream_iterator<ptype>(std::cin)), std::istream_iterator<ptype>());\n\nWhat does it do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T21:23:20.900", "Id": "5741", "Score": "0", "body": "@Matthew: it's not really a function -- it's defining a `vector` named `values`, and initializing it from a pair of `iterator`s (in this case, `istream_iterator`s, which read data from an `istream` using `operator>>`). In case you care, the double parens around the first argument are to prevent the \"most vexing parse\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T21:30:38.273", "Id": "5744", "Score": "0", "body": "I guess I was just having a hard time reading the syntax. Typedefs really throw me for a loop sometimes. Being taught Java in school has done me much harm. Thanks for the clarification." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T01:43:12.957", "Id": "5747", "Score": "1", "body": "@Matthew: To paraphrase George Bernard Shaw, \"C++ and Java are two languages separated by a common syntax.\"" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T20:28:40.170", "Id": "3793", "ParentId": "3783", "Score": "3" } }, { "body": "<p>This is an alternative solution that also uses many things from the STL. It doesn't separate input from calculation, though.</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;map&gt;\n#include &lt;numeric&gt;\n#include &lt;string&gt;\n#include &lt;utility&gt;\n\nusing std::cin;\nusing std::cout;\nusing std::map;\nusing std::pair;\nusing std::string;\n\n/********************************************************************\n * Read a sequence of possibly whitespace-separated (name,value)\n * pairs, where the name is a single whitespaace-separated word and\n * the value is an integer or floating-point value. Compute and print\n * the sum and mean for each name and the sum and mean for all names\n * ******************************************************************/\n\nvoid data_print_plain(const string &amp;name, double sum, int count) {\n double mean = sum / count;\n cout &lt;&lt; name &lt;&lt; \" sum \" &lt;&lt; sum &lt;&lt; \" mean \" &lt;&lt; mean &lt;&lt; \"\\n\";\n}\n\nvoid data_print(const pair&lt;string, pair&lt;double, int&gt; &gt; &amp;p) {\n data_print_plain(p.first, p.second.first, p.second.second);\n}\n\ndouble add(double x, const pair&lt;string, pair&lt;double, int&gt; &gt; &amp;p) {\n return x + p.second.first;\n}\n\nint main() {\n map&lt;string, pair&lt;double, int&gt; &gt; data;\n\n string name;\n double value;\n while (cin &gt;&gt; name &gt;&gt; value) {\n pair&lt;double, int&gt; &amp;p = data[name];\n p.first += value;\n p.second++;\n }\n\n for_each(data.begin(), data.end(), data_print);\n\n cout &lt;&lt; \"\\n\";\n double total = accumulate(data.begin(), data.end(), 0.0, add);\n data_print_plain(\"total\", total, data.size());\n\n return 0;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-20T07:19:01.193", "Id": "4255", "ParentId": "3783", "Score": "0" } } ]
{ "AcceptedAnswerId": "3793", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-01T09:45:24.167", "Id": "3783", "Score": "3", "Tags": [ "c++", "stream" ], "Title": "Compute and print the sum and mean of name and value pairs" }
3783
<p>What I am creating is essentially a binary clock face with touch input for setting values as well as displaying - so I need to convert both ways between an int and a binary sequence in a BitArray.</p> <p>I cobbled this together (borrow and modifying a bit from a couple different examples I found):</p> <pre><code> public class BinaryConverter { public static BitArray ToBinary(int numeral) { BitArray binary = new BitArray(new int[] { numeral }); bool[] bits = new bool[binary.Count]; binary.CopyTo(bits, 0); return binary; } public static int ToNumeral(BitArray binary, int length) { int numeral = 0; for (int i = 0; i &lt; length; i++) { if (binary[i]) { numeral = numeral | (((int)1) &lt;&lt; (length - 1 - i)); } } return numeral; } } </code></pre> <p>It isn't especially verbose, but in my head before I started it should have been a couple of lines per method, perhaps better leveraging some .NET classes like System.Convert (though, I can't quite see how to do that). Is there a cleaner way to do this? Do you have any other suggestions for improvement?</p>
[]
[ { "body": "<p>You've made it much more complicated than necessary.</p>\n\n<p>The conversion to a <code>BitArray</code> needlessly copies the values to the bool array <code>bits</code>. You could instead use that on the conversion back to <code>int</code>.</p>\n\n<pre><code>public static class BinaryConverter\n{\n public static BitArray ToBinary(this int numeral)\n {\n return new BitArray(new[] { numeral });\n }\n\n public static int ToNumeral(this BitArray binary)\n {\n if (binary == null)\n throw new ArgumentNullException(\"binary\");\n if (binary.Length &gt; 32)\n throw new ArgumentException(\"must be at most 32 bits long\");\n\n var result = new int[1];\n binary.CopyTo(result, 0);\n return result[0];\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T04:44:31.263", "Id": "3797", "ParentId": "3796", "Score": "17" } } ]
{ "AcceptedAnswerId": "3797", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T03:09:14.860", "Id": "3796", "Score": "12", "Tags": [ "c#", ".net", "converting" ], "Title": "Converting binary value from BitArray to an int and back in C#" }
3796
<p>I wrote below code to crypt and decrypt some bytes in three algorithm with Java but I do not know if I wrote them in correct mode or not. Please tell me about truth of code.</p> <p>First class:</p> <pre><code>public class Cryptography { Cryptography() {} public byte[] Encryption_AES128(byte[] plain , byte[] key) throws Exception { AES128 aes128 = new AES128(); return aes128.encrypt(key, plain); } public byte[] Decryption_AES128(byte[] cipher , byte[] key) throws Exception { AES128 aes128 = new AES128(); return aes128.decrypt(key, cipher); } public byte[] Encryption_DES(byte[] plain , byte[] key) throws Exception { DES des = new DES(key); return des.encrypt(plain); } public byte[] Decryption_DES(byte[] cipher , byte[] key) throws Exception { DES des = new DES(key); return des.decrypt(cipher); } public byte[] Encryption_TripleDES(byte[] plain , byte[] key) throws Exception { TripleDES Tdes = new TripleDES(key); return Tdes.encrypt(plain); } public byte[] Decryption_TripleDES(byte[] cipher , byte[] key) throws Exception { TripleDES Tdes = new TripleDES(key); return Tdes.decrypt(cipher); } } </code></pre> <p>And three other classes: </p> <p>First Triple DES:</p> <pre><code>import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESedeKeySpec; public class TripleDES { SecretKey key; TripleDES(byte [] rawkey) throws Exception { key = readKey(rawkey); } public SecretKey readKey(byte[] rawkey) throws Exception { DESedeKeySpec keyspec = new DESedeKeySpec(rawkey); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede"); SecretKey key = keyfactory.generateSecret(keyspec); return key; } public byte[] encrypt(byte[] plain ) throws Exception { Cipher cipher = Cipher.getInstance("DESede"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encrypted = cipher.doFinal(plain); return encrypted; } public byte[] decrypt(byte[] cipher ) throws Exception { Cipher dcipher = Cipher.getInstance("DESede"); dcipher.init(Cipher.DECRYPT_MODE, key); byte[] decrypted = dcipher.doFinal(cipher); return decrypted; } } </code></pre> <p>DES algorithm: </p> <pre><code>import javax.crypto.Cipher; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.DESKeySpec; public class DES { SecretKey key; DES(byte [] KEY) throws Exception { key = readKey(KEY); } public SecretKey readKey(byte[] rawkey) throws Exception { DESKeySpec keyspec = new DESKeySpec(rawkey); SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DES"); SecretKey key = keyfactory.generateSecret(keyspec); return key; } public byte[] encrypt(byte[] plain ) throws Exception { Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] encrypted = cipher.doFinal(plain); return encrypted; } public byte[] decrypt(byte[] cipher ) throws Exception { Cipher dcipher = Cipher.getInstance("DES"); dcipher.init(Cipher.DECRYPT_MODE, key); byte[] decrypted = dcipher.doFinal(cipher); return decrypted; } } </code></pre> <p>and AES-128: </p> <pre><code>import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; public class AES128 { private byte[] getRawKey(byte[] seed) throws Exception { KeyGenerator kgen = KeyGenerator.getInstance("AES"); SecureRandom sr = SecureRandom.getInstance("SHA1PRNG"); sr.setSeed(seed); kgen.init(128, sr); // 192 and 256 bits may not be available SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded(); return raw; } public byte[] encrypt(byte[] raw, byte[] clear) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(raw), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(clear); return encrypted; } public byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception { SecretKeySpec skeySpec = new SecretKeySpec(getRawKey(raw), "AES"); Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[] decrypted = cipher.doFinal(encrypted); return decrypted; } } </code></pre>
[]
[ { "body": "<p>You may want to use \"DESede/CBC/PKCS5Padding\" and \"AES/CBC/PKCS5Padding\" for added security.</p>\n\n<ul>\n<li><p>\"CBC\" is chained cipher block. Both AES and DES are symmetric block ciphers, they encrypt only a fixed block of at a time. Basically, CBC makes the cipher retain state from previous blocks as you encrypt the next block. This makes it more difficult to perform known-plaintext attacks on your ciphertext.</p></li>\n<li><p>\"PKCS5Padding\" causes the cipher to pad the data, including the size of the source block. This allows it to validate the size of the decrypted data, making it more difficult to attack the ciphertext directly.</p></li>\n</ul>\n\n<p>Your classes are somewhat inconsistent. AES128 doesn't keep any state, requires the key to be passed in, and creates the keys in a different way than the others.</p>\n\n<p>These could probably all be coalesced into a class hierarchy with an abstract base class that took SecureKey and Cipher objects created in the derived constructor. The encrypt/decrypt methods could then be implemented directly in the base class.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-02T23:03:16.427", "Id": "28980", "Score": "1", "body": "In crypto you should never rely on defaults, you have to specify everything. Specify the mode: CBC or CTR if you don't want authentication, GCM if you do. Specify the padding: PKCS7 (sometimes called PKCS5). Don't rely on defaults because they can come back and bite you when the latest version changes the default under you and you can no longer decrypt old stuff." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-03-19T20:47:45.120", "Id": "10159", "ParentId": "3798", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T06:10:22.670", "Id": "3798", "Score": "5", "Tags": [ "java", "cryptography" ], "Title": "DES, Triple DES and AES-128 code in Java" }
3798
<p>I will make it more reader friendly after I get the algorithm completed. Does anything with the quick sort algorithm stand out as for why it is not working 100%? This is not homework; I am just practicing problems out of books and I am caught on this one.</p> <p>Hints, more so than answers, would be more appreciated. Please don't post your own quick sort algorithm, as copying someone else's code does not help me learn. I am just looking for that last bit to help me make the leap across; I don't want you to build another bridge somewhere else, and say "use mine"; it won't help. If my algorithm is a lost cause just say so, and I will go back to the drawing board.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;algorithm&gt; #include &lt;iterator&gt; #include &lt;cmath&gt; #include &lt;ctime&gt; #include &lt;assert.h&gt; using std::vector; using std::cin; using std::cout; using std::endl; using std::vector; using std::ostream_iterator; using std::istream_iterator; void print_part( vector&lt;float&gt;::iterator l, vector&lt;float&gt;::iterator r ) { copy( l,r+1,ostream_iterator&lt;float&gt;( cout," " ) ); cout &lt;&lt; endl; } void print( std::vector&lt;float&gt; &amp;data ) { copy( data.begin( ), data.end( ), ostream_iterator&lt;float&gt;( cout," " ) ); cout &lt;&lt; endl; } void swap( vector&lt;float&gt;::iterator left, vector&lt;float&gt;::iterator right ) { cout &lt;&lt; "Swaping " &lt;&lt; (*left) &lt;&lt; " with " &lt;&lt; (*right) &lt;&lt; endl; float tmp = (*right); (*right) = (*left); (*left) = tmp; } int get_pivot_index( vector&lt;float&gt; &amp;data, vector&lt;float&gt;::iterator left, vector&lt;float&gt;::iterator right ) { int pivot_index = ((right-left)/2); int base = std::distance( data.begin( ),left ); return ( pivot_index+=base ); } void my_qsort( vector&lt;float&gt; &amp;data, vector&lt;float&gt;::iterator left, vector&lt;float&gt;::iterator right, int side ) { ((side==0) ? cout&lt;&lt;"":(side==1) ? cout&lt;&lt;"Left: " : cout&lt;&lt;"Right: " ); print_part( left,right ); if( (right-left)&gt;0) { vector&lt;float&gt;::iterator lit=left; vector&lt;float&gt;::iterator rit=right; int pivot_index = get_pivot_index( data,left,right ); int pivot=data[pivot_index]; cout &lt;&lt; "pivot = " &lt;&lt; pivot &lt;&lt; endl; while( lit &lt;= right &amp;&amp; rit &gt; left &amp;&amp; lit &lt;= rit ) { while( lit &lt;= right &amp;&amp; (*lit) &lt; pivot ) { if( lit &gt; rit ) { break; } else { lit++; } } while( rit &gt; left &amp;&amp; (*rit) &gt;= pivot ) { if( lit &gt; rit ) { break; } else { rit--; } } if( lit &lt; rit ) { swap( lit,rit ); } } my_qsort( data,left,rit,1 ); my_qsort( data,lit+1,right,2 ); } char c; cin &gt;&gt; c; } int main( int argc, char *argv[ ] ) { vector&lt;float&gt; data( ( istream_iterator&lt;float&gt;( cin ) ), ( istream_iterator&lt;float&gt;( ) ) ); cout &lt;&lt; "-----------------------------------------------" &lt;&lt; endl; my_qsort( data,data.begin( ),data.end( )-1,0 ); cout &lt;&lt; "-----------------------------------------------" &lt;&lt; endl; print( data ); return ( 0 ); } </code></pre>
[]
[ { "body": "<p>I have a couple of suggestions.</p>\n\n<ol>\n<li><p>Don't wait until you are finished to make your code reader friendly. That's a bad habit to develop because of situations like the one you are in now. You'd like someone else to look at your code but it's not as easy to read as it should be, so it's hard to get the help you'd like. Also, once you start coding for a living there will be pressure to not \"waste time\" cleaning up something that already works.</p></li>\n<li><p>You didn't mention how you know you have a problem. Does it work on some data sets and not others? If so, what's different between the data sets? If you are testing with large data sets you may have a hard time seeing the key difference. Start your testing with very small data sets: 1, then 2, then 3 elements (using all the permutations of starting order). Small data sets can be traced by hand.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:18:25.603", "Id": "3809", "ParentId": "3799", "Score": "5" } }, { "body": "<ol>\n<li><p>I will ask myself -- \"What are the invariants?\" and use assertions to make sure the invariants are satified by the code. In this case, my_qsort should return a sorted range.</p></li>\n<li><p>I will try to find the simplest failing example to understand what is going wrong. </p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:01:28.233", "Id": "3817", "ParentId": "3799", "Score": "5" } }, { "body": "<p>The mistake lies in your left sort. When the 1st value is greater than 2nd value your sort does not work. So focus on that part of your code. Normally these kind of problems are very small and easy to fix but hard to spot :-)</p>\n\n<p>Also would be interesting to see how you sort 4 and 5 characters that are shuffled differently as it would highlight the left side sort issue :-)</p>\n\n<p>If you need more specific help then let me know</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-02T13:40:08.950", "Id": "112281", "Score": "0", "body": "It is always good to leave a comment when you down vote an answer so the answer can be removed or improved." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-30T16:48:08.823", "Id": "26813", "ParentId": "3799", "Score": "1" } }, { "body": "<ul>\n<li><p>The last three libraries should be removed as they're not being used. There's no need to keep a library around if you're long longer using it or have never used even it.</p>\n\n<p>You may also consider organizing them in some way, such as alphabetically.</p></li>\n<li><p>You don't really need these:</p>\n\n<blockquote>\n<pre><code>using std::vector;\nusing std::cin;\nusing std::cout;\nusing std::endl;\nusing std::vector;\nusing std::ostream_iterator;\nusing std::istream_iterator;\n</code></pre>\n</blockquote>\n\n<p>Just use <code>std::</code> where needed, otherwise it'll just get longer if you add more. Also, you have listed <code>using std::vector</code> twice, but it should just be there once.</p></li>\n<li><p><code>print()</code> isn't modifying any data members (it just prints something):</p>\n\n<blockquote>\n<pre><code>print( std::vector&lt;float&gt; &amp;data )\n</code></pre>\n</blockquote>\n\n<p>so <code>data</code> should be passed by <code>const&amp;</code> to avoid an unnecessary copy:</p>\n\n<pre><code>print(std::vector&lt;float&gt; const&amp; data)\n</code></pre></li>\n<li><p>There's no need to provide your own <code>swap()</code> function; just use <a href=\"http://en.cppreference.com/w/cpp/algorithm/swap\" rel=\"nofollow\"><code>std::swap</code></a>:</p>\n\n<pre><code>std::swap(lit, rit);\n</code></pre></li>\n<li><p>This is not a very common nor maintainable style in <code>my_qsort()</code>:</p>\n\n<blockquote>\n<pre><code>if( lit &gt; rit ) { break; }\nelse { lit++; }\n</code></pre>\n</blockquote>\n\n<p>Put each bracketed statement on its own line, in case you ever need to add to them:</p>\n\n<pre><code>if (lit &gt; rit) {\n break;\n}\nelse {\n lit++;\n}\n</code></pre></li>\n<li><p>Why is there a \"pause\" in <code>my_qsort()</code>?</p>\n\n<blockquote>\n<pre><code>char c;\ncin &gt;&gt; c;\n</code></pre>\n</blockquote>\n\n<p>Just let the function works without such interruptions. But if you must keep it anyway, then at least make the user aware that it's a pause, and tell them to input a character in order to continue.</p></li>\n<li><p>Using parentheses for a simple return is not really needed:</p>\n\n<blockquote>\n<pre><code>return ( 0 );\n</code></pre>\n</blockquote>\n\n<p>Just keep it simple and omit them:</p>\n\n<pre><code>return 0;\n</code></pre>\n\n<p>Moreover, you don't really need this. Reaching the end of <code>main()</code> already implies success, so the compiler will insert the return itself.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-28T01:10:16.597", "Id": "55535", "ParentId": "3799", "Score": "8" } } ]
{ "AcceptedAnswerId": "3817", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T09:36:17.663", "Id": "3799", "Score": "4", "Tags": [ "c++", "sorting", "quick-sort" ], "Title": "My own quicksort algorithm" }
3799
<p>This is a short piece of code but I feel like it could be done more elegantly. What am I missing?</p> <p>The goal: if there are any items in a list, and none of them have a given property, set one of them to have that property.</p> <pre><code>static void GuaranteeAtLeastOne&lt;T&gt;(IEnumerable&lt;T&gt; list, Func&lt;T,bool&gt; getter, Action&lt;T&gt; setter) { if (list.Any() &amp;&amp; !list.Any(getter)) { setter(list.First()); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T19:12:28.997", "Id": "5790", "Score": "2", "body": "I think you've done the best you can." } ]
[ { "body": "<p>I wouldn't assume to go for the First, rather I'd have a <code>Func&lt;T, bool&gt; predicate</code> parameter which you pass to a <code>.FirstOrDefault(predicate)</code> and <code>??</code> it with <code>.First()</code></p>\n\n<p>Also, I'd verify <code>IEnumerable&lt;T&gt; != null</code> before anything.</p>\n\n<pre><code>static void GuaranteeAtLeastOne&lt;T&gt;(IEnumerable&lt;T&gt; list, Func&lt;T,bool&gt; getter, Action&lt;T&gt; setter, Func&lt;T,bool&gt; predicate)\n{\n if (list == null || list.Count == 0 || list.Any(getter))\n {\n return;\n }\n\n setter(list.FirstOrDefault(predicate) ?? list.First());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T17:59:52.690", "Id": "5756", "Score": "1", "body": "Throwing an exception would be the correct behavior for a null argument." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-05T17:41:00.203", "Id": "5866", "Score": "0", "body": "+1 @Ben: I agree ...instead of simply returning, should determine whether to throw NullArgument or InvalidArgument." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-09T14:10:09.550", "Id": "5959", "Score": "0", "body": "@Ben I've gotten in the habit of working with nulls instead of exceptions lately to avoid the performance loss of exception bubbling, but that's just a style thing, however you want to handle the null I was merely suggesting to check for it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-11T12:41:28.697", "Id": "6035", "Score": "0", "body": "@Jimmy I still actually prefer my answer but you've made a lot of good points :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T14:43:45.930", "Id": "3804", "ParentId": "3802", "Score": "4" } }, { "body": "<p>The one thing that you're doing is that you could potentially get the enumerator 3 times for any given sequence. If this is expensive and/or becomes an identifiable bottleneck, you may want to handle your checks in a single loop. You can do that in a <code>foreach</code> with a boolean flag, or you can access the enumerator directly. Whichever feels cleaner to you. </p>\n\n<pre><code>bool hasItem = false;\nT first = null; // or perhaps ... = default(T);\n\nforeach (T item in list)\n{\n if (!hasItem)\n {\n hasItem = true;\n first = item;\n }\n\n if (getter(item))\n return; \n}\n\nif (hasItem)\n{\n setter(first);\n}\n</code></pre>\n\n<p>Or using an enumerator and without a flag </p>\n\n<pre><code>using (var enumerator = list.GetEnumerator())\n{\n if (!enumerator.MoveNext())\n return; \n\n T first = enumerator.Current;\n\n do \n {\n if (getter(enumerator.Current))\n {\n return;\n }\n } while (enumerator.MoveNext());\n\n setter(first);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:29:19.850", "Id": "3811", "ParentId": "3802", "Score": "2" } }, { "body": "<p>I would separate the method into 3 distinct parts:</p>\n\n<ol>\n<li>Guard statement which checks if list is available</li>\n<li>A try to find an item that falls into required condition</li>\n<li>A setter which sets reuiqred property to an item</li>\n</ol>\n\n<p>In that case 2nd and 3rd parts can be easily extracted from the method and be reused if needed.</p>\n\n<pre><code>static void GuaranteeAtLeastOne&lt;T&gt;(IEnumerable&lt;T&gt; list, Func&lt;T,bool&gt; getter, Action&lt;T&gt; setter)\n{\n if (list == null || !list.Any())\n {\n return;\n }\n\n T item = list.Where(getter).FirstOrDefault();\n\n if (item != null)\n {\n return;\n }\n\n setter(list.First());\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T21:04:15.817", "Id": "5792", "Score": "1", "body": "Count() == 0 is inferior to Any() as it requires that the entire list be enumerated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T07:50:52.383", "Id": "5796", "Score": "0", "body": "Yes, a good comment. Then using Any() is better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T20:43:59.820", "Id": "5819", "Score": "0", "body": "Count and Count() are different, Count is a cached property of a list, Count() is the linq extension which does the enumeration you referred to. The Count property is more clear and as O(1)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T22:14:29.120", "Id": "5826", "Score": "0", "body": "Count<T>() uses the ICollection<T> implementation for T that implements that interface, so it may not always require the entire list enumerated, but I think Any() is better since any good IEnumerable implementer should optimize that case." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-07T12:02:24.257", "Id": "5901", "Score": "0", "body": "In the question the interface of the list is IEnumerable which doesn't have Count property. So, we can use only Count() extension method, which is not as fast as using Any() method" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T15:52:55.883", "Id": "3846", "ParentId": "3802", "Score": "0" } } ]
{ "AcceptedAnswerId": "3804", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T13:53:44.013", "Id": "3802", "Score": "5", "Tags": [ "c#", ".net", "linq" ], "Title": "Guarantee at least one in a list" }
3802
<pre><code>&lt;?php class Database { private $_dbh; private $_stmt; private $_queryCounter = 0; public function __construct($user, $pass, $dbname) { $dsn = 'mysql:host=localhost;dbname=' . $dbname; //$dsn = 'sqlite:myDatabase.sq3'; //$dsn = 'sqlite::memory:'; $options = array( PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8', PDO::ATTR_PERSISTENT =&gt; true ); try { $this-&gt;_dbh = new PDO($dsn, $user, $pass, $options); } catch (PDOException $e) { echo $e-&gt;getMessage(); exit(); } } public function query($query) { $this-&gt;_stmt = $this-&gt;_dbh-&gt;prepare($query); } public function bind($pos, $value, $type = null) { if (is_null($type)) { switch (true) { case is_int($value): $type = PDO::PARAM_INT; break; case is_bool($value): $type = PDO::PARAM_BOOL; break; case is_null($value): $type = PDO::PARAM_NULL; break; default: $type = PDO::PARAM_STR; } } $this-&gt;_stmt-&gt;bindValue($pos, $value, $type); } public function execute() { $this-&gt;_queryCounter++; return $this-&gt;_stmt-&gt;execute(); } public function resultset() { $this-&gt;execute(); return $this-&gt;_stmt-&gt;fetchAll(PDO::FETCH_ASSOC); } public function single() { $this-&gt;execute(); return $this-&gt;_stmt-&gt;fetch(PDO::FETCH_ASSOC); } // returns last insert ID //!!!! if called inside a transaction, must call it before closing the transaction!!!!!! public function lastInsertId() { return $this-&gt;_dbh-&gt;lastInsertId(); } // begin transaction // must be innoDatabase table public function beginTransaction() { return $this-&gt;_dbh-&gt;beginTransaction(); } // end transaction public function endTransaction() { return $this-&gt;_dbh-&gt;commit(); } // cancel transaction public function cancelTransaction() { return $this-&gt;_dbh-&gt;rollBack(); } // returns number of rows updated, deleted, or inserted public function rowCount() { return $this-&gt;_stmt-&gt;rowCount(); } // returns number of queries executed public function queryCounter() { return $this-&gt;_queryCounter; } public function debugDumpParams() { return $this-&gt;_stmt-&gt;debugDumpParams(); } } </code></pre> <p>Testing the class.... </p> <pre><code>/** * Establish a DB connection. */ $database = new Database('root', '', 'testing'); /** * Insert 1 new record */ $database-&gt;query('INSERT INTO testing (col1,col2,col3) VALUES (:name,:tag,:date)'); $database-&gt;bind(':name', 'john doe'); $database-&gt;bind(':tag', 'hi'); $database-&gt;bind(':date', 'may 1'); $database-&gt;execute(); //returns last auto increment ID echo $database-&gt;lastInsertId(); /** * Insert 2 new records using Transactions * Also Bind new results without running $database-&gt;query() a second time */ $database-&gt;beginTransaction(); $database-&gt;query('INSERT INTO testing (col1,col2,col3) VALUES (:name,:tag,:date)'); $database-&gt;bind(':name', 'user 1'); $database-&gt;bind(':tag', 'hello'); $database-&gt;bind(':date', 'may 2'); $database-&gt;execute(); // Add second item to DB without runing $database-&gt;query() again $database-&gt;bind(':name', 'user 2'); $database-&gt;bind(':tag', 'hello 2'); $database-&gt;bind(':date', 'may 22'); $database-&gt;execute(); //returns last auto increment ID echo $database-&gt;lastInsertId(); //$database-&gt;cancelTransaction(); $database-&gt;endTransaction(); /** * Select a row of items from DB */ $database-&gt;query('SELECT col1, col2, col3 FROM testing WHERE id &gt; ? LIMIT ?'); $database-&gt;bind(1, 1); $database-&gt;bind(2, 5); $row = $database-&gt;single(); echo "&lt;pre&gt;"; print_r($row); echo "&lt;/pre&gt;"; /** * Create a new query, bind values and return a resultset. */ $database-&gt;query('SELECT col1, col2, col3 FROM testing WHERE col2 = :col2 LIMIT :limit'); $database-&gt;bind(':col2', 'hello 2'); $database-&gt;bind(':limit', 10); $rs = $database-&gt;resultset(); foreach ($rs as $row) { echo $row['col1'] . '&lt;br&gt;'; echo $row['col2'] . '&lt;br&gt;'; echo $row['col3'] . '&lt;br&gt;'; } /** * Show number of queries executed on DB */ echo $database-&gt;queryCounter(); ?&gt; </code></pre> <p>That is what I have so far. I am wanting to modify it though so I can run it more like this below instead of running the separate <code>bind()</code> methods on every item... </p> <pre><code>$query = 'INSERT INTO user(user_id, user_username, user_password) VALUES( :user_id, :user_username, :user_password))'; $args = array( ':user_id' =&gt; $data['user_id'], ':user_username' =&gt; $data['user_username'], ':user_password' =&gt; $data['user_password'] ); $db-&gt;query($query, $args); $query = "SELECT user_id FROM user WHERE user_username = :username LIMIT 1"; $results = $db-&gt;query($query, array(':username' =&gt; $username)); </code></pre> <p>Can someone help modify this code to allow this format? </p> <p>I am also concerned about the new method. My current code allows for me to prepare a statement and bind some params and insert them, then bind some more and insert them without preparing the statement again. Would the new way I am wanting to change it to would kill that functionality?</p>
[]
[ { "body": "<p>I think adding a new method to your existing class and calling existing query,bind and execute methods should be enough: </p>\n\n<pre><code>public function query2($query,$params) { \n $this-&gt;query($query); \n foreach($params as $k=&gt;$v){\n $this-&gt;bind($k, $v);\n }\n return $this-&gt;execute();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-15T19:38:21.780", "Id": "36960", "Score": "0", "body": "binding inside foreach requires reference, you need to use &$v because once the foreach loop ends, $k, and $v not exist anymore..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T18:23:03.713", "Id": "3807", "ParentId": "3806", "Score": "1" } }, { "body": "<p>I am making some minor comments on this now old question.</p>\n\n<p>The way you have made your wrapper hard-codes your choices unnecessarily.</p>\n\n<p>Observe your current constructor:</p>\n\n<pre><code>public function __construct($user, $pass, $dbname)\n{\n $dsn = 'mysql:host=localhost;dbname=' . $dbname;\n //$dsn = 'sqlite:myDatabase.sq3';\n //$dsn = 'sqlite::memory:';\n $options = array(\n PDO::MYSQL_ATTR_INIT_COMMAND =&gt; 'SET NAMES utf8',\n PDO::ATTR_PERSISTENT =&gt; true\n );\n try {\n $this-&gt;_dbh = new PDO($dsn, $user, $pass, $options);\n }\n catch (PDOException $e) {\n echo $e-&gt;getMessage();\n exit();\n }\n}\n</code></pre>\n\n<p>It is clear from your comments that you are already considering a different dsn. You are needlessly locking PDO down to mysql localhost connections. All of these settings <strong>make your class less reusable</strong>.</p>\n\n<p>Catching and calling <code>exit</code> further locks your class down to self-destructing. It gives no chance for someone to use your class, see that the database didn't connect catch the exception themselves and deal with it the way they want.</p>\n\n<h2>What does your class need?</h2>\n\n<p>It needs a PDO object (that is all). The rest of the class does not depend on all of the settings that you made in your constructor.</p>\n\n<p>So, I would construct your PDO object outside of this class. Your constructor then becomes:</p>\n\n<pre><code>public function __constructor(PDO $pdo)\n{\n $this-&gt;_dbh = $pdo;\n}\n</code></pre>\n\n<p>Flexibility and Reusability ensues.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T15:03:45.217", "Id": "76941", "Score": "0", "body": "also lets not forget Dependency Injection which is why your method Paul is better." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-04-24T04:19:28.533", "Id": "11131", "ParentId": "3806", "Score": "3" } } ]
{ "AcceptedAnswerId": "11131", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T17:05:54.080", "Id": "3806", "Score": "6", "Tags": [ "php", "mysql", "pdo" ], "Title": "PDO wrapper class" }
3806
<p>I have a NumPy array of about 2500 data points. This function is called on a rolling basis where 363 data points is passed at a time.</p> <pre><code>def fcn(data): a = [data[i]/np.mean(data[i-2:i+1])-1 for i in range(len(data)-1, len(data)-362, -1)] return a </code></pre> <p>This takes about 5 seconds to run. I think the bottleneck is the list slicing. Any thoughts on how to speed this up?</p>
[]
[ { "body": "<p><code>range</code> returns a list. You could use <code>xrange</code> instead.</p>\n\n<blockquote>\n<pre><code>range([start,] stop[, step]) -&gt; list of integers\n</code></pre>\n \n <p>Return a list containing an arithmetic progression of integers.</p>\n</blockquote>\n\n<p>vs</p>\n\n<blockquote>\n<pre><code>xrange([start,] stop[, step]) -&gt; xrange object\n</code></pre>\n \n <p>Like <code>range()</code>, but instead of returning a list, returns an object that\n generates the numbers in the range on demand. For looping, this is \n slightly faster than <code>range()</code> and more memory efficient.</p>\n</blockquote>\n\n<p>The other thing that strikes me is the slice in the argument to <code>np.mean</code>. The slice is always of length 3. Assuming this is an arithmetic mean, you could turn the division into</p>\n\n<pre><code>(3.0 * data[i] / (data[i - 2] + data[i - 1] + data[i]))\n</code></pre>\n\n<p>So putting it together</p>\n\n<pre><code>def fcn(data):\n return [(3.0 * data[i] / (data[i - 2] + data[i - 1] + data[i])) - 1\n for i in xrange(len(data) - 1, len(data) - 362, -1)]\n</code></pre>\n\n<p>and you could further optimize the sum of last three values by recognizing that if</p>\n\n<pre><code>x = a[n] + a[n+1] + a[n+2]\n</code></pre>\n\n<p>and you have already computed</p>\n\n<pre><code>y = a[n - 1] + a[n] + a[n + 1]\n</code></pre>\n\n<p>then</p>\n\n<pre><code>x = y + (a[n - 1] - a[n + 2])\n</code></pre>\n\n<p>which helps whenever a local variable access and assignment is faster than accessing an element in a series.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T00:46:58.697", "Id": "5770", "Score": "0", "body": "This is great feedback. Your version of fcn runs in half the time as using np.mean!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T23:46:51.160", "Id": "3827", "ParentId": "3808", "Score": "4" } }, { "body": "<p>When using numpy, you should avoid writing loops. Instead you should do operations on the array.</p>\n\n<p>Slicing in numpy is really cheap, because it doesn't actually copy anything. </p>\n\n<p>The tricky part in eliminating the loop is the rolling np.mean(), but see this web page for code to help eliminate that: <a href=\"http://www.rigtorp.se/2011/01/01/rolling-statistics-numpy.html\" rel=\"nofollow\">http://www.rigtorp.se/2011/01/01/rolling-statistics-numpy.html</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T00:47:44.483", "Id": "5771", "Score": "0", "body": "Thanks for the feedback. I'm going to check out np.strides." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T00:09:22.780", "Id": "3828", "ParentId": "3808", "Score": "2" } } ]
{ "AcceptedAnswerId": "3827", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T18:29:16.250", "Id": "3808", "Score": "2", "Tags": [ "python", "array", "numpy" ], "Title": "Rolling loop with an array of data points" }
3808
<p>I've got a case where I need to call a couple of methods, checking if they return null, and return some property from the result of the second when neither returns null. </p> <p>I've thought of two ways to do this - one "verbose" and one "concise". For the purposes of this question, I'll just call the return types 'dynamic' since I'm not interested in those details here.</p> <pre><code>private dynamic VerboseVersion() { var a = CallMethodA(); if ( a == null ) { return null; } var b = CallMethodB( a ); if ( b == null ) { return null; } return b.SomeProperty; } private dynamic ConciseVersion() { dynamic a; dynamic b; if ( ( a = CallMethodA() ) == null || ( b = CallMethodB( a ) ) == null ) { return null; } return b.SomeProperty; } </code></pre> <p>I the first because the intent at each step is very obvious but I find it somewhat verbose; I like the second because the intent of the function seems more obvious and it is less verbose but it may be a bit harder to follow at first.</p> <p>Thoughts?</p> <p><strong>Update:</strong> Corrected a typo and corrected the formatting of the "Verbose" version to what I would actually use in committed code.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:47:50.597", "Id": "5768", "Score": "1", "body": "I fail to see how your second example is more concise. As measured by lines of code it is actually less concise... and harder to read as well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T19:19:33.157", "Id": "5791", "Score": "0", "body": "FYI, there's a typo in your Verbose after the first `return null;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T15:53:55.183", "Id": "5811", "Score": "0", "body": "Thanks everyone! Looks like the consensus is the more verbose version. Since all the answers are so similar, I'm going to accept the highest upvoted one." } ]
[ { "body": "<p>I would modify CallMethodB to return null when it is passed null and then use the following:</p>\n\n<pre><code>private dynamic VerboseVersion()\n{\n var b = CallMethodB( CallMethodA() );\n if ( b == null )\n {\n return null;\n }\n else\n {\n return b.SomeProperty;\n }\n}\n</code></pre>\n\n<p>I prefer to avoid assignments in conditions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:24:01.723", "Id": "3820", "ParentId": "3810", "Score": "1" } }, { "body": "<p>I take great pleasure in the fact that your \"concise\" version is longer than your \"verbose\" version! </p>\n\n<p>If you believe one version to be more readable and the other to be more obscure, I would argue going with readability over obscurity. One obscure detail is that you're relying on people understanding </p>\n\n<pre><code>(a = CallMethodA()) == null\n</code></pre>\n\n<p>Some people might think that to be an error, not realizing the expression on the left actually has a value. </p>\n\n<p>If you want to use less lines of code, you could go with something like this </p>\n\n<pre><code>var a = CallMethodA();\nvar b = (a == null) ? null : CallMethodB(a);\nreturn (b == null) ? null : b.SomeProperty;\n</code></pre>\n\n<p>Which isn't altogether different than your original if/else chain, but is a bit more compressed and has just the one return statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T15:51:14.063", "Id": "5810", "Score": "0", "body": "Good catch on the length -- I usually \"expand\" the return blocks (I've updated the question). Also, I tend to gloss over declaration-only statements when I'm reading code." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:24:54.937", "Id": "3821", "ParentId": "3810", "Score": "8" } }, { "body": "<p>These two versions do not have the same semantics. The first version guarantees CallMethodB receives a non-null param \"a\" whereas the second does not. I don't know what CallMethodB requires, but you could get null pointer exception in b. I personally prefer the first version, clear and precise, I don't feel you lose any readability. If CallMethodB accepts null param, then you might be able to simplify the code by just:</p>\n\n<pre><code>b = CallMethodB(CallMethodA());\n</code></pre>\n\n<p>Correction: As Anthony pointed out, the \"||\" at the end actually would short circuit the evaluation when a is null, so there is no semantic difference with these two version. I've misread the original post. Sorry for my jump the gnu coclusion. Though, I still prefer version 1, it feels just less confusion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:33:56.973", "Id": "5766", "Score": "2", "body": "The second version would also receive non-null. The `if` would short circuit if the `(a = CallMethodA()) == null` condition was met, so `CallMethodB(a)` would not be invoked." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T00:02:36.320", "Id": "5769", "Score": "0", "body": "Ah correct. I've misread that part. Sorry about the incorrect comments." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:31:22.587", "Id": "3822", "ParentId": "3810", "Score": "0" } }, { "body": "<p>I would always prefer the verbose one. It is clear, readable and most importantly it not easy to misunderstand it. I never try to make the code shorter, in fact I believe that even if the code is longer total cost of it may be lower. </p>\n\n<p>Because a misunderstanding or error because of ambiguity always costs way more than typing a few more lines.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T21:18:53.713", "Id": "3824", "ParentId": "3810", "Score": "3" } }, { "body": "<p>I am totally agree with Serkan Özkan.</p>\n\n<p>Despite the fact that the ConciseVersion looks much more \"smarter\" I wouldn't sacrifice redability and would vote for VerboseVersion. This is something most of the developers used to. Moreover, I would put return statements in a separate line, so it would be clear that if something is null then null should be returned</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T06:57:18.257", "Id": "3836", "ParentId": "3810", "Score": "0" } }, { "body": "<p>Another variant is to create an extension method like:</p>\n\n<pre><code> public static class GeneralExtensions\n {\n public static dynamic GetNext&lt;T&gt;(this T objectToProcess,\n Func&lt;T, dynamic&gt; getNextCallback) \n where T : class\n {\n if (objectToProcess != null)\n {\n return getNextCallback(objectToProcess);\n }\n else\n {\n return null;\n }\n }\n }\n</code></pre>\n\n<p>Then your code will be:</p>\n\n<pre><code>return CallMethodA()\n .GetNext(a =&gt; CallMethodB(a)\n .GetNext(b =&gt; b.SomeProperty));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T14:49:17.513", "Id": "3843", "ParentId": "3810", "Score": "0" } }, { "body": "<p>I think the concise version is longer and more confusing, and emphasizes the wrong return (assuming the value of SomeProperty is what is really of interest).</p>\n\n<p>For the verbose, I don't like returning the same value more than once, even if it is a constant - so a variation on the verbose:</p>\n\n<pre><code>private dynamic MyVerboseVersion() \n{\n var a = CallMethodA();\n if (a != null) {\n var b = CallMethodB(a);\n if (b != null) {\n return b.SomeProperty;\n }\n }\n\n return null;\n}\n</code></pre>\n\n<p>I don't really like the burgeoning arrow or the fall through else, but it is how I often solve this pattern.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T19:43:28.843", "Id": "3849", "ParentId": "3810", "Score": "0" } }, { "body": "<p>If I have the opportunity to modify methods, and expect that the result of a method would return a null, I will rewrite and follow the <code>TryXXX</code> pattern.</p>\n\n<pre><code>private dynamic TryVersion()\n{\n dynamic a;\n dynamic b;\n\n if (TryCallMethodA(out a)) {\n if (TryCallMethodB( a, out b )){\n return b.SomeProperty;\n }\n }\n\n return null;\n}\n</code></pre>\n\n<p>If you really want to shorten this, you could:</p>\n\n<pre><code>if (TryCallMethodA(out a) &amp;&amp; TryCallMethodB( a, out b )){\n return b.SomeProperty;\n} \n</code></pre>\n\n<p>Note: the second snippet is untested but I believe it would work as the left TryCall must be resolved to move on to the right TryCall.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T19:57:33.773", "Id": "3885", "ParentId": "3810", "Score": "0" } }, { "body": "<p>Why does the Methods <code>CallMethodA</code> and <code>CallMethodB</code> return null? Wouldn't it be better to throw an exception, that you can signal that something went terribly wrong?<br/>\nIn my opinion returning null is always bad for developers who are using your code, becaus they don't know what went wrong and what to change.<br/>\nAt your example you are expecting CallMethodB to return an Object. So if nobody throws an exception everything has just worked fine, use the return value, if it is null let the nullReferenceException occur and enjoy writing well code.<br/>\nRemoving Null checks would increase your readability and the reusablility of your code!</p>\n\n<pre><code>SampleObject CallMethodA(){\n if(Some())\n return new A();\n throw new SomeThingTerribleException(Can't create SampleObject due to lack of Some\");\n }\n\nSampleObject CallMethodB(SampleObject obj){\n if(obj.IsSomethingSet())\n return new B(obj);\n throw new SomeThingTerribleException(\"Can't create SampleObject due to lack of Some\");\n }\nvoid Main(){\n var a = CallMethodA();\n var b = CallMethodB( a );\n return b.SomeProperty;\n}\n</code></pre>\n\n<p>As you might see no null, no dirty null-checks just clear exceptions for the user of your Methods.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-09-30T14:24:13.477", "Id": "5082", "ParentId": "3810", "Score": "0" } }, { "body": "<p>I also agree with @oberfreak that I feel like that in your example you are using null as an error value to manage errors and do some protections, have you considered using exceptions?</p>\n\n<p>In many cases to avoid uncatched exceptions and try-catch blocks many of us use the null as an error value and probably use another kind of aproximation would be a good alternative.</p>\n\n<p>Also, another option I would suggest is to call CallMethodA inside CallMethodB and there control the return value of CallMethodA</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-05T12:04:09.567", "Id": "40947", "ParentId": "3810", "Score": "2" } } ]
{ "AcceptedAnswerId": "3821", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:21:42.917", "Id": "3810", "Score": "5", "Tags": [ "c#" ], "Title": "Concise null checking vs readability" }
3810
<p>I'm writing a method that takes (1) an array of <code>int</code>s and (2) an <code>int</code>. The purpose of the method is to find the indices of the two numbers in the array that add up to the value passed in as the second parameter to the method (sum) and return those values in an <code>int[]</code>. Exactly two numbers in the passed in array will add up to "sum", so as soon as they are identified the method should finish. I have come up with two solutions so far, but both seem ugly to me:</p> <pre><code>//this method is bad because it has multiple returns private int[] findIndexes(int[] intAr, int sum) { for (int i = 0; i &lt; intAr.length; ++i) { for (int k = i + 1; k &lt; intAr.length; ++k) { if(intAr[i] + intAr[k] == sum) { return new int[] {i + 1, k + 1}; } } } //should never reach here return null; } //this method is bad because it uses "break" outside of a switch statement private int[] findIndexes(int[] intAr, int sum) { int[] indexAr = new int[2]; outer: for (int i = 0; i &lt; intAr.length; ++i) { for (int k = i + 1; k &lt; intAr.length; ++k) { if(intAr[i] + intAr[k] == sum) { indexAr[0] = i + 1; indexAr[1] = k + 1; break outer; } } } return indexAr; } </code></pre> <p>Is there a better way to write this method that does not violate the coding standards mentioned above?</p> <p>The coding standards I was looking at are located <a href="http://www.javaranch.com/styleLong.jsp" rel="nofollow">here</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:49:58.077", "Id": "5757", "Score": "4", "body": "Who told you they're bad? I believe it's a matter of opinion." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:53:53.083", "Id": "5758", "Score": "0", "body": "I see nothing wrong with your first method, nor the second, but I prefer the first." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:54:14.637", "Id": "5759", "Score": "0", "body": "+1 for @Jon. Both of those \"rules\" are made to be broken. In either case, there's a third solution in which you use a boolean flag or two and check it in the loop condition (or equivalently inside the loop) to see whether a solution has been found or not: and it's far uglier than either of these. Personally, I like the first one, which is very clear and easy to follow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:06:09.103", "Id": "5761", "Score": "0", "body": "You're already ignoring 1.1 - Braces in the standards you linked to. Why stick to the others?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:13:56.383", "Id": "5763", "Score": "0", "body": "Is there a reason you are checking the sum of the contents at `i` and `k` in the array, but returning an array populated with `i + 1` and `k + 1` values (not contents)? If your code does what it's stated to, you are assuming that 'x[n] == n + 1' - not something I would bet on in the wild (non-contiguous arrays, starting values not at 1, etc). I would also start `k` at `i`, not `i + 1`, in case the only way to match the sum is to double the number (and no duplicates in the array). Other than that, I like the first solution." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:23:00.057", "Id": "5764", "Score": "0", "body": "@Vlad - What can I say, I never said I was trying to follow their entire standard =)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:23:13.767", "Id": "5765", "Score": "0", "body": "@X-Zero - I am returning i + 1 and k + 1 because the eventual output is not 0 based. Do you think it would be better to return the actual indexes and make the adjustment when the values are printed? And yes, there can be duplicates in the array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:42:23.567", "Id": "5767", "Score": "0", "body": "@fiddlesticks - Two things: 1) My fault, I thought you were supposed to be returning the contents of the array, not the index of the contents (so, 3 + 5 = 8, not numbers at indicies 1 and 5). 2) At the moment, you are returning index values that have *nothing* to do with what you were using for comparisons. It doesn't matter if you don't populate the 0th element of the array, you still need to return the *actual* positions the elements are at. Generally, returning an offset array index is display-only code, would have to know more of the design to see for sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:14:01.093", "Id": "62786", "Score": "0", "body": "First example is very easy to read and understand. Does anyone remember: *return early, return often*?" } ]
[ { "body": "<p>There's nothing wrong with a break statement used outside a switch statement. (2nd example)</p>\n\n<p>If a professor or some other authority figure is enforcing that rule, that's a pain, but the code is perfectly fine. There's even a similar example in the <a href=\"http://download.oracle.com/javase/tutorial/java/nutsandbolts/branch.html\" rel=\"nofollow\">Java Tutorials on Branching</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:52:33.123", "Id": "3814", "ParentId": "3813", "Score": "5" } }, { "body": "<p>There is nothing wrong with having multiple return statements especially to break out of nested ifs.</p>\n\n<p>Here is some discussion on SO about this very topic </p>\n\n<p><a href=\"https://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement\">https://stackoverflow.com/questions/36707/should-a-function-have-only-one-return-statement</a></p>\n\n<p>Additional discussion on GOTO</p>\n\n<p><a href=\"https://stackoverflow.com/questions/46586/goto-still-considered-harmful\">https://stackoverflow.com/questions/46586/goto-still-considered-harmful</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:53:05.837", "Id": "3815", "ParentId": "3813", "Score": "0" } }, { "body": "<p>Your first method seems perfectly fine to me. Having multiple returns in the same method is not necessarily bad -- how else would one implement <a href=\"http://en.wikipedia.org/wiki/Ackermann_function\" rel=\"nofollow\">Ackermann function</a>? :). Your usage of the <code>break</code> in the second method, however, is not very common, and can thus be confusing, but it's also perfectly valid to use a <code>break</code> outside of a switch statement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:53:35.163", "Id": "3816", "ParentId": "3813", "Score": "0" } }, { "body": "<p>As the majority already pointed out, your method is fine concerning the coding standards. However it has an asymptotic complexity of O(n²). For <strong>very</strong> long arrays you may consider a more performant approach having O(n * log n) [...I think]. The code is very easy to understand: Sort the array and search from both ends. The only difficulty is that you need to keep track of the indexes as well, which requires to copy the whole array.</p>\n\n<pre><code>private int[] findIndexes(int[] intAr, int sum) {\n int[][] data = new int[intAr.length][2];\n for(int i = 0; i &lt; intAr.length; i++) {\n data[i] = new int[]{intAr[i], i + 1};\n }\n java.util.Arrays.sort(data, new Comparator&lt;int[]&gt;(){\n public int compare(int[] o1, int[] o2) {\n return o1[0] - o2[0];\n }\n });\n int lower = 0;\n int upper = data.length-1;\n while(lower &lt; upper) {\n int s = data[lower][0] + data[upper][0];\n if(s == sum) {\n return new int[]{data[lower][1], data[upper][1]};\n } else if (s &lt; sum) {\n lower++;\n } else {\n upper--;\n }\n }\n return null;\n}\n</code></pre>\n\n<p>Even if this solution isn't appropriate in your setting, it's useful to know this \"search from both ends\" technique. Obviously this approach would be much simpler if you can assume an already sorted array.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T07:58:06.853", "Id": "3837", "ParentId": "3813", "Score": "2" } }, { "body": "<p>The first one is fine in my eyes: it is easy to read and quite simple. Having multiple returns in such a case is normally far easier to read than the alternative (like your second method).</p>\n\n<p>The only problem I have is the return null statement. I don't think it is a good idea to return null EVER. Wouldn't an empty array be appropriate in such a case? Or if, as your comment says, this should never happen, consider throwing an exception instead. At least, if that statement is reached, you will know right away why and not find it out 5 method calls up the stack with a NullPointerException.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T13:51:17.657", "Id": "3841", "ParentId": "3813", "Score": "0" } } ]
{ "AcceptedAnswerId": "3814", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T19:47:03.513", "Id": "3813", "Score": "3", "Tags": [ "java", "comparative-review" ], "Title": "Finding array indices that add up to another number" }
3813
<p>This code gets me where I need to be, but my word it is ugly. </p> <p>I am checking for the existence of two $_GET variables with if() statements. I am setting the variables to empty strings first so I do not get an error when I echo them back.</p> <pre><code>$getvar1 =''; $getvar2 =''; $np =''; if(isset($_GET['getvar1'])) $page_id = $_GET['getvar2']; if(isset($_GET['getvar2'])) $route = $_GET['getvar2']; if(($getvar1 == '' &amp;&amp; $getvar1 == '') || $getvar1 == '4') $np = 'np'; echo "$getvar1 $getvar2 $np"; </code></pre> <p>Is there a better way to declare the variables than setting them to empty strings?</p> <p>Is there a better way to check and set the $_GET variables?</p>
[]
[ { "body": "<p>How about writing a function like this:</p>\n\n<pre><code>function getOrDefault($index, $default)\n{\n return (!isset($_GET[$index]) || empty($_GET[$index]) ? $default : $_GET[$index]);\n}\n\n$getVar1 = getOrDefault('getvar1', '');\n$getVar2 = getOrDefault('getvar2', '');\n</code></pre>\n\n<p>This function should be as general as possible and be located somewhere in a <code>function-library</code>. I don't know about the rest of your project. But for example if you do have some kind of <code>request</code> object (containing all information about the current (http)request), you could write specialized versions:</p>\n\n<pre><code>class Request()\n{\n public function getPost($param, $default = '')\n {\n if(!isset($_POST[$param]) || empty($_POST[$param])\n {\n return $default;\n }\n return $_POST[$param];\n }\n\n // If param is set both in $_GET and $_POST, $_GET is return.\n public function getParam($param, $default = '')\n {\n if(!isset($_GET[$param]) || empty($_GET[$param))\n {\n return $this-&gt;getPost($param, $default);\n }\n return $_GET[$param];\n }\n}\n\n$getVar1 = $request-&gt;getParam('getVar1', '');\n$getVar2 = $request-&gt;getParam('getVar2', '');\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-04-26T08:25:08.600", "Id": "473356", "Score": "0", "body": "You could use $_REQUEST as well..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T00:13:59.717", "Id": "3829", "ParentId": "3819", "Score": "3" } }, { "body": "<p>If it's a small app something like that would probably be better:</p>\n\n<pre><code>$getvar = isset($_GET['getvar']) ? $_GET['getvar'] : 'somedefault';\n</code></pre>\n\n<p>If you want to test more stuff:</p>\n\n<pre><code>$getvar = isset($_GET['getvar']) &amp;&amp; $JUST_PUT_IT_HERE ? $_GET['getvar'] : 'somedefault';\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-06T23:35:39.770", "Id": "163204", "Score": "1", "body": "Don't forget to sanitize/filter when you're pulling in data like $_GET, $_POST, $_REQUEST, etc or you could have vulnerabilities later on \nhttp://php.net/manual/en/function.filter-input.php" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T03:39:56.850", "Id": "3832", "ParentId": "3819", "Score": "4" } }, { "body": "<p><strong>Array Merge</strong></p>\n\n<p>If you're just setting defaults, you could use <a href=\"http://php.net/manual/en/function.array-merge.php\" rel=\"nofollow noreferrer\"><code>array_merge()</code></a>:</p>\n\n<pre><code>$defaults = array(\n 'getvar1' =&gt; 'default setting', //a default value\n 'getvar2' =&gt; false //now you can just test\n);\n\n$params = array_merge($defaults, $_GET); //any missing elements get the default value\n\necho $params['getvar1']; //will output 'default setting' if $_GET['getvar1'] was not set\n\nif($params['getvar2']){\n //do something if $_GET['getvar2'] was set to a non-false value\n}\n</code></pre>\n\n<p>It should be noted that this only works with things like <code>$_GET</code> - that are already arrays. The <a href=\"http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary\" rel=\"nofollow noreferrer\">ternary</a> <a href=\"https://codereview.stackexchange.com/questions/3819/php-checking-for-get-variables-with-if-statements/3832#3832\">method</a>, a <a href=\"https://codereview.stackexchange.com/questions/3819/php-checking-for-get-variables-with-if-statements/3829#3829\"><code>getOrDefault()</code></a> function, or some <a href=\"https://stackoverflow.com/questions/1732403/can-someone-explain-this-line-of-code-please-logic-assignment-operators/1732428#1732428\">enigmatic logic operator</a> code is better suited when setting defaults not already in an array.</p>\n\n<p><strong>Logic Operators</strong></p>\n\n<p>Here's an example of using logic operators (similar to using ternary operator) from the default Zend MVC <code>index.php</code>:</p>\n\n<pre><code>defined('APPLICATION_PATH')\n || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));\n</code></pre>\n\n<p>Using the question's example, it would look something like this:</p>\n\n<pre><code>isset($_GET['getvar1']) || $_GET['getvar1'] = 'default value';\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T19:33:34.123", "Id": "3883", "ParentId": "3819", "Score": "2" } } ]
{ "AcceptedAnswerId": "3832", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-02T20:20:39.010", "Id": "3819", "Score": "4", "Tags": [ "php" ], "Title": "PHP: checking for $_GET variables with if statements" }
3819
<p>I'm just curious if this is clear to the average person.</p> <pre><code>template&lt;typename IteratorType&gt; inline IteratorType skip_over( IteratorType begin, IteratorType end, typename std::iterator_traits&lt;IteratorType&gt;::value_type skippedCharacter) { typedef typename std::iterator_traits&lt;IteratorType&gt;::value_type value_type; return std::find_if(begin, end, std::not1( std::bind2nd(std::equal_to&lt;value_type&gt;(), skippedCharacter) ) ); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T03:56:06.687", "Id": "5777", "Score": "0", "body": "It took me a while to work out what it did (comments would not go amiss)." } ]
[ { "body": "<p>A few comments:</p>\n\n<ul>\n<li><p>Algorithms typically use the names <code>first</code> and <code>last</code> for the iterators they take, not <code>begin</code> and <code>end</code> (in common usage, <code>begin</code> and <code>end</code> refer specifically to the iterators that delimit a range in a container).</p></li>\n<li><p>The use of <code>find_if</code> seems a bit excessive: yes, it is good to use the Standard Library algorithms, but if you are writing your own algorithm, you may as well just write a loop, especially if it makes the code much clearer.</p></li>\n<li><p>With respect to template parameter naming, it is helpful if you say what category of iterator is required; this helps to document the algorithm.</p></li>\n</ul>\n\n<p>Consider the following, alternative implementation:</p>\n\n<pre><code>template &lt;typename ForwardIterator, typename T&gt;\nForwardIterator skip_over(ForwardIterator first, ForwardIterator last, T const&amp; x)\n{\n while (first != last &amp;&amp; *first == x)\n ++first;\n\n return first;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T22:10:29.900", "Id": "5825", "Score": "1", "body": "I'm not sure why, but I think I'd prefer `for (;first!=last && *first==x; ++first); return first;` (with the empty semicolon on its own line, of course)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T02:51:12.603", "Id": "3831", "ParentId": "3830", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T01:37:17.850", "Id": "3830", "Score": "5", "Tags": [ "c++", "algorithm", "iterator" ], "Title": "Skip_over() algorithm" }
3830
<p>I've been seeking to optimize this algorithm, perhaps by eliminating one of the loops, or with a better test to check for prime numbers.</p> <p>I'm trying to calculate and display 100000 prime numbers has the script pausing for about 6 seconds as it populates the list with primes before the primes list is returned to the console as output.</p> <p>I've been experimenting with using</p> <pre><code>print odd, </code></pre> <p>to simply print every found prime number, which is faster for smaller inputs like n = 1000, but for n = 1000000 the list itself prints much faster (both in the Python shell and in the console).</p> <p>Perhaps the entire code/algorithm should be revamped, but the script should remain essentially the same: The user types in the number of prime numbers to be printed (n) and the script returns all prime numbers up to the nth prime number.</p> <pre><code>from time import time odd = 1 primes = [2] n = input("Number of prime numbers to print: ") clock = time() def isPrime(number): global primes for i in primes: if i*i &gt; number: return True if number%i is 0: return False while len(primes) &lt; n: odd += 2 if isPrime(odd): primes += [odd] print primes clock -= time() print "\n", -clock raw_input() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T18:10:55.187", "Id": "5787", "Score": "3", "body": "Take a look at http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes for ideas." } ]
[ { "body": "<p>Welcome to programming and code review!</p>\n\n<p>Your code is pretty good especially for a beginner, but I'm going to be picky:</p>\n\n<pre><code>from time import time\n</code></pre>\n\n<p>I recommend putting at least one blank line between the imports and the code proper</p>\n\n<pre><code>odd = 1\n</code></pre>\n\n<p>You don't use this until much later. Don't declare variables until you actually need them. It will make the code easier to read.</p>\n\n<pre><code>primes = [2]\nn = input(\"Number of prime numbers to print: \")\n</code></pre>\n\n<p>Rather than using input, I recommend using int(raw_input(. Input actually interprets the text entered as a python expression which means it can do anything. If you really just wanted a number, using int(raw_input is better. Also, input has been modified in python 3 to be like raw_input.</p>\n\n<pre><code>clock = time()\ndef isPrime(number):\n</code></pre>\n\n<p>Typically functions are defined before the actual code not in the middle of it.</p>\n\n<pre><code> global primes\n</code></pre>\n\n<p>global is only necessary if you want to modify the primes. Since you don't modify it, you don't need it. </p>\n\n<pre><code> for i in primes:\n if i*i &gt; number:\n</code></pre>\n\n<p>It's not immediately obvious why you can stop here. A comment would be helpful.</p>\n\n<pre><code> return True\n if number%i is 0:\n</code></pre>\n\n<p>Put spaces around your operators: %</p>\n\n<pre><code> return False\nwhile len(primes) &lt; n:\n odd += 2\n if isPrime(odd):\n primes += [odd]\n</code></pre>\n\n<p>When adding a single element to a list use primes.append(odd)</p>\n\n<pre><code>print primes\nclock -= time()\n</code></pre>\n\n<p>That's kinda confusing. I'd suggest doing start_time = .., end_time = ..., time_spent = end_time - start_time. That ways it clear what you are doing, whereas what you've done with the clock is unusual and not immeadiately obvious.</p>\n\n<pre><code>print \"\\n\", -clock\nraw_input()\n</code></pre>\n\n<p>Also, don't put logic in the top level scope of your program. Put all logic especially loops inside a function. It'll run faster in the function, and will keep the program neater.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T06:25:49.057", "Id": "3835", "ParentId": "3833", "Score": "7" } }, { "body": "<p>To format your code in python is to write it so you have your title/author comments on top, imports below, classes, functions and then your main.</p>\n\n<p>Generally <code>is</code> is considered poor coding prose in python mainly because it attracts unnecessary bugs. <code>is</code> compares two objects in memory, == compares their values, with the latter as what coder usually means.</p>\n\n<p>A global variable here is completely unnecessary, there are few cases when it is useful and this is definitely not one of them. Just send it as an argument.</p>\n\n<p>i*i can be rewritten as i**2</p>\n\n<p>Other than that and what Winston mentioned, very impressive for a beginner. Keep going!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T15:32:01.567", "Id": "42877", "ParentId": "3833", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T03:48:57.560", "Id": "3833", "Score": "4", "Tags": [ "python", "optimization", "algorithm", "beginner", "primes" ], "Title": "Optimizing this 'print up to the nth prime number' script" }
3833
<p>I have an mail object that returns its headers as an Enumerator of Header objects, which have two methods, getName and getValue. I need to convert that to a nice Clojure map so I wrote this short function:</p> <pre><code>(defn extract-headers [message] (reduce (fn [hs h] (conj hs {(.getName h) (.getValue h)})) {} (enumeration-seq (.getAllHeaders message)))) </code></pre> <p>Anything to change or improve here?</p>
[]
[ { "body": "<p>You can use <code>into</code>, for example: </p>\n\n<pre><code>(defn extract-headers [message]\n (let [headers (enumeration-seq (.getAllHeaders message))]\n (into {} (map #(vector (.getName %1) (.getValue %1)) headers))))\n</code></pre>\n\n<p>first, with <code>map</code> you build sequence of 2-element vectors, that later is converted into map</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T11:18:43.013", "Id": "3840", "ParentId": "3834", "Score": "3" } }, { "body": "<p>Reading the other answer, a simple small improvement would be:</p>\n\n<pre><code>(defn extract-headers [message]\n (reduce #(conj %1 {(.getName %2) (.getValue %2)})\n {}\n (enumeration-seq (.getAllHeaders message))))\n</code></pre>\n\n<p>Only to make it a little shorter.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T06:33:01.420", "Id": "5793", "Score": "0", "body": "use of explicit `fn` could make life easier + it allows to put type hint before argument" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T15:12:29.600", "Id": "3844", "ParentId": "3834", "Score": "1" } }, { "body": "<p>I rather like the into approach, I think it's more idiomatic to use a dedicated function than reduce, which is quite general. However, I think using threading is easier to read long term.</p>\n\n<pre><code>(defn extract-headers [^Mail message]\n (letfn [(project [^Header h] (list (.getName h) (.getValue h)))]\n (-&gt;&gt;\n message\n .getAllHeaders\n enumeration-seq\n (map project)\n (into {}))))\n</code></pre>\n\n<p>As you can see, I've also incorporated Alex's suggestion to use an explict fn, which avoids reflection.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T09:58:33.583", "Id": "3867", "ParentId": "3834", "Score": "1" } } ]
{ "AcceptedAnswerId": "3840", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T06:11:43.780", "Id": "3834", "Score": "2", "Tags": [ "clojure" ], "Title": "From enumerator to map" }
3834
<p>I am using the following template to program my 2D games in. Is there any way I can improve it?</p> <p><strong>Splash screen:</strong></p> <pre><code>package com.dingle.template2d; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class template2d extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //set screen setContentView(R.layout.splash); // thread for displaying the SplashScreen Thread splashTread = new Thread() { @Override public void run() { try { int waited = 0; boolean _active; int _splashTime; _active = true; _splashTime = 500; while(_active &amp;&amp; (waited &lt; _splashTime)) { sleep(100); if(_active) { waited += 100; } } startActivity(new Intent("com.dingle.template2d.MENU")); } catch(InterruptedException e) { // do nothing } finally { finish(); } } }; splashTread.start(); } } </code></pre> <p><strong>Menu screen:</strong></p> <pre><code>package com.dingle.template2d; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.Window; import android.widget.Button; public class menu extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); this.button(); } private void button(){ Button play_button = (Button)this.findViewById(R.id.play_button); play_button.setOnClickListener( new Button.OnClickListener() { public void onClick(View v) { // parentButtonClicked(v); startActivity(new Intent("com.dingle.template2d.GAME")); } }); } } </code></pre> <p><strong><code>GameView</code> class:</strong> (this is where I put all the game code)</p> <pre><code>package com.dingle.template2d; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.os.Bundle; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.Window; public class GameView extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(new Panel(this)); } public class Panel extends SurfaceView implements SurfaceHolder.Callback{ private MainThread _thread; public Panel(Context context) { super(context); getHolder().addCallback(this); _thread = new MainThread(getHolder(), this); setFocusable(true); } final int windowHeight = getResources().getDisplayMetrics().heightPixels; final int windowWidth = getResources().getDisplayMetrics().widthPixels; final float tscale = getResources().getDisplayMetrics().density; final int scale = (int) tscale; public int _x = 0; public int _y = 0; Bitmap _scratch = BitmapFactory.decodeResource(getResources(), R.drawable.icon); /** * *I Declare everything here * **/ @Override public void onDraw(Canvas canvas) { /** * *I run all my code here * **/ } /* @Override public boolean onTouchEvent(MotionEvent event) { _x = (int) event.getX(); _y = (int) event.getY(); return true; }*/ @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { // TODO Auto-generated method stub } @Override public void surfaceCreated(SurfaceHolder holder) { _thread.setRunning(true); _thread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { // simply copied from sample application LunarLander: // we have to tell thread to shut down &amp; wait for it to finish, or else // it might touch the Surface after we return and explode boolean retry = true; _thread.setRunning(false); while (retry) { try { _thread.join(); retry = false; } catch (InterruptedException e) { // we will try it again and again... } } } } } </code></pre> <p><strong>Main Thread:</strong></p> <pre><code>package com.dingle.template2d; import com.dingle.template2d.GameView.Panel; import android.graphics.Canvas; import android.view.SurfaceHolder; public class MainThread extends Thread { private SurfaceHolder _surfaceHolder; private Panel _panel; private boolean _run = false; public MainThread(SurfaceHolder surfaceHolder, Panel panel) { _surfaceHolder = surfaceHolder; _panel = panel; } public void setRunning(boolean run) { _run = run; } @Override public void run() { Canvas c; while (_run) { c = null; try { c = _surfaceHolder.lockCanvas(null); synchronized (_surfaceHolder) { _panel.onDraw(c); } } finally { // do this in a finally so that if an exception is thrown // during the above, we don't leave the Surface in an // inconsistent state if (c != null) { _surfaceHolder.unlockCanvasAndPost(c); } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-18T19:28:07.987", "Id": "151854", "Score": "0", "body": "When you say you put all the game code in the `GameView` class, do you mean only rendering and UI code? Or are you putting all of your game model in this class also?" } ]
[ { "body": "<p>Notions in no particular order, not probably what you're expecting though:</p>\n\n<p><strong>On the unpredictability of sleep</strong> </p>\n\n<p>In the loop </p>\n\n<pre><code>int waited = 0;\nwhile(_active &amp;&amp; (waited &lt; _splashTime)) {\n sleep(100);\n if(_active) {\n waited += 100;\n }\n}\n</code></pre>\n\n<p>Method <code>sleep</code> might not guarantee that the time slept is actually 100 ms. It might more or it might be less depending on the context and clock accuracy etc. It might be better if you relied on the system clock instead of a counter: </p>\n\n<pre><code>long started = System.currentTimeMillis();\nwhile(_active &amp;&amp; System.currentTimeMillis() - start &lt; _splashTime) {\n sleep(100);\n}\n</code></pre>\n\n<p>If you end up using the <code>waited</code> counter, the <code>if(_active)</code> conditions might not be necessary.</p>\n\n<p><strong>On initial values</strong></p>\n\n<p>If you have no particular reason for defining the variables initial values on separate lines, you could define them in the same line </p>\n\n<pre><code>int waited = 0;\nboolean _active;\nint _splashTime;\n_active = true;\n_splashTime = 500;\n</code></pre>\n\n<p>becomes</p>\n\n<pre><code>int waited = 0;\nboolean _active = true;\nint _splashTime = 500;\n</code></pre>\n\n<p><strong>On naming</strong></p>\n\n<p>I've seen underscore to denote instance variables and I after a quick skimming I thought <code>_active</code>and <code>_splashTime</code> were such. Instead they were local variables. Perhaps not using and underscore might be more conventional.</p>\n\n<p>You use underscore on instance variables as well, which is OK though I'm not a big fan of it. </p>\n\n<p>There's also some inconsistency with variable names with multiple words: compare <code>surfaceHolder</code> and <code>play_button</code>. In Java it's convetional that variable names are in camel-case without spaces; <code>playButton</code> would be better. </p>\n\n<p>Names of classes usually begin with a capital letter e.g. <code>Template2d</code>, <code>Menu</code>.</p>\n\n<p><strong>On constants</strong> </p>\n\n<p>It seems to me you're trying to declare a constant <code>_splashTime</code>. Why not just do so with </p>\n\n<pre><code>public class template2d extends Activity {\n private static final SPLASH_TIME_IN_MILLISECONDS = 500;\n}\n</code></pre>\n\n<p><strong>On visibity</strong> </p>\n\n<p>I would prefer if all instance variables would be either <code>private</code> or <code>final</code>.</p>\n\n<p>It's at least not a bad idea to keep the scope of your variables as small as possible. In </p>\n\n<pre><code>Canvas c;\nwhile (_run) {\n c = null;\n try {\n c = _surfaceHolder.lockCanvas(null);\n synchronized (_surfaceHolder) {\n _panel.onDraw(c);\n }\n } finally {\n // do this in a finally so that if an exception is thrown\n // during the above, we don't leave the Surface in an\n // inconsistent state\n if (c != null) {\n _surfaceHolder.unlockCanvasAndPost(c);\n }\n }\n}\n</code></pre>\n\n<p>The canvas variable <code>c</code> exists outside of the <code>while</code>-loop while it isn't used anywhere but in it. You could declare the variable inside the loop to limit it's scope </p>\n\n<pre><code>while (_run) {\n Canvas c = null;\n try {\n c = _surfaceHolder.lockCanvas(null);\n synchronized (_surfaceHolder) {\n _panel.onDraw(c);\n }\n } finally {\n // do this in a finally so that if an exception is thrown\n // during the above, we don't leave the Surface in an\n // inconsistent state\n if (c != null) {\n _surfaceHolder.unlockCanvasAndPost(c);\n }\n }\n}\n</code></pre>\n\n<p><strong>On order of things</strong></p>\n\n<p>The contents of a class is usually in an order not unline the following</p>\n\n<ol>\n<li>The class signature </li>\n<li>public static constants</li>\n<li>private static constants</li>\n<li>private static variables </li>\n<li>private constants </li>\n<li>private variables</li>\n<li>constructors</li>\n<li>public methods</li>\n<li>private methods</li>\n</ol>\n\n<p>It makes the code harder to follow if there are instance variable declarations in more than one place. </p>\n\n<p>Lately I've been experimenting on how it feels like when everything private is tucked down to the bottom of the class and I like it. Coding conventions trump personal preferences though. </p>\n\n<p><strong>On doing just one thing</strong> </p>\n\n<p>Each class and object should preferably do just one thing i.e. they should have a <a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow noreferrer\">single responsibility</a>. At least the class <code>Panel</code> contain the responsibilities of drawing the surface and responding to events. These two things could be split into two different classes if it makes sense. </p>\n\n<p><strong>On different ways of writing the same code</strong></p>\n\n<p>In this code</p>\n\n<pre><code>retry = true;\nwhile (retry) {\n try {\n _thread.join();\n retry = false;\n } catch (InterruptedException e) {\n // we will try it again and again...\n }\n}\n</code></pre>\n\n<p>You could achieve the same thing with a break statement to get rid of an extra variable</p>\n\n<pre><code>while (true) { // or for(;;)\n try {\n _thread.join();\n break; \n } catch (InterruptedException e) {\n // we will try it again and again...\n }\n} \n</code></pre>\n\n<p>or defining the logic in a method to describe your intent more clearly</p>\n\n<pre><code>while(!hasThreadStopped) {\n // Retry until thread stops\n} \n...\n\nprivate boolean hasThreadStopped() {\n try {\n _thread.join();\n return true;\n } catch (InterruptedException e) {\n return false;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T13:33:15.923", "Id": "5781", "Score": "0", "body": "Thankyou, this is the exact critism i was looking for, could you please tell me more about running all my code in the draw event?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T13:34:40.587", "Id": "5782", "Score": "0", "body": "i used to use game maker, so there was always a \"Step\" event and a \"Draw\" event, the step event was where all code that wasnt needed for drawing was executed, is there something like this in java? as im just not seeing it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T16:13:26.223", "Id": "5783", "Score": "0", "body": "You have to implement the step and draw events yourself because java doesn't provide certain specialized abstractions out of the box. I may elaborate this later if nobody else is faster." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T08:14:58.713", "Id": "5797", "Score": "0", "body": "+1 esp on the underscore before variable name. _varname is an old habit of C programmer, and while it's okay to compile, using this underscore should not be encouraged." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T11:55:01.173", "Id": "5801", "Score": "0", "body": "@Aleksi i would very much like to hear about the step event, i have some big projects planned, and i need everything to run as smooth as possible" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2011-08-03T10:40:15.263", "Id": "3839", "ParentId": "3838", "Score": "13" } }, { "body": "<p>I cannot comment on 2D gaming but will suggest a better alternative of creating a thread to delay the splash screen. Instead of…</p>\n\n<blockquote>\n<pre><code>// thread for displaying the SplashScreen\nThread splashTread = new Thread() {\n @Override\n public void run() {\n try {\n int waited = 0;\n boolean _active;\n int _splashTime;\n _active = true;\n _splashTime = 500;\n while(_active &amp;&amp; (waited &lt; _splashTime)) {\n sleep(100);\n if(_active) {\n waited += 100;\n }\n }\n startActivity(new Intent(\"com.dingle.template2d.MENU\"));\n } catch(InterruptedException e) {\n // do nothing\n } finally {\n finish();\n\n\n }\n }\n};\nsplashTread.start();\n</code></pre>\n</blockquote>\n\n<p><code>Handler().postDelayed</code> will call the run method of runnable after set time and redirect to your menu.</p>\n\n<pre><code>new Handler().postDelayed(new Runnable() {\n @Override\n public void run() {\n startActivity(new Intent(\"com.dingle.template2d.MENU\"));\n finish();\n }\n }, 5000);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-18T19:22:33.520", "Id": "84391", "ParentId": "3838", "Score": "8" } } ]
{ "AcceptedAnswerId": "3839", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T08:35:11.160", "Id": "3838", "Score": "8", "Tags": [ "java", "game", "android", "template" ], "Title": "Template for creating 2D games" }
3838
<p>How would I accomplish the same thing in a functional paradigm?</p> <pre><code>Player.prototype.d2 = function(ratingList, rdList) { var tempSum = 0; for (var i = 0; i &lt; ratingList.length; i++) { var tempE = this.e(ratingList[i], rdList[i]); tempSum += Math.pow(this.g(rdList[i]), 2) * tempE * (1 - tempE); } return 1 / Math.pow(q, 2) * tempSum; }; </code></pre>
[]
[ { "body": "<p>I think something like this will work for you.</p>\n\n<pre><code>Array.prototype.zip = function(other) {\n if (!Array.prototype.isPrototypeOf(other)) {\n throw new TypeError('Expecting an array dummy!');\n }\n if (this.length !== other.length) {\n throw new Error('Must be the same length!');\n }\n var r = [];\n for (var i = 0, length = this.length; i &lt; length; i++) {\n r.push([this[i], other[i]]); \n }\n return r;\n};\n\nPlayer.prototype.d2 = function (ratingList, rdList) {\n var self = this;\n return 1 / Math.pow(q, 2) *\n ratingList\n .zip(rdList)\n .map(function (elem) {\n var tempE = self.e(elem[0], elem[1]);\n return Math.pow(self.g(elem[1]), 2) * tempE * (1 - tempE);\n })\n .reduce(function (acc, value) {\n return acc + value;\n });\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-05T12:16:40.367", "Id": "5848", "Score": "0", "body": "Do you actually need `var self = this`? I haven't had to use that anywhere else so far." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-06T18:09:47.680", "Id": "5878", "Score": "0", "body": "@Austin - Yes you do need it. Try removing it and see what happens." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T16:59:58.443", "Id": "5944", "Score": "0", "body": "I'm guessing it's because inside the `map` function, `this` would refer to uh... Array.prototype?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-08T17:18:53.450", "Id": "5945", "Score": "0", "body": "@Austin - I believe that it will normally be the global object." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-12T00:09:03.223", "Id": "304100", "Score": "0", "body": "@ChaosPandion: interesting approach with zip, to make tuples :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-12T00:12:02.997", "Id": "304101", "Score": "0", "body": "You would only need to do \"var self = this\" if you don't use Arrow functions. Otherwise you could always use scoped references like \" return Math.pow( Player.g(elem[1]), 2) * tempE * (1 - tempE);\"" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T15:30:05.510", "Id": "3845", "ParentId": "3842", "Score": "1" } }, { "body": "<p>I think this is essentially what you're looking for, if I'm not mistaken:</p>\n\n<pre><code>Player.prototype.d2 = function(ratingList, rdList) {\n return Math.pow(q, -2) * ( \n ratingList.reduce( ( sum, val, idx ) =&gt; {\n let tempE = this.e( val, rdList[idx] );\n return sum + Math.pow( this.g(rdList[idx]), 2 ) * tempE * ( 1 - tempE ); \n }, 0)\n );\n};\n</code></pre>\n\n<p>We start out with an anonymous function for <code>d2</code>, whose body is simply a return of the entire functional expression, which uses the <code>Array.prototype.reduce</code> function to compose a sum.</p>\n\n<p>I've chosen to use ES6 so I can maintain scope <code>this</code> throughout my entire function.</p>\n\n<p><a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce\" rel=\"nofollow noreferrer\">Reduce explained on MDN</a> and you should checkout <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions\" rel=\"nofollow noreferrer\">Arrow functions</a>.</p>\n\n<p>One thing to note: a <code>for</code> loop is more performant than functional equivalents.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-12T00:14:53.497", "Id": "304102", "Score": "0", "body": "Do you realize this question is almost six years old?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-12T00:16:26.733", "Id": "304103", "Score": "1", "body": "lol, i do now..... it's been a long day." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-12T01:34:49.663", "Id": "304107", "Score": "1", "body": "Actually, I like this because the accepted answer is a code-only answer, which we consider low-quality here. It only gets a pass because it's old and accepted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-13T21:51:06.673", "Id": "304593", "Score": "0", "body": "@r10y It's actually `1 / Math.pow(q, 2) …`, which could be written as `Math.pow(q, -2) …`. Also a little detail – you're missing a semicolon after `return`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-13T23:33:04.713", "Id": "304609", "Score": "0", "body": "cool, updated my answer to reflect your feedback. thanks." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-04-12T00:01:57.497", "Id": "160488", "ParentId": "3842", "Score": "1" } } ]
{ "AcceptedAnswerId": "3845", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T14:25:18.877", "Id": "3842", "Score": "1", "Tags": [ "javascript", "functional-programming" ], "Title": "Replacing a for loop that iterates over an array with the functional programming equivalent" }
3842
<p>This is my personal project. This class is responsible for running jobs asynchronously that are registered using dependency injection.</p> <p>All improvement suggestions are welcome. It can be as small as using a better name for a variable, re-architect the whole class, whatever. I'm just trying to improve myself.</p> <p><a href="https://github.com/kayone/NzbDrone/blob/master/NzbDrone.Core/Providers/Jobs/JobProvider.cs" rel="nofollow">GitHub</a></p> <pre><code>using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Threading; using Ninject; using NLog; using NzbDrone.Core.Model.Notification; using NzbDrone.Core.Repository; using PetaPoco; namespace NzbDrone.Core.Providers.Jobs { /// &lt;summary&gt; /// Provides a background task runner, tasks could be queue either by the scheduler using QueueScheduled() /// or by explicitly calling QueueJob(type,int) /// &lt;/summary&gt; public class JobProvider { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private readonly IDatabase _database; private readonly NotificationProvider _notificationProvider; private readonly IList&lt;IJob&gt; _jobs; private static readonly object ExecutionLock = new object(); private Thread _jobThread; private static bool _isRunning; private static readonly List&lt;Tuple&lt;Type, Int32&gt;&gt; _queue = new List&lt;Tuple&lt;Type, int&gt;&gt;(); private ProgressNotification _notification; [Inject] public JobProvider(IDatabase database, NotificationProvider notificationProvider, IList&lt;IJob&gt; jobs) { _database = database; _notificationProvider = notificationProvider; _jobs = jobs; } /// &lt;summary&gt; /// Initializes a new instance of the &lt;see cref="JobProvider"/&gt; class. by AutoMoq /// &lt;/summary&gt; /// &lt;remarks&gt;Should only be used by AutoMoq&lt;/remarks&gt; [EditorBrowsable(EditorBrowsableState.Never)] public JobProvider() { } /// &lt;summary&gt; /// Gets the active queue. /// &lt;/summary&gt; public static List&lt;Tuple&lt;Type, Int32&gt;&gt; Queue { get { return _queue; } } /// &lt;summary&gt; /// Returns a list of all registered jobs /// &lt;/summary&gt; public virtual List&lt;JobDefinition&gt; All() { return _database.Fetch&lt;JobDefinition&gt;().ToList(); } /// &lt;summary&gt; /// Adds/Updates definitions for a job /// &lt;/summary&gt; /// &lt;param name="definitions"&gt;Settings to be added/updated&lt;/param&gt; public virtual void SaveDefinition(JobDefinition definitions) { if (definitions.Id == 0) { Logger.Trace("Adding job definitions for {0}", definitions.Name); _database.Insert(definitions); } else { Logger.Trace("Updating job definitions for {0}", definitions.Name); _database.Update(definitions); } } /// &lt;summary&gt; /// Iterates through all registered jobs and queues any that are due for an execution. /// &lt;/summary&gt; /// &lt;remarks&gt;Will ignore request if queue is already running.&lt;/remarks&gt; public virtual void QueueScheduled() { lock (ExecutionLock) { if (_isRunning) { Logger.Trace("Queue is already running. Ignoring scheduler's request."); return; } } var counter = 0; var pendingJobs = All().Where( t =&gt; t.Enable &amp;&amp; (DateTime.Now - t.LastExecution) &gt; TimeSpan.FromMinutes(t.Interval) ).Select(c =&gt; _jobs.Where(t =&gt; t.GetType().ToString() == c.TypeName).Single()); foreach (var job in pendingJobs) { QueueJob(job.GetType()); counter++; } Logger.Trace("{0} Scheduled tasks have been added to the queue", counter); } /// &lt;summary&gt; /// Queues the execution of a job asynchronously /// &lt;/summary&gt; /// &lt;param name="jobType"&gt;Type of the job that should be queued.&lt;/param&gt; /// &lt;param name="targetId"&gt;The targetId could be any Id parameter eg. SeriesId. it will be passed to the job implementation /// to allow it to filter it's target of execution.&lt;/param&gt; /// &lt;remarks&gt;Job is only added to the queue if same job with the same targetId doesn't already exist in the queue.&lt;/remarks&gt; public virtual void QueueJob(Type jobType, int targetId = 0) { Logger.Debug("Adding [{0}:{1}] to the queue", jobType.Name, targetId); lock (ExecutionLock) { lock (Queue) { var queueTuple = new Tuple&lt;Type, int&gt;(jobType, targetId); if (!Queue.Contains(queueTuple)) { Queue.Add(queueTuple); Logger.Trace("Job [{0}:{1}] added to the queue", jobType.Name, targetId); } else { Logger.Info("[{0}:{1}] already exists in the queue. Skipping.", jobType.Name, targetId); } } if (_isRunning) { Logger.Trace("Queue is already running. No need to start it up."); return; } _isRunning = true; } if (_jobThread == null || !_jobThread.IsAlive) { Logger.Trace("Initializing queue processor thread"); ThreadStart starter = () =&gt; { try { ProcessQueue(); } catch (Exception e) { Logger.ErrorException("Error has occurred in queue processor thread", e); } finally { _isRunning = false; } }; _jobThread = new Thread(starter) { Name = "JobQueueThread" }; _jobThread.Start(); } else { Logger.Error("Execution lock has fucked up. Thread still active. Ignoring request."); } } /// &lt;summary&gt; /// Starts processing of queue synchronously. /// &lt;/summary&gt; private void ProcessQueue() { do { Tuple&lt;Type, int&gt; job = null; using (NestedDiagnosticsContext.Push(Guid.NewGuid().ToString())) { try { lock (Queue) { if (Queue.Count != 0) { job = Queue.First(); } } if (job != null) { Execute(job.Item1, job.Item2); } } catch (Exception e) { Logger.FatalException("An error has occurred while processing queued job.", e); } finally { if (job != null) { Queue.Remove(job); } } } } while (Queue.Count != 0); Logger.Trace("Finished processing jobs in the queue."); return; } /// &lt;summary&gt; /// Executes the job synchronously /// &lt;/summary&gt; /// &lt;param name="jobType"&gt;Type of the job that should be executed&lt;/param&gt; /// &lt;param name="targetId"&gt;The targetId could be any Id parameter eg. SeriesId. it will be passed to the timer implementation /// to allow it to filter it's target of execution&lt;/param&gt; private void Execute(Type jobType, int targetId = 0) { var jobImplementation = _jobs.Where(t =&gt; t.GetType() == jobType).Single(); if (jobImplementation == null) { Logger.Error("Unable to locate implementation for '{0}'. Make sure it is properly registered.", jobType); return; } var settings = All().Where(j =&gt; j.TypeName == jobType.ToString()).Single(); using (_notification = new ProgressNotification(jobImplementation.Name)) { try { Logger.Debug("Starting '{0}' job. Last execution {1}", settings.Name, settings.LastExecution); var sw = Stopwatch.StartNew(); _notificationProvider.Register(_notification); jobImplementation.Start(_notification, targetId); _notification.Status = ProgressNotificationStatus.Completed; settings.LastExecution = DateTime.Now; settings.Success = true; sw.Stop(); Logger.Debug("Job '{0}' successfully completed in {1}.{2} seconds.", jobImplementation.Name, sw.Elapsed.Seconds, sw.Elapsed.Milliseconds / 100, sw.Elapsed.Seconds); } catch (Exception e) { Logger.ErrorException("An error has occurred while executing job " + jobImplementation.Name, e); _notification.Status = ProgressNotificationStatus.Failed; _notification.CurrentMessage = jobImplementation.Name + " Failed."; settings.LastExecution = DateTime.Now; settings.Success = false; } } //Only update last execution status if was triggered by the scheduler if (targetId == 0) { SaveDefinition(settings); } } /// &lt;summary&gt; /// Initializes jobs in the database using the IJob instances that are /// registered using ninject /// &lt;/summary&gt; public virtual void Initialize() { Logger.Debug("Initializing jobs. Count {0}", _jobs.Count()); var currentTimer = All(); foreach (var timer in _jobs) { var timerProviderLocal = timer; if (!currentTimer.Exists(c =&gt; c.TypeName == timerProviderLocal.GetType().ToString())) { var settings = new JobDefinition { Enable = timerProviderLocal.DefaultInterval &gt; 0, TypeName = timer.GetType().ToString(), Name = timerProviderLocal.Name, Interval = timerProviderLocal.DefaultInterval, LastExecution = new DateTime(2000, 1, 1) }; SaveDefinition(settings); } } } /// &lt;summary&gt; /// Gets the next scheduled run time for a specific job /// (Estimated due to schedule timer) /// &lt;/summary&gt; /// &lt;returns&gt;DateTime of next scheduled job execution&lt;/returns&gt; public virtual DateTime NextScheduledRun(Type jobType) { var job = All().Where(t =&gt; t.TypeName == jobType.ToString()).Single(); return job.LastExecution.AddMinutes(job.Interval); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T17:56:09.113", "Id": "5785", "Score": "1", "body": "You should try to focus your review question to a particular area. See FAQ: http://codereview.stackexchange.com/faq#make-sure-you-include-your-code-in-your-question" } ]
[ { "body": "<p>Taking the processqueue part.... I'd do something like :- </p>\n\n<pre><code> private void ExecuteJob(Tuple&lt;Type,int&gt; job)\n {\n try\n { \n Execute(job.Item1, job.Item2); \n } \n catch (Exception e)\n {\n using (NestedDiagnosticsContext.Push(Guid.NewGuid().ToString()))\n {\n Logger.FatalException(\"An error has occurred while processing queued job.\", e);\n }\n }\n\n }\n\n private void ProcessQueue()\n { \n List&lt;Tuple&lt;Type, int&gt;&gt; jobs;\n lock (Queue)\n {\n jobs = Queue.ToList();\n Queue.Clear(); \n }\n jobs.ForEach(ExecuteJob); \n Logger.Trace(\"Finished processing jobs in the queue.\");\n }\n</code></pre>\n\n<p>This means you only lock once ( you have a bug in that you don't lock when you remove), your try catch is finer grained, your using is finer grained. </p>\n\n<p>But the I'd probably turn the tuple into a Class. The rest of the code has similar issues.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T05:01:11.577", "Id": "3856", "ParentId": "3848", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T16:33:50.957", "Id": "3848", "Score": "4", "Tags": [ "c#", "asynchronous", "scheduled-tasks" ], "Title": "Asynchronous task runner" }
3848
<p>I am learning Scala while solving some exercises and I am currently solving an exercise where I need to initialize a <a href="http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes" rel="nofollow">Sieve of Eratosthenes</a>.</p> <p>I am using the following code:</p> <pre><code> val sieve = Array.fill[Boolean](100)(true) for (p &lt;- 2 until sieve.length if sieve(p) &amp;&amp; math.pow(p, 2) &lt;= sieve.length) { for (i &lt;- p * 2 until sieve.length by p) { sieve(i) = false } } </code></pre> <p>I see some problems with this approach, for example, the outer loop still evaluates all numbers from some Y until sieve.length to test the condition <code>sieve(p) &amp;&amp; math.pow(p,2) &lt;= sieve.length</code>, although the code inside the loop is not executed for those values of <code>p</code>.</p> <p>I think this could be solved with the following code:</p> <pre><code> var p = 2 while(math.pow(p, 2) &lt;= sieve.length) { if(sieve(p)) for (i &lt;- p * 2 until sieve.length by p) sieve(i) = false p += 1 } </code></pre> <p>I may be wrong, but I think I am complicating too much.</p> <p>What's a good way to initialize a Sieve of Eratosthenes using Scala?</p>
[]
[ { "body": "<p>There are many other ways of writing a Sieve of Eratosthenes in Scala. Regarding this particular code, the for-comprehension is better written as:</p>\n\n<pre><code>val sieve = Array.fill[Boolean](100)(true)\n\nfor {\n p &lt;- 2 until sieve.length \n if sieve(p) &amp;&amp; math.pow(p, 2) &lt;= sieve.length\n i &lt;- p * 2 until sieve.length by p\n} sieve(i) = false\n</code></pre>\n\n<p>Also,</p>\n\n<blockquote>\n <p>the outer loop still evaluates all numbers from some <code>Y</code> until\n <code>sieve.length</code> to test the condition <code>sieve(p) &amp;&amp; math.pow(p,2) &lt;=\n sieve.length</code>,</p>\n</blockquote>\n\n<p>You could compute the square root too, though that's an expensive computation. You can use <code>takeWhile</code> to avoid it:</p>\n\n<pre><code>p &lt;- 2 until sieve.length takeWhile (x =&gt; x * x &lt; sieve.length)\n</code></pre>\n\n<p>Also, the starting place of the final loop can be improved:</p>\n\n<pre><code>i &lt;- p * p until sieve.length by p\n</code></pre>\n\n<p>Altogether, you get this:</p>\n\n<pre><code>val sieve = Array.fill[Boolean](100)(true)\n\nfor {\n p &lt;- 2 until sieve.length takeWhile (x =&gt; x * x &lt; sieve.length)\n if sieve(p)\n i &lt;- p * p until sieve.length by p\n} sieve(i) = false\n</code></pre>\n\n<p>Now, I wouldn't use booleans for this, nor an <code>Array</code>. Instead, my preferred implementation (for efficiency) uses <code>BitSet</code> instead. For example:</p>\n\n<pre><code>val last = 100\nval numbers = 2 to last\nval sieve = collection.mutable.BitSet(numbers: _*)\nfor (p &lt;- numbers takeWhile (x =&gt; x * x &lt;= last) if sieve(p))\n sieve --= p * p to last by p\n</code></pre>\n\n<p>There are other implementations I value for their functional nature, but I'll leave that to others.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-07T00:28:49.347", "Id": "5894", "Score": "0", "body": "Thanks, I didn't know I could pass a {} block to a for like that.\nHow about the _* you used to initialize the BitSet, where is that documented?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-07T16:20:20.660", "Id": "5907", "Score": "0", "body": "@simao you'll probably find that documented where varargs are discussed. It is just a wa of saying that the sequence elements are the parameters, instead of the sequence itself being one parameter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-07T16:22:00.410", "Id": "5908", "Score": "0", "body": "ah! so i guess it's like python's *args and **kwargs syntax. Thanks!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T00:03:04.890", "Id": "3853", "ParentId": "3850", "Score": "6" } } ]
{ "AcceptedAnswerId": "3853", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-03T22:31:20.920", "Id": "3850", "Score": "3", "Tags": [ "scala", "sieve-of-eratosthenes" ], "Title": "Initialize a Sieve of Eratosthenes in Scala" }
3850
<p>I am working on using STL and in general safe C++ practices. Instead of posting large samples of code I am working with a small sample to catch problems before I move onto larger ones.</p> <p>How do you find out if an <code>istringstream</code> found an input that is not of the desired type? That is, you have a string and you want to verify if it is a <code>float</code> or not.</p> <p>Using the program below, when I input </p> <blockquote> <pre><code>[mehoggan@desktop argument_processing]$ ./args 1 2 3 4 2y </code></pre> </blockquote> <p>I get:</p> <blockquote> <pre><code>1 2 3 4 2 </code></pre> </blockquote> <p>which is not what I want, since not all arguments where numeric.</p> <p>I should of gotten:</p> <blockquote> <pre><code>ERROR: 2y is not numeric </code></pre> </blockquote> <p>What improvements would you make to this small program?</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;sstream&gt; #include &lt;iterator&gt; namespace CLP { using std::vector; using std::istringstream; using std::string; using std::cerr; using std::endl; vector&lt;float&gt; all_numeric_arguments( int argc, char *argv[ ] ) { vector&lt;float&gt; v_argv; vector&lt;string&gt; v_tmp; copy( &amp;argv[1],&amp;argv[argc],back_inserter( v_tmp ) ); for( vector&lt;string&gt;::iterator it=v_tmp.begin( );it!=v_tmp.end( );it++ ) { istringstream iss( (*it) ); float f=0.0; if( iss &gt;&gt; f &gt;&gt; std::dec ) { v_argv.push_back( f ); } else { cerr &lt;&lt; "ERROR: " &lt;&lt; (*it) &lt;&lt; " is not numeric " &lt;&lt; endl; return v_argv; } } return v_argv; } } int main( int argc, char *argv[ ] ) { std::vector&lt;float&gt; v = CLP::all_numeric_arguments( argc, argv ); if( v.size( ) == (unsigned)(argc-1) ) { copy( v.begin( ),v.end( ),std::ostream_iterator&lt;float&gt;( std::cout," " ) ); std::cout &lt;&lt; std::endl; } } </code></pre>
[]
[ { "body": "<p>Here are two small points regarding the formatting:</p>\n\n<ol>\n<li><p>In <code>all_numeric_arguments</code> after introducing <code>v_tmp</code>, you should call <code>v_tmp.reserve(argc);</code> so that you won't do to many reallocations. (This is purely an optimization which is probably not important in this example, but since you know the size it is a good idea.)</p></li>\n<li><p>In the <code>for</code> loop, you should use <code>const_iterator</code>s to make clear that you won't modify <code>v_tmp</code>. Also (another optimization which is simply a good habit) do not call <code>v_tmp</code> repeatedly.</p>\n\n<p>So your <code>for</code> loop should read like this:</p>\n\n<pre><code>for( vector&lt;string&gt;::const_iterator it = v_tmp.begin(),\n end = v_tmp.end();\n it != end ; ++it )\n{\n //...\n}\n</code></pre>\n\n<p>or if you can use C++0x already:</p>\n\n<pre><code>for (auto it = v_tmp.cbegin(), end = v_tmp.cend(); it != end; ++it) { /* ... */ }\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-28T10:28:38.613", "Id": "97368", "Score": "1", "body": "If C++0x is available then why use iterators (if they are not needed)? `for(auto const& elem: v_tmp){/*...*/}` is much more concise." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T09:41:22.160", "Id": "3866", "ParentId": "3857", "Score": "4" } }, { "body": "<p>In your case, you apparently want to verify that there was not only a successful conversion, but also that the conversion consumed all the input. Given that this is exactly what Boost <code>lexical_cast</code> does, my immediate advice would be to use its existing code to do the job. If you can't do that, I'd still write a similar function, and probably give it the same name, so people who already know about <code>lexical_cast</code> will be able to recognize what you're doing without having to read through the code to do it.</p>\n\n<p>As far as other changes go, rather than using <code>std::copy</code> to copy <code>argv</code> into <code>v_tmp</code>, I'd probably just initialize <code>v_tmp</code> from <code>argv</code>. I'd also note that <code>&amp;x[y]</code> is generally equivalent to <code>x+y</code>, and simplify that part of the code a bit, giving:</p>\n\n<pre><code>std::vector&lt;string&gt; v_tmp(argv+1, argv+argc);\n</code></pre>\n\n<p>That gives us code that looks like:</p>\n\n<pre><code>template&lt;typename Target, typename Source&gt;\nTarget lexical_cast(const Source&amp; arg) { \n // ...\n}\n\nstd::vector&lt;string&gt; v_tmp(argv+1, argv+argc);\nvector&lt;float&gt; v_argv;\n\nfor (int i=0; i&lt;v_tmp.size(); i++)\n v_argv.push_back(lexical_cast&lt;float&gt;(v_tmp[i]);\n</code></pre>\n\n<p>That does leave one real question, however: exactly how you want to signal the fact that your <code>lexical_cast</code> has failed. Boost <code>lexical_cast</code> throws an exception. One possible alternative to that would be to return a NaN instead. I'm not at all sure I'd recommend that, but I can imagine situations where it might be the preferred way to go.</p>\n\n<p>Assuming you go the route of throwing an exception, the code would change to something like this:</p>\n\n<pre><code>for (int i=0; i&lt;v_tmp.size(); i++) {\n try { \n v_argv.push_back(lexical_cast&lt;float&gt;(v_tmp[i]));\n }\n catch (bad_lexical_cast const &amp;) {\n std::cerr &lt;&lt; \"Error: \" &lt;&lt; v_tmp[i] &lt;&lt; \" is not numeric.\\n\";\n }\n}\n</code></pre>\n\n<p>That leaves us with the definition of <code>lexical_cast</code> itself. Most of it would quite obviously be essentially identical to the code you had, just adding a check that after we do the conversion, the stream is empty:</p>\n\n<pre><code>template&lt;typename Target, typename Source&gt;\nTarget lexical_cast(const Source&amp; arg) { \n istringstream iss(arg);\n Target f = Target(); // generic equivalent to your `0.0` initialization\n\n iss &gt;&gt; f;\n char c;\n\n // if the conversion failed, or we can read another character, we \n // couldn't convert, or there's data left in the stream, which we \n // consider a failure.\n if (iss.fail() || iss.get(c))\n throw bad_lexical_cast();\n return f;\n}\n</code></pre>\n\n<p>Since that's throwing a <code>bad_lexical_cast</code>, we'll also have to define that type. In this case, we'll keep it simple:</p>\n\n<pre><code>class bad_lexical_cast {};\n</code></pre>\n\n<p>In reality, you <em>usually</em> want to derive your exception classes (directly or indirectly) from <code>std::exception</code> (unless you've defined a similar hierarchy of your own -- in any case you typically want a common base class for all your exceptions). You probably also want to include an indication of what failed and why in the exception object itself, so the code that catches it doesn't need as much information about what was being done at the time as we used here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T14:55:55.577", "Id": "3874", "ParentId": "3857", "Score": "7" } } ]
{ "AcceptedAnswerId": "3874", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T05:16:58.077", "Id": "3857", "Score": "6", "Tags": [ "c++", "strings", "console" ], "Title": "Determining which command line arguments are numeric" }
3857
<p>Looking at <code>$wpdb</code> class, I found <code>get_row</code>, and I am unsure if the function automatically prepares the query. I believe it does not and I may have to reexamine my code to prevent a future disaster.</p> <p>Here is what my code looks, and I feel that it is vulnerable:</p> <pre><code>$wpdb-&gt;get_row("SELECT * FROM `my_table` WHERE column = '".$_GET['fromUrl']."'", ARRAY_A); </code></pre> <p>However, I have tried injecting a malicious input with the follow: <code>' or column = 'value'</code></p> <p>And it seems not to work, should I go ahead and prepare my statements anyway?</p>
[]
[ { "body": "<p>Yes, you should prepare the statement or at least SQL escape the value of <code>$_GET['fromUrl']</code>. It's good practice to be paranoid about any input potentially provided by the user as it will be wrong at some point. </p>\n\n<p>The <a href=\"http://codex.wordpress.org/Class_Reference/wpdb#Protect_Queries_Against_SQL_Injection_Attacks\" rel=\"nofollow\">wpdb-reference</a> says:</p>\n\n<blockquote>\n <p>Briefly, though, all data in SQL queries <strong>must be SQL-escaped</strong>\n before the SQL query is executed to prevent against SQL injection\n attacks.</p>\n</blockquote>\n\n<p>The prepared query would look something like this </p>\n\n<pre><code>$wpdb-&gt;get_row(\n $wpdb-&gt;prepare(\"SELECT * FROM `my_table` WHERE column = %s\",\n $_GET['fromUrl']),\n ARRAY_A);\n</code></pre>\n\n<p>which in my opinion is more readable, particularly the SQL query is easier to follow.</p>\n\n<p>Furthermore, inspecting the user input may allow you provide the user better experience by creating meaningful notifications describing what has happened and how the user can cope with the inconvinience. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T10:48:11.090", "Id": "3869", "ParentId": "3862", "Score": "2" } } ]
{ "AcceptedAnswerId": "3869", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-08-04T08:17:54.297", "Id": "3862", "Score": "2", "Tags": [ "php", "mysql", "security", "wordpress" ], "Title": "Wordpress $wpdb->row Query Check" }
3862