body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I often find myself writing code as follows...</p> <pre><code>var startX, startY, dragging = false, element = document.getElementById("whatever"); var start = function(e){ dragging = true; startX = e.pageX; startY = e.pageY; element.style.opacity = 0.5; } var move = function(e){ if (!dragging) return; var deltaX = startX - e.pageX; var deltaY = startY - e.pageY; //apply to element } var end = function(e){ dragging = false; element.style.opacity = 1; } element.addEventListener("mousedown", start, false); document.addEventListener("mousemove", move, false); document.addEventListener("mouseup", end, false); </code></pre> <p>Now, my problem is really basic, it feels to me that the functions should be auxiliary and belong to the bottom part of my program, but I don't know how to attach the functions to the event listeners without declaring them first. How do I restructure my code so that it is more evident what I'm going to do with these functions?</p>
[]
[ { "body": "<p>You could simply declare the functions inline, like:</p>\n\n<pre><code>element.addEventListener(\"mousedown\", function (e){\n dragging = true;\n startX = e.pageX;\n startY = e.pageY;\n element.style.opacity = 0.5;\n}, false);\n</code></pre>\n\n<p>And likewise for the other 2 functions.</p>\n\n<p>But that can get messy in a hurry. Especially because <code>startX</code>, <code>startY</code> and <code>dragging</code> would still be outside.</p>\n\n<p>So instead you could put the handler in an object literal, just to keep them separated:</p>\n\n<pre><code>var dragEvents, element = document.getElementById(\"whatever\"),\n\ndragEvents = (function () {\n var dragging = false, startX, startY;\n return {\n start: function (e){\n dragging = true;\n startX = e.pageX;\n startY = e.pageY;\n element.style.opacity = 0.5;\n },\n\n move: function (e){\n if (!dragging) return;\n var deltaX = startX - e.pageX;\n var deltaY = startY - e.pageY;\n //apply to element\n },\n\n end: function(e){\n dragging = false;\n element.style.opacity = 1;\n }\n };\n}());\n\nelement.addEventListener(\"mousedown\", dragEvents.start, false);\ndocument.addEventListener(\"mousemove\", dragEvents.move, false);\ndocument.addEventListener(\"mouseup\", dragEvents.end, false);\n</code></pre>\n\n<p>I've wrapped it in an immediately invoked function so the dragging-related vars can be kept in there too.</p>\n\n<p>However, might as well go the extra step and put everything in a function, instead of relying on <code>element</code> being a closure:</p>\n\n<pre><code>function makeDraggable(elementId) {\n var startX,\n startY,\n dragging = false,\n element = document.getElementById(elementId);\n\n function start(e){\n dragging = true;\n startX = e.pageX;\n startY = e.pageY;\n element.style.opacity = 0.5;\n }\n\n function move(e){\n if (!dragging) return;\n var deltaX = startX - e.pageX;\n var deltaY = startY - e.pageY;\n //apply to element\n }\n\n function end(e){\n dragging = false;\n element.style.opacity = 1;\n }\n element.addEventListener(\"mousedown\", start, false);\n document.addEventListener(\"mousemove\", move, false);\n document.addEventListener(\"mouseup\", end, false);\n}\n</code></pre>\n\n<p>The last suggestion I'd make would be to skip the <code>dragging</code> variable in favor of simply adding the <code>move</code> and <code>end</code> handlers on mouse down, and removing them on mouse up, like so:</p>\n\n<pre><code>function makeDraggable(elementId) {\n var startX,\n startY,\n element = document.getElementById(elementId);\n\n function move(e){\n var deltaX = startX - e.pageX;\n var deltaY = startY - e.pageY;\n //apply to element\n }\n\n function end(e){\n element.style.opacity = 1;\n element.removeEventListener(\"mousedown\", move, false);\n element.removeEventListener(\"mousedown\", end, false);\n }\n\n element.addEventListener(\"mousedown\", function (e){\n startX = e.pageX;\n startY = e.pageY;\n element.style.opacity = 0.5;\n document.addEventListener(\"mousemove\", move, false);\n document.addEventListener(\"mouseup\", end, false);\n }, false);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T15:42:57.977", "Id": "27872", "Score": "0", "body": "Why is `dragging` a bad pattern? I've read that keeping state is bad in programming, but I'm not sure if it's related to this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T16:20:19.663", "Id": "27874", "Score": "0", "body": "@Duopixel Personally, I just find it more straightforward to only have the event handlers there, when they're needed, instead of having them fire for _every_ mousemove and mouseup. No need to explicitly keep state" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T11:43:16.570", "Id": "17522", "ParentId": "17521", "Score": "2" } }, { "body": "<p>You can use <em>hoisting</em>. Declare the functions wherever you want, in this case, later, but declare them this way:</p>\n\n<pre><code>function start(e){\n\n}\n</code></pre>\n\n<p>When declared this way, they are hoisted (<a href=\"https://stackoverflow.com/a/7610883/401137\">read about it here</a>), and can be used before the declaration.</p>\n\n<p>Your code, restructured, would look like this:</p>\n\n<pre><code>var startX, startY, dragging = false, element = document.getElementById(\"whatever\");\n\n\n\nelement.addEventListener(\"mousedown\", start, false);\ndocument.addEventListener(\"mousemove\", move, false);\ndocument.addEventListener(\"mouseup\", end, false);\n\nfunction start(e){\n dragging = true;\n startX = e.pageX;\n startY = e.pageY;\n element.style.opacity = 0.5;\n}\n\nfunction move(e){\n if (!dragging) return;\n var deltaX = startX - e.pageX;\n var deltaY = startY - e.pageY;\n //apply to element\n}\n\nfunction end(e){\n dragging = false;\n element.style.opacity = 1;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T15:40:12.850", "Id": "27871", "Score": "0", "body": "I've been using javascript for so long and I had no idea about hoisting, thanks so much!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T15:59:34.680", "Id": "27873", "Score": "0", "body": "@Duopixel Sure. Not many people do." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T15:18:17.713", "Id": "17524", "ParentId": "17521", "Score": "2" } } ]
{ "AcceptedAnswerId": "17524", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T11:22:05.620", "Id": "17521", "Score": "1", "Tags": [ "javascript" ], "Title": "How to reorganize event listeners in javascript" }
17521
<p>Problem:</p> <blockquote> <p>Given a randomly ordered array of <em>n</em>-elements, partition the elements into two subsets such that elements &lt;= x are in one subset and elements</p> <blockquote> <p>x are in the other subset.</p> </blockquote> <p>One way to do this is to sort the array in ascending order. But with this solution we actually ordered the array in addition to partition. Also sort is costly.</p> <p>For example, let's take this array \$[37,36,27,11,15,12,34,29,4,10]\$ and partition value is <code>17</code>.</p> <p>So the array after partition should be \$[10,4,12,11,15,27,34.29.36,37]\$</p> <p>Comparing these two data sets we can see that elements from left side greater than 17 must be moved to right side and at the right side elements less than 17 to left side.</p> <p>Initially we do not know how many elements are less than &lt; 17. One way to solve this, pass through the array and count the number of elements less than 17. Once we know the partition value (here it is 15), then make another pass through the array to make the exchange. But this is \$0(n^2)\$.</p> <p>We need to find a solution where this can be done with only pass through the array. Looking at these data sets we can find that even if we do not know the partition value(here it is 17), 37 can be exchanged with 10, 36 can be exchanged with 4 and so on.</p> <p>This is something like left partition is growing to right and right is growing to left.</p> <pre><code>| Left Partition -&gt; || &lt;- Right Partition | ^ ^ ^ i=0 partition point j=n (length of array) </code></pre> <p>So we get the basic mechanism to exchange, while two partitions have not met do</p> <ol> <li>Extend the left and right partitions inward exchanging wrongly placed elements.</li> <li><p>Exchange can be done by the standard technique</p> <pre><code>t = a[i]; a[i] = a[j]; t = a[j]; </code></pre></li> <li><p>Moving inwards from left and right can be done by,</p> <p>from left to right: <code>while(a[i] &lt;= x) i = i + 1;</code></p> <p>from right to left: <code>while(x &lt; a[j]) j = j - 1;</code></p> <p>where <code>a</code> is the array, <code>i</code> is the starting index 0, <code>j</code> is last index that is the length of the array.</p></li> </ol> <p>One case is, initially we don't know <code>a[i]</code> and <code>a[j]</code> should be exchanged since there is no initial move inwards from the left and right to check if an exchange is really necessary. we can overcome this by placing a check before passing through the array:</p> <pre><code>while(a[i] &lt;= x) i = i + 1; while(x &lt; a[j]) j = j - 1; </code></pre> <p>Algorithm (it is based on R. G. Dromey's How to solve it by computer):</p> <ol> <li><p>Establish an array \$a[1...n]\$ and partition value <code>x</code>.</p></li> <li><p>Move the two partitions towards each other until a wrongly placed pair of elements is encountered.</p></li> <li>While two partitions have not met or crossed do <ul> <li>exchange wrongly placed pairs and extend both partitions inwards by one element.</li> <li>extend left partition while elements less than or equal to x</li> <li>extend right partition while elements greater than x</li> </ul></li> <li>Print partitioning index p and partitioned array.</li> </ol> </blockquote> <p>Here is my solution:</p> <pre><code>public class PartitionArray { public static void main(String args[]) { int[] elements = {37, 36, 27, 11, 15, 12, 34, 29, 4, 10}; int x = 17; int p = 0; int i = 0; int j = elements.length - 1; while (elements[i] &lt;= x &amp;&amp; i &lt; j) i = i +1; while (x &lt; elements[j] &amp;&amp; i &lt; j) j = j - 1; int tmp; while (i &lt; j) { tmp = elements[i]; elements[i] = elements[j]; elements[j] = tmp; i = i + 1; j = j - 1; while (elements[i] &lt;= x &amp;&amp; i &lt; j) i = i +1; while (x &lt; elements[j] &amp;&amp; i &lt; j) j = j - 1; p = j; } print("P: " + elements[p]); print("Partitioned Array: " + Arrays.toString(elements)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T03:45:36.607", "Id": "27907", "Score": "0", "body": "Technically it's still `O(n)`. A second pass is `O(2n) == O(n)`." } ]
[ { "body": "<p>Unless it is a homework for sort algorithm study :</p>\n\n<ul>\n<li>Manage <code>ArrayList</code> and load your list of number,</li>\n<li>put all <code>number&lt;=x</code> in a new ArrayList,</li>\n<li>delete them from the original ArrayList,</li>\n<li>finish with <code>.addAll(..),</code> to concatenate if needed.<br></li>\n</ul>\n\n<p>Knowing that VM is optmized, it would be interesting to compare performance of this approach with your one.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T15:04:00.357", "Id": "27935", "Score": "0", "body": "Inserting or deleting an element from an ArrayList is `O(N)` (if we exclude special cases)." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T09:13:00.957", "Id": "17549", "ParentId": "17523", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T13:51:24.730", "Id": "17523", "Score": "4", "Tags": [ "java", "algorithm", "performance", "array" ], "Title": "Partitioning array elements into two subsets" }
17523
<p>This function checks if an attribute has been passed and if not, asks user for input.</p> <p>I'm new in bash scripting and would like to get some feedback. Is it okay or should I refactor this code somehow to make it more concise?</p> <pre><code>#!/usr/bin/env bash fn() { if [ -z "$1" ]; then read -p "username:" username else username=$1 fi echo "username is $username" } </code></pre>
[]
[ { "body": "<p>What you're doing is perfectly fine.</p>\n\n<p>If you absolutely want to shorten it (at a slight loss of readability) for whatever reason you could do it this way (at least in bash):</p>\n\n<pre><code>fn() {\n [ -z \"$1\" ] &amp;&amp; read -p \"username:\" username || username=$1\n echo \"username is $username\"\n}\n</code></pre>\n\n<p>Output (in a bash environment):</p>\n\n<pre><code>$ fn() {\n&gt; [ -z \"$1\" ] &amp;&amp; read -p \"username:\" username || username=$1\n&gt; echo \"username is $username\"\n&gt; }\n$ fn\nusername:xx\nusername is xx\n$ fn yy\nusername is yy\n$\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:46:18.137", "Id": "27985", "Score": "0", "body": "You're welcome. Shell programmers love to exploit the shell features and often use such kind of shortening, so it's handy to know and look for it. While code readability is high on my priority list, even I occasionally do this, just so long as the result is fairly easy to understand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-26T22:15:04.693", "Id": "200125", "Score": "0", "body": "As a habit, or maybe some considerations for `set -e`, I prefer using logical ORs. Therefore, the code will look like `[ \"$1\" ] || read` (some may prefer this test with `-n` though)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T13:16:53.310", "Id": "17552", "ParentId": "17526", "Score": "7" } }, { "body": "<p>Here's an ugly little one-liner:</p>\n\n<pre><code>fn () {\n username=${1:-$(read -p \"username:\"; echo \"$REPLY\")}\n}\n</code></pre>\n\n<p>If <code>$1</code> has a non-null value, that is assigned to <code>username</code>. Otherwise,\nwe <code>read</code> a value and <code>echo</code> it in a command substitution, which captures\nthe <code>echo</code>ed value to store in <code>username</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T16:13:24.637", "Id": "23445", "ParentId": "17526", "Score": "1" } } ]
{ "AcceptedAnswerId": "17552", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T16:53:00.803", "Id": "17526", "Score": "5", "Tags": [ "bash" ], "Title": "A little bash function, assigning attributes" }
17526
<p>I've created <a href="http://jsfiddle.net/9SXLJ/" rel="nofollow noreferrer">this fiddle</a> to demonstrate something I've been working on. I've been trying to mimic the behaviour of Twitter where if a tweet is expanded, the border-radius and margins of the previous and next tweets are altered.</p> <p>I've used toggleclass to get this working. I would like advice about how to clean up my code. I'm sure I have more lines of code than I need and I'm sure there are more simple or better ways to achieve the desired effect.</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> $(document).ready(function(){ $(".things").hide(); $(".listname .btn-group").hide(); $(".expand, .expandfirst").click(function(){ $(this).prev(".btn-group").toggle(); $(this).children("span").toggle(); $(this).toggleClass('active'); $(this).closest(".list").find(".things").toggle(); $(this).parents(".list").next().find(".expand").toggleClass('after-expanded'); $(this).parents(".list").prev().find(".expand").toggleClass('before-expanded'); $("#listview, #thingview").removeClass('active'); }); $(".expand").click(function(){ $(this).toggleClass('expanded-list'); }); $("#listview").click(function(){ $(".things").hide(); $(".listname .btn-group").hide(); $(".listname a span").show(); $(".expand").removeClass('active expanded-list after-expanded'); $(".expandfirst").removeClass('active'); }); $("#thingview").click(function(){ $(".things").show(); $(".listname .btn-group").show(); $(".listname a span").hide(); $(".expand").addClass('active expanded-list after-expanded'); $(".expandfirst").addClass('active'); }); });</code></pre> <pre class="snippet-code-css lang-css prettyprint-override"><code>@import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css'); #lists { padding-top: 20px; } .nav &gt; li &gt; a { font-weight: bold; } .list .btn-group, .list .share { margin: 7px; } .header { background: #fff; border: 1px solid #ccc; border-radius: 5px 5px 0 0; font-weight: bold; padding: 8px; } .header h4 { margin: 5px 0; } .header span { margin-top: 3px; } .list ol { border: 1px solid #ccc; border-top: none; border-radius: 0 0 5px 5px; background-color: #fff; list-style-position: inside; margin: 0; padding: 0; } .list ol li { border-top: 1px solid #ccc; padding: 8px; position: relative; } .list ol li:first-child { border-top: none; } .list .btn-group { margin-top: 8px; } .listname { font-weight: bold; } .things li a { margin-left:14px; } .list a.btn { text-align: left; border: 1px solid #ccc; border-top: none; border-radius: 0; } .expand, .expandfirst { display: block; padding: 8px 0; } .list a.before-expanded { border-bottom-left-radius: 6px; border-bottom-right-radius: 6px; } .list a.expanded-list, .list a.after-expanded { border-top-left-radius: 6px; border-top-right-radius: 6px; border-top: 1px solid #ccc; margin-top: 20px; }</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;div id="lists"&gt; &lt;div class="header"&gt; &lt;h4 style="display: inline-block;"&gt;Header&lt;/h4&gt; &lt;div class="btn-group pull-right"&gt; &lt;button class="agree btn btn-mini dropdown-toggle" data-toggle="dropdown"&gt;Sort by&lt;/button&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="list"&gt; &lt;div class="listname"&gt; &lt;button class="share btn btn-mini pull-left"&gt;&lt;i class="icon-heart-logo"&gt;&lt;/i&gt;&lt;/button&gt; &lt;div class="btn-group pull-right"&gt; &lt;button class="btn btn-mini dropdown-toggle pull-right" data-toggle="dropdown"&gt;&lt;i class="icon-5hearts"&gt;&lt;/i&gt;&lt;/button&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;a class="expandfirst btn" href="#"&gt;Colors&lt;span class="pull-right" style="margin-right: 8px;"&gt;56,789&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;ol class="things"&gt; &lt;li&gt;&lt;a href="#"&gt;White&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Blue&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Red&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Green&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Orange&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;div class="list"&gt; &lt;div class="listname"&gt; &lt;button class="share btn btn-mini pull-left"&gt;&lt;i class="icon-heart-logo"&gt;&lt;/i&gt;&lt;/button&gt; &lt;div class="btn-group pull-right"&gt; &lt;button class="btn btn-mini dropdown-toggle pull-right" data-toggle="dropdown"&gt;&lt;i class="icon-5hearts"&gt;&lt;/i&gt;&lt;/button&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;a class="expand btn" href="#"&gt;Colors&lt;span class="pull-right" style="margin-right: 8px;"&gt;56,789&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;ol class="things"&gt; &lt;li&gt;&lt;a href="#"&gt;White&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Blue&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Red&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Green&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Orange&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;div class="list"&gt; &lt;div class="listname"&gt; &lt;button class="share btn btn-mini pull-left"&gt;&lt;i class="icon-heart-logo"&gt;&lt;/i&gt;&lt;/button&gt; &lt;div class="btn-group pull-right"&gt; &lt;button class="btn btn-mini dropdown-toggle pull-right" data-toggle="dropdown"&gt;&lt;i class="icon-5hearts"&gt;&lt;/i&gt;&lt;/button&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;a class="expand btn" href="#"&gt;Colors&lt;span class="pull-right" style="margin-right: 8px;"&gt;56,789&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;ol class="things"&gt; &lt;li&gt;&lt;a href="#"&gt;White&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Blue&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Red&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Green&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Orange&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;div class="list"&gt; &lt;div class="listname"&gt; &lt;button class="share btn btn-mini pull-left"&gt;&lt;i class="icon-heart-logo"&gt;&lt;/i&gt;&lt;/button&gt; &lt;div class="btn-group pull-right"&gt; &lt;button class="btn btn-mini dropdown-toggle pull-right" data-toggle="dropdown"&gt;&lt;i class="icon-5hearts"&gt;&lt;/i&gt;&lt;/button&gt; &lt;ul class="dropdown-menu"&gt; &lt;li&gt;&lt;a href="#"&gt;1&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;2&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;3&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;a class="expand btn" href="#"&gt;Colors&lt;span class="pull-right" style="margin-right: 8px;"&gt;56,789&lt;/span&gt;&lt;/a&gt; &lt;/div&gt; &lt;ol class="things"&gt; &lt;li&gt;&lt;a href="#"&gt;White&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Blue&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Red&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Green&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;Orange&lt;/a&gt;&lt;span class="pull-right"&gt;56,789&lt;/span&gt;&lt;/li&gt; &lt;/ol&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[]
[ { "body": "<p>at first glance here's a few things that immediately come to mind (not a criticism, just an observation):</p>\n\n<ol>\n<li>You're right--there's a lot of extra markup to accomplish what you're trying to do, but that's something you can work on easily</li>\n<li>Your writing a more jQuery-handlers than you need. You can either wrap this all into a plugin, or use something like jQuery UI or even better, use <a href=\"http://twitter.github.com/bootstrap/\" rel=\"nofollow\">http://twitter.github.com/bootstrap/</a> -- which has components that are built to do exactly this.</li>\n</ol>\n\n<p>Now, if you want to roll your own solution (which is awesome too), I suggest you look at using <a href=\"http://docs.jquery.com/Plugins/livequery\" rel=\"nofollow\">livequery</a>, which gives you the ability to easily bind event handlers to DOM elements. It even handles automatic bindings when new DOM elements are added, so you don't have to repeatedly run initializations for your controls.</p>\n\n<p>An approach I would take for your toggle controls would be this:</p>\n\n<pre><code>&lt;div class=\"toggle-container state-expanded\"&gt;\n &lt;div class=\"toggle-content\"&gt;\n ... Your content ...\n &lt;/div&gt;\n &lt;a href=\"#\" class=\"toggle-control\"&gt;Expand/Collapse&lt;/a&gt; \n&lt;/div&gt;\n</code></pre>\n\n<p>Your jQuery should look something like this (assuming you go ahead and add livequery):</p>\n\n<pre><code>jQuery(function(){\n\n $('.toggle-control').livequery( 'click', function(){\n\n // Store a reference to the element so you don't keep calling $( this ) every time...\n var obj = $( this );\n // References to your elements\n var container = obj.closest('.toggle-container');\n var content = container.find('toggle-content');\n\n // Expand and collapse the content container\n content.slideToggle(256, function(){\n if(!content.is(':visible') )\n {\n container.addClass('state-collapsed').removeClass('state-expanded');\n }\n else\n {\n container.addClass('state-expanded').removeClass('state-collapsed');\n }\n });\n\n // Then deal with anything else you want to do with your elements, e.g. show or hide other elements, more initializations etc.\n });\n\n\n\n});\n</code></pre>\n\n<p>I'm probably going to catch some flack for not using toggleClass(), but it's failed me more times that I care to remember, and being slightly more verbose about the conditions provides an opportunity to do more within that condition, e.g. handle the state of other elements.</p>\n\n<p><strong>To address your initial question:</strong> the above example can be extended to add/remove classes of all other <code>.toggle-container</code> elements within the <code>slideToggle()</code> callback. This way you don't have to deal with it procedurally. </p>\n\n<p>This approach gives you a chance to reduce the number of CSS rules and pare down your jQuery a little. I would still consider wrapping this all up into a plugin for reusability purposes and to isolate it from your general code.</p>\n\n<p>As an alternative, you can bind the <code>change</code> event for each <code>.toggle-container</code> to respond to changes in the class attribute. Just be mindful of the fact that with the <code>change</code> event, it's possible to have other <code>change</code> events bubble up, which can result in some unwanted behavior. Keep it simple.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T20:58:43.860", "Id": "27885", "Score": "0", "body": "Thanks very much for such a thorough and helpful answer. I did consider using bootstrap 'collapse'. Do you think this is my best option? I suppose I could add to the classes 'collapse' uses to adjust things like margin and border radius when an object is expanded/collapsed? Thanks for your livequery example. I may well go down this road but even if not, I understand a lot more about how to approach this problem so I'm grateful for that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:11:12.177", "Id": "27887", "Score": "0", "body": "Bootstrap's collapse component is just one option; I suggested it since you're including the CSS for it, so for consistency's sake, it's nice. I tend to roll my own components since most of the plugins out there have more features that I have use-cases for. It's also nice to have a consolidated collection of common controls of your own--if only for the fact that you know how they're built and how to modify them if you need more features (livequery is and awesome tool for these types things.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T01:27:30.360", "Id": "27897", "Score": "0", "body": "I thought I would have a go at using bootstrap collapse - can you tell me if I'm on the right track here? http://jsfiddle.net/9SXLJ/4/ I've added the line: $this[$(target).hasClass('in') ? 'removeClass' : 'addClass']('active') to the Collapse Data-API and I've used the classes 'collapsed' and 'in' to adjust margin and border-radius. The only part I'm struggling to implement now is adjusting the margin and border-radius for the previous and next objects." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T03:12:46.843", "Id": "27903", "Score": "0", "body": "I understand your approach, but it's not a good practice to alter a third-party plugin, since you'll lose the benefit of consistency when it's updated, e.g. you'll be forced to re-add your snippet every time there's a new version of the plugin. I learned that the hard way back in the day. The Collapse plugin has a callback parameter specified in, `transition: function (method, startEvent, completeEvent){...}`, see `completeEvent`. Hook this event with your own function/handler when you initialize the plugin. Alternately, you can extend/add or even override methods to inject your own logic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T03:23:14.613", "Id": "27904", "Score": "0", "body": "Oh, and to reset/update the prev/next elements -- I would handle that (assuming you'll hook the `completeEvent` or `startEvent` event) by targeting all the `.list` elements and removing the `.active` class from the toggle, then applying the `.active` class to the single list you expanded." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T02:08:29.183", "Id": "28069", "Score": "0", "body": "Thanks again for your suggestions. What I've ended up doing is using the \"show\" and \"hide\" events of Bootstrap collapse to add and remove classes that achieve the desired effect: http://jsfiddle.net/9SXLJ/9/ I think I'm getting closer to an elegant solution? I need to figure out how not to call the \"expanded\" class for the first list because I don't want the border style to change but otherwise, I think I'm almost there." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T18:16:46.320", "Id": "17529", "ParentId": "17527", "Score": "1" } }, { "body": "<p>This is <em>not</em> really a direct answer, but mostly me trying a slightly different approach. I just wanted to see how far one can get with more CSS and less JS. In fact, I ended up with only 4-5 lines of JS (well, CoffeeScript actually), but this is admittedly for a demo that's heavily simplified compared to the question.</p>\n\n<p>The demo is <a href=\"http://jsfiddle.net/flambino/hmY2e/\" rel=\"nofollow\">here</a></p>\n\n<p>The main point is that only 2 classes are really necessary: <code>expanded</code> and <code>precedes-expanded</code>. The rest can be handled with CSS2's <code>first-child</code>/<code>last-child</code> and <code>+</code> selectors. CSS doesn't provide a way to manipulate preceding elements (i.e. parents or previous siblings), otherwise just one class would be necessary.</p>\n\n<p>Note, though, that this demo probably isn't terribly cross-browser compatible (works great in WebKit, though). Some of it is just a matter of including the vendor-specific syntax for stuff like border-radius, but the selectors mentioned above don't have perfect support everywhere.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T06:31:22.553", "Id": "18645", "ParentId": "17527", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T17:21:32.457", "Id": "17527", "Score": "2", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "Toggleclass for mimicking certain Twitter tweet behavior" }
17527
<p>This is what the code should do:</p> <blockquote> <p>Check if the first dimensions and the second dimensions of each 2-dimensionalarray are the same. If they are not the same, then return a 0x0 2-dimensional array. array, otherwise do the following;</p> <ul> <li><p>Allocate memory for a local 2-dim. array with the same dimensions as one of the 2-dim. array parameters</p></li> <li><p>Add each corresponding element in the parameter 2-dim. arrays and store the result in the corresponding element ofthe local 2-dim. array (use nested for loops)</p></li> <li><p>Return the local 2-dim. array </p></li> </ul> </blockquote> <pre><code>import java.lang.Math; public class Homework2 { public static void main(String[] args){ int d1 = (int) (Math.random()*(10-3+1)+3); int d2 = (int) (Math.random()*(10-3+1)+3); double[][] doubMatrix1 = new double[d1][d2]; double[][] doubMatrix2 = new double[d1][d2]; double[][] doubMatrix3 = new double[d1][d2]; doubMatrix1 = getdoubMatrix(d1,d2); doubMatrix2 = getdoubMatrix(d1,d2); doubMatrix3 = addMatrices(doubMatrix1, doubMatrix2); } public static double[][] getdoubMatrix(int d1, int d2){ double[][] tempArray = new double[d1][d2]; for(int i =0; i &lt;tempArray.length;i++ ) for(int j =0;j &lt; tempArray[i].length;j++) tempArray[i][j] = Math.random()*(10.0); return tempArray; } public static double[][] addMatrices(double doubMatrix1[][], double doubMatrix2[][]){ double[][] tempArray = null; int i,j = 0; for(i = 0; i&lt; doubMatrix1.length;i++) for(j = 0; j&lt; doubMatrix1[i].length;j++ ) { if(doubMatrix1[i][j] == doubMatrix2[i][j]) { tempArray = new double[i][j]; tempArray[i][j] = doubMatrix1[i][j] + doubMatrix2[i][j]; } else { return tempArray = new double[0][0]; } } return tempArray; } } </code></pre>
[]
[ { "body": "<p>You probably should reread the specifications. “Check if the first dimensions and the second dimensions of each 2-dim. array array are the same” means that you should check if first and second matrix lengths match; it does <em>not</em> mean to test <code>doubMatrix1[i][j] == doubMatrix2[i][j]</code>. Also test sizes of <code>doubMatrix1[0]</code> and <code>doubMatrix2[0]</code>; ie besides testing <code>doubMatrix1.length</code> vs <code>doubMatrix2.length</code>, test <code>doubMatrix1[0].length</code> vs <code>doubMatrix2[0].length</code>. If the sizes don't match, then do your <code>return tempArray = new double[0][0];</code> statement, or perhaps <code>return new double[0][0];</code>. That particular statement should be before, not inside, the nested for loops.</p>\n\n<p>“Add each corresponding element in the parameter 2-dim. arrays and store the result” means to do something like your<br>\n<code>tempArray[i][j] = doubMatrix1[i][j] + doubMatrix2[i][j];</code>\nstatement. However, your code repeatedly reallocates <code>tempArray[][]</code>, so <code>tempArray[][]</code> never has more than one element set in it. Allocate the array earlier in your program, perhaps after you know the sizes match.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:09:32.517", "Id": "17532", "ParentId": "17531", "Score": "5" } }, { "body": "<p>This is Java, not C-before-C99. You can declare your variables in the loop statement, rather than before the loop statement:</p>\n\n<blockquote>\n<pre><code>int i,j = 0;\nfor(i = 0; i&lt; doubMatrix1.length;i++)\n for(j = 0; j&lt; doubMatrix1[i].length;j++ )\n</code></pre>\n</blockquote>\n\n<p>Change that to:</p>\n\n<pre><code>for(int i = 0; i&lt; doubMatrix1.length;i++)\n for(int j = 0; j&lt; doubMatrix1[i].length;j++ )\n</code></pre>\n\n<p>The first statement is entirely redundant as you never use them outside the scope of the loop.</p>\n\n<hr>\n\n<p>You should format your code better. <code>j&lt; doubMatrix1[i].length;j++ )</code> is messy, and should read as <code>j &lt; doubMatrix1[i].length; j++)</code></p>\n\n<hr>\n\n<p>Your indentation is messy too. Mainly, you should be consistent, and 4 spaces is the typical Java standard. This, for example, is difficult to read and see the scope automatically:</p>\n\n<blockquote>\n<pre><code>}\n public static double[][] getdoubMatrix(int d1, int d2){\n</code></pre>\n</blockquote>\n\n<hr>\n\n<blockquote>\n<pre><code>int i,j = 0;\n</code></pre>\n</blockquote>\n\n<p>That assignment only assigns <code>j</code>, <code>i</code> is unassigned. As I mentioned earlier, these are redundant anyway, but you should know about this behavior. If you want <code>i</code> assigned too, you have to do <code>int i = 0, j = 0;</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-14T18:42:38.897", "Id": "211088", "Score": "0", "body": "_This is Java, not C. You can declare your variables in the loop statement, rather than before the loop statement:_ <- you can in C99 too" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-14T18:35:42.503", "Id": "113943", "ParentId": "17531", "Score": "5" } } ]
{ "AcceptedAnswerId": "17532", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T19:47:19.827", "Id": "17531", "Score": "2", "Tags": [ "java", "matrix", "mathematics" ], "Title": "Adding matrices" }
17531
<p>Below is my attempt at the beginnings of a reusable ado.net data access class. Please let me know of any improvements that I could make.</p> <p>Thanks!</p> <pre><code>public class DataAccess : IDisposable { public DbProviderFactory Factory { get; set; } public string Connection { get; set; } public string ProviderName { get; set; } public DataAccess() { Get_ConnectionString_From_AppSettings(); Get_ProviderName_From_AppSettings(); } private void Get_ConnectionString_From_AppSettings() { this.Connection = ConfigurationManager.AppSettings.Get("Database"); } private void Get_ProviderName_From_AppSettings() { this.ProviderName = ConfigurationManager.AppSettings.Get("DBProvider"); } public DataTable Connection_Return_DataTable( string sql) { DbConnection connection = null; try { DbProviderFactory factory = DbProviderFactories.GetFactory(this.ProviderName); this.Factory = factory; connection = Factory.CreateConnection(); connection.ConnectionString = Connection; DataTable dt = FillDataTable(connection, sql); return dt; } catch (DataException ex) { Debug.WriteLine(ex.ToString()); throw; } finally { connection.Close(); connection.Dispose(); } } private DataTable FillDataTable(DbConnection connection, string sql) { DbCommand command = connection.CreateCommand(); command.CommandText = sql; command.Connection = connection; DbDataAdapter adapter = this.Factory.CreateDataAdapter(); adapter.SelectCommand = command; DataTable table = new DataTable(); adapter.Fill(table); return table; } public void Dispose() { this.Factory = null; this.Connection = null; this.ProviderName = null; } } </code></pre>
[]
[ { "body": "<p>You do not need IDisposable in your current implementation as you do not use any unmanaged resources or have any fields or properties which implement IDisposable which your class owns.</p>\n\n<p>Setting the properties to null in the dispose method is unnecessary.</p>\n\n<p>Method names should be Pascal cased and not contain underscores to adhere to standard naming conventions:</p>\n\n<pre><code>private void GetConnectionStringFromAppSettings()\n</code></pre>\n\n<p>Since the class cannot operate without a connection string or provider, you should throw an exception if they are not set:</p>\n\n<pre><code>private void GetConnectionStringFromAppSettings()\n{\n this.Connection = ConfigurationManager.AppSettings.Get(\"Database\");\n\n if (string.IsNullOrEmpty(this.Connection))\n {\n throw new InvalidOperationException(\"No connection string found in the configuration\");\n }\n}\n</code></pre>\n\n<p>You should use the <a href=\"http://msdn.microsoft.com/en-US/library/ms254494%28v=vs.100%29.aspx\">Connection Strings</a> section of the app.config instead of app settings.</p>\n\n<p>You should resolve the factory once in your constructor instead of on every call to <code>ConnectionReturnDataTable</code>.</p>\n\n<p>ConnectionReturnDataTable should be renamed to something like <code>GetQueryResults</code>.</p>\n\n<p>DbCommand and DbDataAdapter are both IDisposable and should be used in a using statement (or a try/finally which is what a using compiles to).</p>\n\n<pre><code>private DataTable FillDataTable(DbConnection connection, string sql)\n{\n using (DbDataAdapter adapter = this.Factory.CreateDataAdapter())\n {\n using (DbCommand command = connection.CreateCommand())\n {\n command.CommandText = sql;\n command.Connection = connection;\n adapter.SelectCommand = command;\n\n DataTable table = new DataTable();\n adapter.Fill(table);\n\n return table;\n }\n }\n}\n</code></pre>\n\n<p>The connection property should be called <code>ConnectionString</code></p>\n\n<pre><code>public string ConnectionString { get; set; }\n</code></pre>\n\n<p>In fact, the properties should probably become private fields as they shouldn't be modified from outside the class if you are using the app.config to specify their values.</p>\n\n<p>You should be using parameterised queries instead of raw SQL</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:08:49.667", "Id": "27899", "Score": "3", "body": "Suggestion. Do we really need the two private methods to set the connection and provider? I would probably consider also making them read-only and just set them directly in the constructor for simplicities sake?? Or, even consider injecting them in the constructor instead..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T11:40:47.627", "Id": "27917", "Score": "0", "body": "No, you are right if the constructor reads the connection strings section and assigns the 3 fields that would be the better approach." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T22:12:01.163", "Id": "17535", "ParentId": "17533", "Score": "10" } } ]
{ "AcceptedAnswerId": "17535", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T21:09:58.213", "Id": "17533", "Score": "2", "Tags": [ "c#", ".net", "database" ], "Title": "reusable data access class in C#" }
17533
<p>I have been programming in C++ for around a month now, just long enough, I figure, to develop bad habits. Can anyone point out where I'm making mistakes and offer topics I should investigate to understand why?</p> <pre><code>#include &lt;iostream&gt; #include &lt;cassert&gt; #include &lt;sstream&gt; #include &lt;string&gt; using namespace std; string get_line(); int long get_integer(); int* flex(long int num); void test_flex(); int main() { //flex(get_integer()); test_flex(); } /* * === FUNCTION ============================================================= * Name: flex * Description: flex takes one integer argument and returns an then number * of odd, even and zero digits. * flex(111022) -&gt; [3,2,1] i.e [odd,even,zero's] * ============================================================================ */ int* flex (long int num) { int res; int even = 0; int odd = 0; int zero = 0; while(num != 0){ res = num % 10; if(res == 0){ zero++; } else if(res % 2 == 0){ even++; } else{ odd++; } num = (num - (num % 10))/10; } int oez[3] = {odd,even,zero}; return oez; } /* ----- end of function flex ----- */ /* * === FUNCTION ============================================================= * Name: test_flex * Description: test suite for flex function * ============================================================================ */ void test_flex ( ) { assert(flex(1)[0] == 1); assert(flex(1)[1] == 0); assert(flex(1)[2] == 0); assert(flex(112220)[0] == 2); assert(flex(112220)[1] == 3); assert(flex(112220)[2] == 1); } /* ----- end of function test_flex ----- */ /* * === FUNCTION ====================================================================== * Name: get_integer * Description: checks if input is integer * ===================================================================================== */ long int get_integer () { while(true){ stringstream converter; converter &lt;&lt; get_line(); int long result; if(converter &gt;&gt; result){ char remaining; if(converter &gt;&gt; remaining) cout &lt;&lt; "Unexpected character: " &lt;&lt; remaining &lt;&lt; endl; else{ return result; } } else cout &lt;&lt; "Please enter an integer." &lt;&lt; endl; cout &lt;&lt; "Retry:" &lt;&lt; endl; } } /* ----- end of function get_integer ----- */ /* * === FUNCTION ====================================================================== * Name: get_line * Description: wraps getline * ===================================================================================== */ string get_line() { string result; getline(cin,result); return result; } /* ----- end of function get_line ----- */ </code></pre>
[]
[ { "body": "<p>I presume your code's brace format and function heading format is dictated by instructor and I won't comment on it. The code is presented clearly enough. One comment says problem 8, a couple of others say 10.</p>\n\n<p>I deem it inappropriate to have a <code>get_line</code> routine; for code that would take 2 lines inline and be perfectly clear, you have about 13 lines of subroutine with no obvious reason for same.</p>\n\n<p>The digit-counting code looks rather verbose to me, with tests like <code>num != 0</code> and tests in awkward order. I'd rewrite the digit-counting code as follows.</p>\n\n<pre><code> while (num) {\n res = num % 10;\n if (res)\n if (res &amp; 1)\n ++odd;\n else\n ++even;\n else\n ++zero;\n num /= 10;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T04:21:54.393", "Id": "27908", "Score": "0", "body": "Yea, i don't know why i made get_line its own function. It's also now obvious to me that num - (num % 10), isn't doing anything. My instructor hasn't dictated anything. I'm bouncing between different styles i see in different texts and what i was comfortable with in python..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T00:28:25.030", "Id": "17539", "ParentId": "17536", "Score": "7" } }, { "body": "<p>Do not see the point in: <code>get_line()</code></p>\n\n<pre><code>get_line(line);\n\n// Vs\n\nstd::getline(std::cin, line);\n</code></pre>\n\n<p>Get Integer is well done. Most people forget to test if there is anything else remaining on the line.</p>\n\n<p>A simple enhancement is:</p>\n\n<pre><code> char remaining;\n if(converter &gt;&gt; remaining)\n\n // easier to rewrite as:\n if (!converter.str().empty())\n</code></pre>\n\n<p>Also there is already a boost function that does something similar:</p>\n\n<pre><code>long value = boost::lexical_cast&lt;long&gt;(line); // Will throw if anything left on line.\n</code></pre>\n\n<p>Over complicating this:</p>\n\n<pre><code> num = (num - (num % 10))/10;\n</code></pre>\n\n<p>You can simplify it too:</p>\n\n<pre><code> num /= 10; // Integer division truncates.\n</code></pre>\n\n<p>I think this is a logical error:</p>\n\n<pre><code> if(res == 0){\n zero++;\n }\n else if(res % 2 == 0){ // zero is an even number\n // do you really want that else?\n</code></pre>\n\n<p>Your one major error is:</p>\n\n<pre><code>int oez[3] = {odd,even,zero};\nreturn oez;\n</code></pre>\n\n<p>You are returning a pointer to an array that has gone out of scope. Personally I would return a <code>std::vector&lt;int&gt;</code>. Don't worry on a simple returning like this the copy back of the array will be optimized out (look up RVO and NVRO).</p>\n\n<pre><code>std::vector&lt;int&gt; oez = {odd,even,zero};\nreturn oez;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T14:40:41.303", "Id": "17559", "ParentId": "17536", "Score": "8" } } ]
{ "AcceptedAnswerId": "17559", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-14T22:34:46.767", "Id": "17536", "Score": "4", "Tags": [ "c++", "beginner" ], "Title": "Determine number of even, odd, and zero digits of a given integer" }
17536
<p>I would really like to hear how I can improve my form validator. Next, I want to refactor it into OO and learn a testing framework like Jasmine.</p> <p>Some things I know I could improve:</p> <ul> <li>Don't make it tied to the DOM as much (using <code>parent().parent()</code>, for ex.).</li> <li>Combined validations can't be used. For example, using <code>isBlank</code> and <code>isInteger</code> will not validate properly because if <code>isInteger</code> fails, it throws an error and <code>isBlank</code> passes and clears <em>all</em> errors.</li> <li>Make a config object to update with custom error messages.</li> <li>Possibly make a jQuery plugin so passing the object to validate is easier.</li> </ul> <p><a href="http://bit.ly/SUIvOC" rel="nofollow">Github repo</a></p> <pre><code> jQuery -&gt; # on Document ready errorCount = null valEl = $('.validate') # cache .validate elements submitBtn = valEl.parent().parent().find('input[type=submit]') valEl.on "blur", -&gt; input = $(this) validate(input) validate = (input) -&gt; inputVal = input.val() inputLen = inputVal.length validations = input.data() #cache data-xxx tags if validations.notblank is on if inputLen &lt;= 0 throwError("This field can't be blank", input) else removeError(input) if validations.minchars &gt; 0 if inputLen &lt; validations.minchars throwError("You need at least 5 chars", input) else removeError(input) if validations.isinteger is on isInteger = /^\d+$/ if isInteger.test(inputVal) is false throwError("Must be a whole number", input) else removeError(input) throwError = (message, input) -&gt; if !input.hasClass('has-error') errorCount += 1 input.addClass "has-error" input.nextAll('.errorContainer').append(message) removeError = (input) -&gt; if input.hasClass('has-error') errorCount -= 1 input.removeClass("has-error") input.nextAll('.errorContainer').empty() submitBtn.on "click", (e) -&gt; e.preventDefault() if errorCount is 0 valEl.parent().parent().submit() </code></pre>
[]
[ { "body": "<p>You could break out your validation functions into a separate object, like so:</p>\n\n<pre><code>validators =\n isinteger: (input) -&gt;\n # check that value is an int\n\n notblank: (input) -&gt;\n # check that value is present\n</code></pre>\n\n<p>These functions could return a simple boolean, or they could return an error message if validation fails and <code>null</code> if it passes.</p>\n\n<p>The point is that you keep the functions separate, so they're easier to manage and customize. But it also means that you can give your inputs data attributes like <code>data-validator</code> which simply is the name of the validation method to use. So you can say, for example</p>\n\n<pre><code>method = $(input).data \"validator\"\nresult = validators[method]?(input)\n</code></pre>\n\n<p>With a little string-splitting, you could make the field plural, like <code>data-validators=\"isinteger, notblank\"</code>, and check each.</p>\n\n<p>You could also make the error-throwing into an event you can listen for elsewhere. Then you avoid having your error presentation mixed up with your validations, and you don't have to rely on a predefined <code>.errorContainer</code> element. For instance:</p>\n\n<pre><code>throwError = (message, input) -&gt;\n $(input).trigger 'validation:error', message\n\n# ... elsewhere ...\n\n$(document).on 'validation:error', 'input', (event) -&gt;\n # handle error event\n</code></pre>\n\n<hr>\n\n<p>Other stuff I noticed:</p>\n\n<ol>\n<li><p>Don't bind to the submit button's <code>click</code> event! Forms can also be submitted by simply pressing enter/return, without ever clicking the submit button. Instead, bind the form element's <code>submit</code> event which is fired regardless of how the form is submitted, and use <code>preventDefault()</code> to stop the submission if necessary.</p></li>\n<li><p>Your <code>notblank</code> logic won't complain if the user just enters some space characters. In most cases the field should probably be considered blank, if it only contains whitespace. So use <code>$.trim()</code> on the value first, to trim off leading and trailing whitespace. </p></li>\n<li><p>HTML5 has a <code>required</code> attribute you can add to inputs - no need to have your own syntax for say an input should be <code>notblank</code>. Check for the <code>required</code> attribute instead (<code>if $(input).attr('required') ...</code>). It makes the HTML more semantically correct.</p></li>\n</ol>\n\n<hr>\n\n<p>I don't know if you already have solutions for the specific things you mention, but here are my ideas:</p>\n\n<ul>\n<li><p>You can use <code>.closest(\"form\")</code> to find the form element instead of <code>parent().parent()</code></p></li>\n<li><p>If you store all validation failures in an array, you just need to check the array's length, to see if the were any errors. Multiple validations won't override each other, and you don't need <code>errorCount</code></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:24:02.987", "Id": "28045", "Score": "0", "body": "Wow thanks! I can't wait to start refactoring!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T00:49:42.187", "Id": "17541", "ParentId": "17538", "Score": "1" } }, { "body": "<p>One thing you could consider doing is following the approach set out by @Flambino with different <code>Validator</code> objects. You could start with a <code>ValidatorBase</code> object that you can decorate with additional methods or even override existing methods with new definitions (see Javascript Decorator pattern at: <a href=\"http://www.joezimjs.com/javascript/javascript-design-patterns-decorator/\" rel=\"nofollow\">http://www.joezimjs.com/javascript/javascript-design-patterns-decorator/</a>).</p>\n\n<p>Here's a really crude/untested example of what I'm getting at:</p>\n\n<pre><code>var ValidatorBase = function() {\n console.log('Booya baby1');\n}\n\nValidatorBase.prototype = {\n validate: function() {\n console.log('ValidatorBase::validate()');\n }\n}\n\nValidatorDecorator = function( objValidator ){\n this.validator = objValidator;\n\n}\n\nValidatorDecorator.prototype = {\n validate: function( objElement ) {\n console.log('ValidatorDecorator::validate()');\n return ( objElement &amp;&amp; objElement.value != '' );\n }\n}\n\nDateValidator = function( objValidator ){\n ValidatorDecorator.call( this, objValidator );\n}\n\nDateValidator.prototype = new ValidatorDecorator();\nDateValidator.prototype.checkDate = function( date ) {\n return date.match(/^(?:(0[1-9]|1[012])[\\- \\/.](0[1-9]|[12][0-9]|3[01])[\\- \\/.](19|20)[0-9]{2})$/);\n}\nDateValidator.prototype.validate = function( objElement ) {\n console.log('DateValidator::validate()');\n return (/* validation logic, returns True|False*/ this.validator.validate( objElement ) &amp;&amp; ( this.checkDate( objElement.value ) ) );\n}\n</code></pre>\n\n<p>Personally, I'd refactor this and wrap it into a module or plugin (same thing in jQuery land.)</p>\n\n<p>This approach let's you take advantage of jQuery's event bindings while providing you with the ability to consistently apply different types of validators to the types of elements/data you want to validate. You may still want to map fields to validators types, or use the data-attribute, e.g. <code>&lt;input type=\"text\" data-validator-type=\"DateValidator\" /&gt;</code> to specify which validator gets applied (this can be done in a single validate() method or you can handle it during serialization of your data if you're using AJAX... or hook the submit event on your form.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:23:37.700", "Id": "28044", "Score": "0", "body": "Cool, i'll have to read up on the decorator pattern!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T04:11:13.057", "Id": "17544", "ParentId": "17538", "Score": "1" } } ]
{ "AcceptedAnswerId": "17541", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T00:03:30.807", "Id": "17538", "Score": "2", "Tags": [ "validation", "coffeescript" ], "Title": "Simple form validation" }
17538
<p>I updated my code according to a few suggestions from <a href="https://codereview.stackexchange.com/questions/16386/howd-i-do-on-this-card-matching-game-link-and-code-inside">my last post</a>, so I thought I'd repost it to see what other feedback I could get. I also commented it heavily and fixed some of the functionality. </p> <p>One question I do have is what is the difference between defining a function by doing </p> <pre><code>var funcName = function(){}; </code></pre> <p>rather than</p> <pre><code>function funcName() {}; </code></pre> <p>Which one is better or is neither better and it's just a convention to do one over the other?</p> <p>You can check out the game at <a href="http://mattgowie.com/project-2" rel="nofollow noreferrer">mattgowie.com/project-2/</a>. And here is the source: </p> <pre><code> // Author: Matt Gowie // Created on: 10/01/12 // Project for Web Dev 2400 $(document).ready(function(){ "use strict"; var numberOfPairs = 30; var cardsToFlip = []; var prevCardClasses = []; var matches = 0; var score = 0; var multiplier = 10; var that = this; var $board = $('.board'), $winMessage = $('.win-message'); // Check if the player won the game by matching all of the card pairs var checkForWin = function() { // Are there no more cards on the board? if($('.card-container').length === 0) { // Then the player must have won! Hide the board and show the win message $board.hide(); $winMessage.show(); } }; $('.win-message a').click(function() { // How are the previous cards being reset here? $('.matches').html('0'); $('.score').html('0'); $('.mult').html('10X'); matches = 0; score = 0; multiplier = 10; buildGameBoard(); }); // Build a deck of cards // // numberOfPairs - integer for how many pairs we need, and is // currently restricted to &lt;= 30 // // Returns an array of pairs of integers. ex: [1, 1, 2, 2, 3, 3, ... ] function buildDeck(numberOfPairs) { var deck = []; for(var i = 0; i &lt; numberOfPairs; i++){ deck.push(i,i); } return deck; }; // Shuffle the given ordered deck // deck - An ordered array of pairs of integers // Returns an array of pairs of integers which are no longer ordered function shuffleDeck(deck) { var rand, shuffled = []; // Randomly access each pair in the given deck and add it to the resulting // shuffled deck while(deck.length &gt; 0){ rand = Math.random() * deck.length; shuffled.push(deck.splice(rand, 1)[0]); } return shuffled; }; // Build the cards for the given deck and append them to the board // deck - a shuffled deck // Returns void function buildCards(deck) { var row = 1, col = 1; // Loop through each card in the deck, initializing it with it's relevent info for( var i = 1; i &lt;= deck.length ; i++ ) { buildCard(deck[i - 1], row, col, i); col += 1; // Increment the row and reset the cols for every 10 cards if(i % 10 === 0) { row += 1; col = 1; } } }; // Build the html for a card and append it to the board // cardClass - integer which corresponds to a specific card in the deck // row - integer corresponding to this cards row number // col - integer corresponding to this cards col number // id - integer for identifing the card for click events // Returns void function buildCard(cardClass, row, col, id) { var $card = $('&lt;div class="card back"&gt;&lt;/div&gt;'); var $container = $('&lt;div class="container"&gt;'); var $cardContainer = $('&lt;div class="card-container"&gt;'); // Associate this card with the given class, so we know what it is when flipped $card.data('cardClass', 'card' + cardClass); if(cardClass === 's-ace'){ $card.addClass('debug'); } // For debugging! // Associate the cards container with the current side of the card, which // when the game starts is always on its back $cardContainer.data('cardSide', 'back'); // Add the id, row, and col to the card container for positioning and // card identification when clicking $container.attr('id', "card" + id).addClass("row" + row).addClass("col" + col); // Put the card and containers inside one another, and then append them to the board $container.html($cardContainer.html($card)); $board.append($container); } // Reset and build the game board by creating a deck, shuffling, and dealing function buildGameBoard() { // Reset the GameBoard area $winMessage.hide(); $board.show().html(''); // Initialize a new deck, shuffle, and deal. var deck = buildDeck(numberOfPairs); deck = shuffleDeck(deck); buildCards(deck); // Bind the click function for every card on the new board $('.container').click(function() { clickCard(this); }); }; buildGameBoard(); // Flip the clicked card and if &gt; 1 card is flip check for a match // container - the container of the card that was clicked var clickCard = function(container) { var cardId = $(container).attr('id'); // Do we currently have two cards flipped? Which implies we are checking for a match if(cardsToFlip.length &lt; 2) { // Flip the card if we don't have two cards flipped and the card clicked // is not the same card that is already flipped if(cardsToFlip.length &lt;= 1 &amp;&amp; cardsToFlip[0] !== cardId){ cardsToFlip.push(cardId); flipCard(container); } // If there are two cards flipped over check for a match if(cardsToFlip.length === 2){ // checkMatch is delayed 2 seconds to allow player to look at cards setTimeout(function(){ checkMatch(); }, 2000); } } } function incrementScoreBoard() { matches += 1; $('.matches').html(matches); score += 10 * multiplier; $('.score').html(score); $('.mult').html('10X'); multiplier = 10; } // Check to see if the two cards which are flipped over are a match var checkMatch = function() { console.log('checkMatch called!'); var cardOneClass = $('#' + cardsToFlip[0]).find('.card').data('cardClass'); var cardTwoClass = $('#' + cardsToFlip[1]).find('.card').data('cardClass'); if(cardOneClass === cardTwoClass){ // Do these cards match? // Clear the cards from the board, increment the score board, and // check to see if the user won. $(cardsToFlip).each(function(i, e){ $("#" + e).html(''); }); incrementScoreBoard(); checkForWin(); } else { // No match so lower the multiplyer if(multiplier !== 1){ multiplier -= 1; } $('.mult').html(multiplier + 'X'); // Flip the cards onto their back side $(cardsToFlip).each(function(i, e){ flipCard($("#" + e)); }); } // Add the cards which were just flipped to the previous card area $('.prev-card1').attr('class', 'card back prev-card1 ' + prevCardClasses[0]); $('.prev-card2').attr('class', 'card back prev-card2 ' + prevCardClasses[1]); prevCardClasses = []; cardsToFlip = []; }; // Flip the card container in the given container. var flipCard = function(container) { var classToRemove, classToAdd, flipDir; var $cardContainer = $(container).children('.card-container'); var $card = $cardContainer.children('.card'); var cardSide = $cardContainer.data('cardSide'); var cardClass = $card.data('cardClass'); if(cardSide === 'back'){ // Is this card face down? classToRemove = 'back'; classToAdd = cardClass; flipDir = 'rl'; $cardContainer.data('cardSide', 'front'); } else { // This card is face up. classToRemove = 'front ' + cardClass; classToAdd = 'back'; flipDir = 'lr'; $cardContainer.data('cardSide', 'back'); prevCardClasses.push(cardClass); } // Use jquery.flip plugin to flip the card up or down depending on vars // set previously $card.css("background-color", "#AB0000" ); $card.flip({ direction: flipDir, onBefore: function() { $card.removeClass(classToRemove).addClass(classToAdd); }, onEnd: function() { $card.css({ 'background-color': 'rgba(0, 0, 0, 0.0)' }); }, speed: '200', color: '#AB0000' }); }; }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T01:10:32.283", "Id": "27896", "Score": "5", "body": "You can look at this post to see the [difference between a function expression vs declaration in Javascript][1]\r\n\r\n\r\n [1]: http://stackoverflow.com/questions/1013385/what-is-the-difference-between-a-function-expression-vs-declaration-in-javascrip" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T10:25:42.470", "Id": "27916", "Score": "1", "body": "Pretty nice update. Perhaps the `checkMatch` function is still doing a little too much (i.e. not just checking for a match, but also calculating the multiplier, flipping cards, updating the prev-cards stuff). That's the kind of stuff that could be broken into separate functions. But I'll let someone else take a closer look this time :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-23T16:07:21.510", "Id": "63164", "Score": "0", "body": "The link you provided is dead, can you provide a link to the previous review ?" } ]
[ { "body": "<p>I like your code</p>\n\n<ul>\n<li>\"Use Strict\" within a IFFE</li>\n<li>Good level of comments</li>\n<li>Correct casing and decent naming</li>\n<li>Nice size of methods</li>\n</ul>\n\n<p>Some very minor stuff</p>\n\n<ul>\n<li>JsHint says you never use <code>that</code> ( line 12 ) nor <code>i</code> declard on line 163 and line 171</li>\n<li>function(){} should not have a semicolon after the closing curly brace (<code>buildCards</code>)</li>\n<li>var f = function(){} should have a semicolon after the closing curly brace (<code>clickCard</code>)</li>\n<li>You have a magical constant in <code>buildCards</code> which could be extracted and named.</li>\n<li>You have a magical constant in <code>incrementScoreBoard</code> which could be extracted and named.</li>\n<li>You should take out all debugging related code in your final version</li>\n</ul>\n\n<p>As for <code>var funcName = function(){};</code> versus <code>function funcName() {};</code>, I always thought the second form was silly. Until I read <a href=\"http://ejohn.org/blog/javascript-as-a-first-language/\" rel=\"nofollow\">this</a>:</p>\n\n<pre><code>// Don't do this:\nfunction getData() { }\n\n// Do this instead:\nvar getData = function() { };\n</code></pre>\n\n<p>Whenever JR says something about JavaScript, one should pay attention. Since 2011 though we have come to the practical conclusion that anonymous functions in the callstack are a major PITA. which means that if we stick to 'Do this instead' we ought to write.</p>\n\n<pre><code>var getData = function getData(){};\n</code></pre>\n\n<p>And that just looks wrong ( not DRY ), and should be avoided in my book.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-07T00:31:34.660", "Id": "64667", "Score": "0", "body": "Hey, I posted this a long time ago and it's long since been forgotten, but thanks for the feedback. One interesting thing you brought up that I've just recently started changing about my code is the\n\n`var funcName = function(){}; versus function funcName() {};` convention. After this project I start doing the former, but I recently switched to the latter. I switched because of the function.name field which isn't populated when using the anon function route. Using your last example ('var getData..') would fix this issue, but I agree with you on the ugliness. What do you do exactly?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-30T14:14:02.060", "Id": "38323", "ParentId": "17542", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T00:57:52.540", "Id": "17542", "Score": "5", "Tags": [ "javascript", "html", "css", "game", "playing-cards" ], "Title": "Card-matching game" }
17542
<p>I have created iterator and generator versions of Python's <a href="http://docs.python.org/library/functions.html#range" rel="nofollow"><code>range()</code></a>:</p> <h3>Generator version</h3> <pre><code>def irange(*args): if len(args) &gt; 3: raise TypeError('irange() expected at most 3 arguments, got %s' % (len(args))) elif len(args) == 1: start_element = 0 end_element = args[0] step = 1 else: start_element = args[0] end_element = args[1] if len(args) == 2: step = 1 elif (args[2] % 1 == 0 and args[2] != 0): step = args[2] else: raise ValueError('irange() step argument must not be zero') if((type(start_element) is str) or (type(end_element) is str) or (type(step) is str)): raise TypeError('irange() integer expected, got str') count = 0 while (( start_element + step &lt; end_element ) if 0 &lt; step else ( end_element &lt; start_element + step )) : if count == 0: item = start_element else: item = start_element + step start_element = item count +=1 yield item </code></pre> <h3>Iterator version</h3> <pre><code>class Irange: def __init__(self, start_element, end_element=None, step=1): if step == 0: raise ValueError('Irange() step argument must not be zero') if((type(start_element) is str) or (type(end_element) is str) or (type(step) is str)): raise TypeError('Irange() integer expected, got str') self.start_element = start_element self.end_element = end_element self.step = step self.index = 0 if end_element is None: self.start_element = 0 self.end_element = start_element def __iter__(self): return self def next(self): if self.index == 0: self.item = self.start_element else: self.item = self.start_element + self.step if self.step &gt; 0: if self.item &gt;= self.end_element: raise StopIteration elif self.step &lt; 0: if self.item &lt;= self.end_element: raise StopIteration self.start_element = self.item self.index += 1 return self.item </code></pre> <h3>Usage</h3> <pre><code> &gt;&gt;&gt; for i in irange(2,5): ... print i, 2 3 4 &gt;&gt;&gt; for i in irange(2,-3,-1): ... print i, 2 1 0 -1 -2 &gt;&gt;&gt; for i in Irange(3): ... print i, 0 1 2 </code></pre> <p>I would like to know if the approach is correct.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T18:10:01.257", "Id": "29647", "Score": "1", "body": "how is this different than `xrange`? Or are you just testing your ability to write generators/iterators?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T18:16:49.140", "Id": "29649", "Score": "0", "body": "This is same as xrange but using generator/iterator" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T19:03:54.870", "Id": "29651", "Score": "1", "body": "If you are looking for the behavior of an iterator, does this accomplish the same for you? `def irange(*args): return iter(xrange(*args))`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-16T04:59:08.223", "Id": "29765", "Score": "0", "body": "this sounds good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-18T15:50:19.880", "Id": "44997", "Score": "0", "body": "In python 2 xrange is an iterable returning an Iterator http://stackoverflow.com/a/10776268/639650" } ]
[ { "body": "<p>First of all, to validate that the function is working,\nit's good to use <code>assert</code> statements:</p>\n\n<pre><code>assert [0, 1, 2, 3, 4] == [x for x in irange(5)]\nassert [2, 3, 4] == [x for x in irange(2, 5)]\nassert [2, 1, 0, -1, -2] == [x for x in irange(2, -3, -1)]\n</code></pre>\n\n<p>With these statements covering my back,\nI refactored your <code>irange</code> method to this:</p>\n\n<pre><code>def irange(*args):\n len_args = len(args)\n\n if len_args &gt; 3:\n raise TypeError('irange() expected at most 3 arguments, got %s' % len_args)\n\n if len_args &lt; 1:\n raise TypeError('irange() expected at least 1 arguments, got %s' % len_args)\n\n sanitized_args = [int(x) for x in args]\n\n if len_args == 1:\n start_element = 0\n end_element = sanitized_args[0]\n step = 1\n else:\n start_element = sanitized_args[0]\n end_element = sanitized_args[1]\n step = 1 if len_args == 2 else sanitized_args[2]\n\n current = start_element\n\n if step &gt; 0:\n def should_continue():\n return current &lt; end_element\n else:\n def should_continue():\n return current &gt; end_element\n\n while should_continue():\n yield current\n current += step\n</code></pre>\n\n<p>Points of improvement:</p>\n\n<ul>\n<li>Since <code>len(args)</code> is used repeatedly, I cache it in <code>len_args</code></li>\n<li>Added <code>len(args) &lt; 1</code> check too, in the same fashion as <code>len(args) &gt; 3</code></li>\n<li>Simplified the type checking of args:\n<ul>\n<li>Sanitize with a single, simple list comprehension</li>\n<li>If there are any non-integer arguments, a <code>ValueError</code> will be raised with a reasonably understandable error message</li>\n</ul></li>\n<li>Simplified the initialization of <code>start_element</code>, <code>end_element</code> and <code>step</code></li>\n<li>Greatly simplified the stepping logic</li>\n</ul>\n\n<p>As for the iterator version,\nit would be easiest and best to implement that in terms of the generator version.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-21T08:12:51.320", "Id": "74378", "ParentId": "17543", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T03:15:57.977", "Id": "17543", "Score": "4", "Tags": [ "python", "reinventing-the-wheel", "iterator", "generator" ], "Title": "Iterator and Generator versions of Python's range()" }
17543
<p>I have a use case where I want to use both <code>HttpRequestInterceptor</code> and <code>HttpResponseInterceptor</code> in one <code>class</code>.</p> <p><br/> I'm asking if the following would be a good solution and what are the potential problems?</p> <pre><code>public interface HttpRequestResponseInterceptor extends HttpRequestInterceptor, HttpResponseInterceptor {} </code></pre> <p><br/> Then I implement this interface:</p> <pre><code>public class AuthenticatingResponseInterceptor implements HttpRequestResponseInterceptor{ private static final String TAG = AuthenticatingResponseInterceptor.class.getSimpleName(); @Inject private Authenticator authenticator; @Inject private CookieStore cookieStore; @Inject private RequestCache requestCache; @Override public void process(HttpResponse httpResponse, HttpContext httpContext) throws HttpException, IOException { //Implementation } @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { //Implementation } } </code></pre> <p><br/> The part I am unsure about it is when I pass this into 2 separate methods:</p> <pre><code>@Inject private HttpRequestResponseInterceptor interceptor; httpClient.addResponseInterceptor(interceptor); httpClient.addRequestInterceptor(interceptor); </code></pre> <p>I should probably point out that the <code>HttpRequestResponseInterceptor</code> is a singleton. Is this a good solution?</p>
[]
[ { "body": "<p>You don't necessarily need to have another interface that extends the two you want to combine, you just have to say that he class implements both of them. One java class can implement as many interfaces as you desire. </p>\n\n<p>Problems may arise if you have any shared data problems, but by saying you are implementing the interface you are guaranteeing that the class has the specified functions.</p>\n\n<hr>\n\n<pre><code>import java.util.concurrent.Callable;\nimport java.util.concurrent.ExecutorService;\nimport java.util.concurrent.Executors;\n\npublic class MyClass{\n\n\n public interface Combined extends Runnable, Callable&lt;Object&gt; {}\n\npublic class Mixed implements Runnable, Callable&lt;Object&gt; {\n\n @Override\n public Mixed call() throws Exception {\n System.out.println(\"Called Mixed\");\n return this;\n }\n\n @Override\n public void run() {\n System.out.println(\"Ran Mixed\");\n }\n\n}\n\npublic class Single implements Combined{\n @Override\n public Single call() throws Exception {\n System.out.println(\"Called Single\");\n return this;\n }\n\n @Override\n public void run() {\n System.out.println(\"Ran Single\");\n }\n}\n\n/**\n * @param args\n */\npublic static void main(String[] args) {\n MyClass top = new MyClass();\n Mixed mixed = top.new Mixed();\n Single single = top.new Single();\n ExecutorService es = Executors.newFixedThreadPool(1);\n\n es.execute(mixed);\n es.execute(single);\n\n es.submit((Callable&lt;Object&gt;) mixed);\n es.submit((Callable&lt;Object&gt;) single);\n\n}\n\n}\n</code></pre>\n\n<p>Output is:</p>\n\n<pre><code>Ran Mixed\nRan Single\nCalled Mixed\nCalled Single\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T16:39:29.317", "Id": "27964", "Score": "0", "body": "no the problem comes when instanisating. As I want to pass the same object into 2 separate methods which require 2 separate types. As shown in the last part of the code" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T16:50:04.203", "Id": "27965", "Score": "1", "body": "Which is exactly what interfaces are for. Because it extends an interface it can be treated as that object, so there is no problem, unless you don't actually implement said interface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T17:03:17.260", "Id": "27966", "Score": "0", "body": "yes but you can only instantiate one object that is instansiate as both HttpRequestResponseInterceptor and HttpRequestRequestInterceptor, unless you use my approach. Or am I wrong in saying that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T18:49:16.207", "Id": "27969", "Score": "1", "body": "Absolutely wrong. The interface only guarantees that the functions it defines are present in the class that implements them. It can make your code cleaner if you have one interface that extends many, but it doesn't change anything. The code that calls your class could care less what else it has in it, unless it uses reflection it only sees the methods guaranteed by the interface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T07:51:30.660", "Id": "27988", "Score": "0", "body": "Ah ok, I missed a little details out, In my case I am using google guice to inject a specific instance so I define only the interface and not the class. In any case this has cleared things up" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T15:14:47.343", "Id": "28016", "Score": "0", "body": "It doesn't matter how you provide a class, where it comes from, what it does inside, or who provides it. If it implements an interface it HAS to have the desired methods, or the compiler won't let it compile. So you really don't have to worry about what you get when you interact with the actual implementation of the interface." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T16:08:47.820", "Id": "28022", "Score": "0", "body": "but surely it will not compile when you do the following...\n\nCallable mixed = new Mixed();\nes.execute(mixed);" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:43:22.770", "Id": "28047", "Score": "0", "body": "Ok, I see where the confusion is. You are correct in your last statement because it will be treated as a Callable object, which is not a Runnable. You are getting around that limitation by providing an interface that combines the other interfaces, which you don't have to do if you just provide the name of a class that implements the interfaces. private HttpRequestResponseInterceptor interceptor; could be replaced with private AuthenticatingResponseInterceptor interceptor; and get the same result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T07:32:46.677", "Id": "28082", "Score": "0", "body": "Well thats why I mentioned Google guice. That provides the class for me, which ever I need." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T16:27:49.833", "Id": "17573", "ParentId": "17551", "Score": "4" } } ]
{ "AcceptedAnswerId": "17573", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T11:33:24.670", "Id": "17551", "Score": "5", "Tags": [ "java", "android" ], "Title": "Is this the best approch to combine 2 Interfaces?" }
17551
<p>This is a Java method that takes as input a 2 dimensional array called <code>grid</code>.</p> <p>It uses the <code>i1</code> and <code>j1</code> values from when the corresponding <code>grid[i1][j1]</code> position is <code>true</code> for the first time, and then <code>i2</code> and <code>j2</code> from when the corresponding <code>grid[i2][j2]</code> position is <code>true</code> for the second time. </p> <p>A call is then made to <code>drawLine(i1, j1, i2, j2)</code> to draw line between those two points in the screen. </p> <p>I wrote the following code to take all stuff I want to plot, but the code works but looks bad, is there any better way to write this. This code works fine, I just want to improve on it.</p> <pre><code> for(int x1 = 0; x1 &lt; rows; x1++) { for (int y1 = 0; y1 &lt; columns; y1++) { if (grid[x1][y1] == true) { int x2 = x1 + 1; for(int y2 = 0; y2 &lt; 500; y2++) { if (grid[x2][y2] == true) { drawLine(x1, y1, x2, y2); break; } } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T00:55:20.120", "Id": "27921", "Score": "0", "body": "Watever language the above code is, Its a small piece of code so performance wont matter much unless you are providing really large data. However, declaring a integer inside two for loops may decrease the performance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T00:56:36.037", "Id": "27922", "Score": "3", "body": "Also, what's the significance of that \"magic number\" `500`. You should declare this as a well-made constant so that its meaning is clear (and so it can be re-used more easily without needing to update its value in more than one place)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-13T03:47:37.527", "Id": "27923", "Score": "0", "body": "Your break statement breaks out of only the inner-most for loop. Do you intend for it to continue looking for other lines to draw?" } ]
[ { "body": "<p>I would create a support method that knows to look for the next true value in the grid</p>\n\n<pre><code>void FindTrue(int &amp;x, int &amp;y, bool[][] grid)\n{\n for(; x &lt; rows; x++, y = 0)\n for(; y &lt; columns; y++)\n if (grid[x][y]) return;\n}\n</code></pre>\n\n<p>now your method can call this method like this:</p>\n\n<ol>\n<li>With x=0,y=0 and after that store them to x1, x2.</li>\n<li>Advance x, y by one locating (may need to drop a line).</li>\n<li>With untouched x, y.</li>\n<li>Call drawLine(x1,y1,x,y)</li>\n</ol>\n\n<p>consider this pseudo code cuz I am not fluent in java.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T01:39:33.487", "Id": "27924", "Score": "0", "body": "+1. NB my answer is roughly a concrete (albeit C#.Net, not java) implementation of this answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T01:07:14.983", "Id": "17554", "ParentId": "17553", "Score": "2" } }, { "body": "<p>try the while loop</p>\n\n<pre><code>while(true) {\n int x1 = 0;\n if(x1 &lt; rows) break;\n\n for (int y1 = 0; y1 &lt; columns; y1++) { \n if (grid[x1][y1] == true) { \n int x2 = x1 + 1; \n for(int y2 = 0; y2 &lt; 500; y2++) { \n if (grid[x2][y2] == true) { .\n drawLine(x1, y1, x2, y2); \n break; \n }\n }\n }\n }\n x1++;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T01:23:04.847", "Id": "17555", "ParentId": "17553", "Score": "0" } }, { "body": "<p>My implementation:</p>\n\n<p>(Is C#.Net but you'll be able to translate easily).</p>\n\n<pre><code> public class Point()\n {\n public int X {get; set;}\n public int Y {get; set;}\n\n public Point (int x, int y)\n {\n this.X=x;\n this.Y=y;\n }\n }\n\n public void calcLine(bool[][] grid)\n {\n int rows = 500;\n int columns = 500;\n\n Point p1 = new Point(0, 0);\n // Change this outer 'if' to 'while' if should continue searching for all lines to draw\n if (canFindNextPoint(grid, rows, columns, p1))\n {\n Point p2 = new Point(p1.X + 1, 0);\n if (canFindNextPoint(grid, rows, columns, p2))\n {\n drawline(p1.X, p1.Y, p2.Y, p2.Y);\n }\n }\n }\n\n private bool canFindNextPoint(bool[][] grid, int rows, int columns, Point p)\n {\n bool found = false;\n for (int x = p.X; x &lt; rows; x++)\n for (int y = p.Y; y &lt; columns; y++)\n if (grid[x][y])\n {\n found = true;\n p.X = x;\n p.Y = y;\n break;\n }\n return found;\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T01:29:28.007", "Id": "27925", "Score": "0", "body": "Which is actually pretty much a concrete implementation of @Algebra's answer, I think." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T01:54:14.860", "Id": "27926", "Score": "0", "body": "I understood your idea but I cannot write this in Java as I cannot pass parameters by reference in Java? like is there any \"passing parameters by value\" alternative of this code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T02:12:20.310", "Id": "27927", "Score": "0", "body": "Ouch. A cleaner approach would be to wrap your x,y values as a \"Point\" _object_, with x and y _properties_. You can then pass your \"point\" in (and while the _reference_ to your point object will be passed as a by-value parameter, you'll still be able to work on the point _object_ that is referenced, and its new values will be available to the calling scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T02:17:42.003", "Id": "27928", "Score": "0", "body": "@user1739762 Have updated answer to reflect this suggestion. Thanks for the accept!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T05:12:36.670", "Id": "27980", "Score": "0", "body": "+1. It seems easy to miss that `canFindNextPoint` modifies the given `Point` instance. Instead of this I'd return a new `Point` object or `null` and rename the method to `getNextPoint` or something similar." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:34:55.650", "Id": "27982", "Score": "0", "body": "@palacsint I had originally posted a .NET-based solution, which just passed X & Y parameters by reference, and hence it is obvious in .NET due to the `ref` keyword proceeding them that X and Y were being changed. So yes agree in principal with your more functional-programming approach of _returning_ the next value rather than it being a \"side effect\" of the test. A rename of the method could clarify this though, eg `haveUpdatedPointToNextPoint` (although as I'm writing that, I'm cringing a little...)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T01:28:05.903", "Id": "17556", "ParentId": "17553", "Score": "3" } } ]
{ "AcceptedAnswerId": "17556", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T00:50:27.720", "Id": "17553", "Score": "10", "Tags": [ "java" ], "Title": "Better way to write nested loop, if condition and breaking it" }
17553
<p>I'm trying to make a Node.js server as minimal as possible to show a landing page, but i'm not sure this is the greatest and fastest way to do it.</p> <p>I'm using dirty to store my html data.</p> <p><strong>My app.js file</strong></p> <pre><code>var http = require('http') , db = require('dirty')('pages.db') , url = require('url') , fs = require('fs'); http.createServer(function (request, response) { var pathname = url.parse(request.url).pathname; var html = db.get(pathname); //Check if the requsted file is CSS or JS if (/\.(css)$/.test(pathname) || /\.(js)$/.test(pathname)){ fs.createReadStream(__dirname + pathname, { 'bufferSize': 4 * 1024 }).pipe(response) } else if (!!html &amp;&amp; pathname !== '/admin' ) { //Pages from our Dirty DB response.writeHead(200, {'Content-Type': 'text/html'}); response.end(html); } else if (pathname === '/admin') { //Display Admin page response.writeHead(200, {'Content-Type': 'text/html'}); response.end('Admin!'); } else { //Show 404 Page response.writeHead(404, {'Content-Type': 'text/html'}); response.end(db.get('404')); } }).listen(80); console.log('Server running at http://192.168.56.101:80/'); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T13:00:16.237", "Id": "27932", "Score": "0", "body": "You question is a little vague. You code looks acceptable... you may want to add a response.end() after .pipe(response), I'm not sure if it's really necessary though. Also it seems like your assuming paths will always be in lower case, is it alright to assume that url.parse(request.url) will produce lowercase paths?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T13:19:56.427", "Id": "27933", "Score": "0", "body": "Adding response.end() seems to break the code. And with the lowercase paths, yes I do assume they will be all lowercase." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T14:43:15.527", "Id": "27934", "Score": "0", "body": "According to the documentation for `stream`, `pipe()` will call the destination's `end()` method when the source stream emits an `end` event, unless you use `{ end: false }` as its second argument. Calling `end()` more than once on a stream is an error." } ]
[ { "body": "<p>Good question,\nmade me learn some more about <code>dirty</code>.</p>\n\n<p>Some observations:</p>\n\n<ul>\n<li>1 <code>var</code> block is good, having the commas not at the end of each line looks odd</li>\n<li>I wonder if it is faster to get the extension of the requested resource and compare to <code>js</code> and <code>css</code> instead of executing 2 regexes</li>\n<li>Your 3 <code>if</code> blocks contain the same statement: <code>response.writeHead(200, {'Content-Type': 'text/html'});</code> you should extract that statement into 1 place.</li>\n<li>'80' should be in a <code>var</code> which you then use for your last <code>console.log</code> statement</li>\n<li>Similarly, hard coding the ip address in your <code>log</code> statement does not make sense, you should get that info from node.</li>\n<li>Always calculating 4*1024 and creating an options object seems like a lot work, that ought to get done only once\n*</li>\n</ul>\n\n<p>I would counter propose something like this:</p>\n\n<pre><code>var http = require('http'),\n db = require('dirty')('pages.db'),\n url = require('url'),\n fs = require('fs'),\n port = 80,\n streamOptions = { 'bufferSize': 4 * 1024 },\n htmlHeader = {'Content-Type': 'text/html'};\n\nhttp.createServer(function (request, response)\n{\n var pathname = url.parse(request.url).pathname;\n var html = db.get(pathname);\n\n //First check if the requsted file is css or js\n if (/\\.(css)$/.test(pathname) || /\\.(js)$/.test(pathname))\n {\n fs.createReadStream(__dirname + pathname,streamOptions).pipe(response);\n } \n else \n {\n response.writeHead(200, htmlHeader );\n if (!!html &amp;&amp; pathname !== '/admin' ) \n { //Pages from our Dirty DB \n response.end(html); \n } \n else if (pathname === '/admin') \n { //Display Admin page\n response.end('Admin!'); \n } \n else \n { //Not found..\n response.end(db.get('404'));\n }\n }\n }).listen(port);\n\nconsole.log('Server running on port' , port );\n</code></pre>\n\n<p>If you absolutely want to show the IP address, then you should check out this excellent <a href=\"https://stackoverflow.com/q/3653065/7602\">question</a>.</p>\n\n<p>Finally, any hacker can access your admin pages with <code>/./admin</code> tricks unless either <code>dirty</code> or <code>url</code> is smarter than I give it credit for.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T14:32:39.203", "Id": "40848", "ParentId": "17560", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-12T12:46:23.870", "Id": "17560", "Score": "2", "Tags": [ "javascript", "node.js" ], "Title": "Node.js Is this a great way to show pages in a minimal way as possible?" }
17560
<p>I had an exercise as below for an interview. I used two design patterns: factory and decorator. I put my code at the end of it. </p> <p>How could I improve the solution?</p> <hr> <h2>Basic OOD &amp; Solution Design Requirements</h2> <p>Develop a simple Visual Studio CONSOLE Application which simulates a vector-based drawing package.<br> Your application should support the following 5 drawing primitives (we'll call them widgets):</p> <p>1) rectangle 2) square 3) ellipse 4) circle 5) textbox</p> <p>The application should allow a user to Add a new widget to the drawing, stating the location and size/shape of the widget.<br> The location can be a standard x/y coordinate on an imaginary page. The size/shape depends on the widget, as follows:</p> <ul> <li>rectangle – width and height</li> <li>square – width</li> <li>ellipse –horizontal and vertical diameter</li> <li>circle – diameter</li> <li>textbox – bounding rectangle (i.e., the rectangle which surrounds the textbox; the text will be centred within this rectangle).</li> </ul> <p>NOTE: - there is no need to worry about rotation. - integer units are fine for all dimensions. - for the textbox you only need to configure the text to display (which will be rendered horizontally within the bounding rectangle). Don’t worry about font face /size / alignment, etc. - as per our coding standards, please use a separate .cs file for each class.</p> <p>Your console application should be able to 'print out' the current drawing by printing the key details of each widget (type, location, size/shape) to the console.<br> You don't need to actually render the widgets in any manner - we're just simulating a drawing package at this stage.</p> <p>Your application can use the Console Application Main() method to test the drawing simulator by adding a hard-coded set of widgets to the drawing. </p> <p>PLEASE ADD ONE OF EACH WIDGET TO YOUR DRAWING</p> <p>*<em>*</em> Important Note: You DO NOT need to concern yourself with handling any input from the user. Our widgets will be hard-coded within the Main() method.</p> <p>Time allowed: 2 hours. </p> <p><strong>My solution follows:</strong></p> <pre><code>public interface IDraw { void Print(); } class Shape { private int X { get; set; } private int Y { get; set; } public Shape(int x, int y) { this.X = x; this.Y = y; } public string GetLocation() { return "(" + this.X + "," + this.Y + ")"; } } class Square : Shape, IDraw { public Square(int x, int y) : base(x, y) { } public int size { get; set; } public void Print() { Console.WriteLine("{0} {1} size={2}", typeof(Square).Name, base.GetLocation(), this.size); } } class Rectangle : Shape, IDraw { public int Width { get; set; } public int Height { get; set; } public Rectangle(int x, int y) : base(x, y) { } class Textbox : Rectangle, IDraw { public Textbox(int x, int y) : base(x, y) { } public string Text { get; set; } public new void Print() { Console.WriteLine("{0} {1} Width={2} Height={3} Text={4}", typeof(Textbox).Name, base.GetLocation(), this.Width, this.Height, "\"" + this.Text + "\""); } } public void Print() { Console.WriteLine("{0} {1} Width={2} Height={3} ", typeof(Rectangle).Name, base.GetLocation(), this.Width, this.Height); } } class Ellipse : Shape, IDraw { public Ellipse(int x, int y) : base(x, y) { } public int HorizontalDiameter { get; set; } public int VerticalDiameter { get; set; } public void Print() { Console.WriteLine("{0} {1} diameterH={2} diameterY={3}", typeof(Ellipse).Name, base.GetLocation(), this.HorizontalDiameter, this.VerticalDiameter); } } class Circle : Shape, IDraw { public Circle(int x, int y) : base(x, y) { } public int size { get; set; } public void Print() { Console.WriteLine("{0} {1} size={2}", typeof(Circle).Name, base.GetLocation(), this.size); } } class Program { static void Main(string[] args) { //Hard-coded set of widgets var widgets = new List&lt;IDraw&gt;() { new Rectangle(10, 10) { Width = 30, Height = 40 }, new Square(15, 30) { size = 35 }, new Ellipse(100, 150) { HorizontalDiameter = 300, VerticalDiameter = 200 }, new Circle(1, 1) { size = 300 }, new Textbox(5, 5) { Width = 200, Height = 100, Text = "Sample text!" } }; foreach (var widget in widgets) { try { widget.Print(); } catch (Exception ex) { Console.WriteLine(ex.Message); } } Console.ReadKey(); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T14:57:24.007", "Id": "27936", "Score": "1", "body": "This isn't really on topic for SO. Programmers...maybe. (If you re-work the actual question you're asking.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T14:58:19.880", "Id": "27937", "Score": "3", "body": "We can't tell you _why_ someone else decided against you. Could be any number of reasons. Call them and ask for feedback - you might learn something." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T14:58:47.540", "Id": "27938", "Score": "0", "body": "@Servy - Not the way it is, not if the question is about _why_ this is supposedly incorrect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T15:00:17.110", "Id": "27939", "Score": "0", "body": "@Oded Yeah, that's why I said \"maybe\". It's more that, this question can't really be fixed up enough to stay on SO; it might be able to be re-phrased into something that's appropriate for programmers. It's also why I voted to close as NARQ rather than off topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T15:12:25.487", "Id": "27940", "Score": "0", "body": "Did you not implement \"Textbox\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T15:17:58.920", "Id": "27941", "Score": "0", "body": "I had implemented that class as well I just put it in the code:)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T15:43:46.680", "Id": "27942", "Score": "0", "body": "Why didn't you use Factory and Decorator?" } ]
[ { "body": "<p>Off the bat I see a couple of things with regards to MS published coding standards, although I'm not sure what their standards are.</p>\n\n<p>I'm not sure why the X/Y locations are private. Seems to me that you'd want those properties exposed as public members with regular fields backing them and default values set. Exa:</p>\n\n<pre><code>private int _x = 0;\npublic int X { \n get { return _x; }\n set { _x = value; }\n}\n</code></pre>\n\n<p>As it stands now, the only way to get the location is through the GetLocation method which returns a string already formatted for display... not exactly what you want as that couples display to implementation which is a no-no.</p>\n\n<p>Next public properties should always follow proper capitalization. You have:</p>\n\n<p><code>public int size { get; set; }</code></p>\n\n<p>which should be:</p>\n\n<p><code>public int Size { get; set; }</code></p>\n\n<p>Although, again, I'd set a default value or ensure some type of constraints on it.</p>\n\n<p>Next, instead of having a generic try .. catch. I'd simply test if the object implemented the IDraw interface and, if so, call it's method. The try .. catch, especially with a generic catch, is lazy and for those whom performance is critical not a good thing.</p>\n\n<p>Finally, I'm not sure that I would implement the print formatting within the classes themselves anyway. Again, that's coupling presentation with logic. Perhaps it would have been better to have another class whose job it is to emit the objects.</p>\n\n<p>Finally/Finally, I would think 2 hours is probably 4 times longer than necessary to whip this out, even under pressure. Then again, I type fast.</p>\n\n<hr>\n\n<p>All in all, if I was judging your entry against the requirements I'd estimate that you were a junior developer that needs some training. Yes, you met the requirements however the code itself would need additional work before going into a production type environment. If I was looking for a senior guy I wouldn't bother bringing you in for more questions. </p>\n\n<p>Hope that helps. This answer is not meant to be bashing in any way but rather just a real world breakdown of what one person that routinely hires developers (not for them) sees wrong. So I hope it's taken in that vain.</p>\n\n<hr>\n\n<p>Just my 0.02. Apart from the above points, especially since you presented it as a simple OOD exercise, I would have implemented a \"Drawing\" class with Print and Add methods instead of using a simple List.</p>\n\n<p>Furthermore, your use of the new modifier in the Print method of Rectangle really annoys me, and would have made me look for someone else.</p>\n\n<p>I think that I would have defined Shape as implementing IDraw, too, with a virtual version of Print printing just the position of the Shape (or even an abstract version of the method, if you prefer). Then you can override the method as you want in all your subclasses.</p>\n\n<p>In the majority of cases having to use the new modifiers makes me look for bad design decisions. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T15:32:40.727", "Id": "27943", "Score": "1", "body": "For the record, I did vote to close AND answered the question (in a wiki format). I'm not sure this question belongs here but at the same time I think helping people understand how to grow is a good thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T12:04:36.727", "Id": "27944", "Score": "0", "body": "Thank you very much. I think it was a graet review of codes. You are right about creating a new class and having those methods there. It was a main thing that I missied. Not sure why this quetion has been blocked as it is a good practice for reviewing and coding." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T14:01:09.910", "Id": "27945", "Score": "0", "body": "@patricgh: I changed your question slightly to be more inline with a regular code review type instead of asking the community to guess what the hiring team thought." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-05T15:39:01.767", "Id": "27946", "Score": "0", "body": "Thank you very much. I think, now, it makes mush sense than before. Hope it can help other coders." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T16:11:52.593", "Id": "27963", "Score": "1", "body": "\"Typically in c# private variables are prefixed with an underscore.\" Not in current Microsoft standards, no. Camel-cased with no additional decoration is preferred layout for the name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T17:09:11.397", "Id": "27967", "Score": "0", "body": "@JesseC.Slicer: Actually, looking a little closer, the MS guidelines cover protected fields, not private ones that back properties. The issue boils down to CLS Compliancy. You can't have backing fields that have the exact same name, except for case, and be CLS Compliant. Hence, the reason you prepend underscore to the backing field name. It reduces confusion as to public/protected or private and allows you to mark the assembly as CLSCompliant so it can be used by VB, C# or whatever other .net language you want." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T21:23:02.070", "Id": "27977", "Score": "0", "body": "@ChrisLively I think you have that wrong, you can have a private field which differs from a public property only in case but not 2 properties which differ only in case for CLS compliance." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T21:50:15.813", "Id": "27979", "Score": "0", "body": "@TrevorPilley: Just tested.. and I stand corrected regarding CLS compliancy. Updating my post." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T15:08:25.440", "Id": "17562", "ParentId": "17561", "Score": "4" } } ]
{ "AcceptedAnswerId": "17562", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-04T14:54:52.327", "Id": "17561", "Score": "5", "Tags": [ "c#", "object-oriented", "design-patterns" ], "Title": "Basic OOP & Solution Design" }
17561
<pre><code>selected_hour=12 dates=[] date1 = datetime.datetime(2012, 9, 10, 11, 46, 45) date2 = datetime.datetime(2012, 9, 10, 12, 46, 45) date3 = datetime.datetime(2012, 9, 10, 13, 47, 45) date4 = datetime.datetime(2012, 9, 10, 13, 06, 45) dates.append(date1) dates.append(date2) dates.append(date3) dates.append(date4) for i in dates: if (i.hour&lt;=selected_hour+1 and i.hour&gt;=selected_hour-1): if not i.hour==selected_hour: if i.hour==selected_hour-1 and i.minute&gt;45: print i if i.hour==selected_hour+1 and i.minute&lt;=15: print i if i.hour==selected_hour: print i </code></pre> <p>Result is :</p> <pre><code> 2012-09-10 11:46:45 2012-09-10 12:46:45 2012-09-10 13:06:45 </code></pre> <p>I want to filter my dates based on <code>selected_hour</code>. The output should be 15 minutes later and before of the <code>selected_hour</code> including all <code>selected_hour</code>'s minutes. This codes does what I want but, i am looking for a nicer way to do that. How to get same results in a shorter and better way ? </p>
[]
[ { "body": "<p>Try something like this:</p>\n\n<pre><code>for i in dates:\n if i.hour == selected_hour:\n print i\n elif i.hour == (selected_hour - 1) % 24 and i.minute &gt; 45:\n print i\n elif i.hour == (selected_hour + 1) % 24 and i.minute &lt;= 15:\n print i\n</code></pre>\n\n<p>The biggest technique I used to condense your code basically was \"Don't repeat yourself\"! You have a lot of redundant <code>if</code> statements in your code which can be simplified.</p>\n\n<p>Another thing that makes my code more understandable is that it's flat, not nested. Ideally, you'd want to minimize the number of logic branches.</p>\n\n<p>Edit: As @Dougal mentioned, my original code wouldn't work on the special case of midnight. I added in a modulus operator on my two <code>elif</code> conditions so that the <code>selected_hour</code> test wraps in a 24 digit circle, just like real time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:09:32.827", "Id": "27947", "Score": "2", "body": "Note that this doesn't wrap around at midnight well (like the OP's)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:12:03.377", "Id": "27948", "Score": "0", "body": "Maybe I'm not seeing that - what's a datetime that I can see the deficiency with?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:13:07.163", "Id": "27949", "Score": "2", "body": "If we're selecting for 11pm (`i.hour == 23`), then it should presumably allow times up through 12:15am, but this would look for `i.hour == 24`, which won't happen." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:02:37.980", "Id": "17565", "ParentId": "17564", "Score": "5" } }, { "body": "<p>I have a question before the answer. I don't know if you want to filter this case, but if you take this datetime:</p>\n\n<pre><code>selected_hour=12\ndate4 = datetime.datetime(2012, 9, 10, 13, 15, 45)\n</code></pre>\n\n<p>you don't filter that result, and being strict, that datetime is over 15 minutes your selected_hour.</p>\n\n<p>Anyway, if you have the year, month and day too, you can use <code>datetime</code> data type and <code>timedelta</code> to solve this problem.</p>\n\n<pre><code>import datetime\nfrom datetime import timedelta\n\nselected_hour=12\ndates=[]\ndate1 = datetime.datetime(2012, 9, 10, 11, 44, 59)\ndate2 = datetime.datetime(2012, 9, 10, 11, 45, 00)\ndate3 = datetime.datetime(2012, 9, 10, 13, 15, 00)\ndate4 = datetime.datetime(2012, 9, 10, 13, 15, 01)\ndate5 = datetime.datetime(2011, 5, 11, 13, 15, 00)\ndate6 = datetime.datetime(2011, 5, 11, 13, 15, 01)\ndates.append(date1)\ndates.append(date2)\ndates.append(date3)\ndates.append(date4)\ndates.append(date5)\ndates.append(date6)\n\nfor i in dates:\n ref_date = datetime.datetime(i.year, i.month, i.day, selected_hour, 0, 0)\n time_difference = abs( (i-ref_date).total_seconds() )\n if (i &lt; ref_date):\n if time_difference &lt;= 15 * 60:\n print i\n else:\n if time_difference &lt;= 75 * 60:\n print i\n</code></pre>\n\n<p>Result is:</p>\n\n<pre><code>2012-09-10 11:45:00\n2012-09-10 13:15:00\n2011-05-11 13:15:00\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:43:44.733", "Id": "27951", "Score": "1", "body": "I read the question as selecting on the hour without depending on the date itself. It's unfortunate that all the examples used the same date." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:52:24.383", "Id": "27952", "Score": "0", "body": "Yes, you're possibly right. I understood it the other way because of the data. It would be nice if John Smith clarified it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T13:58:18.760", "Id": "27953", "Score": "0", "body": "@MarkRansom I made a change and now it works in the way you mentioned." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T14:32:33.700", "Id": "27954", "Score": "0", "body": "Yes, that's much better. It still has a problem around midnight though - test with `selected_hour=0` and `23:59`." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T02:37:10.797", "Id": "17566", "ParentId": "17564", "Score": "0" } }, { "body": "<p>If you want to ignore the date, then you could use <code>combine</code> to shift every date to some arbitrary base date. Then you can still use datetime inequalities to compare the times:</p>\n\n<pre><code>import datetime as dt\nselected_hour=12\ndate1 = dt.datetime(2011, 9, 10, 11, 46, 45)\ndate2 = dt.datetime(2012, 8, 10, 12, 46, 45)\ndate3 = dt.datetime(2012, 9, 11, 13, 47, 45)\ndate4 = dt.datetime(2012, 10, 10, 13, 06, 45)\ndates=[date1, date2, date3, date4]\n\nbase_date = dt.date(2000,1,1)\nbase_time = dt.time(selected_hour,0,0)\nbase = dt.datetime.combine(base_date, base_time)\nmin15 = dt.timedelta(minutes = 15)\nstart = base - min15\nend = base + 5*min15\n\nfor d in dates:\n if start &lt;= dt.datetime.combine(base_date, d.time()) &lt;= end:\n print(d)\n</code></pre>\n\n<p>yields</p>\n\n<pre><code>2011-09-10 11:46:45\n2012-08-10 12:46:45\n2012-10-10 13:06:45\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T04:23:14.333", "Id": "17567", "ParentId": "17564", "Score": "0" } } ]
{ "AcceptedAnswerId": "17565", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T01:37:45.080", "Id": "17564", "Score": "3", "Tags": [ "python" ], "Title": "filter date for a specific hour and minute" }
17564
<p>I'm making a converter app, and after realising I would have to type about 200 lines of code to get it working with more than 5 units converted, I should have a better conversion calculation.</p> <p>What I have currently is a ifelse that find out what units i selected from the wheel, a sting to find out what it should answer and a float to calculate. It looks like this atm:</p> <pre><code> #import "MainViewController.h" @interface MainViewController () @end @implementation MainViewController; @synthesize _convertFrom, _convertTo, _convertRates; @synthesize inputText, picker, resultLabel; - (void)viewDidLoad { [super viewDidLoad]; { [super viewDidLoad]; _convertFrom = @[@"MTPA", @"MMcf/day", @"Mill.Sm3/day", @"MMBTU", @"Boe/day"]; _convertRates = @[ @1.0f, @2.0f, @3.0f, @4.0f, @5.0f]; _convertTo = @[@"MTPA", @"MMcf/day", @"Mill.Sm3/day", @"MMBTU", @"Boe/day"]; _convertRates = @[ @1.0f, @2.0f, @3.0f, @4.0f, @5.0f]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } -(IBAction)textFieldReturn:(id)sender { [sender resignFirstResponder]; } -(IBAction)backgroundTouched:(id)sender { [inputText resignFirstResponder]; } #pragma mark - #pragma mark PickerView DataSource - (NSInteger)numberOfComponentsInPickerView: (UIPickerView *)pickerView { return 2; } - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component { if (component == 0) { return [_convertFrom count]; } return [_convertTo count]; } - (NSString *) pickerView: (UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if (component == 0) { return [_convertFrom objectAtIndex:row]; } return [_convertTo objectAtIndex:row]; } #pragma mark - #pragma mark PickerView Delegate -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { float convertFrom = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:0]] floatValue]; float convertTo = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:1]] floatValue]; float input = [inputText.text floatValue]; float to = convertTo; float from = convertFrom; float convertValue = input; float MTPATilMTPAFloat = convertValue * 1; float MTPATilMMScfdayFloat = convertValue * 133.425; float MTPATilMillSm3dayFloat = convertValue * 3.779735; float MTPATilMMBTUFloat = convertValue * 4; float MTPATilboedayFloat = convertValue * 5; float MMScfdayTilMTPAFloat = convertValue * 0.5; float MMScfdayTilMMScfdayFloat = convertValue * 1; float MMScfdayTilMillSm3dayFloat = convertValue * 6; float MMScfdayTilMMBTUFloat = convertValue * 7; float MMScfdayTilboedayFloat = convertValue * 8; float MillSm3dayTilMTPAFloat = convertValue / 1; float MillSm3dayTilMMScfdayFloat = convertValue / 2; float MillSm3dayTilMillSm3dayFloat = convertValue / 3; float MillSm3dayTilMMBTUFloat = convertValue / 4; float MillSm3dayTilboedayFloat = convertValue / 5; float MMBTUTilMTPAFloat = convertValue * 2; float MMBTUTilMMScfdayFloat = convertValue * 2; float MMBTUTilMillSm3dayFloat = convertValue * 2; float MMBTUTilMMBTUFloat = convertValue * 2; float MMBTUTilboeday = convertValue * 2; float boedayTilMTPAFloat = convertValue * 3; float boedayTilMMScfdayFloat = convertValue * 3; float boedayTilMillSm3dayFloat = convertValue * 3; float boedayTilMMBTUFloat = convertValue * 3; float boedayTilboeday = convertValue * 3; NSString *MTPATilMTPA = [[NSString alloc ] initWithFormat: @" %f MTPA = %f MTPA", convertValue, MTPATilMTPAFloat]; NSString *MTPATilMMScfday = [[NSString alloc ] initWithFormat: @" %f MTPA = %f MMScf/day", convertValue, MTPATilMMScfdayFloat]; NSString *MTPATilMillSm3day = [[NSString alloc] initWithFormat: @" %f MTPA = %f Mill.SM3/day", convertValue, MTPATilMillSm3dayFloat]; NSString *MTPATilMMBTU = [[NSString alloc] initWithFormat: @" %f MTPA = %f MMBTU", convertValue, MTPATilMMBTUFloat]; NSString *MTPATilboeday = [[NSString alloc] initWithFormat: @" %f MTPA = %f Boe/day", convertValue, MTPATilboedayFloat]; NSString *MMScfdayTilMTPA = [[NSString alloc] initWithFormat: @" %f MMScfday = %f MTPA", convertValue, MMScfdayTilMTPAFloat]; NSString *MMScfdayTilMMScfday = [[NSString alloc] initWithFormat: @" %f MMScfday = %f MMScfday", convertValue, MMScfdayTilMMScfdayFloat]; NSString *MMScfdayTilMillSm3day = [[NSString alloc] initWithFormat: @" %f MMScfday = %f MillSm3day", convertValue, MMScfdayTilMillSm3dayFloat]; NSString *MMScfdayTilMMBTU = [[NSString alloc] initWithFormat: @" %f MMScfday = %f MMBTU", convertValue, MMScfdayTilMMBTUFloat]; NSString *MMScfdayTilboeday = [[NSString alloc] initWithFormat: @" %f MMScfday = %f Boe/day", convertValue, MMScfdayTilboedayFloat]; NSString *MillSm3dayTilMTPA = [[NSString alloc] initWithFormat: @" %f MillSm3day = %f MTPA", convertValue, MillSm3dayTilMTPAFloat]; if (from == 1) { if (to == 1) { resultLabel.text = MTPATilMTPA; } else if (to == 2) { resultLabel.text = MTPATilMMScfday; } else if (to == 3) { resultLabel.text = MTPATilMillSm3day; } else if (to == 4) { resultLabel.text = MTPATilMMBTU; } else if (to == 5) { resultLabel.text = MTPATilboeday; } } else if (from == 2) { if (to == 1) { resultLabel.text = MMScfdayTilMTPA; } else if (to == 2) { resultLabel.text = MMScfdayTilMMScfday; } else if (to == 3) { resultLabel.text = MMScfdayTilMillSm3day; } else if (to == 4) { resultLabel.text = MMScfdayTilMMBTU; } else if (to == 5) { resultLabel.text = MMScfdayTilboeday; } } } </code></pre> <p>As you can see, a huge mess with alot of more code needed if I want more units.</p> <p>When I realised that, i tried to calculate it by using a commmon variable that I convert everything into, and then convert back into a output unit. Think of it with lenght calculation. The common variable i want everything to be converted to first, is meters. so 1 meters = 1, 1 cm = 0.01 and 1 mm = 0.001. So, if I wanted to calculate, i would use.</p> <p>unitIwantToConvertToComparedTo1Meter = 0.5 (of 1 meter) result = from * to * input * unitIwantToConvertToComparedTo1Meter.</p> <p>Which, surprisingly, works. As used here:</p> <pre><code>#import "MainViewController.h" @interface MainViewController () @end @implementation MainViewController; @synthesize _convertFrom, _convertTo, _convertRates; @synthesize inputText, picker, resultLabel; - (void)viewDidLoad { [super viewDidLoad]; { [super viewDidLoad]; _convertFrom = @[@"Kubikk M", @"Kubikk CM", @"Kubikk MM", @"MMBTU", @"Boe/day"]; _convertRates = @[ @1.0f, @0.01f, @0.001f, @4.0f, @5.0f]; _convertTo = @[@"Kubikk M", @"Kubikk CM", @"Kubikk MM", @"MMBTU", @"Boe/day"]; _convertRates = @[ @1.0f, @0.01f, @0.001f, @4.0f, @5.0f]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; } -(IBAction)textFieldReturn:(id)sender { [sender resignFirstResponder]; } -(IBAction)backgroundTouched:(id)sender { [inputText resignFirstResponder]; } #pragma mark - #pragma mark PickerView DataSource - (NSInteger)numberOfComponentsInPickerView: (UIPickerView *)pickerView { return 2; } - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent: (NSInteger)component { if (component == 0) { return [_convertFrom count]; } return [_convertTo count]; } - (NSString *) pickerView: (UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component { if (component == 0) { return [_convertFrom objectAtIndex:row]; } return [_convertTo objectAtIndex:row]; } #pragma mark - #pragma mark PickerView Delegate -(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component { float convertFrom = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:0]] floatValue]; float convertTo = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:1]] floatValue]; float input = [inputText.text floatValue]; float to = convertTo; float from = convertFrom; float convertValue = input; float kubikkfot = 0.1; float result = from * convertValue * kubikkfot; NSString *resultString = [[NSString alloc ] initWithFormat: @" %f MTPA = %f MTPA", convertValue, result]; resultLabel.text = resultString; } </code></pre>
[]
[ { "body": "<p><em><strong>Copied from SO with a few edits and additions.</em></strong></p>\n\n<hr>\n\n<p>Dude use C arrays to create an nxn matrix of conversions. Then just have one array with unit names in it. Done and done. If you don't know what a matrix is, then you have more theory to learn.</p>\n\n<p>It goes like this. <code>M</code> is your conversion matrix:</p>\n\n<pre><code>M: inch meter\n +-----------------\ninch | 1 0.0254\nmeter | 39.3701 1\n</code></pre>\n\n<p>So if <code>x</code> is in inches then <code>M[inch][meter] * x</code> is the same length in meters.</p>\n\n<p>And <code>M[i][j] * M[j][i] == 1</code>. Always.</p>\n\n<p>You will have a different conversion matrix for each quantity that you are measuring. That is, you will have one for heat, one for time, one for distance (the example above), one for energy, one for force... etc.</p>\n\n<p>Then each measure is just an index value:</p>\n\n<pre><code>enum { inch = 0, meter = 1 };\ntypedef unsigned int MeasureType;\n</code></pre>\n\n<p>And you can name them like so:</p>\n\n<pre><code>NSArray *measureNames = [NSArray arrayWithObjects:@\"Inches\", @\"Meters\", nil];\n</code></pre>\n\n<p>And you might want to have images for each:</p>\n\n<pre><code>UIImage *inchesImage = [UIImage imageNamed:@\"inches_icon\"];\nUIImage *metersImage = [UIImage imageNamed:@\"meters_icon\"];\nNSArray *measureImages = [NSArray arrayWithObjects:inchesImage, metersImage, nil];\n</code></pre>\n\n<p>And now you have the foundation for building up your GUI and architecture. More than this I won't answer - unless you pay me!</p>\n\n<p>Good luck!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T13:53:20.430", "Id": "17642", "ParentId": "17575", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T18:28:45.243", "Id": "17575", "Score": "3", "Tags": [ "objective-c", "ios" ], "Title": "Improving calculation code" }
17575
<blockquote> <p>Compute the number of connected component in a matrix, saying M. Given two items with coordinates [x1, y1] and [x2, y2] in M, if</p> <ul> <li>M(x1, y1) == -1 <em>and</em></li> <li>M(x2, y2) == -1 <em>and</em></li> <li>|x1-x2| + |y1-y2| == 1</li> </ul> <p>then they are connected.</p> <p>Example:</p> <pre><code>-1 0 -1 0 0 -1 -1 0 -1 -1 0 0 0 0 -1 0 0 0 -1 -1 0 0 0 -1 0 0 -1 0 0 0 0 -1 0 0 0 </code></pre> <p>Output: 4. And they are:</p> <pre><code>-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 </code></pre> </blockquote> <p>My idea is to scan the matrix. </p> <pre><code>Initialization: count = 0. </code></pre> <p>For every item in the matrix, do the following three tests.</p> <blockquote> <ol> <li><p>If it's 0, skip</p></li> <li><p>If it's -1, check its four neighbors. If there is a neighbor whose value is not 0 and -1, assign the value of this neighbor to the current item. Otherwise, <code>count++</code>, ant then assign <code>count</code> to the current item.</p></li> <li><p>If it's not 0 and -1, assign the value of current item to its four neighbors whose value is -1.</p></li> </ol> </blockquote> <p>The following is my code:</p> <pre><code>int num_cc(int m[][COLS]) { int count = 0; int r; int c; for(r = 0; r &lt; ROWS; ++r) { for(c = 0; c &lt; COLS; ++c) { if(m[r][c] == 0) continue; if(m[r][c] == -1) { if(r-1&gt;=0 &amp;&amp; m[r-1][c] &gt; 0) m[r][c] = m[r-1][c]; else if(r+1&lt;ROWS &amp;&amp; m[r+1][c] &gt; 0) m[r][c] = m[r+1][c]; else if(c-1&gt;=0 &amp;&amp; m[r][c-1] &gt; 0) m[r][c] = m[r][c-1]; else if(c+1&lt;COLS &amp;&amp; m[r][c+1] &gt; 0) m[r][c] = m[r][c+1]; else { count++; m[r][c] = count; } } if(m[r][c] &gt; 0) { if(r-1&gt;=0 &amp;&amp; m[r-1][c] == -1) m[r-1][c] = m[r][c]; if(r+1&lt;ROWS &amp;&amp; m[r+1][c] == -1) m[r+1][c] = m[r][c]; if(c-1&gt;=0 &amp;&amp; m[r][c-1] == -1) m[r][c-1] = m[r][c]; if(c+1&lt;COLS &amp;&amp; m[r][c+1] == -1) m[r][c+1] = m[r][c]; } } } return count; } </code></pre> <p>Can anyone help me verify it? Is it correct? Or is there any other solutions?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T08:48:57.627", "Id": "27991", "Score": "0", "body": "Why is the isolated -1 (item 2 in the output) a component? It isn't connected to anything, assuming that off-the-edge shouldn't count." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T13:58:00.847", "Id": "28008", "Score": "0", "body": "@GlennRogers, the diagonal line is not considered as connected." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:00:35.870", "Id": "28057", "Score": "1", "body": "There is of course a more general solution -http://en.wikipedia.org/wiki/Connected_component_(graph_theory) -, but you would only need that if you want more than just the number of components." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T22:16:14.040", "Id": "28062", "Score": "0", "body": "@Frank Thanks very much. This is an easier question than the more general connected component problem. We only need to compute the number. And We're able to change the element of the matrix." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T05:48:28.047", "Id": "62797", "Score": "0", "body": "Please check the following link: http://en.wikipedia.org/wiki/Connected-component_labeling" } ]
[ { "body": "<p><em>Style</em>: Depending on coding guidelines and preferences you may want to consider moving the declaration of <code>r</code> and <code>c</code> into the for-loops (<code>for (int r = 0...</code>), as these variables are not supposed to be used outside of the loop, and hence, an outside declaration kind of contradicts this contract.</p>\n\n<p><em>Correctness</em>: I'm afraid your greedy approach does not work out well - in other words: it gives wrong results. Consider the following matrix (or if you loop the other way round its symmetric variant) :</p>\n\n<pre><code> 0 0 0 0 -1\n-1 -1 -1 -1 -1\n</code></pre>\n\n<p>By going through the first row first, you would create your first connected group with this intermediate result, before the row-loop switches to the second row:</p>\n\n<pre><code> 0 0 0 0 1\n-1 -1 -1 -1 1\n</code></pre>\n\n<p>Next, the inner loop will find another -1 cell with no higher-numbered neighbors and create a second connected component, although there really is only one.</p>\n\n<p><em>Succinctness</em>: <em>If</em> the code was correct, you might as well eliminate all the <code>if</code> statements in the loop except for the one comparing against -1. The others are redundant in their behavior.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T05:24:00.840", "Id": "17631", "ParentId": "17577", "Score": "5" } } ]
{ "AcceptedAnswerId": "17631", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T01:52:06.600", "Id": "17577", "Score": "4", "Tags": [ "c++", "c", "algorithm", "interview-questions", "matrix" ], "Title": "The number of connected component" }
17577
<p>Which of the following way of checking whether a function returns <code>TRUE</code> or <code>FALSE</code> is best, in terms of efficiency and code readability?</p> <p>I was told by a friend that Method B is a good practice, but I believe Method A is better since it checks whether function returns <code>TRUE</code> then assigns.</p> <p><strong>Method A:</strong> (Checks whether function is TRUE and <strong>then</strong> assigns.)</p> <pre><code>if ($result = $db-&gt;getResults($id)) { echo $result; } else { echo 'fail'; } </code></pre> <p><strong>Method B:</strong> (First <strong>assigns</strong> the value, then <strong>checks</strong>—<em>two operations</em>.)</p> <pre><code>$result = $db-&gt;getResults(90); if ($result) { echo $result; } else { echo 'fail'; } </code></pre> <hr> <pre><code>public function getResults($no) { if ($no &gt; 85) { $result = 'pass'; return $result; } else { return FALSE; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:34:34.920", "Id": "27983", "Score": "0", "body": "I agree with your friend, method B" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:35:06.643", "Id": "27984", "Score": "0", "body": "@bodi0 and the reason being?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:37:06.697", "Id": "27995", "Score": "0", "body": "The reason being readability. People who devise new, contrived & fabulous ways of doing old & simple things should have their fingers broken. This is one of those great cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:21:45.680", "Id": "28001", "Score": "1", "body": "@TC1 In general I agree with you, but I don't think side-effects in conditional expressions are *always* bad. For example, a pseudo-generator in a while block: `while ($result = getNextResult()) { processResult($result); }` – it would be less readable to express this without the assignment in the conditional part of the expression." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:26:11.027", "Id": "28002", "Score": "1", "body": "@kojiro That's only because there's no decent support for `iterable` and `foreach` in PHP, in almost any other language that construction would be `foreach(result in getResults())` or something like that. It's an ugly workaround, but, arguably, necessary evil..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:28:10.010", "Id": "28003", "Score": "0", "body": "@TC1 touché. It's a lesser evil in a language that forces you to do Bad Things™." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T23:08:09.943", "Id": "28670", "Score": "0", "body": "I seem to recall reading \"somewhere\" on php.net that you shouldn't do assignments in conditionals i.e. if ($a = '') {... can anyone find it? Oh well..." } ]
[ { "body": "<p>The performance difference is irrelevant; it is really minor (if not zero) and if such minor differences mattered not using PHP at all would be the only proper solution.</p>\n\n<p>Since you only need the variable in the true-branch of the if statement and it's likely to be something other than just a plain <code>true</code> using <code>if(($foo = bar()))</code> (with the additional parentheses to indicate that it's not supposed to be <code>==</code>) is the cleanest way - but opinions on that will most likely vary.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:35:16.640", "Id": "17579", "ParentId": "17578", "Score": "6" } }, { "body": "<p>Actually, both methods assign the value first before comparing its value. Therefore, in terms of efficiency, there's no difference.</p>\n\n<p>For code readability, you could write extra parentheses around the assignment if you choose method A. Method B has a slight advantage when you have to perform debugging before the branch, i.e.:</p>\n\n<pre><code>$res = $db-&gt;getResult(95);\nvar_dump($res); // added for debugging without having to move the code out of the condition\necho $res ? $res : 'fail';\n</code></pre>\n\n<p>The ternary operator I've used above is yet another way to do your branching; its efficiency is in the same ballpark though. Since the variable itself is used solely in the truthy branch you can also use the shortened ternary operator (>= 5.3) like so:</p>\n\n<pre><code>echo $res ?: 'fail';\n</code></pre>\n\n<p>Although ternary operators are a powerful concept, they're easy to abuse as well and can cause either bugs or a <a href=\"http://wtfcode.net/\" rel=\"nofollow\">WTF</a> during code review. My personal guideline is to start favouring an <code>if/else</code> construct when either the condition has multiple sub-expressions or when the manual is opened under <a href=\"http://php.net/manual/en/language.operators.precedence.php\" rel=\"nofollow\">operator precedence</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T14:36:29.120", "Id": "28012", "Score": "1", "body": "Just a minor amendment. Ternary is an amazingly powerful tool, but know when to use it. I say this because most people tend to abuse it when they first learn of it. The above is a good example of proper ternary. However, if they start becoming too long, or too complicated, or god forbid, nested, you'll want to revert to using if/else statements instead. Finally, in some instances if/else and ternary aren't even necessary. Instead of returning a \"pseudo\" TRUE/FALSE state (pass/fail), just return the boolean. This produces terser syntax that is still legible, for example: `return $no > 85;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:54:35.783", "Id": "28049", "Score": "0", "body": "Just to confirm - in case someone doubts - that both versions do an assignment, check the paste here: http://ideone.com/5BIgu (look at the second opcode). What PHP is doing is performing the assignment, and then doing the boolean check on the *result* of that assignment (assignment returns the value assigned as a side-effect)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T23:05:56.170", "Id": "28669", "Score": "0", "body": "\"or god forbid, nested\" and they normally come with this comment \"//i dare you to change this\" ><" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:52:25.403", "Id": "17581", "ParentId": "17578", "Score": "10" } }, { "body": "<pre><code>if(!$result = $db-&gt;getResult($id)){\n echo 'fail';\n}else{\n echo $result;\n}\n</code></pre>\n\n<p><strong>Why do you test against false first and true second?</strong> Because, if this is in a function, you may want to choose the easy way out. Like this:</p>\n\n<pre><code>if(!$result = $db-&gt;getResult($id)){\n echo 'fail';\n // It failed, it's over... so bail here quickly.\n return false;\n}\n// We succeeded, continue heavy processing of result\n// without being contained in a cumbersome block.\necho $result;\n</code></pre>\n\n<p>There's no right or wrong way. It's always a choice of design. Do you need to return a false in case of failure, try for false first and return or... continue processing in the main block of the function if it succeeded.</p>\n\n<p>Do remember that PHP is very lax regarding stuff like this. It's always easier and more clear to create variables in place right inside the if. Shorter clean code is easier to read code:</p>\n\n<pre><code>if(($result = $db-&gt;getResult($id)) === true){\n // true\n}else if($result === false){\n // false\n}else{\n // not a bool :) handle it\n}\n</code></pre>\n\n<p>Hope I made sense.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T19:31:16.587", "Id": "17619", "ParentId": "17578", "Score": "3" } } ]
{ "AcceptedAnswerId": "17581", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T06:32:41.043", "Id": "17578", "Score": "8", "Tags": [ "php", "performance", "optimization" ], "Title": "PHP ideal way to check function returns true" }
17578
<p>Its working but I don't think its the best way of doing it. I also changed variable names just to let you know,</p> <pre><code> string [] columnN = AnotherString.Split(','); //Another String is something like this = "HEhehehehehE heeh, aSKdjhkaaksjd, asldkhja slkdlk, asdajsdlka, asdljkasd, asdkasjdasd, asdasdasdl, askdjasd" AnotherString = ""; int i = 0; foreach (string cN in columnN) { if (!string.IsNullOrEmpty(Res.ResourceManager.GetString(cN.ToLower().Trim()))) AnotherEmptyString += Res.ResourceManager.GetString(cN.ToLower().Trim()); else AnotherString += cN; i++; if (i &lt; columnN.Length) AnotherString += ","; } </code></pre> <p>I saved all resources in lower case, also if in case cN doesn't got any resource won't it will give an exception.</p>
[]
[ { "body": "<p>Ok a few things:</p>\n\n<ol>\n<li>Do this once and cache the result <code>Res.ResourceManager.GetString(cN.ToLower().Trim())</code>, the call <code>.ToLower()</code> creates a new string and then the <code>.Trim()</code> call creates yet another so you save the creation of 2 extra strings for each <code>cN</code>.</li>\n<li>Use a string builder instead of concatenation - every time you do <code>+=</code> on a string, a new string is created in memory.</li>\n</ol>\n\n<p>That gives you something like this:</p>\n\n<pre><code>string[] columnN = AnotherString.Split(','); //Another String is something like this = \"HEhehehehehE heeh, aSKdjhkaaksjd, asldkhja slkdlk, asdajsdlka, asdljkasd, asdkasjdasd, asdasdasdl, askdjasd\"\n\nvar stringBuilder = new StringBuilder();\n\nint i = 0;\n\nforeach (string cN in columnN)\n{\n var resourceText = Res.ResourceManager.GetString(cN.ToLower().Trim());\n\n if (!string.IsNullOrEmpty(resourceText))\n {\n stringBuilder.Append(resourceText);\n }\n else\n {\n stringBuilder.Append(cN);\n }\n\n i++;\n\n if (i &lt; columnN.Length)\n {\n stringBuilder.Append(\",\");\n }\n}\n\nAnotherString = stringBuilder.ToString()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:00:11.873", "Id": "28040", "Score": "0", "body": "A personal preference but I would probably reverse your if statement to remove the need for the !. Just for me makes it easier to read although (i.e. don't need to think about the not) but I know there are some arguments for this way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:14:32.230", "Id": "28043", "Score": "1", "body": "@dreza that's a fair comment, I wouldn't actually write it this way myself either however I've noticed that sometimes people answer with a better implementation but without explaining why it's an improvement. My intention was to point out what the issues with the original code were rather than to re-write the method so that the OP could actually learn what the problems were rather than just blindly copying a smaller implementation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T22:49:00.037", "Id": "28064", "Score": "0", "body": "Fair enough. I definitely agree that copying code tends to not lead to actual learning and potentially makes life more difficult int he long ." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:21:06.233", "Id": "17589", "ParentId": "17586", "Score": "7" } }, { "body": "<p>Your code should work ok. However, I would have used a list to store the intermediate results, and then <code>string.Join</code> to create the result. (Also perhaps Linq to filter the data, but then someone not familiar with Linq will have trouble maintaining the code.) Something like</p>\n\n<pre><code>string[] columnN = AnotherString.Split(',');\nstring[] stringList = new string[columnN.Length];\n\nfor (int i = 0; i &lt; columnN.Length; i++)\n{\n string cN = columnN[i];\n string resource = Res.ResourceManager.GetString(cN.ToLower().Trim()));\n stringList[i] = resource ?? cN;\n}\n\nAnotherString = string.Join(\",\", stringList);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:23:03.143", "Id": "27992", "Score": "2", "body": "You've missed the part where you add `cN` if resource is null." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:23:49.180", "Id": "27993", "Score": "1", "body": "You can also prevent the list from having to resize by doing `List<string>(columnN.Length);`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:37:31.830", "Id": "27996", "Score": "2", "body": "You can also update this `stringList[i] = (resource != null) ? resource : cN;` to use the null coalescing operator `stringList[i] = resource ?? cN;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:46:47.637", "Id": "27997", "Score": "5", "body": "Now I wonder if I should start submitting my own code for review here :-D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:56:39.903", "Id": "27998", "Score": "7", "body": "I think we all should :-)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:21:12.693", "Id": "17590", "ParentId": "17586", "Score": "10" } }, { "body": "<p>I think using LINQ makes perfect sense here:</p>\n\n<pre><code>var strings = AnotherString.Split(',')\n .Select(s =&gt; Res.ResourceManager.GetString(s.ToLower().Trim())) ?? s);\nAnotherString = string.Join(\",\", strings);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T22:18:45.747", "Id": "28063", "Score": "0", "body": "can you add comments to your code please :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T17:38:48.770", "Id": "17618", "ParentId": "17586", "Score": "10" } } ]
{ "AcceptedAnswerId": "17590", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T09:28:03.260", "Id": "17586", "Score": "7", "Tags": [ "c#", "optimization" ], "Title": "Can someone improve this C# code" }
17586
<p>I'm writing an ORPG. The code below is client-side.</p> <p>I have a main thread looping in <code>Game::Run</code>:</p> <pre><code>Game::~Game() { PopAllStates(); } void Game::Run() { sf::Event Event; while(Window-&gt;isOpen()) { if(LoadQueueMutex.try_lock()) { while(!LoadQueue.empty()) { LoadQueue.front().first-&gt;Load(LoadQueue.front().second); LoadQueue.pop(); } LoadQueueMutex.unlock(); } while(Window-&gt;pollEvent(Event)) { StateStack.top()-&gt;HandleEvent(Event); } Window-&gt;clear(); StateStack.top()-&gt;Draw(); Window-&gt;display(); StateStack.top()-&gt;Update(); } } void Game::AddToLoadQueue(Loadable* pLoadable, WorldPacket Argv) { boost::mutex::scoped_lock lock(LoadQueueMutex); LoadQueue.push(std::make_pair(pLoadable, Argv)); } void Game::PushState(GameState* pState) { StateStack.push(pState); } void Game::PopState() { if(!StateStack.empty()) { delete StateStack.top(); StateStack.pop(); } } void Game::PopAllStates() { while(!StateStack.empty()) { PopState(); } } </code></pre> <p>And another thread waiting for a packet:</p> <pre><code>void WorldSession::Start() { Packet = WorldPacket((uint16)MSG_NULL); boost::asio::async_read(Socket, boost::asio::buffer(Packet.GetDataWithHeader(), WorldPacket::HEADER_SIZE), boost::bind(&amp;WorldSession::HandleHeader, this, boost::asio::placeholders::error)); } </code></pre> <p>When the packet "arrives", this is usually done because OpenGL breaks if loaded from another thread:</p> <pre><code>void WorldSession::HandleSomeCoolOpcode() { //... sGame-&gt;AddToLoadQueue(pSomethingCool, Packet); } </code></pre> <p>When the main thread loads the <code>Loadable*</code>, it will usually mess with the state stack:</p> <pre><code>void World::Load(WorldPacket Argv) { //... sGame-&gt;PopState(); sGame-&gt;PushState(this); } </code></pre> <p>Is there any way to improve this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T15:20:57.553", "Id": "29627", "Score": "0", "body": "what's the point of the pushState/popState mechanism? Is is possible to temporarily load/start a game, play it, and close it to return to the previously opened one?" } ]
[ { "body": "<ul>\n<li><p>Your variables and functions should either be in camelCase or another naming convention that differentiates them from user-defined types (such as <code>Game</code> here), which are capitalized.</p></li>\n<li><p>If a parameter is not supposed to be modified, and it's not a primitive type (such as an <code>int</code>), pass it by <code>const</code>-reference in order to avoid an unnecessary copy.</p>\n\n<p>In both <code>AddToLoadQueue()</code> and <code>PushState()</code>, you're passing a raw pointer to an object that will not be modified within the function. This is also discouraged as you should refrain from passing raw pointers to functions in C++, mostly due to issues such as <a href=\"http://en.wikipedia.org/wiki/Dangling_pointer\" rel=\"nofollow noreferrer\">dangling pointers</a>. If you still need to pass around pointers, pass <a href=\"https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one\">smart pointers</a> instead (if you have C++11).</p>\n\n<p><code>Argv</code> in <code>AddToLoadQueue()</code> should also be passed by <code>const</code>-reference, not by value.</p></li>\n<li><p>Prefer <em>not</em> to cast the C-way in C++:</p>\n\n<blockquote>\n<pre><code>Packet = WorldPacket((uint16)MSG_NULL);\n</code></pre>\n</blockquote>\n\n<p>Cast the C++ way, with <code>static_cast&lt;&gt;</code> in this case:</p>\n\n<pre><code>Packet = WorldPacket(static_cast&lt;uint16&gt;(MSG_NULL));\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/1255015\">this answer</a> for more information on different types of casts.</p></li>\n<li><p>It's not exactly clear how <code>StateStack</code> is supposed to be used here. You use <code>delete</code> on its elements in <code>PopState()</code>, so it's assumed that <code>push()</code> uses <code>new</code> to add new elements, which then means it's a dynamic container. Either way, this implementation should be provided here.</p>\n\n<p>However, if this is entirely identical to a regular dynamic stack, then just use <a href=\"http://en.cppreference.com/w/cpp/container/stack\" rel=\"nofollow noreferrer\"><code>std::stack</code></a>. It will also handle all the memory-management for you (no <code>new</code> and <code>delete</code> necessary).</p>\n\n<pre><code>std::stack&lt;GameState&gt; stateStack;\n</code></pre>\n\n<p>You'll also no longer need to use a separate <code>top()</code> and <code>pop()</code> when popping a state:</p>\n\n<pre><code>stateStack.pop();\n</code></pre></li>\n<li><p>If <code>PopAllStates()</code> is just done in the destructor, then you can just put that code there instead of defining a separate function.</p>\n\n<p>It also calls <code>empty()</code> twice (<code>PopState()</code> also calls <code>empty()</code>), which isn't necessary. If this is only needed in the destructor, put that code (with just one check) into it:</p>\n\n<pre><code>Game::~Game()\n{\n while (!StateStack.empty())\n {\n delete StateStack.top();\n StateStack.pop();\n }\n}\n</code></pre>\n\n<p>If you use <code>std::stack</code>, you'll just need a call to <code>pop()</code>, not <code>top()</code>.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-24T23:10:29.880", "Id": "45268", "ParentId": "17588", "Score": "11" } }, { "body": "<p>First and biggest point: I <em>really</em> dislike spreading mutex locking throughout the code if it can be avoided. The first (and biggest) thing I'd change would be to create a <code>concurrent_stack</code> that handles the locking and unlocking internally. </p>\n\n<pre><code>template &lt;class T&gt;\nclass concurrent_stack { \n std::stack&lt;T&gt; data;\n Boost::mutex guard;\npublic:\n void push(T const &amp;t) { \n boost::mutex::scoped_lock lock(guard);\n data.push(t);\n }\n\n void pop() {\n boost::mutex::scoped_lock lock(guard);\n data.pop();\n }\n // and so on.\n};\n</code></pre>\n\n<p>With this in place, the rest of the code can generally ignore threading issues for that stack, and just push and pop as needed. Obviously there are limits to that, but for the case at hand, it's probably adequate. The result is considerably safer code--it basically eliminates the possibility of forgetting to lock the mutex when you manipulate the stack.</p>\n\n<p>I'd (sort of) disagree with @Jamal on his first point. While I agree with him that you should do something to distinguish type names from variable names, I don't think camelCase is the only (or necessarily best) convention to use. Personally, I prefer what's sometimes called \"snake case\", which uses underscores to separate words, so (for example) <code>state_stack</code> instead of <code>StateStack</code>. In any case, the basic point is pretty simple: you should use some convention to distinguish types from variables, but camelCase isn't the only convention available.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T22:05:37.107", "Id": "79067", "Score": "0", "body": "While I up-voted this, I don't know if it's a good idea. I don't know about `boost::mutex`, but locking is generally an expensive operation. For instance, in his `Game::Run()` function, he performs 4 `LoadQueue.*` operations in a single critical section. With your strategy, it seems like he would be creating (implicitly) 4 different critical sections for each operation. I would imagine that the overhead could be quite excessive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-26T03:05:55.733", "Id": "79103", "Score": "0", "body": "@jliv902: As you say, this *can* be an issue, but when/if it is, I'd prefer to handle it the same basic way: do all the locking in a single class, not spread throughout all the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T03:25:54.820", "Id": "45279", "ParentId": "17588", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T09:48:25.127", "Id": "17588", "Score": "13", "Tags": [ "c++", "multithreading", "game", "boost", "state" ], "Title": "Handling game states for an online RPG game" }
17588
<p>I need to check if a map is subset of another map. For this, I have written the following code:</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;map&gt; using namespace std; /** * Checks if rhs is a subset of lhs */ template&lt;class Map&gt; bool map_compare(Map &amp;lhs, Map &amp;rhs) { if(rhs.size() &gt; lhs.size() || rhs.empty()) return false; typename Map::iterator litr = lhs.begin(); for (typename Map::iterator ritr = rhs.begin(); ritr != rhs.end(); ritr++) { if(litr == lhs.end() &amp;&amp; ritr != rhs.end()) return false; while (litr != lhs.end()) { if (litr-&gt;first == ritr-&gt;first) { if (litr-&gt;second == ritr-&gt;second) { litr++; break; } return false; } else { litr++; } } } return true; } int main() { map&lt;int, string&gt; a, b; a[0] = "0"; a[1] = "1"; b[0] = "0"; cout &lt;&lt; "b ⊆ a? " &lt;&lt; map_compare(a, b) &lt;&lt; " (should be 1)\n"; b[1] = "1"; cout &lt;&lt; "b ⊆ a? " &lt;&lt; map_compare(a, b) &lt;&lt; " (should be 1)\n"; b[2] = "2"; cout &lt;&lt; "b ⊆ a? " &lt;&lt; map_compare(a, b) &lt;&lt; " (should be 0)\n"; } </code></pre> <p>I am looking for another implementation of <code>map_compare</code> which is either shorter or more efficient.</p>
[]
[ { "body": "<p>I believe you will find the standard library has the appropriate functions:</p>\n<p><a href=\"http://www.sgi.com/tech/stl/includes.html\" rel=\"noreferrer\">Includes</a></p>\n<blockquote>\n<p>Includes tests whether one sorted range includes another sorted range. That is, it returns true if and only if, for every element in [first2, last2), an equivalent element [1] is also present in [first1, last1) [2]. Both [first1, last1) and [first2, last2) must be sorted in ascending order.</p>\n<p>The two versions of includes differ in how they define whether one element is less than another. The first version compares objects using operator&lt;, and the second compares objects using the function object comp.</p>\n</blockquote>\n<p>You can see all the <a href=\"http://www.sgi.com/tech/stl/table_of_contents.html\" rel=\"noreferrer\">algorithms here</a></p>\n<p>Your code would look like this:</p>\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;iostream&gt;\n#include &lt;map&gt;\n\nint main()\n{\n std::map&lt;int, std::string&gt; a;\n std::map&lt;int, std::string&gt; b;\n\n a[0] = &quot;0&quot;;\n a[1] = &quot;1&quot;;\n\n b[0] = &quot;0&quot;;\n\n std::cout &lt;&lt; &quot;b ⊆ a? &quot; &lt;&lt; std::includes(a.begin(), a.end(), b.begin(), b.end()) &lt;&lt; &quot; (should be 1)\\n&quot;;\n\n b[1] = &quot;1&quot;;\n std::cout &lt;&lt; &quot;b ⊆ a? &quot; &lt;&lt; std::includes(a.begin(), a.end(), b.begin(), b.end()) &lt;&lt; &quot; (should be 1)\\n&quot;;\n\n b[2] = &quot;2&quot;;\n std::cout &lt;&lt; &quot;b ⊆ a? &quot; &lt;&lt; std::includes(a.begin(), a.end(), b.begin(), b.end()) &lt;&lt; &quot; (should be 0)\\n&quot;;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T15:07:30.737", "Id": "17608", "ParentId": "17591", "Score": "6" } } ]
{ "AcceptedAnswerId": "17608", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T10:36:44.733", "Id": "17591", "Score": "1", "Tags": [ "c++" ], "Title": "Checking if the entries of a map exist in another map" }
17591
<p>I have a relatively simple project to parse some HTTP server logs using Python and SQLite. I wrote up the code but I'm always looking for tips on being a better Python scripter. Though this is a simple task and my code works as written, I was hoping for some pointers to improve my coding ability.</p> <pre><code>import re import sqlite3 ## Load in the log file file = open("logs") rawdata = file.read() ## Create a database conn = sqlite3.connect("parsed_logs.sqlite3") c = conn.cursor() # Build the SQLite database if needed #c.execute('''CREATE TABLE requests (ip text, date text, requested_url text, response_code int, referer text, agent text);''') #conn.commit() ## Prepare data lines = rawdata.split("\n") for line in lines: #print line # Parse data from each line date = re.findall("\[.*?\]", line) date = re.sub("\[", "", date[0]) date = re.sub("\]", "", date) quoted_data = re.findall("\".*?\"", line) #print quoted_data requested_url = quoted_data[0] referer = quoted_data[1] agent = quoted_data[2] unquoted_data_stream = re.sub("\".*?\"", "", line) unquoted_data = unquoted_data_stream.split(" ") ip = unquoted_data[0] response_code = unquoted_data[6] #print ip #print date #print requested_url #print response_code #print referer #print agent ## Insert elements into rows c.execute("INSERT INTO requests VALUES (?, ?, ?, ?, ?, ?)", [ip, date, requested_url, response_code, referer, agent]) conn.commit() ## Check to see if it worked for row in c.execute("SELECT count(*) from requests"): print row </code></pre> <p>Here is some sample data:</p> <pre><code>99.122.86.237 - - [14/Oct/2012:00:01:06 -0400] "GET /epic/running_epic_tier_cover_300w.jpg HTTP/1.1" 200 81804 "http://images.google.com/search?num=10&amp;hl=en&amp;site=&amp;tbm=isch&amp;source=hp&amp;q=epic&amp;oq=epic&amp;gs_l=img.3..0l10.2603.4210.0.4470.5.5.0.0.0.0.137.412.4j1.5.0...0.0...1ac.1.Ycx4MqWP66w&amp;biw=1024&amp;bih=672&amp;sei=mzd6UIjlKMrcqQHM3YGwAg" "Mozilla/5.0 (iPad; CPU OS 5_0_1 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A405 Safari/7534.48.3" 209.131.41.49 - - [14/Oct/2012:00:01:36 -0400] "GET /newsfeeds/boingboing.xml HTTP/1.1" 301 612 "-" "Yahoo Pipes 2.0" 66.249.73.139 - - [14/Oct/2012:00:01:48 -0400] "GET /editorials/67 HTTP/1.1" 404 419 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 180.76.5.181 - - [14/Oct/2012:00:01:52 -0400] "GET /review_462.html HTTP/1.1" 200 5982 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" 208.94.116.217 - - [14/Oct/2012:00:01:58 -0400] "GET /index.xml HTTP/1.1" 200 112946 "-" "Fever/1.26 (Feed Parser; http://feedafever.com; Allow like Gecko)" 50.30.9.10 - - [14/Oct/2012:00:02:03 -0400] "GET /index.xml HTTP/1.1" 200 6335 "-" "Motorola" 66.228.33.168 - - [14/Oct/2012:00:02:11 -0400] "GET /feed/ HTTP/1.1" 301 469 "-" "Fever/1.26 (Feed Parser; http://feedafever.com; Allow like Gecko)" 66.228.33.168 - - [14/Oct/2012:00:02:11 -0400] "GET /index.xml/ HTTP/1.1" 404 383 "-" "Fever/1.26 (Feed Parser; http://feedafever.com; Allow like Gecko)" 209.131.41.48 - - [14/Oct/2012:00:02:16 -0400] "GET /newsfeeds/boingboing.xml HTTP/1.1" 301 612 "-" "Yahoo Pipes 2.0" 184.73.130.89 - - [14/Oct/2012:00:02:47 -0400] "GET /index.xml HTTP/1.1" 200 129755 "-" "Python-urllib/2.7" 74.125.176.24 - - [14/Oct/2012:00:02:51 -0400] "GET /index.xml HTTP/1.1" 301 444 "-" "Feedfetcher-Google; (+http://www.google.com/feedfetcher.html; feed-id=10448260103645447977)" 74.125.19.39 - - [14/Oct/2012:00:02:51 -0400] "GET /index.xml HTTP/1.1" 200 6335 "-" "Feedfetcher-Google; (+http://www.google.com/feedfetcher.html; feed-id=10448260103645447977)" 209.131.41.49 - - [14/Oct/2012:00:03:27 -0400] "GET /newsfeeds/boingboing.xml HTTP/1.1" 301 612 "-" "Yahoo Pipes 2.0" 173.199.114.115 - - [14/Oct/2012:00:03:28 -0400] "GET /robots.txt HTTP/1.1" 301 445 "-" "Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/)" 173.199.114.115 - - [14/Oct/2012:00:03:28 -0400] "GET /robots.txt HTTP/1.1" 404 381 "-" "Mozilla/5.0 (compatible; AhrefsBot/4.0; +http://ahrefs.com/robot/)" 180.76.5.140 - - [14/Oct/2012:00:03:43 -0400] "GET /loral/001432.html HTTP/1.1" 200 9211 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)" 98.139.134.97 - - [14/Oct/2012:00:03:49 -0400] "GET /newsfeeds/boingboing.xml HTTP/1.1" 301 612 "-" "Yahoo Pipes 2.0" 192.55.29.140 - - [14/Oct/2012:00:03:55 -0400] "GET /index.xml HTTP/1.1" 304 197 "-" "Motorola" 50.53.20.104 - - [14/Oct/2012:00:04:08 -0400] "GET /feed/ HTTP/1.1" 301 450 "-" "RSSOwl/2.1.2.201108131746 (Windows; U; en)" 50.53.20.104 - - [14/Oct/2012:00:04:09 -0400] "GET /index.xml/ HTTP/1.1" 404 381 "-" "RSSOwl/2.1.2.201108131746 (Windows; U; en)" 209.131.41.48 - - [14/Oct/2012:00:04:12 -0400] "GET /newsfeeds/boingboing.xml HTTP/1.1" 301 612 "-" "Yahoo Pipes 2.0" 184.18.38.106 - - [14/Oct/2012:00:04:15 -0400] "GET /index.xml HTTP/1.1" 304 216 "-" "Planet Spoon -- D&amp;D +http://blacksun/planetspoon/dnd Planet/2.0 +http://www.planetplanet.org UniversalFeedParser/4.1 +http://feedparser.org/" 95.108.158.239 - - [14/Oct/2012:00:04:15 -0400] "GET /wp-content/uploads/2010/03/shoshanna.jpg HTTP/1.1" 200 41791 "-" "Mozilla/5.0 (compatible; YandexImages/3.0; +http://yandex.com/bots)" 91.206.113.167 - - [14/Oct/2012:00:04:21 -0400] "GET /robots.txt HTTP/1.1" 301 450 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 91.206.113.167 - - [14/Oct/2012:00:04:22 -0400] "GET /robots.txt HTTP/1.1" 404 381 "http://www.slyflourish.com/robots.txt" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 91.206.113.234 - - [14/Oct/2012:00:04:22 -0400] "GET / HTTP/1.1" 200 7381 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 65.55.24.245 - - [14/Oct/2012:00:04:25 -0400] "GET /robots.txt HTTP/1.1" 404 416 "-" "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)" 64.130.10.15 - - [14/Oct/2012:00:04:37 -0400] "GET /index.xml HTTP/1.1" 200 6354 "-" "UniversalFeedParser/4.1 +http://feedparser.org/" 66.249.73.234 - - [14/Oct/2012:00:04:38 -0400] "GET /Mikes_Rollerball_and_Foun.html HTTP/1.1" 200 24064 "-" "Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)" 98.139.134.99 - - [14/Oct/2012:00:04:46 -0400] "GET /newsfeeds/boingboing.xml HTTP/1.1" 301 612 "-" "Yahoo Pipes 2.0" 217.146.191.19 - - [14/Oct/2012:00:05:07 -0400] "GET /newsfeeds/boingboing.xml HTTP/1.1" 301 612 "-" "Yahoo Pipes 2.0" 83.140.155.184 - - [14/Oct/2012:00:05:19 -0400] "GET /index.xml HTTP/1.1" 304 197 "-" "Bloglovin/1.0 (http://www.bloglovin.com; 1 subscribers)" 98.139.134.96 - - [14/Oct/2012:00:05:20 -0400] "GET /newsfeeds/boingboing.xml HTTP/1.1" 301 612 "-" "Yahoo Pipes 2.0" 184.72.46.156 - - [14/Oct/2012:00:05:27 -0400] "GET /feed/ HTTP/1.1" 301 469 "-" "RockMeltService" 184.72.46.156 - - [14/Oct/2012:00:05:27 -0400] "GET /index.xml/ HTTP/1.1" 404 400 "-" "RockMeltService" 85.234.131.115 - - [14/Oct/2012:00:05:31 -0400] "GET /index.xml HTTP/1.1" 304 253 "-" "Protopage/3.0 (http://www.protopage.com)" 69.10.177.43 - - [14/Oct/2012:00:05:37 -0400] "GET /comments/feed/ HTTP/1.1" 404 383 "-" "Motorola" 69.10.177.43 - - [14/Oct/2012:00:05:37 -0400] "GET /comments/feed/ HTTP/1.1" 404 383 "-" "Jakarta Commons-HttpClient/3.1" 24.116.85.10 - - [14/Oct/2012:00:05:42 -0400] "GET / HTTP/1.1" 200 7437 "http://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;ved=0CB8QFjAA&amp;url=http%3A%2F%2Fslyflourish.com%2F&amp;ei=Ezp6UJCjJYW3qAHDsYDYDQ&amp;usg=AFQjCNGlwfi63WJY_SLVcnA2cPxzN2NsIQ" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1" 184.72.46.160 - - [14/Oct/2012:00:05:42 -0400] "GET /feed/ HTTP/1.1" 301 469 "-" "RockMeltService" 24.116.85.10 - - [14/Oct/2012:00:05:42 -0400] "GET /style.css HTTP/1.1" 200 1605 "http://slyflourish.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1" 24.116.85.10 - - [14/Oct/2012:00:05:42 -0400] "GET /sfbook.jpg HTTP/1.1" 200 23087 "http://slyflourish.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1" 24.116.85.10 - - [14/Oct/2012:00:05:42 -0400] "GET /running_epic_tier_cover_200w.jpg HTTP/1.1" 200 34283 "http://slyflourish.com/" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1" 184.72.46.160 - - [14/Oct/2012:00:05:42 -0400] "GET /index.xml/ HTTP/1.1" 404 400 "-" "RockMeltService" 24.116.85.10 - - [14/Oct/2012:00:05:42 -0400] "GET /favicon.ico HTTP/1.1" 404 437 "-" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:15.0) Gecko/20100101 Firefox/15.0.1" 69.10.179.173 - - [14/Oct/2012:00:05:43 -0400] "GET /index.xml HTTP/1.1" 304 197 "-" "Motorola" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-12T13:08:32.560", "Id": "87102", "Score": "0", "body": "Read [http://www.dabeaz.com/generators/]. There's a wonderful amount of information in there about how to deal with logs in a scalable manner." } ]
[ { "body": "<p>It would probably be better if you didn't read the whole log file at once. You could try something like this instead</p>\n\n<pre><code>with open('logs','r') as f:\n for line in f:\n #print line\n # Parse data from each line\n date = re.findall(\"\\[.*?\\]\", line)\n ...\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:04:12.760", "Id": "17593", "ParentId": "17592", "Score": "2" } }, { "body": "<pre><code>import re\nimport sqlite3\n\n## Load in the log file\n\nfile = open(\"logs\")\n</code></pre>\n\n<p>Its usually recommended to have any sort of logic inside a <code>main</code> function. As @Matt suggests, use <code>with</code> to make sure the file gets closed, and its probably best to avoid reading the whole file in.</p>\n\n<pre><code>rawdata = file.read()\n\n\n## Create a database\n\nconn = sqlite3.connect(\"parsed_logs.sqlite3\")\nc = conn.cursor()\n\n# Build the SQLite database if needed\n#c.execute('''CREATE TABLE requests (ip text, date text, requested_url text, response_code int, referer text, agent text);''')\n#conn.commit()\n</code></pre>\n\n<p>Rather then comment this out, I'd add a <code>CREATE_TABLE = False</code> line at the top of the file, and check that variable. That way you can just flip it to re-enable this piece of code.</p>\n\n<pre><code>## Prepare data\n\nlines = rawdata.split(\"\\n\")\nfor line in lines:\n</code></pre>\n\n<p><code>for line in file</code> gets you the same effect</p>\n\n<pre><code> #print line\n # Parse data from each line\n date = re.findall(\"\\[.*?\\]\", line)\n</code></pre>\n\n<p><code>.*?</code> is the same as <code>.*</code>, there isn't really a reason to use the ?. Furthermore if you make the expression <code>\\[(.*)\\]</code> then findall will only return the part in parens. That'll get rid of the [ and ] thus saving the next two lines</p>\n\n<pre><code> date = re.sub(\"\\[\", \"\", date[0])\n date = re.sub(\"\\]\", \"\", date)\n</code></pre>\n\n<p>If just replacing a character, it probably makes sense to use strings replace rather than a regular expression.</p>\n\n<pre><code> quoted_data = re.findall(\"\\\".*?\\\"\", line)\n #print quoted_data\n requested_url = quoted_data[0]\n referer = quoted_data[1]\n agent = quoted_data[2]\n unquoted_data_stream = re.sub(\"\\\".*?\\\"\", \"\", line) \n unquoted_data = unquoted_data_stream.split(\" \")\n ip = unquoted_data[0]\n response_code = unquoted_data[6]\n</code></pre>\n\n<p>The problem is that its a bit tricky to follow the logic of where things are coming from. </p>\n\n<pre><code> #print ip\n #print date\n #print requested_url\n #print response_code\n #print referer\n #print agent\n</code></pre>\n\n<p>Please remove debug code</p>\n\n<pre><code> ## Insert elements into rows\n c.execute(\"INSERT INTO requests VALUES (?, ?, ?, ?, ?, ?)\", [ip, date, requested_url, response_code, referer, agent])\n\nconn.commit()\n\n## Check to see if it worked\n\nfor row in c.execute(\"SELECT count(*) from requests\"):\n print row\n</code></pre>\n\n<p>Here's how I reworked your parsing code:</p>\n\n<pre><code>file = StringIO(open(\"logs\").read().replace('[','\"').replace(']','\"'))\nreader = csv.reader(file, delimiter=' ')\nfor line in reader:\n ip, _, _, date, url, response_code, _, referer, agent = line\n</code></pre>\n\n<p>I replace the [ and ], which makes your log a valid space delimited file which can be read using python's <code>csv</code> module. From there, its a simple task to decode the parts in local variables.</p>\n\n<p>I don't love the replacement trick here. But I'd probably develop a generic parsing system to handle both [] and \" and then return the result of each row as a list and decode as I've done above.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T14:27:39.673", "Id": "17601", "ParentId": "17592", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T11:35:13.870", "Id": "17592", "Score": "3", "Tags": [ "python", "parsing", "regex" ], "Title": "Parsing HTTP server logs" }
17592
<p>The following code is a simple random password generator that spits out a randomized password based on some input flags.</p> <pre><code>import string import random import argparse def gen_char(lower, upper, digit, special): _lower_letters = string.ascii_lowercase _upper_letters = string.ascii_uppercase _digits = string.digits _special = "!@#$%^&amp;*()" _rand = random.SystemRandom() _case = "" if lower: _case += _lower_letters if upper: _case += _upper_letters if digit: _case += _digits if special: _case += _special if _case: return _rand.choice(_case) else: return _rand.choice(_lower_letters+_upper_letters+_digits+_special) def main(): """ The following lines of code setup the command line flags that the program can accept. """ parser = argparse.ArgumentParser() parser.add_argument("length", type=int, help="length of password") parser.add_argument("--lower", "-l", help="Generates passwords with lower case letters", action="store_true") parser.add_argument("--upper", "-u", help="Generates passwords with upper case letters", action="store_true") parser.add_argument("--digit", "-d", help="Generates passwords with digits", action="store_true") parser.add_argument("--special", "-s", help="Generates passwords with special characters", action="store_true") args = parser.parse_args() """ The following lines of code calls upon the gen_char() function to generate the password. """ _pass = "" for x in range(args.length): _pass += gen_char(args.lower, args.upper, args.digit, args.special) print _pass main() </code></pre> <p>The code is in working condition. I'm looking for tips in terms of coding styles, readability and perhaps optimizations if any.</p> <p>If anyone is interested, the code can be found on <a href="https://github.com/Ayrx/Password_Generator" rel="noreferrer">github</a>.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T17:44:35.063", "Id": "28035", "Score": "0", "body": "I don't think `_case` is a particularly good name here. Consider `alphabet` instead." } ]
[ { "body": "<p>Re-assembling the _case character list for each character is rather wasteful. I would get rid of the gen_char function.</p>\n\n<pre><code>import string\nimport random\nimport argparse\n\ndef main():\n\n \"\"\"\n\n The following lines of code setup the command line flags that the\n program can accept.\n\n \"\"\"\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"length\", type=int, help=\"length of password\")\n parser.add_argument(\"--lower\", \"-l\", \n help=\"Generates passwords with lower case letters\",\n action=\"store_true\")\n parser.add_argument(\"--upper\", \"-u\",\n help=\"Generates passwords with upper case letters\",\n action=\"store_true\")\n parser.add_argument(\"--digit\", \"-d\",\n help=\"Generates passwords with digits\",\n action=\"store_true\")\n parser.add_argument(\"--special\", \"-s\",\n help=\"Generates passwords with special characters\",\n action=\"store_true\")\n\n args = parser.parse_args()\n\n\n \"\"\"\n\n The following lines of code generate the password.\n\n \"\"\"\n\n _lower_letters = string.ascii_lowercase\n _upper_letters = string.ascii_uppercase\n _digits = string.digits\n _special = \"!@#$%^&amp;*()\"\n\n _case = \"\"\n\n if lower:\n _case += _lower_letters\n\n if upper:\n _case += _upper_letters\n\n if digit:\n _case += _digits\n\n if special:\n _case += _special\n\n if !_case:\n _lower_letters+_upper_letters+_digits+_special\n\n _rand = random.SystemRandom()\n\n _pass = \"\"\n\n for x in range(args.length):\n\n _pass += _rand.choice(_case)\n\n print _pass\n\nmain()\n</code></pre>\n\n<p>You could, perhaps, use a function to make the list the one time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:54:26.340", "Id": "28005", "Score": "0", "body": "Ahhh! Good point." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:49:43.193", "Id": "17595", "ParentId": "17594", "Score": "5" } }, { "body": "<p>In addition to what has been said about not calling <code>gen_char()</code> every iteration, you are prefixing your variable names with an underscore, which is the python standard for private variables - the issue here is that you are doing this inside a function definition - as these are local variables that will go out of scope and get garbage collected when the function ends, there really isn't much point. I would recommend just using normal variable names.</p>\n\n<p>I would also argue <code>gen_char()</code> could be improved by using default values:</p>\n\n<pre><code>def gen_char(lower=string.ascii_lowercase, upper=string.ascii_upercase,\n digit=string.digits, special=\"!@#$%^&amp;*()\"):\n rand = random.SystemRandom()\n return rand.choice(\"\".join(\n group for group in (lower, upper, digit, special) if group)\n</code></pre>\n\n<p>This makes it clear what the default is, makes it possible to change the character range used, and makes it easy to disable certain parts.</p>\n\n<p>It's noted that <code>str.join()</code> is preferable over repeated concatenation, and using it allows us to stop repeating ourself and say that if we get a value, use it.</p>\n\n<p>This would require changing your use of <code>argparse</code>, prehaps like so:</p>\n\n<pre><code>kwargs = {}\nif not args.lower:\n kwargs[\"lower\"] = False\n...\ngen_char(**kwargs)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T13:20:57.757", "Id": "17598", "ParentId": "17594", "Score": "5" } }, { "body": "<pre><code>import string\nimport random\nimport argparse\n\ndef gen_char(lower, upper, digit, special):\n\n _lower_letters = string.ascii_lowercase\n _upper_letters = string.ascii_uppercase\n _digits = string.digits\n _special = \"!@#$%^&amp;*()\"\n</code></pre>\n\n<p>Its against python convention to prefix local variables with <code>_</code>. Just don't do it. All of these categories would be better in a dictionary. That is create a global dict like:</p>\n\n<pre><code>CHARACTER_CATEGORIES = {\n 'lower' : string.ascii_lowercase,\n 'upper' : string.ascii_uppercase,\n 'digits' : string.digits,\n 'special' : \"!@#$%^&amp;*()\"\n}\n</code></pre>\n\n<p>Then take a list of categories as your parameters to this function instead. </p>\n\n<pre><code> _rand = random.SystemRandom()\n</code></pre>\n\n<p>You should create a random number generator once in your program, not once per random choice.</p>\n\n<pre><code> _case = \"\"\n</code></pre>\n\n<p>case? why case?</p>\n\n<pre><code> if lower:\n _case += _lower_letters\n\n if upper:\n _case += _upper_letters\n\n if digit:\n _case += _digits\n\n if special:\n _case += _special\n\n if _case:\n return _rand.choice(_case)\n\n else:\n return _rand.choice(_lower_letters+_upper_letters+_digits+_special)\n</code></pre>\n\n<p>this is really the wrong place to do this. the decision to include all categories if non are specifically selected is part of interpretating the user's input. So you should do it when you are parsing that, not here.</p>\n\n<pre><code>def main():\n\n \"\"\"\n\n The following lines of code setup the command line flags that the\n program can accept.\n\n \"\"\"\n</code></pre>\n\n<p>Not a very useful comment, because its pretty obvious that's whats happening here.</p>\n\n<pre><code> parser = argparse.ArgumentParser()\n\n parser.add_argument(\"length\", type=int, help=\"length of password\")\n parser.add_argument(\"--lower\", \"-l\", \n help=\"Generates passwords with lower case letters\",\n action=\"store_true\")\n parser.add_argument(\"--upper\", \"-u\",\n help=\"Generates passwords with upper case letters\",\n action=\"store_true\")\n parser.add_argument(\"--digit\", \"-d\",\n help=\"Generates passwords with digits\",\n action=\"store_true\")\n parser.add_argument(\"--special\", \"-s\",\n help=\"Generates passwords with special characters\",\n action=\"store_true\")\n\n args = parser.parse_args()\n\n\n \"\"\"\n\n The following lines of code calls upon the gen_char() function to\n generate the password.\n\n \"\"\"\n _pass = \"\"\n\n for x in range(args.length):\n\n _pass += gen_char(args.lower, args.upper, args.digit, args.special)\n</code></pre>\n\n<p>Its not very efficient to do it this way as other have pointed out. But its also bad because adding strings in python is expensive, better to put all the letters in a list and join them.</p>\n\n<pre><code> print _pass\n\nmain()\n</code></pre>\n\n<p>Better to do</p>\n\n<pre><code>if __name__ == '__main__':\n main()\n</code></pre>\n\n<p>That way you could import this module elsewhere, and use its features.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T01:42:59.897", "Id": "28068", "Score": "0", "body": "Thanks! Excellent breakdown of where I went wrong. Will keep in mind your suggestions for future codes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T15:00:57.337", "Id": "17607", "ParentId": "17594", "Score": "6" } } ]
{ "AcceptedAnswerId": "17607", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T12:43:36.570", "Id": "17594", "Score": "5", "Tags": [ "python" ], "Title": "Code review for python password generator" }
17594
<p>The Monty Hall Problem is a simple puzzle involving probability that even stumps professionals in careers dealing with some heavy-duty math. Here's the basic problem:</p> <p><strong>Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?</strong></p> <p>You can find numerous explanations of the solution here: <a href="http://en.wikipedia.org/wiki/Monty_Hall_problem" rel="nofollow">http://en.wikipedia.org/wiki/Monty_Hall_problem</a> Goal of my simulation: Prove that a switching strategy will win you the car 2/3 of the time.</p> <p>I got curious and wanted to write a little function that simulates the problem many times and returns the proportion of wins if you switched and the proportion of wins if you stayed with your first choice. The function then plots the cumulative wins. </p> <p>This function takes a long time to run once I get to about 10,000 simulations. I know I don't need this many simulations to prove this but I'd love to hear some ideas on how to make it more efficient. Thanks for your feedback!</p> <pre><code>Monty_Hall=function(repetitions){ doors=c('A','B','C') stay_wins=0 switch_wins=0 series=data.frame(sim_num=seq(repetitions),cum_sum_stay=replicate(repetitions,0),cum_sum_switch=replicate(repetitions,0)) for(i in seq(repetitions)){ winning_door=sample(doors,1) contestant_chooses=sample(doors,1) if(contestant_chooses==winning_door) stay_wins=stay_wins+1 else switch_wins=switch_wins+1 series[i,'cum_sum_stay']=stay_wins series[i,'cum_sum_switch']=switch_wins } plot(series$sim_num,series$cum_sum_switch,col=2,ylab='Cumulative # of wins', xlab='Simulation #',main=sprintf('%d Simulations of the Monty Hall Paradox',repetitions),type='l') lines(series$sim_num,series$cum_sum_stay,col=4) legend('topleft',legend=c('Cumulative wins from switching', 'Cumulative wins from staying'),col=c(2,4),lty=1) result=list(series=series,stay_wins=stay_wins,switch_wins=switch_wins, proportion_stay_wins=stay_wins/repetitions, proportion_switch_wins=switch_wins/repetitions) return(result) } #Theory predicts that it is to the contestant's advantage if he #switches his choice to the other door. This function simulates the game #many times, and shows you the proportion of games in which staying or #switching would win the car. It also plots the cumulative wins for each strategy. Monty_Hall(100) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T21:53:01.020", "Id": "28006", "Score": "2", "body": "parallel computing is a solution and it's been done in R with this very problem. See this post: http://librestats.com/2012/03/15/a-no-bs-guide-to-the-basics-of-parallelization-in-r/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T11:25:30.437", "Id": "28007", "Score": "0", "body": "For extra credit, enhance your code to allow N doors, of which M<N have prizes. Amaze and entertain your friends at parties!" } ]
[ { "body": "<p>R has vectorized operators and using those is much more efficient in this case:</p>\n\n<pre><code>Monty_Hall2 &lt;- function(repetitions){\n doors &lt;- c('A','B','C')\n winning_door &lt;- sample(doors, repetitions, replace=TRUE)\n contestant_choose &lt;- sample(doors, repetitions, replace=TRUE)\n stay_wins &lt;- winning_door == contestant_choose\n switch_wins &lt;- winning_door != contestant_choose\n series &lt;- data.frame(sim_num = seq_len(repetitions),\n cum_sum_stay = cumsum(stay_wins),\n cum_sum_switch = cumsum(switch_wins))\n plot(series$sim_num,series$cum_sum_switch,col=2,ylab='Cumulative # of wins',\n xlab='Simulation #',main=sprintf('%d Simulations of the Monty Hall Paradox',repetitions),type='l')\n lines(series$sim_num,series$cum_sum_stay,col=4)\n legend('topleft',legend=c('Cumulative wins from switching',\n 'Cumulative wins from staying'),col=c(2,4),lty=1)\n list(series = series,\n stay_wins = series[repetitions,\"cum_stay_wins\"],\n switch_wins = series[repetitions,\"cum_switch_wins\"],\n proportion_stay_wins = series[repetitions,\"cum_stay_wins\"]/repetitions,\n proportion_switch_wins = series[repetitions,\"cum_switch_wins\"]/repetitions)\n}\n</code></pre>\n\n<p>That is, generate all the answers and guesses, check for each one (vectorized) which (staying or switching) would be a win, and then accumulate those results. The rest is just to put the data in the same format that your function already had.</p>\n\n<pre><code>&gt; system.time(tmp &lt;- Monty_Hall(10000))\n user system elapsed \n 6.04 0.00 6.04 \n&gt; system.time(tmp &lt;- Monty_Hall2(10000))\n user system elapsed \n 0.01 0.02 0.03 \n</code></pre>\n\n<p>So approximately 1/600 of the time. Or, since I didn't do proper benchmarking, say between 2 and 3 orders of magnitude quicker.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T21:59:54.200", "Id": "17597", "ParentId": "17596", "Score": "8" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-15T21:33:57.840", "Id": "17596", "Score": "2", "Tags": [ "r" ], "Title": "Increase efficiency for an R simulator of the Monty Hall Puzzle" }
17596
<p>I'm a Clojure n00b (but am experienced with other languages) and am learning the language as I find time - enjoying it so far, though the strange dreams and accidental use of parenthesis elsewhere (e.g. Google searches) are a bit disconcerting!</p> <p>Usually when learning a new language the first thing I do is implement Conway's Game of Life, since it's just complex enough to give a good sense of the language, but small enough in scope to be able to whip up in a couple of hours (most of which is spent wrestling with syntax). I did <a href="https://stackoverflow.com/questions/3066227/critique-my-scala-code">this with Scala a while back</a>, and really appreciated the comments I received.</p> <p>Anyhoo, having gone through this exercise with Clojure I was hoping to get similar feedback on my efforts so far?</p> <p>I'm after any kind of feedback - algorithmic improvements, stylistic improvements, alternative APIs or language constructs, disgust at my insistence on checking argument types - whatever feedback you've got, I'm keen to hear it!</p> <pre><code>; ; Copyright (c) 2012 Peter Monks (pmonks@gmail.com) ; ; This work is licensed under the Creative Commons Attribution-ShareAlike ; 3.0 Unported License. To view a copy of this license, visit ; http://creativecommons.org/licenses/by-sa/3.0/ or send a letter to ; Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, ; 94041, USA. ; (ns ClojureGameOfLife.core (:use clojure.set)) (defrecord Cell [^Integer x ^Integer y]) (def block #{(Cell. 0 0) (Cell. 1 0) (Cell. 0 1) (Cell. 1 1)}) (def beehive #{ (Cell. 1 0) (Cell. 2 0) (Cell. 0 1) (Cell. 3 1) (Cell. 1 2) (Cell. 2 2)}) (def blinker #{(Cell. 0 0) (Cell. 0 1) (Cell. 0 2)}) (def glider #{ (Cell. 1 0) (Cell. 2 1) (Cell. 0 2) (Cell. 1 2) (Cell. 2 2)}) (defn flat-map "Maps the function to the given set, returning a new set (flattened, in the case where f itself returns a set for each element). Note: There has to be a better way to do this..." [f s] {:pre [(set? s)] :post [(set? %)]} (-&gt;&gt; s (map f) (map seq) flatten set)) (defn alive? "Is the given cell alive in the given generation?" [generation cell] {:pre [(set? generation) (instance? Cell cell)] :post [(instance? Boolean %)]} (contains? generation cell)) (defn neighbours "Returns all of the neighbours of a given cell." [cell] {:pre [(instance? Cell cell)] :post [(set? %)]} (let [x (:x cell) y (:y cell)] #{ (Cell. (dec x) (dec y)) (Cell. x (dec y)) (Cell. (inc x) (dec y)) (Cell. (dec x) y) (Cell. (inc x) y) (Cell. (dec x) (inc y)) (Cell. x (inc y)) (Cell. (inc x) (inc y)) })) (defn number-of-living-neighbours "Returns the number of living neighbours of the given cell in the given generation." [generation cell] {:pre [(set? generation) (instance? Cell cell)] :post [(instance? Integer %)]} (count (intersection generation (neighbours cell)))) (defn should-live? "Should the given cell live in the next generation?" [generation cell] {:pre [(set? generation) (instance? Cell cell)] :post [(instance? Boolean %)]} (let [alive (alive? generation cell) living-neighbours (number-of-living-neighbours generation cell)] (if alive (or (= 2 living-neighbours) (= 3 living-neighbours)) (= 3 living-neighbours)))) (defn next-generation "Returns the next-generation board, given a generation." [generation] {:pre [(set? generation)] :post [(set? %)]} (set (filter #(should-live? generation %) (flat-map neighbours generation)))) (defn values "The values of the given generation's given dimension." [generation elem] {:pre [(set? generation)] :post [(set? %)]} (set (map elem generation))) (defn x-values "The X values of the given generation." [generation] {:pre [(set? generation)] :post [(set? %)]} (values generation :x)) (defn y-values "The Y values of the given generation." [generation] {:pre [(set? generation)] :post [(set? %)]} (values generation :y)) (defn min-x "Minimum X value of a generation." [generation] {:pre [(set? generation)]} (reduce min (x-values generation))) (defn min-y "Minimum Y value of a generation." [generation] {:pre [(set? generation)]} (reduce min (y-values generation))) (defn max-x "Maximum X value of a generation." [generation] {:pre [(set? generation)]} (reduce max (x-values generation))) (defn max-y "Maximum Y value of a generation." [generation] {:pre [(set? generation)]} (reduce max (y-values generation))) (defn extend-by-1 "Extends a collection of numbers by 1 in each direction (both up and down)." [c] (let [minimum (reduce min c) maximum (reduce max c)] (conj c (dec minimum) (inc maximum)))) (defn print-generation "Prints a generation." [generation] {:pre [(set? generation)]} (doseq [y (sort (extend-by-1 (y-values generation)))] (doseq [x (sort (extend-by-1 (x-values generation)))] (if (alive? generation (Cell. x y)) (print "# ") (print ". "))) (println))) (defn clear-screen "Clears the screen, using ANSI control characters." [] (let [esc (char 27)] (print (str esc "[2J")) ; ANSI: clear screen (print (str esc "[;H")))) ; ANSI: move cursor to top left corner of screen (defn -main "Run Conway's Game of Life." [&amp; args] (loop [saved-generations #{} generation glider] (if (not (contains? saved-generations generation)) (do (clear-screen) (print-generation generation) (flush) (Thread/sleep 250) (recur (conj saved-generations generation) (next-generation generation)))))) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T03:37:58.643", "Id": "28014", "Score": "0", "body": "Take a look at this neat little implementation of life in Clojure: http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T03:43:07.817", "Id": "28015", "Score": "0", "body": "Thanks mikera - I'll have to have a closer look at frequencies, mapcat and cells!" } ]
[ { "body": "<p>Some quick points / ideas:</p>\n\n<ul>\n<li>The code looks pretty decent overall for a first attempt at Clojure, and you have made good use of the \"functional\" style. Nice work!</li>\n<li>You have used a <code>defrecord</code> for the cells data structure. This isn't really buying you anything, since you can just use a vector e.g. <code>[1 2]</code> or a map e.g. <code>{:x 1 :y 1}</code> directly. I'd probably use a vector: more lightweight, shorter and therefore more readable, it's clear in the context that it it is an [x y] vector.</li>\n<li>This min-x, min-y, x-values etc. functions add a lot of lines of code but are extremely short functions. I'd probably be more tempted to do these inline, especially since they are only used once or twice.</li>\n</ul>\n\n<p>Also take a look at these neat Game of Life implementations: </p>\n\n<ul>\n<li><a href=\"http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/\">http://clj-me.cgrand.net/2011/08/19/conways-game-of-life/</a></li>\n<li><a href=\"http://programmablelife.blogspot.sg/2012/08/conways-game-of-life-in-clojure.html\">http://programmablelife.blogspot.sg/2012/08/conways-game-of-life-in-clojure.html</a></li>\n<li><a href=\"https://github.com/mikera/clojure-golf/blob/master/src/main/clojure/clojure-golf/examples/life.clj\">https://github.com/mikera/clojure-golf/blob/master/src/main/clojure/clojure-golf/examples/life.clj</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T16:48:24.917", "Id": "28025", "Score": "1", "body": "Thanks mikera. As you may have noticed I'm having great trouble letting go of my typed background - in fact I originally implemented it using vectors but got freaked out about people passing in vectors of the wrong length, containing the wrong data types etc. Any hints on getting over my fear of \"lack of types\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T01:29:13.367", "Id": "28067", "Score": "0", "body": "Yes: Unit testing. It's absolutely essential when creating a program of any complexity in a dynamic language without the support of static type checking. Learn to love your test suite." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T22:13:03.643", "Id": "28111", "Score": "2", "body": "Not to take this too off-topic, but while tests are good, they're no substitute for a specification (which is partly what type systems are about). Here's a good article on this topic: http://bertrandmeyer.com/2012/10/14/a-fundamental-duality-of-software-engineering/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T23:30:57.283", "Id": "28113", "Score": "1", "body": "@Peter - that's why I'm excited about Typed Clojure (https://github.com/frenchy64/typed-clojure). OTOH, with the exception of \"simple\" cases like type checking the majority of specifications can't easily be automatically validated (in the way that executable tests can). I therefore argue you need *both* tests and specifications for different reasons." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T03:57:01.897", "Id": "17604", "ParentId": "17603", "Score": "5" } }, { "body": "<p>My suggestions:</p>\n\n<p>Remove the <code>values</code> function and, as <a href=\"https://stackoverflow.com/users/214010/mikera\">mikera</a> suggests, do these types of things inline. Most clojure programmers will know what you mean.</p>\n\n<p>There is no need to <code>reduce</code> with the <code>max</code> function when <code>max</code> is a variable-arity function.</p>\n\n<pre><code>(reduce max [1 2 3 4]) ;; 4\n</code></pre>\n\n<p>can be</p>\n\n<pre><code>(apply max [1 2 3 4]) ;; 4\n</code></pre>\n\n<p>When you <code>reduce</code>, you are effectively doing the following</p>\n\n<pre><code>(max (max (max 1 2) 3) 4) ;; 4\n</code></pre>\n\n<p>When using <code>apply</code> would equate to </p>\n\n<pre><code>(max 1 2 3 4) ;; 4\n</code></pre>\n\n<p>To show you an example, <code>max-y</code> could be as follows</p>\n\n<pre><code>(defn max-y\n [generation]\n (apply max (map :y generation)))\n</code></pre>\n\n<p>I'm on the fence about this one but you could even go as far as to generalize those 2 functions:</p>\n\n<pre><code>(defn maximum\n [k hash]\n (apply max (map k hash)))\n\n(maximum :y generation)\n(maximum :x generation)\n</code></pre>\n\n<p>A few more simple tips:</p>\n\n<p>There is an <a href=\"http://clojuredocs.org/clojure_core/clojure.core/if-not\" rel=\"nofollow noreferrer\"><code>if-not</code></a> macro that can be useful. But the way you have it is perfectly fine.</p>\n\n<pre><code>(if (not (contains? saved-generations generation)) ... )\n\n(if-not (contains? saved-generations generation) ... )\n</code></pre>\n\n<p>Also, there is a <a href=\"http://clojuredocs.org/clojure_core/clojure.core/when-not\" rel=\"nofollow noreferrer\"><code>when-not</code></a> macro that has an implied <code>do</code> form.</p>\n\n<pre><code>(if (not (contains? saved-generations generation))\n (do ... ))\n\n(when-not (contains? saved-generations generation)\n ...)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T16:57:54.420", "Id": "28027", "Score": "0", "body": "Thanks Kyle - really appreciate the pointers to those functions and macros. I'm discovering that half the trick with Clojure seems to be knowing the core library." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T17:16:29.243", "Id": "28031", "Score": "0", "body": "@Peter, you're welcome and correct. It seems like there is a fn for almost everything in clojure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:32:40.570", "Id": "28060", "Score": "0", "body": "Regarding your comment \"do these types of things inline\" - how do you decide whether to inline something or separate it out as an explicitly named function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:35:06.307", "Id": "28061", "Score": "0", "body": "@Peter, it's all personal preference really. If it's not obvious what you are doing, a function usually is better. It's difficult when you are starting out because `(apply max (map :y generation))` is not really obvious until you are comfortable with functional programming or clojure specifically." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T04:32:20.587", "Id": "17605", "ParentId": "17603", "Score": "5" } }, { "body": "<h2>From :</h2>\n\n<pre><code>(defn values\n \"The values of the given generation's given dimension.\"\n [generation\n elem]\n {:pre [(set? generation)]\n :post [(set? %)]}\n (set (map elem generation)))\n\n(defn x-values\n \"The X values of the given generation.\"\n [generation]\n {:pre [(set? generation)]\n :post [(set? %)]}\n (values generation :x))\n\n(defn y-values\n \"The Y values of the given generation.\"\n [generation]\n {:pre [(set? generation)]\n :post [(set? %)]}\n (values generation :y))\n</code></pre>\n\n<h2>To:</h2>\n\n<pre><code>(defn values\n \"The values of the given generation's given dimension.\"\n [elem generation]\n {:pre [(set? generation)]\n :post [(set? %)]}\n (set (map elem generation)))\n\n(def x-value (partial values :x))\n(def y-value (partial values :y))\n</code></pre>\n\n<hr>\n\n<h2>All min-*/max-* can be compressed to:</h2>\n\n<pre><code>(defn get-by\n [selector source generation]\n {:pre [(set? generation)]}\n (apply selector (source generation)))\n\n(def min-x (partial get-by min x-value))\n(def max-x (partial get-by max x-value))\n(def min-y (partial get-by min y-value))\n(def max-x (partial get-by max y-value))\n</code></pre>\n\n<hr>\n\n<h2>flat-map can be:</h2>\n\n<pre><code>(defn flat-map [f s] (set (mapcat f s)))\n</code></pre>\n\n<hr>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T16:58:47.663", "Id": "28028", "Score": "0", "body": "Thanks Ankur. mapcat looks very useful indeed - I'll have to read up some more! Any pointers on good ways of discovering / exploring the core libraries?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T11:28:50.197", "Id": "17606", "ParentId": "17603", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T00:23:27.380", "Id": "17603", "Score": "5", "Tags": [ "clojure", "game-of-life" ], "Title": "Critique my Clojure \"Game of Life\" code" }
17603
<p>Previously I asked a <a href="https://stackoverflow.com/questions/9791778/grouping-python-dictionaries-in-hierachical-form" title="question">question</a> on how to group dictionaries in a list in a hierarchical structure.</p> <p>Initially I wanted to group a list of dictionaries that looks like the following, using multiple keys:</p> <pre><code>[{'dept':1, 'age':10, 'name':'Sam'}, {'dept':1, 'age':12, 'name':'John'}, . . . {'dept':2,'age':20, 'name':'Mary'}, {'dept':2,'age':11, 'name':'Mark'}, {'dept':2,'age':11, 'name':'Tom'}] </code></pre> <p>And the output would be:</p> <pre><code>[ { 2: { 20: [ { 'age': 20, 'dept': 2, 'name': 'Mary' } ] }, { 11: [ { 'age': 11, 'dept': 2, 'name': 'Mark' }, { 'age': 11, 'dept': 2, 'name': 'Tom' } ] } }, { 1: { 10: [ { 'age': 10, 'dept': 1, 'name': 'Sam' } ] }, { 12: [ { 'age': 12, 'dept': 1, 'name': 'John' } ] } } ] </code></pre> <p>Using this code:</p> <pre><code>import itertools, operator l = [{'dept':1, 'age':10, 'name':'Sam'}, {'dept':1, 'age':12, 'name':'John'}, {'dept':2,'age':20, 'name':'Mary'}, {'dept':2,'age':11, 'name':'Mark'}, {'dept':2,'age':11, 'name':'Tom'}] groups = ['dept', 'age', 'name'] groups.reverse() def hierachical_data(data, groups): g = groups[-1] g_list = [] for key, items in itertools.groupby(data, operator.itemgetter(g)): g_list.append({key:list(items)}) groups = groups[0:-1] if(len(groups) != 0): for e in g_list: for k,v in e.items(): e[k] = hierachical_data(v, groups) return g_list print hierachical_data(l, groups) </code></pre> <p>This method works fine, but now I need to optimize. The dictionaries has a big memory overhead and this grouping gets pretty slow when we are dealing with huge number of records.</p> <p>I was wondering if there is any algorithm I could use to reduce the time needed to do the grouping.</p> <p>P.S: I wouldn't mind changing the data-structure as long as it gives me the same hierarchical format, or any better suggestion of course. </p> <p>Thanks. </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:36:36.470", "Id": "28046", "Score": "1", "body": "Welcome to Code Review. If you read the FAQ, you will find that you need to post your code into your question or we'll have to close it. Please edit your post and paste in your code so that we can review it. For a really great question (worthy of upvoting) please include everything needed (including data) so that others can execute your code easily." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T02:18:12.123", "Id": "28070", "Score": "0", "body": "@WinstonEwert Thanks a lot for your comment. I added the code and data input and output examples." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T02:22:31.753", "Id": "28071", "Score": "0", "body": "Why not use some sort of database table with indexes instead?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T02:28:54.203", "Id": "28072", "Score": "1", "body": "@Leonid Actually that's currently the solution I am using. To make it clear these records come from a database and then they are serialized into a dictionary. I use grouping and aggregation functions on the database side to reduce the number of records returned, but I was wondering if I can make my python code (the part that does the rest of the processing) even better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T03:05:47.120", "Id": "28073", "Score": "0", "body": "What do you do with this data structure after you have created it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T03:27:52.717", "Id": "28074", "Score": "0", "body": "It's a small reporting engine. So, calculations on the returned records are performed both on the detail level and the groups levels." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T12:14:56.690", "Id": "28085", "Score": "1", "body": "It would be useful to have an actual sample of large data so we could run that. Otherwise, we are optimizing in the dark." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T12:27:43.673", "Id": "28086", "Score": "1", "body": "it seams weird that your output data structure is a list of dictionaries with only one key in each. IMHO you need a list only at the last nesting level (where you store you originals record)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T13:16:40.500", "Id": "28088", "Score": "0", "body": "@WinstonEwert I can try to generate some random data as a test case. Would that be useful ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T13:18:09.820", "Id": "28090", "Score": "0", "body": "@thelinuxer, yah, I attempted to create my own larger data set and it seems to be really fast no matter how large I make the thing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T13:18:12.540", "Id": "28091", "Score": "0", "body": "@FabienAndre I think this would improve the memory usage dramatically, but would it also help in speed ? I was actually thinking about using tuples, which uses less memory than lists." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T13:19:10.697", "Id": "28092", "Score": "0", "body": "@WinstonEwert How large? Like a 100,000 records ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T13:59:25.697", "Id": "28094", "Score": "0", "body": "It will not dramatically speed your code. It depends on how far you have to cut corners... This cuts on constant(no complexity). Overload is small at creation, but might be more significant while accessing your datas." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T17:49:07.977", "Id": "28101", "Score": "0", "body": "Large enough that you see the speed issues when you try it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T21:37:05.370", "Id": "28109", "Score": "1", "body": "The perhaps you should use the power of the database partly - `select dept, age, name from something order by dept, age;` This is `O(n)`, but if this is too slow, then yes - hack away." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T14:27:26.513", "Id": "28278", "Score": "0", "body": "Your result does match what you want it to do: It should be grouping by name after the age." } ]
[ { "body": "<p>Try doing a recursive sequence that iterates through each group, by passing a group index to each call, and find and build the tree as it receives inputs:</p>\n\n<pre><code>def generate_hierarchical_hash(entries, groups):\n \"\"\"Returns hierarchical hash of entries, grouped at each level by the groups\"\"\"\n hierarchy = {}\n for to_insert in entries:\n insert_into_hierarchy(to_insert, hierarchy, groups, 0)\n return hierarchy\n\n\ndef insert_into_hierarchy(to_insert, hierarchy, groupings, current_grouping_level):\n if current_grouping_level == len(groupings):\n # if at final level, do not do anything - protection case\n pass\n else:\n grouping_at_level = groupings[current_grouping_level]\n grouping_key = to_insert[grouping_at_level]\n is_final_group = current_grouping_level == len(groupings) - 1\n if is_final_group:\n # if at last grouping, nodes will contain lists, so create or retrieve list\n # and append value to it\n if grouping_key in hierarchy:\n list_for_group = hierarchy[grouping_key]\n else:\n # create new list and insert it into hierarchy\n list_for_group = list()\n hierarchy[grouping_key] = list_for_group\n\n # insert to insert into end of list\n list_for_group.append(to_insert)\n else:\n # otherwise, find or create hash for this grouping,\n if grouping_key in hierarchy:\n hierarchy_for_group = hierarchy[grouping_key]\n else:\n # create hash and insert into parent hash\n hierarchy_for_group = {}\n hierarchy[grouping_key] = hierarchy_for_group\n # recursive call, go down a level and group\n insert_into_hierarchy(to_insert, hierarchy_for_group, groupings, current_grouping_level + 1)\n</code></pre>\n\n<p>This could be called like:</p>\n\n<pre><code>input =[{'dept':1, 'age':10, 'name':'Sam'},\n {'dept':1, 'age':12, 'name':'John'},\n {'dept':2,'age':20, 'name':'Mary'},\n {'dept':2,'age':11, 'name':'Mark'},\n {'dept':2,'age':11, 'name':'Tom'}]\n\ngroups = ['dept', 'age', 'name']\n\nhierarchical_hash = generate_hierarchical_hash(input, groups)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T18:08:25.653", "Id": "28285", "Score": "0", "body": "Thanks a lot for your answer. Please allow me sometime to test it before I mark the question as answered." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T15:44:55.077", "Id": "29708", "Score": "0", "body": "Any luck with this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-18T13:28:43.503", "Id": "29902", "Score": "0", "body": "I am sorry I haven't checked it yet things have been crazy at my end." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T14:22:36.940", "Id": "17751", "ParentId": "17611", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "16", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T15:21:18.533", "Id": "17611", "Score": "3", "Tags": [ "python", "optimization", "algorithm", "performance" ], "Title": "Need an algorithm to optimize grouping python dictionaries in hierarchical form" }
17611
<p>What is the simplest way of hiding labels and inputs in a way that they <strong>do not</strong> affect the layout. See image and the code below. The label <em>text3</em> is hidden and there is no extra gap between <em>text2</em> and <em>text4</em>. In this implementation I put both in <code>div</code> container and change its <code>.style.display</code> property.</p> <p><strong>Edit</strong>: the figure is excactly what I want but the implementation is not good. In other words, how to rewrite the function (e.g. getting rid of div and using css...).</p> <p><img src="https://i.stack.imgur.com/12tt5.png" alt="Example of hiding a row"></p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;script type="application/javascript"&gt; function hideableLabelAndTextInput(divId, inputId, labelTxt){ // container var hiderDiv = document.createElement('div'); hiderDiv.style.display = 'block'; hiderDiv.id = divId // label var newLabel = document.createElement('label'); newLabel.innerHTML = labelTxt; // textBox var newTextBox = document.createElement('input'); newTextBox.type = 'text'; newTextBox.id = 'inputId'; // grouping hiderDiv.appendChild(newLabel); hiderDiv.appendChild(newTextBox); return hiderDiv; } for (var i=0; i&lt;10; i++){ elem = hideableLabelAndTextInput('div' + i, 'text' + i, 'text' + i); document.body.appendChild(elem); } document.getElementById('div3').style.display = 'none'; document.getElementById('div6').style.display = 'none'; &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:03:08.183", "Id": "28041", "Score": "1", "body": "So you _want_ to have a gap between 2 and 4? Just trying to make sure I understand" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:50:30.037", "Id": "28048", "Score": "0", "body": "No, I want it to exactly like that. I just think that my implementation is bad..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T23:39:38.150", "Id": "28183", "Score": "0", "body": "Why not just add the label name as a data attribute to the element it's for? Example `<div data-label=\"text1\">Test 1</div>`" } ]
[ { "body": "<p>I would use a combination of CSS and JavaScript for this use-case. Essentially what you want to achieve is a simple solution to showing and hiding form elements.</p>\n\n<p>This is what I would suggest for markup:</p>\n\n<pre><code>&lt;form id=\"myform\" method=\"POST\" action=\"/some/processing/script\"&gt;\n &lt;fieldset id=\"group-a\" class=\"input-group\"&gt;\n &lt;label for=\"my-input-element-1\" class=\"input-wrapper\"&gt;\n &lt;span&gt;My Element Label&lt;/span&gt;\n &lt;input type=\"text\" id=\"my-input-element-1\" value=\"\" /&gt;\n &lt;/label&gt;\n\n &lt;!-- Repeat as many times as you need --&gt;\n &lt;/fieldset&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#myform label {\n display: block;\n margin: 0 0 10px 0; /* Set the bottom margin to whatever you want */\n}\n\n#myform label &gt; span {\n display: block; /* display:block will force the input element below it */\n margin: 0 0 3px 0; /* Set the bottom margin to whatever you want */\n}\n\n#myform label &gt; input[type=\"text\"] {\n display: block; /* The default is inline, but we want to span the whole width */\n width: 100%; /* Full width */\n padding: 5px 0; /* Trick to allow an input to span the full width, without poking out of the containing element */\n margin: 0; /* Set the bottom margin to whatever you want */\n text-indent: 5px; /* Indent the text to make it appear normally */\n}\n\n#myform label.hidden {\n display: none !important;\n visibility: hidden !important;\n}\n\n/* OR */\n\n.hidden {\n display: none !important;\n visibility: hidden !important; /* Prevent element from affecting the box model, e.g. whitespace between visible, surrounding elements */\n}\n</code></pre>\n\n<p>Now, with this setup in mind, you should only have to add or remove the class <code>.hidden</code> from either the containing <code>&lt;label /&gt;</code> element or apply it to the <code>&lt;fieldset /&gt;</code> element if you want to hide the whole group.</p>\n\n<p>Also, if you're going to go to the trouble of hiding input fields, I'd recommend setting the disabled attribute, e.g. <code>&lt;input type=\"text\" disabled=\"disabled\" /&gt;</code> to prevent it's values from being serialized/submitted as part of the form.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T03:31:26.760", "Id": "17630", "ParentId": "17620", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T19:40:46.817", "Id": "17620", "Score": "1", "Tags": [ "javascript", "html" ], "Title": "What is the simplest way to hide labels and inputs with javascript?" }
17620
<p>I would like to get some feedback on the following implementation of disjoint sets, based on disjoint-sets forests (<em>Cormen, et.al., Introduction to Algorithms, 2nd ed., p.505ff</em>). It should have the following properties:</p> <ul> <li>Abstracts away all internal data structures and can be used to create disjoint sets of any type <code>T</code></li> <li>Supports the traditional disjoint set operations: <code>add</code>, <code>union</code>, <code>find</code></li> <li>Performs union-by-rank and path compression optimizations</li> </ul> <p>Any general advice is welcome, but I have my doubts in particular about the following points:</p> <ul> <li>Mixture of object-oriented and functional programming - it feels like best of both worlds, but I'm always unsure on which side to lean stronger.</li> <li>Thread-safety: is it sufficient to synchronize the public methods and initialization? is it necessary? (not sure about <code>add</code> and <code>size</code>)</li> <li>The <code>MatchError</code>: what is a best practice to deal with this sort of thing?</li> </ul> <p></p> <pre><code>import scala.annotation.tailrec /** * This class implements a disjoint-sets algorithm with * union-by-rank and path compression. The forest/sets/etc. are * internal data structures not exposed to the outside. Instead, * it is possible to add new elements (which end up in a newly * created set), union two elements, and hence, their sets, and * find the representative of a disjoint-set by a given element of * the set. */ class DisjointSets[T](initialElements : Seq[T] = Nil) { /** * Add a new single-node forest to the disjoint-set forests. It will * be placed into its own set. */ def add(elem : T) : Unit = synchronized { nodes += (elem -&gt; DisjointSets.Node(elem, 0, None)) } /** * Union the disjoint-sets of which &lt;code&gt;elem1&lt;/code&gt; * and &lt;code&gt;elem2&lt;/code&gt; are members of. * @return the representative of the unioned set * @precondition elem1 and elem2 must have been added before */ def union(elem1 : T, elem2 : T) : T = synchronized { // lookup elements require(nodes.contains(elem1) &amp;&amp; nodes.contains(elem2), "Only elements previously added to the disjoint-sets can be unioned") // retrieve representative nodes (nodes.get(elem1).map(_.getRepresentative), nodes.get(elem2).map(_.getRepresentative)) match { // Distinguish the different union cases and return the new set representative // Case #1: both elements already in same set case (Some(n1), Some(n2)) if n1 == n2 =&gt; n1.elem // Case #2: rank1 &gt; rank2 -&gt; make n1 parent of n2 case (Some(n1 @ DisjointSets.Node(_, rank1, _)), Some(n2 @ DisjointSets.Node(_, rank2, _))) if rank1 &gt; rank2 =&gt; n2.parent = Some(n1) n1.elem // Case #3: rank1 &lt; rank2 -&gt; make n2 parent of n1 case (Some(n1 @ DisjointSets.Node(_, rank1, _)), Some(n2 @ DisjointSets.Node(_, rank2, _))) if rank1 &lt; rank2 =&gt; n1.parent = Some(n2) n2.elem // Case #4: rank1 == rank2 -&gt; keep n1 as representative and increment rank case (Some(n1 @ DisjointSets.Node(_, rank1, _)), Some(n2 @ DisjointSets.Node(_, rank2, _))) /*if rank1 == rank2*/ =&gt; n1.rank = rank1 + 1 n2.parent = Some(n1) n1.elem // we are guaranteed to find the two nodes in the map, // and the above cases cover all possibilities case _ =&gt; throw new MatchError("This should never have happened") } } /** * Finds the representative for a disjoint-set, of which * &lt;code&gt;elem&lt;/code&gt; is a member of. */ def find(elem : T) : Option[T] = synchronized { nodes.get(elem) match { case Some(node) =&gt; val rootNode = node.getRepresentative // path compression if (node != rootNode) node.parent = Some(rootNode) Some(rootNode.elem) case None =&gt; None } } /** * Returns the number of disjoint-sets managed in this data structure. * Keep in mind: this is a non-vital/non-standard operation, so we do * not keep track of the number of sets, and instead this method recomputes * them each time. */ def size : Int = synchronized { nodes.values.count(_.parent == None) } //// // Internal parts private val nodes : scala.collection.mutable.Map[T, DisjointSets.Node[T]] = scala.collection.mutable.Map.empty // Initialization synchronized { initialElements map (add _) } } object DisjointSets { def apply[T](initialElements : Seq[T] = Nil) = new DisjointSets[T](initialElements) //// // Internal parts private case class Node[T](val elem : T, var rank : Int, var parent : Option[Node[T]]) { /** * Compute representative of this set. * @return root element of the set */ @tailrec final def getRepresentative: Node[T] = parent match { case None =&gt; this case Some(p) =&gt; p.getRepresentative } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-17T18:29:54.763", "Id": "31523", "Score": "0", "body": "FWIW, Sylvain Conchon and J.C. Filliatre have an axiomatized (and proven correct) implementation in \"A Persistent Union-Find Data Structure\" which reads in Ocaml... I was trying to find a ready-made implementation and found both your work and theirs... I'm off to code my own now!" } ]
[ { "body": "<p>I have a feeling that your <code>find</code> is suboptimal. I'd say you should compress the whole path up to the root, not just the parent of the single node. So you should find the root node first and then traverse the path again and set <code>parent</code> to <code>Some(rootNode)</code> for all of the nodes.</p>\n\n<p>Concerning <code>MatchError</code>s, I'd perhaps use</p>\n\n<pre><code>def union(elem1 : T, elem2 : T) : T =\n // retrieve representative nodes\n (nodes.get(elem1).map(_.getRepresentative), \n nodes.get(elem2).map(_.getRepresentative)) match {\n case (Some(n1), Some(n2)) if n1 == n2 =&gt; // ...\n\n // ...\n\n case _ =&gt; // one of the values is None\n require(false,\n \"Only elements previously added to the disjoint-sets can be unioned\")\n }\n</code></pre>\n\n<hr>\n\n<p>Concerning synchronization, I'd let the user pick if (s)he wants a synchronized implementation or not. I'd define a trait with all the operations (that's always a good idea to separate the contract):</p>\n\n<pre><code>trait DisjointSets[T] {\n def add(elem : T) : Unit;\n def union(elem1 : T, elem2 : T) : T;\n def find(elem : T) : Option[T];\n def size : Int;\n}\n</code></pre>\n\n<p>and then something like</p>\n\n<pre><code>class DisjointSetsImpl[T] private (initialElements : Seq[T] = Nil)\n extends DisjointSets[T]\n{\n // ...\n}\n</code></pre>\n\n<p>and then a wrapper (either explicit or just within a method on the companion object)</p>\n\n<pre><code>class DisjointSetSync[T](val underlying: DisjointSet[T])\n extends DisjointSet[T]\n{\n override def add(elem: T) : Unit = synchronized {\n underlying.add(elem);\n }\n\n // etc.\n}\n</code></pre>\n\n<p>You will need to synchronize all public operations, including <code>add</code> and <code>size</code> (consider one thread is reading the <code>size</code> while the other one is adding a new element to the set using <code>add</code>).</p>\n\n<p>This way users can use faster, default, non-synchronized implementation, and wrap it into a synchronized one, if needed. In most cases, users will want their own synchronization anyway, because they often use other synchronization primitives (such as locks or semaphores) or need to synchronize several operations at once.</p>\n\n<p>Also, you don't need to synchronize initializing code such as</p>\n\n<pre><code>// Initialization\nsynchronized { initialElements map (add _) }\n</code></pre>\n\n<p>because at the time of the initialization of an object, nobody has a reference to it yet, so it's not possible that other threads access it concurrently.</p>\n\n<p>I'd perhaps use a different name for <code>size</code>, something like <code>setCount</code>, because it can be easily confused with the number of elements, not the number of disjoint sets. You could also make <code>size</code> faster by keeping count of the number of distinct sets, and just decrementing it after each successful <code>union</code>. (I vaguely recall that this operation was useful for some algorithm, but I can't remember which one.)</p>\n\n<p>You could also consider extending Scala's standard traits (after renaming <code>size</code>) to make your class even more useful:</p>\n\n<ul>\n<li><code>Growable</code> (this would replace <code>add</code> with <code>+=</code>).</li>\n<li><code>Traversable</code> which would traverse all elements in all sets.</li>\n<li><code>PartialFunction[T,T]</code> to find a representative for a node (if it's in the set - this would be a synonym for <code>find</code>).</li>\n</ul>\n\n<p>This won't cost you anything and can be useful sometimes.</p>\n\n<hr>\n\n<p>There has been <a href=\"https://stackoverflow.com/q/17409641/1333025\">a request</a> for an implementation like yours, perhaps you could consider publishing it as a small library somewhere.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T17:56:15.290", "Id": "28003", "ParentId": "17621", "Score": "2" } }, { "body": "<p>Adding to the excellent remarks from Petr:</p>\n\n<p>I think you could gain some storage efficiency and reduce the number of temporary objects by having parent as a field of Node[T] (instead of having a parent of type Option[Node[T]]). You would just initialize it with this (which is the correct initial value).</p>\n\n<pre><code>object DisjointSets {\n def apply[T](initialElements : Seq[T] = Nil) = new DisjointSets[T](initialElements)\n\n ////\n // Internal parts\n private case class Node[T](val elem : T, var rank : Int) {\n\n var parent: Node[T] = this\n\n /**\n * Compute representative of this set.\n * @return root element of the set\n */\n\n @tailrec\n final def getRepresentative: Node[T] = \n if(parent eq this) this else parent.getRepresentative\n } \n }\n}\n</code></pre>\n\n<p>Regarding synchronization: I wouldn't bother. Keep it completely out of your code, and put a big warning in the docs that the thing is not thread-safe. When people want to use it in a multithreaded context they will probably have to put a lock around it anyway because they have multiple data structures that they need to keep synchronized. And in scala mutable data structures are mostly used from safe context such as the internal state of an actor. For this use case synchronization by default would just add additional overhead.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-01T20:32:31.497", "Id": "28010", "ParentId": "17621", "Score": "0" } } ]
{ "AcceptedAnswerId": "28003", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:51:47.330", "Id": "17621", "Score": "11", "Tags": [ "algorithm", "scala" ], "Title": "Disjoint sets implementation" }
17621
<p>I am trying to write a merge sort algorithm. I can't tell if this is actually a canonical merge sort. If I knew how to calculate the runtime I would give that a go. Does anyone have any pointers?</p> <pre><code>public static void main(String[] argsv) { int[] A = {2, 4, 5, 7, 1, 2, 3, 6}; int[] L, R; L = new int[A.length/2]; R = new int[A.length/2]; int i = 0, j = 0, k; PrintArray(A); // Make left and right arrays for (k = 0; k &lt; A.length; k++) { if (k &lt; A.length/2) { L[i] = A[k]; i++; } else { R[j] = A[k]; j++; } } PrintArray(L); PrintArray(R); i = 0; j = 0; // Merge the left and right arrays for (k = 0; k &lt; A.length; k++) { System.out.println(i + " " + j + " " + k); if (i &lt; L.length &amp;&amp; j &lt; R.length) { if (L[i] &lt; R[j]) { PrintArray(A); A[k] = L[i]; i++; } else { PrintArray(A); A[k] = R[j]; j++; } } } PrintArray(L); PrintArray(R); PrintArray(A); } public static void PrintArray(int[] arrayToPrint) { for (int i = 0; i &lt; arrayToPrint.length; i++) { System.out.print(arrayToPrint[i] + " "); } System.out.print("\n"); } </code></pre>
[]
[ { "body": "<p>When a prospective employer asks you a question like this one, they most likely want to see something original. They want you to show them that you can create code and not just copy and paste bits and pieces of code.</p>\n\n<p>If what you wrote works and runs correctly, then you have accomplished the answer.</p>\n\n<p>Sometimes employers are trying to find out if you know the theory behind a merge sort. It looks to me like you have done that as well.</p>\n\n<hr>\n\n<p>The only thing that I can think of that you could do to make your code better is to improve the naming of your variables.</p>\n\n<pre><code>int[] A = {2, 4, 5, 7, 1, 2, 3, 6};\nint[] L, R;\n\nL = new int[A.length/2];\nR = new int[A.length/2];\n</code></pre>\n\n<p>Change them to </p>\n\n<pre><code>int[] array = {2, 4, 5, 7, 1, 2, 3, 6};\nint[] leftSide;\nint[] rightSide;\n\nleftSide = new int[array.length/2];\nrightSide = new int[array.length/2];\n</code></pre>\n\n<p>This would make it much easier to read.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:03:03.640", "Id": "28058", "Score": "1", "body": "Thank you very much, I appreciate you taking the time to answer what I feel was an odd question. I suppose there must be a bunch of mergesort implementations, i.e. ones written in functional languages, ones that deal with an odd number of elements, ones that use sentinels, etc. Thanks again Malachi :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:00:51.810", "Id": "17623", "ParentId": "17622", "Score": "5" } }, { "body": "<p>If you already have a separate function for printing the arrays, then you should have others to do the sorting. A function should be responsible for doing one thing, which is essential in maintaining <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\">separation of concerns</a>. This will also make the program easier to maintain as each segment will be separated.</p>\n\n<p>You should have the array initialized in <code>main()</code>, pass it to the function, sort the array, return it, and pass it to the displaying function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T03:55:56.510", "Id": "46877", "ParentId": "17622", "Score": "5" } }, { "body": "<p>I would say this is a solid, workmanlike implementation of a merge sort. </p>\n\n<p>I can see some areas for improvement though. As far as style goes, the most obvious improvement would be to use variable names that are longer and more descriptive. Names like <code>A</code>, <code>L</code> and <code>R</code> are of only fairly minimal help. Given that you have both <code>L</code> and <code>R</code>, it's pretty easy to guess that you intended them to stand for <code>left</code> and <code>right</code> respectively. I'd much rather see them spelled out though.</p>\n\n<p>It may also be worth considering some algorithmic improvements. As it stands right now, you do recursive calls approximately \\$\\log_2{N}\\$ deep, and make a new copy of all the data in the input array each time. That gives a space requirement of approximately \\$\\log_2{N}\\$.</p>\n\n<p>One easy way to reduce this would be to just keep track of the dividing line between the \"left\" and \"right\" arrays easy each call instead of creating entirely new arrays. This makes it pretty easy to reduce your space requirement to approximately 2N.</p>\n\n<p>If you want to go even further, you could implement one of the in-place merging algorithms I cited in <a href=\"https://codereview.stackexchange.com/a/43944/489\">another answer</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-11T03:58:35.253", "Id": "46878", "ParentId": "17622", "Score": "5" } } ]
{ "AcceptedAnswerId": "17623", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T20:47:10.337", "Id": "17622", "Score": "7", "Tags": [ "java", "algorithm", "sorting", "mergesort" ], "Title": "Is this attempt at a merge sort correct?" }
17622
<p>Below is a module that executes a sequence of actions in any possible order. <code>LANGUAGE_DataKinds</code> and <code>LANGUAGE_DefaultSignatures</code> are predefined cpp symbols.</p> <p>Is this permutation applicative/monad implementation clear? I am particularly concerned about the use of DataKinds and GADTs, and if I should instead split it in to two separate implementations (one for Applicative/Alternative, one for Monad/MonadPlus).</p> <pre><code>{-# LANGUAGE CPP #-} #ifdef LANGUAGE_DataKinds {-# LANGUAGE DataKinds #-} #else {-# LANGUAGE EmptyDataDecls #-} #endif {-# LANGUAGE FlexibleInstances , GADTs , MultiParamTypeClasses , Rank2Types , TypeSynonymInstances , UndecidableInstances #-} {- | Stability: experimental Portability: non-portable -} module Control.Monad.Perm.Internal ( Perm , runPerm , PermT , runPermT , PermC , liftPerm , hoistPerm ) where import Control.Applicative hiding (Applicative) import qualified Control.Applicative as Applicative (Applicative) import Control.Monad hiding (Monad) import qualified Control.Monad as Monad (Monad) import Control.Monad.Catch.Class import Control.Monad.IO.Class import Control.Monad.Reader.Class import Control.Monad.State.Class import Control.Monad.Trans.Class (MonadTrans (lift)) import Data.Foldable (foldr) import Data.Monoid ((&lt;&gt;), mempty) import Prelude (Maybe (..), ($), (.), const, flip, fst, id, map, maybe) -- | The permutation applicative type Perm = PermC Applicative -- | The permutation monad type PermT = PermC Monad {- | The permutation action, available as either an 'Applicative.Applicative' or a 'Monad.Monad', determined by the combinators used. -} data PermC c m a = Choice (Maybe a) [Branch c m a] data Branch c m b where Ap :: PermC c m (a -&gt; b) -&gt; m a -&gt; Branch c m b Bind :: (a -&gt; PermT m b) -&gt; m a -&gt; Branch Monad m b #ifdef LANGUAGE_DataKinds data Constraint = Applicative | Monad #else data Applicative data Monad #endif instance Functor (PermC c m) where fmap f (Choice a xs) = Choice (f &lt;$&gt; a) (fmap f &lt;$&gt; xs) instance Functor (Branch c m) where fmap f (Ap perm m) = Ap (fmap (f .) perm) m fmap f (Bind k m) = Bind (fmap f . k) m instance Applicative.Applicative (PermC c m) where pure a = Choice (pure a) mempty f@(Choice f' fs) &lt;*&gt; a@(Choice a' as) = Choice (f' &lt;*&gt; a') (fmap (`apB` a) fs &lt;&gt; fmap (f `apP`) as) (*&gt;) = liftThen (*&gt;) apP :: PermC c m (a -&gt; b) -&gt; Branch c m a -&gt; Branch c m b f `apP` Ap perm m = (f .@ perm) `Ap` m f `apP` Bind k m = Bind ((f `ap`) . k) m (.@) :: Applicative.Applicative f =&gt; f (b -&gt; c) -&gt; f (a -&gt; b) -&gt; f (a -&gt; c) (.@) = liftA2 (.) apB :: Branch c m (a -&gt; b) -&gt; PermC c m a -&gt; Branch c m b Ap perm m `apB` a = flipA2 perm a `Ap` m Bind k m `apB` a = Bind ((`ap` a) . k) m flipA2 :: Applicative.Applicative f =&gt; f (a -&gt; b -&gt; c) -&gt; f b -&gt; f (a -&gt; c) flipA2 = liftA2 flip instance Alternative (PermC c m) where empty = liftZero empty (&lt;|&gt;) = plus instance Monad.Monad (PermT m) where return a = Choice (return a) mempty Choice Nothing xs &gt;&gt;= k = Choice Nothing (map (bindP k) xs) Choice (Just a) xs &gt;&gt;= k = case k a of Choice a' xs' -&gt; Choice a' (map (bindP k) xs &lt;&gt; xs') (&gt;&gt;) = liftThen (&gt;&gt;) fail _ = Choice mzero mempty bindP :: (a -&gt; PermT m b) -&gt; Branch Monad m a -&gt; Branch Monad m b bindP k (Ap perm m) = Bind (\ a -&gt; k . ($ a) =&lt;&lt; perm) m bindP k (Bind k' m) = Bind (k &lt;=&lt; k') m instance MonadPlus (PermT m) where mzero = liftZero mzero mplus = plus instance MonadTrans (PermC c) where lift = liftPerm instance MonadIO m =&gt; MonadIO (PermT m) where liftIO = lift . liftIO instance MonadReader r m =&gt; MonadReader r (PermT m) where ask = lift ask local f (Choice a xs) = Choice a (map (localBranch f) xs) localBranch :: MonadReader r m =&gt; (r -&gt; r) -&gt; Branch Monad m a -&gt; Branch Monad m a localBranch f (Ap perm m) = Ap (local f perm) (local f m) localBranch f (Bind k m) = Bind (local f . k) (local f m) instance MonadState s m =&gt; MonadState s (PermT m) where get = lift get put = lift . put #ifdef LANGUAGE_DefaultSignatures instance MonadThrow e m =&gt; MonadThrow e (PermT m) #else instance MonadThrow e m =&gt; MonadThrow e (PermT m) where throw = lift . throw #endif liftThen :: (Maybe a -&gt; Maybe b -&gt; Maybe b) -&gt; PermC c m a -&gt; PermC c m b -&gt; PermC c m b liftThen thenMaybe m@(Choice m' ms) n@(Choice n' ns) = Choice (m' `thenMaybe` n') (map (`thenB` n) ms &lt;&gt; map (m `thenP`) ns) thenP :: PermC c m a -&gt; Branch c m b -&gt; Branch c m b m `thenP` Ap perm m' = (m *&gt; perm) `Ap` m' m `thenP` Bind k m' = Bind ((m &gt;&gt;) . k) m' thenB :: Branch c m a -&gt; PermC c m b -&gt; Branch c m b Ap perm m `thenB` n = (perm *&gt; fmap const n) `Ap` m Bind k m `thenB` n = Bind ((&gt;&gt; n) . k) m liftZero :: Maybe a -&gt; PermC c m a liftZero zeroMaybe = Choice zeroMaybe mempty plus :: PermC c m a -&gt; PermC c m a -&gt; PermC c m a m@(Choice (Just _) _) `plus` _ = m Choice Nothing xs `plus` Choice b ys = Choice b (xs &lt;&gt; ys) -- | Unwrap a 'Perm', combining actions using the 'Alternative' for @f@. runPerm :: Alternative m =&gt; Perm m a -&gt; m a runPerm = lower where lower (Choice a xs) = foldr ((&lt;|&gt;) . f) (maybe empty pure a) xs f (perm `Ap` m) = m &lt;**&gt; runPerm perm -- | Unwrap a 'PermC', combining actions using the 'MonadPlus' for @f@. runPermT :: MonadPlus m =&gt; PermT m a -&gt; m a runPermT = lower where lower (Choice a xs) = foldr (mplus . f) (maybe mzero return a) xs f (perm `Ap` m) = flip ($) `liftM` m `ap` runPermT perm f (Bind k m) = m &gt;&gt;= runPermT . k -- | A version of 'lift' without the @'Monad.Monad' m@ constraint liftPerm :: m a -&gt; PermC c m a liftPerm = Choice empty . pure . liftBranch liftBranch :: m a -&gt; Branch c m a liftBranch = Ap (Choice (pure id) mempty) {- | Lift a natural transformation from @m@ to @n@ into a natural transformation from @'PermC' c m@ to @'PermC' c n@. -} hoistPerm :: (forall a . m a -&gt; n a) -&gt; PermC c m b -&gt; PermC c n b hoistPerm f (Choice a xs) = Choice a (hoistBranch f &lt;$&gt; xs) hoistBranch :: (forall a . m a -&gt; n a) -&gt; Branch c m b -&gt; Branch c n b hoistBranch f (perm `Ap` m) = hoistPerm f perm `Ap` f m hoistBranch f (Bind k m) = Bind (hoistPerm f . k) (f m) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T16:14:09.117", "Id": "28099", "Score": "1", "body": "Can you add a usage example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T17:23:40.403", "Id": "28100", "Score": "0", "body": "Yes, some example, and perhaps describing how this monad works, would be helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T15:52:00.300", "Id": "28232", "Score": "0", "body": "With parsec: `runPermT $ lift (char 'a') *> lift (char 'b')` should match `\"ab\"` or `\"bc\"` and always return `'b'`. The same should happen if `>>` is used instead of `*>`, as well as if `liftPerm` is used instead of `lift`, assuming the underlying monad's `Applicative` and `Monad` instances are coherent." } ]
[ { "body": "<p>Below is what I have now. For modifications to this solution, please add a new answer that I can choose (rather than comment on it). Disadvantages compared to the original implementation include an additional <code>Monad n</code> constraint on <code>hoistPerm</code>. Advantages include a simpler exposed data type (no odd phantom type parameter) and the removal of the dubious use of <code>DataKinds</code>. I am still very open to advice, and will leave the question open. Of particular concern now is how <code>runPermT</code> does not use <code>Applicative m</code>, but instead relies on the equivalent <code>Monad</code> operations - should <code>Ap</code> be changed to include a local <code>Applicative m</code> constraint? Doing so would add another constraint to <code>hoistPerm</code> of <code>Applicative n</code> - which though trivially satisfied, is still kind of odd.</p>\n\n<pre><code>{-# LANGUAGE\n CPP\n , FlexibleInstances\n , GADTs\n , MultiParamTypeClasses\n , Rank2Types\n , UndecidableInstances #-}\n{- |\nStability: experimental\nPortability: non-portable\n-}\nmodule Control.Monad.Perm.Internal\n ( Perm\n , runPerm\n , PermT\n , runPermT\n , liftPerm\n , hoistPerm\n ) where\n\nimport Control.Applicative\nimport Control.Monad\nimport Control.Monad.Catch.Class\nimport Control.Monad.IO.Class\nimport Control.Monad.Reader.Class\nimport Control.Monad.State.Class\nimport Control.Monad.Trans.Class (MonadTrans (lift))\n\nimport Data.Foldable (foldr)\nimport Data.Monoid (mempty)\n#if defined(__GLASGOW_HASKELL__) &amp;&amp; __GLASGOW_HASKELL__ &gt;= 704\nimport Data.Monoid ((&lt;&gt;))\n#else\nimport Data.Monoid (Monoid, mappend)\n#endif\n\nimport Prelude (Maybe (..), ($), (.), const, flip, fst, id, map, maybe)\n\n#if !defined(__GLASGOW_HASKELL__) || __GLASGOW_HASKELL__ &lt; 704\n(&lt;&gt;) :: Monoid m =&gt; m -&gt; m -&gt; m\n(&lt;&gt;) = mappend\n{-# INLINE (&lt;&gt;) #-}\n#endif\n\n-- | The permutation applicative\ntype Perm = PermT\n\n-- | The permutation monad\ndata PermT m a = Choice (Maybe a) [Branch m a]\n\ndata Branch m b where\n Ap :: PermT m (a -&gt; b) -&gt; m a -&gt; Branch m b\n Bind :: Monad m =&gt; (a -&gt; PermT m b) -&gt; m a -&gt; Branch m b\n\ninstance Functor (PermT m) where\n fmap f (Choice a xs) = Choice (f &lt;$&gt; a) (fmap f &lt;$&gt; xs)\n\ninstance Functor (Branch m) where\n fmap f (Ap perm m) = Ap (fmap (f .) perm) m\n fmap f (Bind k m) = Bind (fmap f . k) m\n\ninstance Applicative (PermT m) where\n pure a = Choice (pure a) mempty\n f@(Choice f' fs) &lt;*&gt; a@(Choice a' as) =\n Choice (f' &lt;*&gt; a') (fmap (`apB` a) fs &lt;&gt; fmap (f `apP`) as)\n (*&gt;) = liftThen (*&gt;)\n\napP :: PermT m (a -&gt; b) -&gt; Branch m a -&gt; Branch m b\nf `apP` Ap perm m = (f .@ perm) `Ap` m\nf `apP` Bind k m = Bind ((f `ap`) . k) m\n\n(.@) :: Applicative f =&gt; f (b -&gt; c) -&gt; f (a -&gt; b) -&gt; f (a -&gt; c)\n(.@) = liftA2 (.)\n\napB :: Branch m (a -&gt; b) -&gt; PermT m a -&gt; Branch m b\nAp perm m `apB` a = flipA2 perm a `Ap` m\nBind k m `apB` a = Bind ((`ap` a) . k) m\n\nflipA2 :: Applicative f =&gt; f (a -&gt; b -&gt; c) -&gt; f b -&gt; f (a -&gt; c)\nflipA2 = liftA2 flip\n\ninstance Alternative (PermT m) where\n empty = liftZero empty\n (&lt;|&gt;) = plus\n\ninstance Monad m =&gt; Monad (PermT m) where\n return a = Choice (return a) mempty\n Choice Nothing xs &gt;&gt;= k = Choice Nothing (map (bindP k) xs)\n Choice (Just a) xs &gt;&gt;= k = case k a of\n Choice a' xs' -&gt; Choice a' (map (bindP k) xs &lt;&gt; xs')\n (&gt;&gt;) = liftThen (&gt;&gt;)\n fail _ = Choice mzero mempty\n\nbindP :: Monad m =&gt; (a -&gt; PermT m b) -&gt; Branch m a -&gt; Branch m b\nbindP k (Ap perm m) = Bind (\\ a -&gt; k . ($ a) =&lt;&lt; perm) m\nbindP k (Bind k' m) = Bind (k &lt;=&lt; k') m\n\ninstance Monad m =&gt; MonadPlus (PermT m) where\n mzero = liftZero mzero\n mplus = plus\n\ninstance MonadTrans PermT where\n lift = liftPerm\n\ninstance MonadIO m =&gt; MonadIO (PermT m) where\n liftIO = lift . liftIO\n\ninstance MonadReader r m =&gt; MonadReader r (PermT m) where\n ask = lift ask\n local f (Choice a xs) = Choice a (map (localBranch f) xs)\n\nlocalBranch :: MonadReader r m =&gt; (r -&gt; r) -&gt; Branch m a -&gt; Branch m a\nlocalBranch f (Ap perm m) = Ap (local f perm) (local f m)\nlocalBranch f (Bind k m) = Bind (local f . k) (local f m)\n\ninstance MonadState s m =&gt; MonadState s (PermT m) where\n get = lift get\n put = lift . put\n\n#ifdef LANGUAGE_DefaultSignatures\ninstance MonadThrow e m =&gt; MonadThrow e (PermT m)\n#else\ninstance MonadThrow e m =&gt; MonadThrow e (PermT m) where\n throw = lift . throw\n#endif\n\nliftThen :: (Maybe a -&gt; Maybe b -&gt; Maybe b) -&gt;\n PermT m a -&gt; PermT m b -&gt; PermT m b\nliftThen thenMaybe m@(Choice m' ms) n@(Choice n' ns) =\n Choice (m' `thenMaybe` n') (map (`thenB` n) ms &lt;&gt; map (m `thenP`) ns)\n\nthenP :: PermT m a -&gt; Branch m b -&gt; Branch m b\nm `thenP` Ap perm m' = (m *&gt; perm) `Ap` m'\nm `thenP` Bind k m' = Bind ((m &gt;&gt;) . k) m'\n\nthenB :: Branch m a -&gt; PermT m b -&gt; Branch m b\nAp perm m `thenB` n = (perm *&gt; fmap const n) `Ap` m\nBind k m `thenB` n = Bind ((&gt;&gt; n) . k) m\n\nliftZero :: Maybe a -&gt; PermT m a\nliftZero zeroMaybe = Choice zeroMaybe mempty\n\nplus :: PermT m a -&gt; PermT m a -&gt; PermT m a\nm@(Choice (Just _) _) `plus` _ = m\nChoice Nothing xs `plus` Choice b ys = Choice b (xs &lt;&gt; ys)\n\n-- | Unwrap a 'Perm', combining actions using the 'Alternative' for @f@.\nrunPerm :: Alternative m =&gt; Perm m a -&gt; m a\nrunPerm = lower\n where\n lower (Choice a xs) = foldr ((&lt;|&gt;) . f) (maybe empty pure a) xs\n f (perm `Ap` m) = m &lt;**&gt; runPerm perm\n f (Bind k m) = m &gt;&gt;= runPerm . k\n\n-- | Unwrap a 'PermT', combining actions using the 'MonadPlus' for @f@.\nrunPermT :: MonadPlus m =&gt; PermT m a -&gt; m a\nrunPermT = lower\n where\n lower (Choice a xs) = foldr (mplus . f) (maybe mzero return a) xs\n f (perm `Ap` m) = flip ($) `liftM` m `ap` runPermT perm\n f (Bind k m) = m &gt;&gt;= runPermT . k\n\n-- | A version of 'lift' without the @'Monad.Monad' m@ constraint\nliftPerm :: m a -&gt; PermT m a\nliftPerm = Choice empty . pure . liftBranch\n\nliftBranch :: m a -&gt; Branch m a\nliftBranch = Ap (Choice (pure id) mempty)\n\n{- |\nLift a natural transformation from @m@ to @n@ into a natural transformation\nfrom @'PermT'' c m@ to @'PermT'' c n@.\n-}\nhoistPerm :: Monad n =&gt; (forall a . m a -&gt; n a) -&gt; PermT m b -&gt; PermT n b\nhoistPerm f (Choice a xs) = Choice a (hoistBranch f &lt;$&gt; xs)\n\nhoistBranch :: Monad n =&gt; (forall a . m a -&gt; n a) -&gt; Branch m b -&gt; Branch n b\nhoistBranch f (perm `Ap` m) = hoistPerm f perm `Ap` f m\nhoistBranch f (Bind k m) = Bind (hoistPerm f . k) (f m)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T15:14:17.980", "Id": "17647", "ParentId": "17626", "Score": "0" } }, { "body": "<p>As <code>Alternative</code> and <code>MonadPlus</code> are both monoids <code>foldMap</code> seems more appropriate than <code>foldr</code>. Note that you need to define the instances using newtypes. Fortunately these instances are defined in <code>reducers</code> package. So:</p>\n\n<pre><code>foldMonadPlus2 f x = getMonadSum $ foldMap (MonadSum . f) x\nfoldAlternative2 f x = getAlternate $ foldMap (Alternate . f) x\n</code></pre>\n\n<p>It doesn't look very nice, but you can use <code>newtype</code> package to make it better:</p>\n\n<pre><code>foldMonadPlus3 f x = ala (MonadSum . f) foldMap x\nfoldAlternate3 f x = ala (Alternate . f) foldMap x\n</code></pre>\n\n<p>Unfortunately you have to define two instances so it's not any shorter:</p>\n\n<pre><code>instance MonadPlus m =&gt; Newtype (MonadSum m a) (m a) where\n pack = MonadSum\n unpack = getMonadSum\n\ninstance Alternative m =&gt; Newtype (Alternate m a) (m a) where\n pack = Alternate\n unpack = getAlternate\n</code></pre>\n\n<p>Maybe someone else could exploit this idea further.</p>\n\n<p>Another approach is to use <code>msum</code> and <code>asum</code>:</p>\n\n<pre><code>foldMonadPlus f x = asum $ fmap f x\nfoldAlternative f x = msum $ fmap f x\n</code></pre>\n\n<p>You then can define</p>\n\n<pre><code>lower (Choice a xs) = foldMonadPlus f xs `mplus` (maybe mzero return a)\n</code></pre>\n\n<p>And similar for <code>Applicative</code>. Note that <code>x</code> is not any <code>Foldable</code> but always a list so you may want just to import <code>foldr</code> from <code>Prelude</code> instead. </p>\n\n<p>I use the following code to test:</p>\n\n<pre><code>let a x = Perm2.liftPerm (print x) in runPermT (a 0 &gt;&gt; a 0 &gt;&gt; a 1 &gt;&gt; mzero)\n</code></pre>\n\n<p>Couldn't invent anything similar for <code>Applicative</code>.</p>\n\n<p>I could extract common code from <code>runPerm</code> and <code>runPermT</code>:</p>\n\n<pre><code>prepare g f (Choice a xs) = maybe id ((:) . g) a $ map f xs\n</code></pre>\n\n<p>The functions look identical, just <code>lower</code> is respectively:</p>\n\n<pre><code>lower = asum . prepare pure f\nlower = msum . prepare return f\n</code></pre>\n\n<p>Import of <code>Data.Monoid</code> can be removed without a loss of genericity as only the list monoid is actually used. So all <code>&lt;&gt;</code> can be replaced with <code>++</code> and <code>mempty</code> with <code>[]</code>. Are there any other <code>Foldable a, Monoid a</code> types useful to store branches besides lists?</p>\n\n<p>I think it is a good idea to try to extract a recursor for <code>Choice</code> and write everything else non-recursively if it is possible.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T15:55:54.453", "Id": "17649", "ParentId": "17626", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T23:52:50.533", "Id": "17626", "Score": "2", "Tags": [ "haskell", "monads" ], "Title": "Module that executes a sequence of actions in any possible order" }
17626
<p>I have the following code:</p> <pre><code>var sessionsWithError = SessionsFilteredByDate .Where(i =&gt; i.TrackerId &gt; 0 &amp;&amp; i.StatusId == 0) .Select(i =&gt; i.SessionId); var sessionsWithErrorFixed = BusinessClient.Instance.Tracker .GetAllTrackerAttempts() .Select(i =&gt; i.SessionId); var sessionsWithErrorIntersection = sessionsWithError.Intersect(sessionsWithErrorFixed); var sessionsWithErrorsNotFixed = sessionsWithError.Except(sessionsWithErrorIntersection); </code></pre> <p>Then I have to create a <code>IEnumerable</code> where I put all the <code>SessionsFilteredByDate</code> where the <code>sessionID</code> is included in <code>sessionsWithErrorsNotFixed</code>, but this operation, since I am using the <code>Any</code> operator, it's slow, apparently \$O(m*n)\$.</p> <p>How can I achieve this operation with a lower complexity?</p> <pre><code>SessionsFilteredByDateAndErrors = SessionsFilteredByDate .Where(i =&gt; sessionsWithErrorsNotFixed.Any(y =&gt; y == i.SessionId)); </code></pre>
[]
[ { "body": "<p>Put the values into a <code>HashSet&lt;T&gt;</code> (see <a href=\"http://msdn.microsoft.com/en-us/library/bb359438.aspx\" rel=\"nofollow\">here</a>) as the lookup for that is constant O(1).</p>\n\n<pre><code>var sessionsWithErrorSet = new HashSet&lt;int&gt;(\n SessionsFilteredByDate.Where(i =&gt; i.TrackerId &gt; 0 &amp;&amp; i.StatusId == 0).Select(i =&gt; i.SessionId));\n\nvar sessionsWithErrorFixedSet = new HashSet&lt;int&gt;(\n BusinessClient.Instance.Tracker.GetAllTrackerAttempts().Select(i =&gt; i.SessionId));\n\nvar sessionsWithErrorIntersection = sessionsWithError.IntersectWith(sessionsWithErrorFixed);\nvar sessionsWithErrorsNotFixed = sessionsWithError.ExceptWith(sessionsWithErrorIntersection);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T11:34:22.710", "Id": "17638", "ParentId": "17636", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T11:08:01.927", "Id": "17636", "Score": "4", "Tags": [ "c#", "performance", ".net", "linq", "asp.net" ], "Title": "Optimization code for checking if a list contains any element ID of another list" }
17636
<p>I have just started learning some Scheme this weekend. I recently solved a problem that goes something like:</p> <pre><code>Count the number of ways possible to give out a certain amount of change using 1 5 10 25 and 50 cent pieces. --SICP 1.16 </code></pre> <p>So my code to this question looks like this:</p> <pre><code>(define (make-change amount) (define coin-total 5) ;;#Function that actually does the calculating (define (calculate amount coins) ;;#Lookup values on the table vector, if none is found find it and add it. (define (lookup) ;;#Location on the table vector (define position (- (+ coins (* coin-total (- amount 1))) 1)) ;;#Get the value in the table vector (define (search-for amount coins) (vector-ref table position)) ;;#Not quite so functional, but we need to add it somehow (define (update val) (begin (vector-set! table position val) val)) (let ((result (search-for amount coins))) (if (= result 0) (let* ((left-branch (calculate amount (- coins 1))) (right-branch (calculate (- amount (coin-value coins)) coins))) (update (+ left-branch right-branch))) result))) (cond ((= amount 0) 1 ) ((or (&lt; amount 0) (= coins 0)) 0) (else (lookup)))) ;;#Table stuff (define table (make-vector (* amount coin-total) 0)) (define (init-table position) (if (&lt; position 0) 0 (begin (vector-set! table position 1) (init-table (- position 1))))) ;;#The entry point, sets up the table and starts the calculation (begin (init-table 4) (calculate amount coin-total))) ;;#Mapping from coin number to value, order doesn't matter (define (coin-value n) (cond ((= n 1) 1) ((= n 2) 5) ((= n 3) 10) ((= n 4) 25) ((= n 5) 50))) </code></pre> <p>The logic in this code is sound, it "works" but I'm worried that I'm not writing it very idiomatically. What suggestions or alterations would you make for this code?</p> <p>Note: I stuck this # in the comments here so that the code highlighting would stop treating it like code and messing up the syntax highlighting </p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-01-14T17:47:50.063", "Id": "217081", "Score": "0", "body": "many scheme implementations offer a 2-D table, which would provide a simpler interface." } ]
[ { "body": "<p>Well, I could try to rewrite it to not use mutation, but it looks like the mutation is just there as a memoization optimization. You could either pass the vector as an argument into calculate, or you could abstract the memoization via something like define/memo provided in <a href=\"http://planet.plt-scheme.org/display.ss?package=memoize.plt&amp;owner=dherman\" rel=\"nofollow\">memoize.plt</a>, or just roll your own customized one as done here, which I think is just fine.</p>\n\n<p>There are some surface changes you can make as well. For starters, the <code>search-for</code> function doesn't do anything with its arguments, so they can be removed. Next, <code>define</code>s have an explicit <code>begin</code> around the body, so the <code>begin</code> in <code>update</code> can be removed as can the <code>begin</code> near what your comments call the entry point.</p>\n\n<p>The <code>(init-table 4)</code> is an optimization (works without it) that I'm not sure is even worth putting in; especially since I think it deserves a comment to explain that the magic number 4 is because <code>(make-change n)</code> should return <code>1</code> for <code>1 &lt;= n &lt;= 4</code>. If you decide to leave it in, at least replace it by <code>(vector-fill! v 1 0 4)</code> assuming your using <a href=\"http://srfi.schemers.org/srfi-43/srfi-43.html#vector-fill-bang\" rel=\"nofollow\">srfi-43</a>. It might be different if your scheme dialect has it's own vector libs.</p>\n\n<p>Finally, mapping coin number to value could use <code>case</code> instead of <code>cond</code> for a little less syntax as in:</p>\n\n<pre><code>(define (coin-value n)\n (case n\n ((1) 1)\n ((2) 5)\n ((3) 10)\n ((4) 25)\n ((5) 50)))\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-27T22:26:06.437", "Id": "19092", "ParentId": "17637", "Score": "2" } }, { "body": "<p>I would write the function like this:</p>\n\n<pre><code>(define (make-change amount)\n (define (make-change-with-coins amount coins)\n (cond ((&lt; amount 0) 0)\n ((= amount 0) 1)\n ((null? coins) 0)\n (else (+ (make-change-with-coins (- amount (car coins)) coins)\n (make-change-with-coins amount (cdr coins))))))\n (make-change-with-coins amount '(50 25 10 5 1)))\n</code></pre>\n\n<p>Most of the problems in the early parts of SICP can be solved with very few lines of code. The main idea behind functional programming is to think in terms of the list data structure and recursive functions without side effects. Note that <code>make-change-with-coins</code> has only one statement: no value is computed and then ignored.</p>\n\n<p>The basic idea of this is that if I have coins of value N0, N1, N2, ... Nk, I can make an amount A in two ways: either with one or more coins of value N0 or with no coins of value N0.</p>\n\n<p>As a general approach, you should write your code in the way that's the clearest expression of your algorithm; ignore optimizations for the moment. If your code is too slow, then go back and see if optimization is possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T00:04:14.980", "Id": "43443", "Score": "0", "body": "I think you're missing the point here. That code is hideously slow. The logic underlying my code is the same as yours, except that mine simply uses table lookup to avoid calculating the same results over and over again. I was just wondering if I was memoizing in an idiomatic lispy way" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-28T03:55:38.207", "Id": "43452", "Score": "0", "body": "If you're trying to answer a SICP problem, I think you're missing the point by writing a 50-line solution that uses memoization, and I don't want people searching for \"SICP 1.16\" to find your solution and think that's what's required. If you're asking about how to write a memoizing function idiomatically in Scheme, that's a different question; feel free to ignore my solution." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-27T22:37:11.837", "Id": "27867", "ParentId": "17637", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T11:33:51.883", "Id": "17637", "Score": "2", "Tags": [ "lisp", "scheme", "functional-programming" ], "Title": "Counting Ways to Make Change -- Is this good functional/Lisp style?" }
17637
<p>The following code works but I am wondering if it can be improved both readability and performance.<br> I am using jquery and underscore.<br> Any suggestions, comments or feedbacks will be appreciate. thanks.</p> <pre><code>var getThemeName = function (theme_name, transparency) { if (theme_name === 'light') { if (transparency) { return translator.get('messages:theme.info.light_with_transparency', { percentage: transparency }); } return translator.get('messages:theme.info.light'); } else if (theme_name === 'dark') { if (transparency) { return translator.get('messages:theme.info.dark_with_transparency', { percentage: transparency }); } return translator.get('messages:theme.info.dark'); } }; var THEME_ITEMS = { themeLight: getThemeName('light'), themeLightTransparency75: getThemeName('light', 75), themeLightTransparency50: getThemeName('light', 50), themeLightTransparency25: getThemeName('light', 25), themeDark: getThemeName('dark'), themeDarkTransparency75: getThemeName('dark', 75), themeDarkTransparency50: getThemeName('dark', 50), themeDarkTransparency25: getThemeName('dark', 25) }; </code></pre>
[]
[ { "body": "<p>If you keep the naming consistent, you could probably do something like:</p>\n\n<pre><code>function getThemeName(themeName, transparency) {\n var name = \"messages:theme.info.\" + themeName;\n if( transparency ) {\n name += \"_with_transparency\";\n return translator.get(name, { percentage: transparency });\n } else {\n return translator.get(name);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T12:51:37.823", "Id": "17641", "ParentId": "17640", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T11:44:28.573", "Id": "17640", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "function to generate values of a javascript object" }
17640
<p>I'm trying to write a Python module to handle matrices. (I know about numpy, this is just for fun) </p> <p>So far I have written a few classes, <code>Matrix</code>, <code>Dim</code>, and <code>Vec</code>. <code>Matrix</code> and <code>Vec</code> are both subclasses of <code>Dim</code>. When creating a matrix, one would first start out with a list of lists and they would create a matrix like:</p> <pre><code>startingList = [[1,2,3],[4,5,6],[7,8,9]] myMatrix = matrix.Matrix(startingList) </code></pre> <p>This should create a <code>Matrix</code>. The created <code>Matrix</code> should contain multiple <code>Dim</code>s all of the same length. Each of these <code>Dim</code>s should contain multiple <code>Dim</code>s all of the same length, etc. The last <code>Dim</code>, the one that contains numbers, should contain only numbers and should be a <code>Vec</code> instead of a <code>Dim</code>. </p> <p>So far this works as I want it to. Here is what I have:</p> <pre><code>from numbers import Number test2DMat = [[1,2,3],[4,5,6],[7,8,9]] test3DMat = [[[1,2,3],[4,5,6],[7,8,9]],[[2,3,4],[5,6,7],[8,9,0]],[[9,8,7],[6,5,4],[3,2,1]]] class Dim(list): def __new__(cls,inDim): # Make sure inDim is iterable iter(inDim) # If every item in inDim is a number create a Vec if all(isinstance(item,Number) for item in inDim): #return Vec(inDim) return Vec.__new__(cls,inDim) # Make sure every item in inDim is iterable try: for item in inDim: iter(item) except TypeError: raise TypeError('All items in a Dim must be iterable') # Make sure every item in inDim has the same length # or that there are zero items in the list if len(set(len(item) for item in inDim)) &gt; 1: raise ValueError('All lists in a Dim must be the same length') # Actually create the Dim because it passed all the tests return list.__new__(cls,inDim) def __init__(self,inDim): inDim = map(Dim,inDim) list.__init__(self,inDim) class Vec(Dim): def __new__(cls,inDim): if cls.__name__ not in [Vec.__name__,Dim.__name__]: newMat = list.__new__(Vec,inDim) newMat.__init__(inDim) return newMat return list.__new__(Vec,inDim) def __init__(self,inDim): list.__init__(self,inDim) class Matrix(Dim): def __new__(cls,inMat): return Dim.__new__(cls,inMat) def __init__(self,inMat): super(Matrix,self).__init__(inMat) </code></pre> <p>This works, but as I have little experience overriding <code>__new__()</code> I'm fairly certain that this could be better. How can I improve this? Answers need not be specific to use of <code>__new__</code> and <code>__init__</code>, but that is what I care most about.</p>
[]
[ { "body": "<p>First, the thing that was most obvious in your code was that you never used a space after a comma.</p>\n\n<p>Second, you have the Matrix class where you override <code>__new__</code> and <code>__init__</code>, however it would be work just fine if you'd use <code>class Matrix(Dim): pass</code>.</p>\n\n<p>That's where I started to wonder why you define a <code>Dim</code> class and than inherit from it for <code>Matrix</code> and <code>Vec</code>, instead of code <code>Matrix</code> and subclass <code>Vec</code> from it. Any reason?</p>\n\n<p>I would move the tests from <code>Dim.__new__</code>, except for the numbers test, to <code>__init__</code>. The iter test is not needed, you'll get an error from the <code>list</code> constructor or the for loop anyway.</p>\n\n<p>One issue I see is that <code>Matrix('abc')</code> will result in endless recursion, because strings are iterable. Those are the places where I regret the absence of <code>chr</code> type in python :)</p>\n\n<p>In <code>Vec.__new__</code>, I would let others customize the way they inherit from, why do you check if the class is a <code>Vec</code> or a <code>Dim</code>?</p>\n\n<p>Last tip, when inheriting types like <code>list</code> or <code>str</code>, you have to override all the operator overloading methods if you plan on doing things like <code>Vec((0, 1, 2)) * Vec((2, 3, 4))</code></p>\n\n<p>Also:</p>\n\n<p><code>[Vec.__name__,Dim.__name__]</code> use tuples here, memory management</p>\n\n<p><code>test2DMat = [[1,2,3],[4,5,6],[7,8,9]]</code> I would break lines here</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T16:34:03.783", "Id": "28237", "Score": "0", "body": "I check if the class is a `Vec` or `Dim` (after some modifications I now use `isinstance(cls,Dim)`) because of how `__new__` appears to work. As I stated, I'm not exactly sure how `__new__` works, but it sometimes calls `__init__` but not always. In my tests `__init__` was not getting called for `Vec` and `Dim` so I had to manually call it. Things like this are what I was hoping to get feedback on. Is there a better way to do that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T16:57:47.053", "Id": "28239", "Score": "0", "body": "`Matrix.__init__` and `Matrix.__new__` are empty in this question as I had not yet gotten around to writing them. I also planned to (and have) added things to `Matrix` that are not part of `Dim`. I asked this question before I had written everything I planned to because I mostly cared about the use of `__new__` and `__init__` and wanted to make sure that was as good as it could be before getting too far into the project." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T18:11:30.923", "Id": "28286", "Score": "0", "body": "\"If __new__() returns an instance of cls, then the new instance’s __init__() method will be invoked like __init__(self[, ...]), where self is the new instance and the remaining arguments are the same as were passed to __new__().\n\nIf __new__() does not return an instance of cls, then the new instance’s __init__() method will not be invoked.\", from http://docs.python.org/reference/datamodel.html#object.__new__" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T18:00:26.817", "Id": "28319", "Score": "0", "body": "Yes, I already had already read that, but my interpretation of it didn't agree with my experience. In code not posted here (a modified version of this) I do not have to call `__init__` if I return a `Vec` and `cls` is `Matrix`. `Matrix` is not an instance of `Vec` so I would have expected to need to manually call `__init__`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T18:23:21.677", "Id": "28320", "Score": "0", "body": "Sounds weird. Could you maybe post the full code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T14:30:46.700", "Id": "28346", "Score": "0", "body": "upon reviewing my code prior to posting it I found that I was mistaken about my previous comment. I have in fact removed that `if cls.__name__ not in [Vec.__name__,Dim.__name__]:` statement in its entirety. I made some changes per: http://stackoverflow.com/a/12958437/1460976 and now that section is unneeded (and could cause `__init__` to be called twice in some cases)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T16:13:34.080", "Id": "17724", "ParentId": "17643", "Score": "4" } } ]
{ "AcceptedAnswerId": "17724", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T14:09:18.527", "Id": "17643", "Score": "11", "Tags": [ "python" ], "Title": "Python __new__ and __init__ usage" }
17643
<p>I have an instructor who is very stringent on makefiles only containing rules and dependencies that need to be included.</p> <p>The structure for the program is very basic. The requirement is to produce two executable files: a3b and a3m. There was some code duplication, so I included that in a source code file called myarray.c (with a header by the same name).</p> <p>I have already tested the makefile, and everything seems to work. However, can the makefile be cleaner or more accurate (such as removing or adding rules or dependencies)?</p> <p><em>The macro names and values were specified by the instructor.</em></p> <pre><code>CFLAGS = -g -Wall - Werror CC = gcc LD = gcc PROG1 = a3b PROG2 = a3m PROG3 = myarray OBJ1 = a3b.o OBJ2 = a3m.o OBJ3 = myarray.o all : $(PROG1) $(PROG2) $(PROG3) $(PROG1) : $(OBJ1) $(PROG3) $(LD) $(OBJ1) $(OBJ3) -o $(PROG1) $(PROG2): $(OBJ2) $(PROG3) $(LD) $(OBJ2) $(OBJ3) -o $(PROG2) $(PROG3): $(OBJ3) $(PROG3).h $(LD) $(PROG3).c -c clean : /bin/rm -f *.o a.out $(PROG1) $(PROG2) $(PROG3) </code></pre>
[]
[ { "body": "<p><code>clean</code> and <code>all</code> are not files should therefore be declared as <a href=\"http://linuxdevcenter.com/pub/a/linux/2002/01/31/make_intro.html?page=2\" rel=\"noreferrer\">phony</a>. </p>\n\n<pre><code>.PHONY: clean all\nall : $(PROG1) $(PROG2) $(PROG3)\n...\nclean :\n /bin/rm -f *.o a.out $(PROG1) $(PROG2) $(PROG3)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T14:48:02.830", "Id": "17646", "ParentId": "17645", "Score": "5" } }, { "body": "<p>Your <code>OBJ*</code> variables are unnecessary, as they are just the executable name with a <code>.o</code> extension. You can simplify by doing something like this:</p>\n\n<pre><code>$(PROG1) : $@.o $(OBJ3) \n $(LD) $^ -o $@\n</code></pre>\n\n<p><code>$@</code> expands to the name of the recipe's target, and <code>$^</code> expands to the list of prerequisites. Note that this also replaces <code>PROG3</code> with <code>OBJ3</code>, since that's what is actually used in the recipe. Using <code>PROG3</code> here can cause unnecessary rebuilding if <code>PROG3</code> changes but <code>OBJ3</code> doesn't (unlikely in your case, but common in more complex makefiles).</p>\n\n<p>If <code>myarray.c</code> is just common code, do you need to build it into its own program? Your <code>PROG3</code> recipe may be unnecessary. If all you really need is <code>myarray.o</code>, You can eliminate the <code>PROG3</code> recipe by simply adding <code>myarray.o</code> to the prerequisite lists of your other targets.</p>\n\n<pre><code>myarray.o: myarray.h\n\n$(PROG1) : $@.o myarray.o\n $(LD) $^ -o $@\n\n$(PROG2): $@.o myarray.o\n $(LD) $^ -o $@\n</code></pre>\n\n<p>The <code>myarray.o</code> target is only there to ensure that it is rebuilt when the header changes. The dependencies will cascade down and cause the programs to be rebuilt as well. You don't need a recipe for this rule if make's default <code>.c</code>-to-<code>.o</code> rule is sufficient for you.</p>\n\n<p>In this form, your two recipes are practically identical. You can take advantage of this to consolidate them into a single, generic rule:</p>\n\n<pre><code>myarray.o: myarray.h\n\n%: %.o myarray.o\n $(LD) $^ -o $@\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T21:19:39.743", "Id": "17653", "ParentId": "17645", "Score": "5" } } ]
{ "AcceptedAnswerId": "17653", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T14:31:54.607", "Id": "17645", "Score": "4", "Tags": [ "c", "makefile" ], "Title": "A clean and efficient makefile for a simple c program" }
17645
<p>I'm in the process of building a small application and obviously I need some sort of way to authenticate users. I'm not sure if I am way off or if this is close to what I should be thinking. Please let me know what you think...</p> <pre><code>&lt;?php class Authentication_controller { private __constructor() { include(Authentication_model.php); $auth_model = new Authentication_Model(); $auth_model-&gt;database_connect(); } public login($username, $password) { if($auth_model-&gt;username($username)) { //Username exists, now check password if($auth_model-&gt;password($username, $password)) { //User is OK to login, send to designated page include(Page_controller.php); $page_controller = new Page_controller(); $page_controller-&gt;go('home'); //Create session session_start(); //Set session variables $_SESSION['logged_in'] = true; $_SESSION['id'] = $auth_model-&gt;id($username); $_SESSION['access_level'] = $auth_model-&gt;access_level($username); } else { //Password didn't match return $error = "Username or password incorrect." } } else { //Username didn't match return $error = "Username or password incorrect." } } public permission($task_access_level) { $user_access_level = $_SESSION['access_level']; if($user_access_level &gt;= $task_access_level) { //User has access level that is high enough for task return true; } else { //User does not have access level high enough for task return false; } } public logout() { session_destroy(); } } </code></pre> <p>Is this typically how a class like this should work? I'm still very new to this stuff.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T20:24:44.097", "Id": "28103", "Score": "1", "body": "Includes should go at the top of the PHP file, before the class declaration, not inside it. Also, use `require_once` rather than `include` - for one `require_once` performs better in that it throws a fatal error if the file is not found and stops the script (rather than letting it continue as include_once or include would, and for two, it checks that the file has not already been included and if it has been included will not require it again. Mind that require() executes faster than require_once(), so if you're sure there are no duplicated includes use require()." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T20:25:52.023", "Id": "28104", "Score": "0", "body": "Is using includes/requires the best way to grab other classes?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T20:28:48.460", "Id": "28105", "Score": "3", "body": "Your code has at least 5 syntax errors in it. Code Review is for reviewing existing code, so please fix those syntax errors. (And @tbowman, your hunch is correct. You should typically avoid explicitly including classes. Autoloading is usually a better approach.)" } ]
[ { "body": "<p>I took the liberty of going through your code - see the comments preceded with MOD (modification), STAT (statement), QUES (question), SOL (solution) and REMOVED (removed)</p>\n\n<pre><code># MOD: Moved all include() to here\n# MOD: Changed from include() to require_once()\n# MOD: Added \"\" around filename\nrequire_once(\"Authentication_model.php\");\nrequire_once(\"Page_controller.php\");\n\nclass Authentication_controller {\n # MOD: added 'function' \n private function __constructor(){\n $auth_model = new Authentication_Model();\n $auth_model-&gt;database_connect();\n }\n\n # MOD: added 'function' \n public function login($username, $password) {\n # QUES: Why are you doing two IF checks, with both returning the same error? \n # Let's make our life easier and do one IF check. \n # STAT: We saved a few milliseconds per request!\n\n if($auth_model-&gt;username($username) &amp;&amp; $auth_model-&gt;password($username, $password)){\n # User is OK to login, send to designated page\n $page_controller = new Page_controller();\n\n # STAT: Seems you're sending the user away to another page before initiating the session\n # SOL: Moved down\n # $page_controller-&gt;go('home');\n\n # Create session\n # MOD: Added '@' to prevent errors if session has already been started elsewhere\n @session_start();\n\n # Set session variables\n $_SESSION['logged_in'] = true;\n $_SESSION['id'] = $auth_model-&gt;id($username);\n $_SESSION['access_level'] = $auth_model-&gt;access_level($username);\n\n # ADD: Moved here\n $page_controller-&gt;go('home');\n } else{\n return $error = \"Username or password incorrect.\"\n }\n\n /* MOD: OLD CODE\n if($auth_model-&gt;username($username)) {\n //Username exists, now check password\n if($auth_model-&gt;password($username, $password)) {\n //User is OK to login, send to designated page\n\n $page_controller = new Page_controller();\n $page_controller-&gt;go('home');\n\n //Create session\n session_start();\n\n //Set session variables\n $_SESSION['logged_in'] = true;\n $_SESSION['id'] = $auth_model-&gt;id($username);\n $_SESSION['access_level'] = $auth_model-&gt;access_level($username);\n } else {\n //Password didn't match\n return $error = \"Username or password incorrect.\"\n }\n } else {\n //Username didn't match\n return $error = \"Username or password incorrect.\"\n }*/\n }\n\n # MOD: added 'function' \n public function permission($task_access_level) {\n # MOD: You're using $user_access_level once - why not just compare against $_SESSION?\n # REMOVED: $user_access_level = $_SESSION['access_level'];\n\n # Determine if user has access level high enough for task\n # MOD: Replaced $user_access_level with $_SESSION['access_level']\n if($_SESSION['access_level'] &gt;= $task_access_level) return true; # High enough \n else return false; # Not high enough\n }\n\n # MOD: added 'function' \n public function logout() {\n session_destroy();\n }\n}\n</code></pre>\n\n<p>And here's the same code with my comments removed</p>\n\n<pre><code>require_once(\"Authentication_model.php\");\nrequire_once(\"Page_controller.php\");\n\nclass Authentication_controller {\n private function __constructor(){\n $auth_model = new Authentication_Model();\n $auth_model-&gt;database_connect();\n }\n\n public function login($username, $password) {\n if($auth_model-&gt;username($username) &amp;&amp; $auth_model-&gt;password($username, $password)){\n # User is OK to login, send to designated page\n $page_controller = new Page_controller();\n\n @session_start(); # Create session\n\n # Set session variables\n $_SESSION['logged_in'] = true;\n $_SESSION['id'] = $auth_model-&gt;id($username);\n $_SESSION['access_level'] = $auth_model-&gt;access_level($username);\n\n $page_controller-&gt;go('home');\n } else{\n return $error = \"Username or password incorrect.\"\n }\n }\n\n # Determine if user has access level high enough for task\n public function permission($task_access_level) {\n if($_SESSION['access_level'] &gt;= $task_access_level) return true; # High enough \n else return false; # Not high enough\n }\n\n public function logout(){ session_destroy(); }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T21:04:21.443", "Id": "28106", "Score": "0", "body": "Wow, I couldn't ask for a better response. Thank you so much for the effort. This is certainly going to help me understand things better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T21:30:49.573", "Id": "28107", "Score": "0", "body": "Not a problem. Just make sure to always check your code for syntax errors as Corbin pointed out." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T22:05:07.210", "Id": "28110", "Score": "0", "body": "Tiny nitpick: `return $error = \"Username or password incorrect.\"` is still a syntax error (and the assignment is pointless in a return)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T04:47:56.427", "Id": "28117", "Score": "0", "body": "Woops! Missing the semicolon and yep, can just return the string...thanks @Corbin!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T20:38:54.063", "Id": "17652", "ParentId": "17650", "Score": "5" } }, { "body": "<p>jsanc623 had some good points, but I think he missed a lot too. In particular, I think you have a fairly major design problem. Without seeing all of the related classes, my comments are a bit limited, but there's a few things below.</p>\n\n<hr>\n\n<p>There's a few different 'concerns' your code is handling here:</p>\n\n<ul>\n<li>Authenticating (is the username/password pair x, y valid?)</li>\n<li>Persisting an identity (remembering that the user is logged in under username x)</li>\n<li>Checking permissions</li>\n</ul>\n\n<p>These <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\">concerns should be separated</a>.</p>\n\n<p>The logic of \"is <code>[x, y]</code> a valid authentication pair?\" and the logic of \"can this person do <code>z</code>?\" have no need to be coupled.</p>\n\n<p>Additionally, there's no reason to hard code all of the session stuff. (The class should definitely not be responsible for starting the session.)</p>\n\n<hr>\n\n<p>Based on the API seen, I have a suspicion that your controller and model classes have convoluted functionality and APIs.</p>\n\n<p>You might want to consider looking into how a few different frameworks have handled authentication. Zend Framework is the only one I have experience with the authentication components. It has a few quirks, but overall, it has a good API. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T22:57:10.713", "Id": "28112", "Score": "3", "body": "The problem with looking at other frameworks is that they have SO much more functionality added into it than I need in order to understand basic concepts, which is why I am here. Honestly, this isn't even a piece of code that is being utilized in a real application yet. It's just something I started to put together so that I can better understand how to arrange the components." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T04:36:11.217", "Id": "28116", "Score": "1", "body": "@tbowman ZF is more of a library than a framework, but yes, it is a bit much to jump into just to look at a few classes." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T22:10:10.497", "Id": "17654", "ParentId": "17650", "Score": "7" } }, { "body": "<p>I'm kind of sad that no one has commented on the global yet. Or the fact that, if the constructor is private, how is it being called?</p>\n\n<p>Every time a programmer uses a global another programmer comes down off their red bull high, loses their wings, and misses a deadline. Globals are old and untrustworthy, especially in a security application such as an authenticator. Typically, if you need to share information between functions, you would pass those variables in as parameters. But with classes you can use properties instead.</p>\n\n<pre><code>private $auth_model;\n\nprivate function __constructor(){\n $this-&gt;auth_model = new Authentication_Model();\n //etc...\n}\n\npublic function login( $username, $password ) {\n if( $this-&gt;auth_model-&gt;username( $username ) ) {\n</code></pre>\n\n<p>As for the private constructor, I'm assuming you meant to use a Singleton pattern here? I don't have much experience with it myself, but I believe you will need to set up a static property and method that checks if the object has been instantiated, instantiates it, and returns a reference to it.</p>\n\n<pre><code>private static $instance;\n\n//constructor, etc...\n\npublic static function getInstance() {\n if( ! self::$instance ) {\n self::$instance = new Authentication_controller();\n }\n\n return self::$instance; \n}\n\n//usage\n$authenticator = Authentication_controller::getInstance();\n$authenticator-&gt;login();\n//etc...\n</code></pre>\n\n<p><strong>Clarification for jsan623's post</strong></p>\n\n<p>The reason that quotation marks are important around those includes, or any other strings for that matter, is that PHP is throwing warnings. If you had your error reporting turned on high enough you would notice the following warning: <code>Authentication_model.php</code> has been undefined, assuming \"Authentication_model.php\". Or something along those lines. This is just PHP's way of gracefully failing. You shouldn't rely on it. Turn up your error reporting so that you can see these kinds of things. Also, parenthesis aren't necessary around any of the include/require family, though that is preference.</p>\n\n<p>The <code>*_once</code> versions are definitely slower than the non-<code>*_once</code> versions as they must make an additional request as to whether the content has already been included. This may not be all that noticeable with one or two includes, but when you start adding 10 or so it will quickly become apparent. So, don't use them unless you have to. You should be able to guarantee that your code wont repeat so this shouldn't be an issue. See Corbin's comment about autoloading.</p>\n\n<p>Don't use error suppression. Do what ever checks you have to do to ensure that it works properly. In this case, start the session in the constructor and make sure it is the only <code>session_start()</code>. Since this appears to be the beginnings of an MVC framework the controller, or router if you decide to use one, should be in charge of sessions, so creating it in the constructor should ensure that it is only started once. I'm not sure why Corbin said the sessions shouldn't be here. Maybe I am wrong, but I would much rather not have my models dependent, or aware of, sessions. Create, manipulate, and read sessions in the controllers, neither your models, nor views need to know what's in the session. Unless someone can make a good point as to why they think they should be elsewhere?</p>\n\n<p><strong>Conclusion</strong></p>\n\n<p>As has already been pointed out. Code Review is for working code. You lucked out that someone decided to review this before it got closed. In the future, please take the time to write a working program before requesting a review. If it is a concept, still flesh it out enough so that it works.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:35:11.950", "Id": "28143", "Score": "0", "body": "That red bull high didn't help me catch errors in the code yesterday. Ech. But as with Corbin - great points pointed out by mseancole. tbowman - would suggest you take the advice of both mseancole and Corbin to heart." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:48:17.250", "Id": "28147", "Score": "0", "body": "I apologize for submitting non-working code, but I do greatly appreciate everyones effort here.\n\nSo are you saying that creating my sessions in a front controller is ideal? Maybe I'm misunderstanding. It seems like they should be started in the Auth controller considering the two go hand in hand." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:29:30.937", "Id": "28153", "Score": "0", "body": "@tbowman: No, they do belong in the Auth controller. I briefly mentioned a router because some people have adopted an MVCR (or MVRC) where the controller requests GET, POST, SESSION, and database connections from the router so that those common commands can be reused between controllers. Its just another level of abstraction that's sometimes helpful." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:33:38.123", "Id": "28164", "Score": "1", "body": "\"I'm not sure why Corbin said the sessions shouldn't be here. Maybe I am wrong, but I would much rather not have my models dependent, or aware of, sessions. \" I meant to comment on this, but did not clarify. In its current state, this is not a controller. It's an authentication adapater. The most controller-y thing about is that it has controller in the name." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:35:09.807", "Id": "28165", "Score": "0", "body": "As for why sessions do not belong in there... Know those globals you mentioned? Know what $_SESSION is? :D. $_SESSION is basically meeting the need of persisting the authentication. This class has two responsibilities though: authenticating, and persisting authentication. Though almost always closely related, they do not have to be, and should not be tied together. Hard coding the session stuff ties them together." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:35:53.800", "Id": "28166", "Score": "0", "body": "What if he wants to check if a username/password is valid without storing it? What if he wants (for some reason) to store the username/password some way other than sessions? It's for these reasons that the persistence should be abstracted away." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:38:54.747", "Id": "28167", "Score": "0", "body": "(Also, though you didn't explicitly encourage it, it probably should've been mentioned that singletons are the wrong approach 99.999999999999999% of the time.) (Also: \"Typically, if you need to share information between functions, you would pass those variables in as parameters. But with classes you can use properties instead.\" This makes it sound like `new` in a constructor is desirable. It's not though. It completely violates dependency injection and inversion of control.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T22:12:56.620", "Id": "28174", "Score": "0", "body": "@Corbin: Wow, slow down. I've only got so many fingers. You are correct, this is not a controller in its current state. I did not stress this enough when I said this \"appears to be the beginnings of an MVC framework\". Session variables, however, are not globals. They are super-globals, as are POST, GET, COOKIES, and whatever that last one is that I never use and always forget. As you said, they are used to persist, though the differences are beyond the scope of the character limit I'm aloud in comments, that and I'm not equipped enough to debate that any more intelligently." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T22:13:37.820", "Id": "28175", "Score": "0", "body": "You are also correct that they don't have to be so closely related, but as you pointed out, they normally are. I was basing my answer off of the provided code and that assumption. If he wants to use something else, then of course he'll have to plan for it, but this is rare and I didn't think it worth mentioning. I usually agree with you when it comes to the Singleton Pattern. However, for a specific database access class, such as this, I thought it was appropriate and common place so I didn't question it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T22:14:03.810", "Id": "28176", "Score": "0", "body": "As for your final comment, perhaps that was poorly worded, but I was not talking about injection at that point, I was discussing encapsulation. Although you are correct, I should have mentioned that it was a bad thing to do, as I did not a minute later in [another post](http://codereview.stackexchange.com/a/17683/12040). To make up for that, here is the same link I provided in said post to [help with IoC and DI]( http://stackoverflow.com/questions/3058/what-is-inversion-of-control/3140#3140)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T22:24:27.090", "Id": "28179", "Score": "0", "body": "@mseancole Superglobals are still globals. I stand by my statement that authentication and ID-persistence are two very discrete concerns, but you're right: there's not enough space in the comments to address how the session stuff should be handled. \n\nI will say though that just because something is frequently done in PHP does not mean it's correct. I've never seen a singleton correctly used in PHP. In fact, I don't know if there really is any non extremely specific use-case where a singleton makes sense in PHP." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T14:34:15.323", "Id": "17678", "ParentId": "17650", "Score": "2" } } ]
{ "AcceptedAnswerId": "17652", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T19:42:20.803", "Id": "17650", "Score": "4", "Tags": [ "php" ], "Title": "Extremely basic authentication class" }
17650
<p>I am writing a simple script to automate my regression testing. I am new to bash scripting and my goal is achieve the most efficient and clean code. I have written a simple function to allow me to select which subject I would like to test. This will loop until I select the exit option. Again, this is quite simple; however I am looking for some feedback on how I can improve.</p> <pre><code>BIO=biology showMenu () { echo "What subject would like to regression test?" echo "1) Physics" echo "2) Sociology" echo "3) Biology" echo "4) Quit" } while [ 0 ] do showMenu read CHOICE case "$CHOICE" in "1") read SUBJECT SUBJECT=physics echo "LOG: REGRESSION TESTING $SUBJECT" $SUBJECT GENERATE_CSS=`lessc /home/developer/oer.exports/css/ccap-$BIO.less &gt; /home/developer/oer.exports/css/ccap-$BIO.css` echo "LOG: CSS GENERATION COMPLETE" GENERATE_PDF=`python collectiondbk2pdf.py -v -s ccap-$BIO -d ./test-ccap/col$SUBJECT $SUBJECT.pdf -t tempdir/$SUBJECT` echo "LOG: GENERATING $SUBJECT PDF WITH $BIO CSS STYLE" ;; "2") read SUBJECT SUBJECT=sociology echo "LOG: REGRESSION TESTING SOCIOLOGY" $SUBJECT GENERATE_CSS=`lessc /home/developer/oer.exports/css/ccap-$BIO.less &gt; /home/developer/oer.exports/css/ccap-$BIO.css` echo "LOG: CSS GENERATION COMPLETE" GENERATE_PDF=`python collectiondbk2pdf.py -v -s ccap-$BIO -d ./test-ccap/col$SUBJECT $SUBJECT.pdf -t tempdir/$SUBJECT` echo "LOG: GENERATING $SUBJECT PDF WITH $BIO CSS STYLE" ;; "3") echo "Biology" DIFF=`diffpdf -a --debug=2 /tmp/pdf/diff bio.pdf bio_slicer.pdf` echo "LOG: DIFF DEV vs STAGING NOW AVAILABLE FOR PDF VIEW. " ;; "4") echo "Exiting now..." exit ;; esac done </code></pre>
[]
[ { "body": "<ol>\n<li><code>while :</code> is a standard idiom for \"loop forever\" in bash. The colon (<code>:</code>) is a synonym for <code>true</code>.</li>\n<li>Prefer <code>$(command)</code> to <code>`command`</code> (\"backticks\"). The former allows you to nest; the latter does not.</li>\n<li>Though in your case, you don't need the backticks at all. These are for capturing the output of the command, which you don't use anywhere.</li>\n<li>It isn't clear why you have the <code>read SUBJECT</code> inside each case -- you throw away the value in the very next statement.</li>\n<li>Don't do this: <code>lessc ccap-$BIO.less &gt; ccap-$BIO.css</code>. (It's a classic mistake in shell scripting; everyone's been bit by it.) This will nuke the file -- it will be truncated by the shell, overwriting the contents before lessc has the chance to read it.</li>\n</ol>\n\n<p>Aside from your code: if your goal is to regenerate the output files whenever one of the input files has changed, you should consider learning <code>make</code>. With a 10-20 line makefile, you can automatically regenerate whichever of the output files need updating whenever one of the input files change.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:23:57.007", "Id": "28141", "Score": "0", "body": "Thanks for you comments and suggestions. Points 2 & 5 were particularly valuable." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T02:30:27.707", "Id": "17659", "ParentId": "17656", "Score": "2" } }, { "body": "<p>Take a look at the <code>select</code> command. The selection loop it provides is slightly different from what you have, but take a look at the following:</p>\n\n<pre><code>PS3=\"What subject would you like to regression test? \"\nselect choice in Physics Biology Sociology Quit; do\n case $choice in\n Physics)\n echo \"Do your Physics code here\"\n ;;\n Biology)\n echo \"Do your Biology code here\"\n ;;\n Sociology)\n echo \"Do your Physics code here\"\n ;;\n Quit)\n exit\n ;;\n esac\ndone\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-04T16:06:13.100", "Id": "23444", "ParentId": "17656", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-17T22:51:47.273", "Id": "17656", "Score": "5", "Tags": [ "optimization", "bash", "beginner" ], "Title": "Script for automating regression testing" }
17656
<p>I am trying to generate LCM by prime factorization. I have already done the other way around to generate LCM using GCD but I am trying to achieve it using prime factorization. </p> <p>I am getting right prime factors but the problem is that to generate LCM we need to multiply each factor the greatest number of times it occurs in either number's factors. <a href="http://www.math.com/school/subject1/lessons/S1U3L3DP.html" rel="nofollow">Reference</a></p> <p>Now I don't like the code I come up with to achieve this. The logic is to retrieve factors of both numbers and then create a hash/counter for each factor. Finally multiply the factor with the result so far and the greatest number of times in each hash counter list.</p> <p>I would like to request to review my all methods IsPrime, PrimeFactors, LeastCommonMultipleByPrimeFactorization etc. In particular the main LeastCommonMultipleByPrimeFactorization method. Please feel free to pass your comments and suggestions. I would be happy to see some simplest way to achieve this. </p> <p>Code snippet:</p> <pre><code> public static bool IsPrime(int n) { for (int i = 2; i &lt;= n; i++) { if (n % i == 0) { if (i == n) return true; else return false; } } return false; } public static int[] PrimeFactors(int n) { var factors = new List&lt;int&gt;(); for (int i = 2; i &lt;= n; i++) { while (n % i == 0 &amp;&amp; IsPrime(i)) { factors.Add(i); n = n / i; } } return factors.ToArray(); } public static int LeastCommonMultipleByPrimeFactorization(int m, int n) { //retrieve prime factors for both numbers int[] mFactors = PrimeFactors(m); int[] nFactors = PrimeFactors(n); //generate hash code to get counter for each factor var mFactorsCountHash = CreateCounterHash(mFactors); var nFactorsCountHash = CreateCounterHash(nFactors); var primeFactors = new List&lt;int&gt;(); primeFactors.AddRange(mFactors); primeFactors.AddRange(nFactors); int result = 1; //On each distinct factor... check either which number factors foreach (int factor in primeFactors.Distinct()) { int mfactorCount = 0; int nfactorCount = 0; if (mFactorsCountHash.ContainsKey(factor)) { mfactorCount = mFactorsCountHash[factor]; } if (nFactorsCountHash.ContainsKey(factor)) { nfactorCount = nFactorsCountHash[factor]; } int numberOfCount = mfactorCount &gt; nfactorCount ? mfactorCount : nfactorCount; result = factor * result * numberOfCount; } return result; } private static Dictionary&lt;int, int&gt; CreateCounterHash(IEnumerable&lt;int&gt; mFactors) { Dictionary&lt;int, int&gt; hash = new Dictionary&lt;int, int&gt;(); foreach (var factor in mFactors) { if (hash.ContainsKey(factor)) hash[factor]++; else hash.Add(factor, 1); } return hash; } </code></pre> <p>To test method, I am using following code</p> <pre><code>[Test] public void LeastCommonMultipleByPrimeFactorizationPositiveTest() { Assert.AreEqual(42, ArthmeticProblems.LeastCommonMultipleByPrimeFactorization(21, 6)); Assert.AreEqual(12, ArthmeticProblems.LeastCommonMultipleByPrimeFactorization(4, 6)); } </code></pre> <blockquote> <p>Note: This is just for fun and revision of my basic concepts</p> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T14:17:33.283", "Id": "28125", "Score": "0", "body": "If you search for factors in increasing order in `IsPrime` and you reach a point where your `i*i > n`, you can safely stop your search (do you understand why that is the case?) Using this simple trick will help you drastically shorten the time it takes to test larger numbers for being prime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:38:52.870", "Id": "28144", "Score": "0", "body": "you can change `for (int i = 2; i <= n; i++)` to `for (int i = 2; i <= Convert.ToInt32(Math.Floor(Math.Sqrt(n))); i++)` in the first snippet" } ]
[ { "body": "<h3>IsPrime</h3>\n\n<pre><code>public static bool IsPrime(int n)\n{\n for (int i = 2; i &lt;= n; i++)\n {\n if (n % i == 0)\n {\n if (i == n)\n return true;\n else\n return false;\n }\n }\n return false;\n}\n</code></pre>\n\n<p>Under what circumstances can the final <code>return false</code> be reached? Why not handle those special cases explicitly, and then simplify the loop body by reducing it?</p>\n\n<pre><code>public static bool IsPrime(int n)\n{\n if (n &lt; 1) throw new ArgumentException(\"n\");\n if (n == 1) return false;\n\n for (int i = 2; i &lt; n; i++)\n {\n if (n % i == 0) return false;\n }\n return true;\n}\n</code></pre>\n\n<p>Of course, there are better ways of testing primality than trial division, but that's beside the point.</p>\n\n<h3>PrimeFactors</h3>\n\n<pre><code>public static int[] PrimeFactors(int n)\n{\n var factors = new List&lt;int&gt;();\n for (int i = 2; i &lt;= n; i++)\n {\n while (n % i == 0 &amp;&amp; IsPrime(i))\n {\n factors.Add(i);\n n = n / i;\n }\n }\n return factors.ToArray();\n}\n</code></pre>\n\n<p>Any particular reason for returning <code>int[]</code> instead of <code>IEnumerable&lt;int&gt;</code>?</p>\n\n<p>What's the purpose of the <code>IsPrime</code> call there? It's easy to prove that it always returns <code>true</code> (and so the <code>IsPrime</code> method isn't needed at all).</p>\n\n<p>As a point of style, I prefer <code>op=</code> methods, but this is really subjective.</p>\n\n<p>The loop guard might be more intelligible as <code>n &gt; 1</code>.</p>\n\n<pre><code>public static IEnumerable&lt;int&gt; PrimeFactors(int n)\n{\n var factors = new List&lt;int&gt;();\n for (int i = 2; n &gt; 1; i++)\n {\n while (n % i == 0)\n {\n factors.Add(i);\n n /= i;\n }\n }\n return factors;\n}\n</code></pre>\n\n<h3>CreateCounterHash</h3>\n\n<pre><code>private static Dictionary&lt;int, int&gt; CreateCounterHash(IEnumerable&lt;int&gt; mFactors)\n{\n Dictionary&lt;int, int&gt; hash = new Dictionary&lt;int, int&gt;();\n foreach (var factor in mFactors)\n {\n if (hash.ContainsKey(factor))\n hash[factor]++;\n else\n hash.Add(factor, 1);\n }\n return hash;\n}\n</code></pre>\n\n<p>Why does the return type use the implementation <code>Dictionary</code> rather than the interface <code>IDictionary</code>?</p>\n\n<p>Why hard-code the type? You don't do anything with it other than equality checking, so it could be <code>IDictionary&lt;T, int&gt; CreateCounterHash&lt;T&gt;(IEnumerable&lt;T&gt; elts)</code> (and then could potentially be an extension method of <code>IEnumerable&lt;T&gt;</code>).</p>\n\n<p><code>ContainsKey</code> followed by a get is a minor inefficiency. Since <code>TryGetValue</code> will give <code>default(int)</code> (i.e. 0) if the key isn't, found, this can be fixed:</p>\n\n<pre><code>private static IDictionary&lt;T, int&gt; CreateCounterHash&lt;T&gt;(IEnumerable&lt;T&gt; elts)\n{\n Dictionary&lt;T, int&gt; hash = new Dictionary&lt;T, int&gt;();\n foreach (var elt in elts)\n {\n int currCount;\n hash.TryGetValue(elt, out currCount);\n hash[elt] = currCount + 1;\n }\n return hash;\n}\n</code></pre>\n\n<h3>LCM</h3>\n\n<pre><code>public static int LeastCommonMultipleByPrimeFactorization(int m, int n)\n{\n //retrieve prime factors for both numbers\n int[] mFactors = PrimeFactors(m);\n int[] nFactors = PrimeFactors(n);\n\n //generate hash code to get counter for each factor \n var mFactorsCountHash = CreateCounterHash(mFactors);\n var nFactorsCountHash = CreateCounterHash(nFactors);\n\n var primeFactors = new List&lt;int&gt;();\n primeFactors.AddRange(mFactors);\n primeFactors.AddRange(nFactors);\n\n int result = 1;\n\n //On each distinct factor... check either which number factors \n foreach (int factor in primeFactors.Distinct())\n {\n int mfactorCount = 0;\n int nfactorCount = 0;\n if (mFactorsCountHash.ContainsKey(factor))\n {\n mfactorCount = mFactorsCountHash[factor];\n }\n\n if (nFactorsCountHash.ContainsKey(factor))\n {\n nfactorCount = nFactorsCountHash[factor];\n }\n\n int numberOfCount = mfactorCount &gt; nfactorCount ? mfactorCount : nfactorCount;\n result = factor * result * numberOfCount;\n }\n\n return result;\n}\n</code></pre>\n\n<p>Looks buggy: <code>factor * numberOfCount</code> will only be correct when <code>numberOfCount == 1</code> or <code>factor == 2 &amp;&amp; numberOfCount == 2</code>.</p>\n\n<p>Also a tad repetitive. Can't you merge the two counts earlier?</p>\n\n<pre><code>public static IDictionary&lt;K, V&gt; MergeDictionaries&lt;K, V&gt;(IDictionary&lt;K, V&gt; d1,\n IDictionary&lt;K, V&gt; d2,\n Func&lt;V, V, V&gt; mergeFunc)\n{\n // Left as an exercise\n // Only call mergeFunc when both dictionaries contain the key\n}\n</code></pre>\n\n<p>You can also use a bit of Linq to do the aggregate, so the LCM simplifies to</p>\n\n<pre><code>public static int LeastCommonMultipleByPrimeFactorization(int m, int n)\n{\n //retrieve prime factors for both numbers\n int[] mFactors = PrimeFactors(m);\n int[] nFactors = PrimeFactors(n);\n\n //generate hash code to get counter for each factor \n var mFactorsCountHash = CreateCounterHash(mFactors);\n var nFactorsCountHash = CreateCounterHash(nFactors);\n\n var combinedCounts = MergeDictionaries(mFactorsCountHash, nFactorsCountHash, Math.Max);\n return combinedCounts.Aggregate(1, (prod, primeWithMult) =&gt; prod * pow(primeWithMult.Key, primeWithMult.Value));\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T13:33:31.653", "Id": "28119", "Score": "0", "body": "+1. Thanks Peter. Is there alternative approach you can think of for LeastCommonMultipleByPrimeFactorization." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:47:24.650", "Id": "28146", "Score": "0", "body": "@AdilMughal, there's the obvious approach of not using prime factorisation, but you've explicitly chosen not to use gcd." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:14:04.573", "Id": "28148", "Score": "0", "body": "since it's just for self-learning and fun, that's why I also tried that. But what I meant with alternative was any better approach to do with prime factorization" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:20:31.743", "Id": "28149", "Score": "0", "body": "You could also skip a larger number of tests in the IsPrime function by using the Math.Sqrt(n) in the for statement ... for (int i = 2; i <= Math.Sqrt(n); i++)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:25:21.393", "Id": "28152", "Score": "0", "body": "@GeneS, true, although that's the worst possible way of doing the early escape. I didn't focus too much on `IsPrime` because I knew I was going to point out that it's unnecessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T17:22:42.203", "Id": "28156", "Score": "0", "body": "@PeterTaylor So for my own education, what would be a better way of doing an early escape?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T07:12:54.167", "Id": "28204", "Score": "0", "body": "@GeneS, either pull the `Sqrt` out of the loop (and downcast to `int`) or invert the test to `i * i < n` (because processors have a single instruction for multiplication, but sqrt is expensive)." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T12:48:44.003", "Id": "17668", "ParentId": "17662", "Score": "3" } }, { "body": "<p>You don't need to determine whether the factor is a prime when you factorize a number, the divide method itself guarantee the factor is prime.\nI have a solution with few code, but not in good performance, and with a limitation of the number less than 1000, so it's just for your reference, the solution use an array to store the factors of a number, the index of the array indicates the factor, and the value of array[index] is the times of that factor, for example factor[3] = 2, means the number has a factor 3 occurs twice.</p>\n\n<pre><code>// Factorize number n\nstatic int[] Factorize(int n)\n{\n int[] factors = new int[1000];\n\n for (int i = 2; n &gt; 1; )\n {\n if (n % i == 0)\n {\n factors[i]++;\n n /= i;\n }\n else\n ++i;\n }\n\n return factors;\n}\n\n// Find the Least common multiple of number a and b\nstatic int LCM(int a, int b)\n{\n int[] factorsA = Factorize(a);\n int[] factorsB = Factorize(b);\n\n int result = 1;\n for (int m = 0; m &lt; factorsA.Length; ++m)\n {\n if (factorsA[m] + factorsB[m] != 0)\n {\n if (factorsA[m] &gt; factorsB[m])\n result *= (int)Math.Pow(m, factorsA[m]);\n else\n result *= (int)Math.Pow(m, factorsB[m]);\n }\n }\n return result;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T14:00:04.117", "Id": "28121", "Score": "0", "body": "I like your approach. The only thing we would lose its extra space...int[1000]. Plus few queries: \n-Is 1000 definite?\n- for (int m = 0; m < factorsA.Length; ++m) would that work if factorsB length is greater than factorsA ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T14:03:24.017", "Id": "28122", "Score": "0", "body": "Yes, you are right, the solution won't work if a or b is 1001, may be we can use a list to store a key-value pair where the key is the factor and the value is the times of that factor, but that will make the code more complexity, I like simple code :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T13:55:46.160", "Id": "17671", "ParentId": "17662", "Score": "2" } }, { "body": "<p>Your code is very inefficient, because it uses a naive algorithm for finding prime numbers, and performs primality checks for the same number multiple times.</p>\n\n<p>A better approach would pre-compute a table of primes, and use numbers from it for all further checking.</p>\n\n<p>Here is how you can make a table of prime numbers suitable for use with <code>int</code>s:</p>\n\n<pre><code>private static readonly ISet&lt;int&gt; Primes = new SortedSet&lt;int&gt;{ 2 };\n\nstatic MyClass() {\n var cand = 3;\n while (cand*cand &gt; 0) {\n var ok = true;\n foreach (var p in Primes) {\n if (cand % p == 0) {\n ok = false;\n break;\n }\n if (p*p &gt; cand) {\n break;\n }\n }\n if (ok) {\n Primes.Add(cand);\n }\n cand += 2;\n }\n}\n</code></pre>\n\n<p>With the set of primes in hand, your first two functions become much simpler, and orders of magnitude faster:</p>\n\n<pre><code>public static bool IsPrime(int n) {\n return Primes.Contains(n);\n}\n\npublic static int[] PrimeFactors(int n) {\n var res = new List&lt;int&gt;();\n foreach (var p in Primes) {\n while (n % p == 0) {\n res.Add(p);\n n /= p;\n }\n if (n == 1) break;\n }\n return res.ToArray();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:04:28.997", "Id": "28138", "Score": "0", "body": "Can you please explain a bit MyClass method? Also I am a bit more curious about LCM method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:15:49.157", "Id": "28140", "Score": "0", "body": "@AdilMughal `MyClass` is the static constructor of your class. Since your code does not show the name of your class, I called your class `MyClass` (I hope this makes sense). Even if you keep your LCM method as is, replacing the first two methods will make it go significantly faster. P.S. Did you prove the `i*i > n` question from my comment? My code is using this fact on the `p*p > cand` line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:32:12.927", "Id": "28142", "Score": "0", "body": "When this would end? while (cand*cand > 0)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:40:05.833", "Id": "28145", "Score": "0", "body": "@AdilMughal Ah, that's a very good question: it will end when the integer overflows, so multiplication of two positive numbers produces a negative result." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T14:48:49.050", "Id": "17679", "ParentId": "17662", "Score": "2" } } ]
{ "AcceptedAnswerId": "17668", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T06:16:40.700", "Id": "17662", "Score": "3", "Tags": [ "c#", "algorithm", "primes" ], "Title": "Prime numbers, Prime Factors and LCM" }
17662
<p>I have the following class inheritances hierarchy:</p> <p>First the abstract parent class:</p> <pre><code>&lt;?php abstract class SegmentParserAbstract{ /** @var ParserResult */ protected $_result; protected $_invalidSegmentMessage; protected $_segmentRegex; protected $_segment; abstract protected function createSegmentObject(); public function __construct() { $this-&gt;_result = new ParserResult(); } public function setSegment($Segment) { $this-&gt;_segment = $Segment; } /** * Function will parse the Segment by validating the input string. * If valid it will create the Segment Object in the result array with no errors. * If invalid it will populate the result array with the error, but no object will be created. */ public function parse() { if ($this-&gt;isValidSegment()) { $this-&gt;createSegmentObject(); } else { $this-&gt;createErrorMessage(); } return $this-&gt;_result; } protected function isValidSegment() { $matchesFound = preg_match($this-&gt;_segmentRegex, $this-&gt;_segment); return ($matchesFound &gt; 0); } protected function createErrorMessage() { $this-&gt;_result-&gt;addError(array($this-&gt;_invalidSegmentMessage . $this-&gt;_segment)); } } ?&gt; </code></pre> <p>The first child:</p> <pre><code>&lt;?php class GsParser extends SegmentParserAbstract { const SUPPLIER_ID_INDEX = 2; const GROUP_HEADER_INDEX = 6; protected $_invalidSegmentMessage= 'Invalid GS segment: '; protected $_segmentRegex="/^GS\*IN\*\w{2,15}\*\w{2,15}\*(\d{6}|\d{8})\*\d{4}\*\d{1,9}\*X\*\d{1,12}$/"; protected function createSegmentObject() { $elements = explode('*', $this-&gt;_segment); $gs = new Gs(); $gs-&gt;setSupplierId($elements[self::SUPPLIER_ID_INDEX]); $gs-&gt;setGroupReference($elements[self::GROUP_HEADER_INDEX]); $this-&gt;_result-&gt;setSegment($gs); } } ?&gt; </code></pre> <p>The second child:</p> <pre><code>&lt;?php class IsaParser extends SegmentParserAbstract { const SUPPLIER_ID_INDEX = 6; protected $_invalidSegmentMessage= 'Invalid ISA segment: '; protected $_segmentRegex="/^ISA\*00\*.{10}\*00\*.{10}\*ZZ\*.{15}\*ZZ\*.{15}\*\d{6}\*\d{4}\*U\*.{5}\*\d{9}\*[0-1]\*[PT]\*&gt;$/"; protected function createSegmentObject() { $elements = explode('*', $this-&gt;_segment); $isa = new Isa(); $isa-&gt;setSupplierId($elements[self::SUPPLIER_ID_INDEX]); $this-&gt;_result-&gt;setSegment($isa); } } ?&gt; </code></pre> <p>Now I'll be having about nearly 16 other parsers extending the same abstract class <code>SegmentParserAbstract</code> with only differing in the implementation of <code>createSegmentObject()</code> and the number of constants (which might have different names of course).</p> <p>Somehow I feel that I can remove all sub classes and only keep the parent class and make it a concrete class that can be configured to work on any Segment provided it knows its regular expression and the data that needs to be extracted and the resulting object type.</p> <p>Any help?!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T09:40:13.400", "Id": "73062", "Score": "0", "body": "See http://stackoverflow.com/a/12907998/1015656 I just had this discussion at SO. It's a simple example, but I hope it helps." } ]
[ { "body": "<p><strong>Edit:</strong> As David pointed out in the comments, I am completely wrong about constructors in the abstract classes. I hid the (ir)relevant section to avoid confusion and attempted to edit the rest of the post so it fit the new context. In case I missed something, Abstract classes CAN have constructors because they CAN'T be instantiated therefore any references to the <code>init()</code> method that may be left over should be assumed to be <code>parent::__construct()</code> instead. Thank you again David.</p>\n\n<blockquote class=\"spoiler\">\n <p>Abstract classes can not, or rather should not, be instantiated. Therefore they should never have a constructor. If you want to have a shared \"constructor\" there are a couple different things you can do. The easiest method is to create an <code>init()</code>-like function and call that in your real constructors. Another method is to extend an actual class. Since you don't seem to be trying to instantiate this class, as some who use \"abstract constructors\" are wont to do, then I think the first solution should be adequate, though I should add that the <code>init()</code> method should not be public to avoid \"accidental\" reinstantion.\n\n<pre> protected function init() {\n $this->_result = new ParserResult();\n }</pre></p>\n</blockquote>\n\n<p>Abstract classes are still classes. Therefore anything defined in it is still defined in its children. Thus, redefining properties should actually be handled in construction, because, if I'm remembering this correctly, redefining them in the children actually throws warnings. Either way, the better place is in construction.</p>\n\n<pre><code>public function __construct() {\n $this-&gt;_invalidSegmentMessage = 'Invalid GS segment: ';\n $this-&gt;_segmentRegex = \"/^GS\\*IN\\*\\w{2,15}\\*\\w{2,15}\\*(\\d{6}|\\d{8})\\*\\d{4}\\*\\d{1,9}\\*X\\*\\d{1,12}$/\";\n\n parent::__construct();\n}\n</code></pre>\n\n<p>So, there are a few principles being violated in your <code>createSegmentObject()</code> method. The first, and most obvious, is the \"Don't Repeat Yourself\" (DRY) principle. This can be observed by how similar all these methods are. If we take into account the Inversion of Control (IoC) Principle as well, then we can see that it is violating both of these principles. IoC is something I've never really thought about before, so I don't feel entirely comfortable explaining it. Google it if you're not sure what it is, I'll be reading up on it more myself after this post. I think you began to notice something was amiss, which is why you added it to the abstract class, you just didn't go quite far enough with it. The third principle, which is making this a little more difficult to see, is that this method also violates the Single Responsibility Principle. This method should be concerned with creating a segment, not creating AND setting. Leave that for after you call the method. If we try setting it immediately then we can't extend it.</p>\n\n<pre><code>//abstract class\nprotected function createSegmentObject( Segment $segment ) {\n $elements = explode('*', segment);\n\n $segment-&gt;setSupplierId( $elements[ self::SUPPLIER_ID_INDEX ] );\n $this-&gt;segment = $segment;\n $this-&gt;elements = $elements;\n}\n\n//extending class\nprotected function createSegmentObject( Segment $segment ) {\n parent::createSegmentObject( $segment );\n\n $this-&gt;segment-&gt;setGroupReference( $this-&gt;elements[ self::GROUP_HEADER_INDEX ] );\n}\n\n//usage\nif ($this-&gt;isValidSegment()) {\n $this-&gt;createSegmentObject();\n $this-&gt;_result-&gt;setSegment( $this-&gt;segment );\n}\n</code></pre>\n\n<p>In case you are curious, <code>createSegmentObject( Segment $segment )</code> is assuming that your \"segments\" are using a common interface or abstract class and that it is called \"Segment\". If you are not using one of these, then I would seriously think about doing so. Assuming for now that you are, then we can declare the parent class as the common denominator and type hint our parameters for it. This will ensure that any object passed to the above method must be a type of <code>Segment</code> and will be able to produce the expected results every time, else PHP will throw errors.</p>\n\n<p>So, we've just eliminated most of the need for multiple classes. The only thing holding us back are these unique properties and the occasional extensions. The interesting thing about these classes is that the properties are very structured and unique. So what do we do when we have a common data structure that needs to be saved and reused? If we create a database with each row denoting a segment and each field a property, then we can construct our segments by calling that specific row in the database. Of course, we should inject these parameters into our constructor to avoid our class becoming dependent. I'll leave the database implementation to you, but here's the constructor:</p>\n\n<pre><code>public function __construct( $id, $group, $type, $regex ) {\n $this-&gt;_supplierIdIndex = $id;\n $this-&gt;_groupHeaderIndex = $group;\n $this-&gt;_invalidSegmentMessage = \"Invalid $type segment: \";\n $this-&gt;_segmentRegex = $regex;\n\n parent::_construct();\n}\n</code></pre>\n\n<p>That leaves us with just extensions holding us back now. We could create an elaborate comparison table and pick and choose when to use what, or we can automate the process and use a factory pattern. Again, I'm going to leave this up to you, for multiple reasons, but the main one being that I haven't played with factories yet and wouldn't be sure where to begin. Besides, without the rest of the subclasses I <em>couldn't</em> begin.</p>\n\n<p>I believe some of this is what Saul linked to, but I just skimmed over it. I did spy something about a factory in there, so maybe much of this is the same, but it lacked a lot of the explanations that I felt were necessary. Hopefully this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:51:21.680", "Id": "28155", "Score": "0", "body": "I felt bad for leaving IoC so vague in my post, so here's a good resource I was looking at yesterday: http://stackoverflow.com/questions/3058/what-is-inversion-of-control/3140#3140" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T03:49:43.773", "Id": "28191", "Score": "1", "body": "The class is abstract so it *cannot* be instantiated directly. There's no need to move the code you'd normally have in a constructor into a separate `init` method. The only difference is the name of the method which adds nothing. Use a constructor and have the children override it if necessary." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T13:40:43.537", "Id": "28224", "Score": "0", "body": "@DavidHarkness: You are absolutely correct. I have no idea how I got it into my head that abstract classes could still be instantiated, but I just spent the last half hour trying to prove this and couldn't. I'll edit my post to reflect this, thank you for putting me straight." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:20:51.573", "Id": "17683", "ParentId": "17664", "Score": "1" } }, { "body": "<p>Another SE user had a related question here: <a href=\"https://codereview.stackexchange.com/questions/15899/when-an-object-has-different-representations-whats-the-oo-pattern/17660#17660\">When an object has different representations… what's the OO pattern?</a></p>\n\n<p>My suggestion would be to consider the Decorator pattern to avoid the kind of repetition (methods/properties) you're dealing with in inherited classes. And to minimize the amount of code you're having to write &amp; maintain. </p>\n\n<p>With an abstract class that you're inheriting form, the method signature for <code>createSegmentObject()</code> is immutable. You can't easily introduce method arguments, or pass dependencies without adding additional methods into the inherited class. </p>\n\n<p>With a decorator (or collection of decorators), you can continue to re-defined the behaviour of your <code>createSegmentObject()</code> method, which also opens up the opportunity for dependency injection as needed (so long as you don't define <code>createSegmentObject()</code> in your interface. It also gives you the added benefit of defining a whole different category of decorators that act upon the decorated object, e.g. persisting to a datastore.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T01:47:27.530", "Id": "17695", "ParentId": "17664", "Score": "1" } }, { "body": "<p>My first thought is to use the <a href=\"http://en.wikipedia.org/wiki/Abstract_factory_pattern\" rel=\"nofollow\">Factory Pattern</a> and supply a <code>SegmentFactory</code> to the <code>SegmentParser</code> which would cease to be abstract.</p>\n\n<pre><code>interface SegmentFactory\n{\n /**\n * Returns true if $segment is valid for this factory.\n *\n * @param string $segment usually split based on a regex\n * @return bool true if valid; false otherwise\n */\n function isValid($segment);\n\n /**\n * Returns a new segment object from $segment.\n *\n * @param string $segment usually split based on a regex\n * @return &lt;whatever is the parent class of Gs and Isa&gt;\n */\n function create($segment);\n\n /**\n * Returns an appropriate error message when the parser cannot parse $segment.\n *\n * @param string $segment the segment that failed to be parsed\n * @return string an error message\n */\n function createErrorMessage($segment);\n}\n</code></pre>\n\n<p>You'll have one implementation per type of segment you need to create, but it will make testing easier by splitting out the creation of segments from their parsing and the result that eventually gets built. Here's the new implementation for <code>SegmentParser</code>:</p>\n\n<pre><code>class SegmentParser\n{\n /** @var SegmentFactory */\n private $_factory;\n\n /** @var ParserResult */\n private $_result;\n\n /** @var string */\n private $_segment;\n\n public function __construct(SegmentFactory $factory) {\n $this-&gt;_factory = $factory;\n $this-&gt;_result = new ParserResult();\n }\n\n /**\n * Function will parse the Segment by validating the input string. \n * If valid it will create the Segment Object in the result array with no errors.\n * If invalid it will populate the result array with the error, but no object will be created.\n *\n * Now this method takes what the factory provides and puts it into the result\n * rather than depending on the subclass having intimate knowledge of the result.\n */\n public function parse($Segment) {\n if ($this-&gt;_factory-&gt;isValid($segment)) {\n $this-&gt;_result-&gt;setSegment($this-&gt;_factory-&gt;create($segment));\n } else {\n $this-&gt;_result-&gt;addError($this-&gt;_factory-&gt;createErrorMessage($segment));\n }\n return $this-&gt;_result;\n }\n}\n</code></pre>\n\n<p>And here's the implementation for <code>GsSegmentFactory</code>:</p>\n\n<pre><code>class GsSegmentFactory implements SegmentFactory\n{\n const SUPPLIER_ID_INDEX = 2;\n const GROUP_HEADER_INDEX = 6;\n const REGEX = \"/^GS\\*IN\\*\\w{2,15}\\*\\w{2,15}\\*(\\d{6}|\\d{8})\\*\\d{4}\\*\\d{1,9}\\*X\\*\\d{1,12}$/\";\n\n /**\n * Returns true if $segment is valid for this factory.\n *\n * @param string $segment usually split based on a regex\n * @return bool true if valid; false otherwise\n */\n public function isValid($segment) {\n return preg_match(self::REGEX, $segment) &gt; 0;\n }\n\n /**\n * Returns a new segment object from $segment.\n *\n * @param string $segment usually split based on a regex\n * @return &lt;whatever is the parent class of Gs and Isa&gt;\n */\n public function create($segment) {\n $elements = explode('*', $segment);\n $gs = new Gs();\n $gs-&gt;setSupplierId($elements[self::SUPPLIER_ID_INDEX]);\n $gs-&gt;setGroupReference($elements[self::GROUP_HEADER_INDEX]);\n return $gs;\n }\n\n /**\n * Returns an appropriate error message when the parser cannot parse $segment.\n *\n * @param string $segment the segment that failed to be parsed\n * @return string an error message\n */\n public function createErrorMessage($segment) {\n return 'Invalid GS segment: ' . $segment;\n }\n}\n</code></pre>\n\n<p>How is this better?</p>\n\n<ol>\n<li>Separating the parser from the factory makes testing easier. You can now test the parser with a mock factory once and each factory without a parser.</li>\n<li>The factory creates the segment or error message while only the parser deals with the result object. This is separate of concerns at its finest.</li>\n<li>Because <code>$segment</code> is now passed to <code>parse</code> you can reuse the same parser (one per factory type) and factories if you like. This also makes testing easier.</li>\n<li>You can create an abstract factory that implements <code>isValid</code> and <code>createErrorMessage</code> as you did with the original parser. Move the regex constant and error message prefix to constructor parameters if all factories work the same.</li>\n</ol>\n\n<p>While it seems like you're just shifting from multiple parsers to multiple factories, it is generally preferable to code to interfaces rather than abstract classes. Abstract classes are great for filling out the most likely implementation of an interface which many concrete subclasses end up overriding. When you find yourself building an abstract class that has nearly all of the functionality and only implementing one template method, a factory or strategy may be a better fit.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T14:29:01.497", "Id": "28226", "Score": "0", "body": "Your interface lacks any kind of method scoping. By default PHP will render them in the public scope, but you should not rely on that. Explicitly defining the expected scope ensures that no method is scoped incorrectly by neglect. BTW: nice rep (1337), you should screenshot that or something." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T18:21:36.830", "Id": "28248", "Score": "0", "body": "@mseancole - Interfaces by definition specify a *public* API that all implementing classes must fulfill with *public* methods. PHP will raise a fatal error if you attempt to implement any of the methods in the interface with anything other than public scope. And if you specify any non-public access modifier in the interface, PHP raises an error telling you it must be omitted. :) This is different from PHP assuming public access for class methods without a modifier. Public is the only option for interface methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T19:43:07.353", "Id": "28257", "Score": "0", "body": "I was under the impression that this default scoping was going to be deprecated. However, I can not find this anywhere to confirm it, so I'm wondering if this really was just a rumor. So maybe this isn't important, but, for the time being, I'm not going to go out of my way to stop adding the public keyword to my interfaces until I am sure. Better safe than sorry. Thanks again, and if I find anything either way I'll let you know." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T04:25:14.137", "Id": "17701", "ParentId": "17664", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T09:15:19.760", "Id": "17664", "Score": "3", "Tags": [ "php", "object-oriented", "design-patterns" ], "Title": "Refactoring a class hierarchy to remove subclasses" }
17664
<p>I tried to implement an <a href="http://en.wikipedia.org/wiki/Unrolled_linked_list" rel="nofollow" title="Wikipedia">unrolled linked list</a> in C#. I only needed to add things and clear the whole list so I didn't implement <code>IList&lt;T&gt;</code> (I tried but it was getting too complex, so I postponed it).</p> <p>Why I did it?<br> I needed a collection that should be able to handle millions of items and I was getting <code>OutOfMemoryException</code>s when I tried <code>List&lt;T&gt;</code> since it needs <em>sequential memory</em> to hold everything in one array.</p> <p>I tried <code>LinkedList&lt;T&gt;</code> but it was too slow. I don't need to enumerate backwards or expose the node class publicly. I also know the size of blocks that I want to keep my items in, so I wrote this:</p> <pre><code>public sealed class UnrolledLinkedList&lt;T&gt; : IEnumerable&lt;T&gt; { // Fields private int _Count; private Node _FirstNode; private Node _LastNode; private int _LastNodeCount; private int _NodeCount; private readonly int _NodeSize; // Properties public int Count { get { return _Count; } } // Constructors public UnrolledLinkedList(int nodeSize) { _NodeCount = 1; _NodeSize = nodeSize; _FirstNode = _LastNode = new Node(nodeSize); } public UnrolledLinkedList() : this(8) { } // Fuctions public void Add(T item) { if (_LastNodeCount == _NodeSize) { _LastNode = (_LastNode.Next = new Node(_NodeSize)); _LastNode.Items[0] = item; _LastNodeCount = 1; _NodeCount++; } else _LastNode.Items[_LastNodeCount++] = item; _Count++; } public void Clear() { _FirstNode = _LastNode = new Node(_NodeSize); // Edit: Just added these: _Count = 0; _LastNodeCount = 0; _NodeCount = 1; } public IEnumerator&lt;T&gt; GetEnumerator() { var current = _FirstNode; if (current == null) yield break; for (; ; ) { if (current.Next == null) { for (int i = 0; i &lt; _LastNodeCount; i++) yield return current.Items[i]; yield break; } else for (int i = 0; i &lt; _NodeSize; i++) yield return current.Items[i]; current = current.Next; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } // Types private class Node { public readonly T[] Items; public Node Next; public Node(int size) { Items = new T[size]; } } } </code></pre> <p>Is there a flaw you can detect?<br> Is there <em>any</em> suggestion/optimization you have?<br> Do you know a better implementation of an unrolled linked list in C#?<br> Do you think this class should implement <code>IList&lt;T&gt;</code>?<br> If so, can you give some pointers for implementing functions like <code>Insert</code>?</p> <p><strong>Updated version</strong><br> It became like this after the answers:</p> <pre><code>public sealed class UnrolledLinkedList&lt;T&gt; : IEnumerable&lt;T&gt; { // Fields private int _Count; private Node _FirstNode; private Node _LastNode; private int _LastNodeCount; private readonly int _NodeSize; // Properties public int Count { get { return _Count; } } // Constructors public UnrolledLinkedList(int nodeSize = 64) { _NodeSize = nodeSize; _FirstNode = _LastNode = new Node(nodeSize); } // Functions public void Add(T item) { if (_LastNodeCount == _NodeSize) { _LastNode.Next = new Node(_NodeSize, item); _LastNode = _LastNode.Next; _LastNodeCount = 1; } else _LastNode.Items[_LastNodeCount++] = item; _Count++; } public void Clear() { _Count = 0; _FirstNode = _LastNode = new Node(_NodeSize); _LastNodeCount = 0; } public IEnumerator&lt;T&gt; GetEnumerator() { for (var current = _FirstNode; current != null; ) { var last = current.Next == null ? _LastNodeCount : _NodeSize; for (var i = 0; i != last; i++) yield return current.Items[i]; current = current.Next; } } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); } // Types private sealed class Node { public readonly T[] Items; public Node Next; public Node(int size) { Items = new T[size]; } public Node(int size, T firstItem) : this(size) { Items[0] = firstItem; } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T23:16:21.797", "Id": "28182", "Score": "0", "body": "I think you shouldn't use `for (;;)`, because it can be confusing to programmers that didn't encounter it before. The idiomatic way to write an infinite loop in C# is `while (true)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T06:41:24.637", "Id": "28200", "Score": "0", "body": "@svick: Thanks, I never really thought about it, you're right. But I liked the dasblinkenlight's version and I guess I'll use that one, anyway." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T07:41:34.187", "Id": "28206", "Score": "1", "body": "Thanks +1 for the fun Wikipedia read. :) This was a new data structure for me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T10:34:08.643", "Id": "28214", "Score": "0", "body": "@David: Glad if you liked, I've read it again by the way (after your suggestion under the answer) and realized that \"See Also\" section also has some cool references. I guess I can use a \"hashed array tree\" in my scenario. Will give it a try." } ]
[ { "body": "<p>I would change <code>GetEnumerator</code> as follows:</p>\n\n<pre><code>public IEnumerator&lt;T&gt; GetEnumerator()\n{\n for (var current = _FirstNode ; current != null ; )\n {\n var last = current.Next == null ? _NodeSize : _LastNodeCount;\n for (var i = 0 ; i != last ; i++) {\n yield return current.Items[i];\n }\n current = current.Next;\n }\n}\n</code></pre>\n\n<p>I would also remove <code>_NodeCount</code>, because you are maintaining it, but not using it anywhere to make decisions.</p>\n\n<p>Finally, since you always insert an item in a <code>Node</code>, I would make <code>Node</code>'s constructor accept the value <code>T</code> to be placed in <code>Items[0]</code>, rather than keeping that code in the <code>Add</code> method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T14:18:00.430", "Id": "28126", "Score": "0", "body": "GetEnumerator seems quite more readable like this, thanks. I guess I created _NodeCount when I tried to implement IList<T> so I could use it in index-related calculations. It's useless here as you have pointed out. And another constructor for Node is also a great idea. +1 and thank you again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T07:43:05.433", "Id": "28207", "Score": "1", "body": "C# has `yield`? Wow, that almost makes up for the choice to use `I` to prefix interfaces and capital letters for both methods and fields so they look like class names. :p Is `yield return` the actual syntax? Can you have `yield` without `return`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T10:37:24.440", "Id": "28215", "Score": "0", "body": "@DavidHarkness Of course it does! ([link](http://msdn.microsoft.com/en-us/library/vstudio/9k7k7cf0.aspx)) It has been there for many years, since C# 2.0." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T14:08:57.647", "Id": "17674", "ParentId": "17670", "Score": "6" } }, { "body": "<p>I would also remove the default constructor and add a default value to the other one</p>\n\n<pre><code>public UnrolledLinkedList(int nodeSize = 8)\n</code></pre>\n\n<p>This just removes a few lines of extra code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T06:39:25.107", "Id": "28199", "Score": "0", "body": "Using a default parameter makes the constructor neater, thank you and +1." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T17:23:10.793", "Id": "17685", "ParentId": "17670", "Score": "4" } }, { "body": "<p>Even though you are keeping every node full (except the last) and thus only need to track the number of elements in the last node, the code would be cleaner if you moved the count into <code>Node</code>. As well, it would allow you to implement the full functionality of <code>IList</code> more easily.</p>\n\n<p>The implementations of <code>Insert</code> and <code>Delete</code> given this design will be slow because they'll have to shift all of the elements past the inserted/deleted element. Because there are multiple nodes you'll need two memory-copy calls per node. I don't know the equivalent in C# but assume it's similar to Java's <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#arraycopy%28java.lang.Object,%20int,%20java.lang.Object,%20int,%20int%29\" rel=\"nofollow\"><code>System.arraycopy</code></a> for moving elements from one array to another or within a single array.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T06:55:07.287", "Id": "28202", "Score": "0", "body": "It would be cleaner, yes. But I only keep track of the elements in the last node so I didn't want to add 4 more bytes to every node. I agree on implementing IList<T> means shifting the whole thing. So I guess I shouldn't implement IList<T> at all or explicitly implement the methods that manipulate the collection. +1 for review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T07:40:22.660", "Id": "28205", "Score": "0", "body": "Yes, if you need insert/delete you are better off paying the four bytes per node. Since you're concerned about node overhead, you should already be using a fairly large number of elements per node which means those four bytes pale in comparison." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T07:45:40.750", "Id": "28208", "Score": "0", "body": "You may be right. I guess it can help me to alter only one array instead of every array in every node if I implement a remove function. It can also be used in insert if an item is removed from that node before. Do I get your point? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T09:15:26.867", "Id": "28210", "Score": "0", "body": "Read the Wikipedia Page again for clarity. By allowing each node to range from half to completely full, you gain improvements in the time to insert and update. This is the classic speed vs. memory tradeoff." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T17:58:59.223", "Id": "17687", "ParentId": "17670", "Score": "3" } }, { "body": "<ol>\n<li><p>Isn't the default node size of 8 too small? If you're dealing with huge amounts of data, I think it would make more sense to make the default much larger. If you're worried that that would waste too much memory, you could make the last node small at first and resize it when it gets full (until it reaches some size, which would mean you would create a new node).</p></li>\n<li><p>I think performing two assignments on a single line, the way you do in <code>Add()</code> can be confusing. I would rewrite it as:</p>\n\n<pre><code>_LastNode.Next = new Node(_NodeSize);\n_LastNode = _LastNode.Next;\n</code></pre>\n\n<p>Or at least drop the parenheses, they don't add anything useful here.</p></li>\n<li><p>Both branches in your <code>Add()</code> method have code that does the same thing, you should factor that out:</p>\n\n<pre><code>public void Add(T item)\n{\n if (_LastNodeCount == _NodeSize)\n {\n _LastNode.Next = new Node(_NodeSize);\n _LastNode = _LastNode.Next;\n _LastNodeCount = 0;\n _NodeCount++;\n }\n _LastNode.Items[_LastNodeCount++] = item;\n _Count++;\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T06:57:23.697", "Id": "28203", "Score": "0", "body": "You're right about node size of 8, I'll increase that (what would you use btw? is ~64 fine?). Resizing is a good idea but I don't think that will be necessary. You're right about that line, too. I have a habbit that makes me think \"shorter is _always_ more readable\" which is not right in cases like this. You _also_ right about the Add method (you didn't set the _LastNodeCount, though), I'm going to change it like this. Thank you so much and +1 for your help." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T14:50:50.360", "Id": "28229", "Score": "0", "body": "You're right, I didn't realize that I have to reset `_LastNodeCount`, fixed now." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T04:27:43.993", "Id": "28266", "Score": "0", "body": "+1 but I disagree with the double-assignment. Leaving it on one line (when it fits) makes it clear that the two variables receive the same value." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T23:29:23.433", "Id": "17693", "ParentId": "17670", "Score": "4" } }, { "body": "<p>I think there's a bug in your <code>GetEnumerator</code>. To wit, I believe the conditional to check the last index in the current node is backward:</p>\n\n<pre><code>var last = current.Next == null ? _NodeSize : _LastNodeCount;\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>var last = current.Next == null ? _LastNodeCount : _NodeSize;\n</code></pre>\n\n<p>instead.</p>\n\n<p>I have a few other changes I would personally make (for instance, seal the private <code>Node</code> class and not use <code>public</code> fields, but rather make them properties), but the updated version is quite good.</p>\n\n<pre><code>using System.Collections.Generic;\n\npublic sealed class UnrolledLinkedList&lt;T&gt; : IEnumerable&lt;T&gt;\n{\n // Fields\n private readonly int nodeSize;\n\n private Node firstNode;\n\n private Node lastNode;\n\n private int lastNodeCount;\n\n // Constructors\n public UnrolledLinkedList(int nodeSize = 64)\n {\n this.nodeSize = nodeSize;\n this.Clear();\n }\n\n // Properties\n public int Count\n {\n get;\n\n private set;\n }\n\n // Methods\n public void Add(T item)\n {\n if (this.lastNodeCount == this.nodeSize)\n {\n this.lastNode.Next = new Node(this.nodeSize, item);\n this.lastNode = this.lastNode.Next;\n this.lastNodeCount = 1;\n }\n else\n {\n this.lastNode.Items[this.lastNodeCount++] = item;\n }\n\n this.Count++;\n }\n\n public void Clear()\n {\n this.Count = 0;\n this.firstNode = this.lastNode = new Node(this.nodeSize);\n this.lastNodeCount = 0;\n }\n\n public IEnumerator&lt;T&gt; GetEnumerator()\n {\n for (var current = this.firstNode; current != null;)\n {\n var last = current.Next == null ? this.lastNodeCount : this.nodeSize;\n\n for (var i = 0; i != last; i++)\n {\n yield return current.Items[i];\n }\n\n current = current.Next;\n }\n }\n\n System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()\n {\n return this.GetEnumerator();\n }\n\n // Types\n private sealed class Node\n {\n private readonly T[] items;\n\n public Node(int size)\n {\n this.items = new T[size];\n }\n\n public Node(int size, T firstItem) : this(size)\n {\n this.items[0] = firstItem;\n }\n\n public T[] Items\n {\n get\n {\n return this.items;\n }\n }\n\n public Node Next\n {\n get;\n\n set;\n }\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T22:50:46.353", "Id": "28262", "Score": "0", "body": "You're right about the bug :) I fixed that. I also sealed the Node but I didn't change its fields to properties (since it's just a private class, accessing the fields directly seemed ok to me). Making Count an auto-implemented property on the other hand, looks pretty good. Thank you, and +1 for your suggestions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T21:50:31.197", "Id": "17733", "ParentId": "17670", "Score": "2" } } ]
{ "AcceptedAnswerId": "17674", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T13:53:57.137", "Id": "17670", "Score": "7", "Tags": [ "c#", ".net", "collections", "linked-list" ], "Title": "A simple unrolled linked list implementation" }
17670
<p>I have to select all the rows from a database table containing a defined <code>(long)sessionId</code> where the <code>sessionId</code> row is indexed. But it is slow, and since the code to access it is really simple, I'm wondering where the problem is. Here is the code of the three layers:</p> <pre><code>var localPath = BusinessClient.Instance.Tracker.GetSpecifiedMilestonesInSessionObjects(milestonesInSession.SessionId).ToList(); public IQueryable&lt;MilestonesInSession&gt; GetSpecifiedMilestonesInSessionObjects(long sessionId) { var query = from m in _milestonesInSessionRepository.GetAll() where m.SessionId == sessionId select m; return query; } public IQueryable&lt;Model.Tracker.MilestonesInSession&gt; GetAll() { var query = from milestoneSession in _dataContext.Repository&lt;Linq.TrackerMilestonesInSession&gt;() select new Model.Tracker.MilestonesInSession { MilestoneId = milestoneSession.MilestoneId, CreatedDate = milestoneSession.CreatedDate, SessionId = milestoneSession.SessionId, ProductId = milestoneSession.ProductId, TrackerId = milestoneSession.TrackerId, StatusId = milestoneSession.StatusId, BankId = milestoneSession.BankId }; return query; } </code></pre> <p>Here attached the screenshot of the performance using ANTS:</p> <p>Presentation Layer <img src="https://i.stack.imgur.com/77rX5.png" alt="Presentation Layer"></p> <p>Business Layer <img src="https://i.stack.imgur.com/sJkdr.png" alt="Business Layer"></p> <p>Data Access Layer <img src="https://i.stack.imgur.com/66HhL.png" alt="Data Access Layer"></p> <p>The <code>sessionId</code> in the database is not unique, but I created an index on them, why accessing it is not an instant operation?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T00:47:41.423", "Id": "28264", "Score": "0", "body": "Just to repeat a now deleted comment by @GeneS: Please run the SQL Profiler and post the SQL Statement that is being executed." } ]
[ { "body": "<p>I think the bottleneck is in <code>IQueryable&lt;Model.Tracker.MilestonesInSession&gt; GetAll()</code> because it looks like you are executing that query into memory by creating a <code>new Model.Tracker.MilestonesInSession</code>\nTry this:</p>\n\n<pre><code>public IQueryable&lt;MilestonesInSession&gt; GetSpecifiedMilestonesInSessionObjects(long sessionId) \n{\n var allMilestones = from milestoneSession in\n _dataContext.Repository&lt;Linq.TrackerMilestonesInSession&gt;() \n select new { \n MilestoneId = milestoneSession.MilestoneId, \n CreatedDate = milestoneSession.CreatedDate, \n SessionId = milestoneSession.SessionId, \n ProductId = milestoneSession.ProductId, \n TrackerId = milestoneSession.TrackerId, \n StatusId = milestoneSession.StatusId, \n BankId = milestoneSession.BankId \n }; \n var query = from m in allMilestones\n where m.SessionId == sessionId \n select new Model.Tracker.MilestonesInSession \n {\n MilestoneId = m.MilestoneId, \n CreatedDate = m.CreatedDate, \n SessionId = m.SessionId, \n ProductId = m.ProductId, \n TrackerId = m.TrackerId, \n StatusId = m.StatusId, \n BankId = m.BankId \n }; \n return query; \n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T09:36:58.917", "Id": "28275", "Score": "0", "body": "By the way: I know it looks weird to create the query called allMilestones, but that's because of not reformatting your existing code to much. Basicly you can skip the first query and directly begin like this: `var query = from m in _dataContext.Repository<Linq.TrackerMilestonesInSession>()`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T09:10:40.670", "Id": "17746", "ParentId": "17672", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T13:56:39.247", "Id": "17672", "Score": "2", "Tags": [ "c#", "performance", ".net", "linq", "asp.net" ], "Title": "Simple retrieving sessionId rows from indexed SQL column is slow" }
17672
<p>This presumably simple task resulted in much more scripting logic than I thought would be necessary.</p> <p><strong>Goal:</strong> when the user clicks a button inside one of the divs, it affects said div.</p> <p><strong>Issues:</strong> I did not wish to have my function target specific elements in my DOM. (ex. targeting <code>&lt;a&gt;</code> by ID). Also, because my function is traversing the DOM and being called in multiple instances, I had to use <code>$(this)</code> format so as not to be specific to one ID.</p> <p>Anyways, here is my code:</p> <pre><code>$(".button").toggle(function(){ $(this).parent().children(".innerBox").fadeIn(); }, function(){ $(this).parent().children(".innerBox").fadeOut(); }); </code></pre> <p>It works fine. However, can someone with a little more jQuery savvy please let me how I could execute this function in the future, without having to parse through siblings and making it more convoluted than need be?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:18:35.357", "Id": "28128", "Score": "4", "body": "You could simplify it some by doing: `$(this).siblings(\".innerBox\")...`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:20:16.413", "Id": "28129", "Score": "0", "body": "You could just use `.toggleClass('on') / .toggleClass('off')` and add `transitions` to your CSS for the fade effect." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:47:23.500", "Id": "28131", "Score": "0", "body": "@Kevin Boucher That wouldn't decrease the amount of code at all, but I see what you were thinking. The amount of code I'm writing doesn't need to be truncated by a CMS or something of the sort. I merely wanted a \"better way of doing this\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:49:08.407", "Id": "28132", "Score": "0", "body": "@JustinWard, probably something like I answered is what you are looking for" } ]
[ { "body": "<p>My only alteration would be</p>\n\n<pre><code>$(this).parent().children(\".innerBox\") \n</code></pre>\n\n<p>to instead </p>\n\n<pre><code>$(this).siblings(\".innerBox\")\n</code></pre>\n\n<p>see here: <a href=\"http://jsbin.com/azamot/1/edit\" rel=\"nofollow\">http://jsbin.com/azamot/1/edit</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:42:01.443", "Id": "28133", "Score": "0", "body": "Haha! a selector called 'siblings'? It can't be that simple can it? Ohh. JQuery, you've done it again - making things as blatantly simple as a slap across the face.\nThanks, ceepee!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:24:28.463", "Id": "17676", "ParentId": "17675", "Score": "1" } }, { "body": "<p>You can certainly cache the lookups, abusing of the scopes.</p>\n\n<pre><code>$(\".button\").each(function(){\n var $btn = $(this);\n var $box = $btn.parent().children(\".innerBox\");\n $btn.toggle(function(){\n $box.fadeIn();\n }, function(){\n $box.fadeOut();\n });\n});\n</code></pre>\n\n<p>Using <a href=\"http://api.jquery.com/fadeToggle/\" rel=\"nofollow\"><code>.fadeToggle()</code></a> instead of <code>.fadeIn()</code> and <code>.fadeOut()</code>.</p>\n\n<pre><code>$(\".button\").each(function(){\n var $btn = $(this);\n var $box = $btn.parent().children(\".innerBox\");\n $btn.click(function(){\n $box.fadeToggle();\n });\n});\n</code></pre>\n\n<p>And last but not least, <a href=\"http://api.jquery.com/siblings/\" rel=\"nofollow\"><code>.siblings()</code></a>.</p>\n\n<pre><code>$(\".button\").each(function(){\n var $btn = $(this);\n var $box = $btn.siblings(\".innerBox\");\n $btn.click(function(){\n $box.fadeToggle();\n });\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T22:01:10.560", "Id": "28134", "Score": "0", "body": "Thanks, Alexander. .fadeToggle is nice! Good call. I too was creating variables, as I thought it might make things simpler, but it becomes a bit too confusing if others are intended to make sense of the code. Personal preferences, I guess. It's for that same reason I'm not a big fan of SASS (CSS) either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T22:04:39.560", "Id": "28135", "Score": "0", "body": "@JustinWard, be advised, jQuery is a monster that you can't use without caching" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T22:54:12.190", "Id": "28136", "Score": "0", "body": "Haha. Yeah, a bit of an oxymoron, eh? Using JQuery but not being a fan of variables...I just meant, I usually don't like creating even *more* variables." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:44:06.210", "Id": "17677", "ParentId": "17675", "Score": "4" } } ]
{ "AcceptedAnswerId": "17677", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T21:15:22.800", "Id": "17675", "Score": "2", "Tags": [ "javascript", "jquery", "dom" ], "Title": "Selector targets overly obtuse - recommendations?" }
17675
<p>I need to upload some images to a server. This is done with a json object. The json object has 2 values, a timestamp and a Base64 encoded string of the image. I am using the jackson library and was wondering if this is a good way to upload the images. I am worried about memory consumption if I happen to upload images asyncronusly in the future. Here is is...</p> <pre><code>@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class Photo { @JsonIgnore private String path; private String id; @JsonProperty("ts") private long timestamp; public Photo(long timestamp, String path) { this.timestamp = timestamp; this.path = path; } public String getData() { Bitmap bm = BitmapFactory.decodeFile(path); ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 50, baos); bm.recycle(); byte[] byteArray = baos.toByteArray(); try { baos.close(); } catch (IOException e) { e.printStackTrace(); } return Base64.encodeToString(byteArray, Base64.DEFAULT); } } </code></pre>
[]
[ { "body": "<p>I'm not familiar with Android at all, so just some generic Java notes:</p>\n\n<ol>\n<li><p>I'd rename <code>bm</code> to <code>bitmap</code>. A little bit longer variable names are usually easier to read and maintain.</p></li>\n<li><p>The constructor should validate its input parameters. Does it make sense to call it with <code>null</code> or empty string as <code>path</code> or a less than zero <code>timestamp</code>? If not, check it and throw a <code>NullPointerException</code> or an <code>IllegalStateException</code>. (<em>Effective Java, Second Edition, Item 38: Check parameters for validity</em>)</p></li>\n<li><p>It is a <a href=\"https://stackoverflow.com/q/3855187/843804\">bad idea to use <code>printStackTrace()</code> in Android exceptions</a>.</p></li>\n<li><p>I don't know if it differs from general Java or not but <a href=\"https://stackoverflow.com/a/2330584/843804\">closing a <code>ByteArrayOutputStream</code> in Java has no effect</a>. You might be able to omit it.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T10:46:35.160", "Id": "17747", "ParentId": "17680", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T15:04:11.823", "Id": "17680", "Score": "3", "Tags": [ "java", "android" ], "Title": "File to String Pattern for uploading to a server" }
17680
<p>I haven't studied a lot about positioning of controls in ASP.NET using .Net framework 3.5 but still I know following control positioning technique isn't the best one, just to mention its a user control,</p> <pre><code> &lt;asp:Label ID="Label2" runat="server" Text="Number of Days"&gt;&lt;/asp:Label&gt; &amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;asp:TextBox ID="TextBox2" runat="server"&gt;&lt;/asp:TextBox&gt; </code></pre> <p>Right now I am using tabs and spaces to position controls but can I do it in a better way.</p>
[]
[ { "body": "<p>Yes, use CSS and some HTML to put things where they belong. Theres is nothing special about ASP.NET controls just check the generated HTML markup on the client side.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:11:18.277", "Id": "17682", "ParentId": "17681", "Score": "3" } } ]
{ "AcceptedAnswerId": "17682", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T16:04:00.230", "Id": "17681", "Score": "3", "Tags": [ "html", "asp.net" ], "Title": "ASP.NET controls positioning" }
17681
<p>This is an assignment question from school:</p> <blockquote> <p>Write a method called <code>licencePlate</code> that takes an array of objectionable words and returns a random licence plate that does not have any of those words in it. Your plate should consist of four letters, a space, then three numbers.</p> </blockquote> <pre><code>import java.util.*; class MethodAssign5{ static String licensePlate(String[] a){ char[] lchars={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'}; char[] nchars={'0','1','2','3','4','5','6','7','8','9'}; boolean contain = true; char[] license = new char[8]; license[4]=' '; Random generator = new Random(); do{ for(int i=0;i&lt;4;i++){ license[i]=lchars[generator.nextInt(26)]; } for(int i=0;i&lt;3;i++){ license[i+5]=nchars[generator.nextInt(10)]; } contain = false; for(String s:a){ boolean same = true; char[] wchars = s.toCharArray(); for(int i=0;i&lt;4;i++){ if(license[i]!=wchars[i]){ same = false; } } if(same==true){ contain = false; } } }while(contain==true); String ans = new String(license); return ans; } public static void main(String[]args){ String[] words ={"HAHA","GORD"}; System.out.println(licensePlate(words)); } } </code></pre> <p>As you can see, I have no idea if my solution is right. It's such a low probability.</p> <p>What do you think about my solution? What should I do if this was an in-class test and had the same problem where the probability of getting the error is low?</p>
[]
[ { "body": "<p>A few suggestions, and then I'll get to how to test it:</p>\n\n<ul>\n<li>Don't be afraid of whitespace -- your code is a little hard to read due to the lack of new lines. Also, it's fairly standard to indent method names inside of classes.</li>\n<li>Always use descriptive names: <code>String[] a</code> tells me nothing about what that parameter is.</li>\n<li>When <code>x</code> is a bool, <code>x == true</code> is equivalent to <code>x</code>.\n<ul>\n<li>On an <em>extremely</em> picky note, <code>contains</code> seems like a more natural variable name for <code>contain</code> (grammatically anyway)</li>\n</ul></li>\n<li>It doesn't really matter when there's only 4 characters (so <code>4 * A.length</code> runs), but when doing a linear comparison, you should typically bail out of it with <code>break</code> or <code>continue</code>\n<ul>\n<li>Also, you might want to look into <code>indexOf</code>, <code>contains</code> and <code>equalsIgnoreCase</code></li>\n</ul></li>\n<li>Obviously this is just a little homework assignment, so it would be a bit overkill, but I would put the license plate generation in its own class in a real application.</li>\n<li>I would also pass the banned words as a parameter to the constructor instead of to a method -- that allows your instance to carry around the words without any farther down consumers having to know what the words are\n<ul>\n<li>Imagine that you make a machine that's used in the DMV. Imagine that this machine has a \"generate license plate\" button. When pressed, a screen simply shows the plate.\n<ul>\n<li>Passing the words to the method is like having to key in the banned words every time the button is pressed -- the DMV employee shouldn't be responsible for knowing/controlling those words</li>\n<li>Storing the words inside of an instance (whether set with a <code>setBannedWords</code> method or passed to the constructor) is like configuring the machine at creation. The DMV employee no longer has to know what the words are, or be responsible for entering them. Years could go by before an employee realized \"Oh my, I just noticed that the machine has never output a cuss word!\"</li>\n<li>For completeness: A third option would be to <em>not</em> filter the words -- it would then be up to the employee to go \"Hrmmm, 'FART 743' is probably a bad license plate.\"</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<hr>\n\n<p>Ok, so does this work? Probably. It looks correct to my rusty-with-Java-eye anyway.</p>\n\n<p>The easiest way to test it would probably be to whittle down the set of possible characters from A-Z to A-D and then make ABC a bad word. After a lot of test runs, you could be fairly certain that it was throwing out any <code>ABCX</code> or <code>XABC</code>.</p>\n\n<p>This just made me realize: did your professor specify that the bad words would always be four characters? If not, your code is wrong.</p>\n\n<hr>\n\n<p>So how could this be tested more properly-ish? Unfortunately it requires that the code become a lot longer. Your professor would probably think you got a bit carried away if you truly made this testable. Despite a fairly simple requirement, to test this with granularity would require breaking it down into quite a few pieces.</p>\n\n<p>I can code this up if you want, but for the sake of brevity and time, I'll just describe it here. </p>\n\n<p>The main problem with testing this is that all of the concerns are mixed together. You have a few concerns:</p>\n\n<ul>\n<li>Generating a license plate\n<ul>\n<li>Generating the text part</li>\n<li>Generating the number part</li>\n</ul></li>\n<li>Filtering a license plate</li>\n</ul>\n\n<p>Note that separating this concerns allows you to test them independently.</p>\n\n<p>\"Does my class properly generate and filter license plates?\" becomes \"Does class X properly generate license plates? Does class Y properly filter license plates?\"</p>\n\n<p>The second option is easier to test because it allows you to pass in a license plate generator that is rigged to generate bad words.</p>\n\n<p>The text and number generation should arguably be separated. That would allow for easily reusing generated numbers when a bad word is in the word part, but other than that, the added complexity would probably not be worth it.</p>\n\n<p>One option would be to use an interface:</p>\n\n<pre><code>public interface LicensePlateGenerator {\n public String generateLicensePlate();\n}\n</code></pre>\n\n<p>You could then have your classes implement it:</p>\n\n<pre><code>public class LicensePlateGeneratorRandom implements LicensePlateGenerator {\n\n private final lchar[] = {'A', 'B', 'C', ...};\n\n private final nchar[] = {'0', '1', '2', ...};\n\n public String generateLicensePlate() {\n\n //Randomly grab 4 lchars\n //Randomly grab 3 nchars \n\n }\n\n}\n\npublic class LicensePlateGeneratorFiltered implements LicensePlateGenerator {\n\n private final LicensePlateGenerator gen;\n private final List&lt;String&gt; badWords;\n\n public LicensePlateGeneratorFiltered(LicensePlateGenerator generator, List&lt;String&gt; badWords) {\n\n this.gen = generator;\n this.badWords = badWords;\n\n }\n\n public String generateLicensePlate() {\n\n //It might be a good idea to test how many plates have already been generated\n //An infinite loop of generating could happen depending on the underlying generator\n //and what kind of badWords are defined\n\n String lp;\n\n do {\n lp = gen.generateLicensePlate();\n } while (isBad(lp));\n\n return lp;\n\n }\n\n private boolean isBad(String lp) {\n //Return false if lp contains any badWords\n //and true otherwise\n }\n\n}\n</code></pre>\n\n<p>Note how this is transparent to any consuming class. A consuming class doesn't need to know whether it has a <code>LicensePlateGeneratorRandom</code> or <code>LicensePlateGeneratorFiltered</code>; it just needs to know it has a LicensePlateGenerator.</p>\n\n<p>Note that this allows you to test very easily. Testing your random generator means just checking a few outputs. Checking your filter could be done by rigging a generator:</p>\n\n<p>(I would probably define this as an anonymous class in actual testing code, but my Java is too rusty to remember the syntax for that :p)</p>\n\n<pre><code>public class LicensePlateGeneratorFake implements LicensePlateGenerator {\n\n private final List&lt;String&gt; words;\n private Iterator&lt;String&gt; currentPos;\n\n public LicensePlateGeneratorFake(List&lt;String&gt; words) {\n this.words = words;\n currentPos = this.words.iterator();\n }\n\n public function generateLicensePlate() {\n if (!currentPos.hasNext()) {\n //Something should happen here... \n //could always just loop back around, or it\n //might also be worth considering having the interface\n //declare a certain exception as being possible in this method. \n //(That would also allow a way out of the infinite loop in the\n //(filter generator)\n //throw new LicensePlateGeneratorException(\"...\");\n //(that could be the base class, and then a LicensePlateGeneratorInfiniteLoopException\n //could be thrown in the filter class)\n }\n //Obviously the end of the iterator should be checked, but I'm lazy\n return currentPos.next() + \" 123\";\n }\n\n}\n</code></pre>\n\n<p>You then configure this fake generator to generate a certain stream of words (\"ABCD\", \"DCBA\", etc). Then, you pass this fake generator to the filter, and give the filter a list of words you know that the fake generator will generate.</p>\n\n<p>If you tell the fake generator to generate \"ABCD\" and you tell the filter to reject \"ABCD\", you can then test success by whether or not the filter generator returns \"ABCD\" in any of the generations.</p>\n\n<hr>\n\n<p>An alternative approach would be to have the filter not be a generator. Instead, your consuming code would be responsible for configuring its own filters and then generating plates until a suitable one is found.</p>\n\n<p>Both designs have fairly strong pros and cons.</p>\n\n<hr>\n\n<p><em>(Note: I completely bastardized the class names in my examples. In a real application, namespaces should be used. The code formatting on here makes namespaces a bit clumsy though, so I didn't use them.)</em></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T01:46:44.207", "Id": "28184", "Score": "1", "body": "Holy, it took me so long to read all of your writings... I thank you very much for your efforts. By the way, for my question bad words would always be four characters. This is grade 12 computer science, that's why rules are simple :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T07:57:29.890", "Id": "28209", "Score": "1", "body": "Crikey thats comprehensive :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T04:42:59.170", "Id": "28268", "Score": "1", "body": "+42 great, comprehensive answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:28:54.217", "Id": "17690", "ParentId": "17689", "Score": "14" } }, { "body": "<p>Some small notes (actually the last few are more or less small comments to Corbin's great answer):</p>\n\n<ol>\n<li><p>The <code>licensePlate</code> method should validate its input parameters. Does it make sense to call it with <code>null</code>? If not, check it and throw a <code>NullPointerException</code>. (<em>Effective Java, Second Edition, Item 38: Check parameters for validity</em>)</p></li>\n<li><p>Method names should be verbs, for example, <code>licensePlate</code> should be <code>generateLicensePlate</code>, while class names shouldn't be verbs. (Check <a href=\"http://www.oracle.com/technetwork/java/codeconventions-135099.html#367\">Code Conventions for the Java Programming Language, Naming Conventions</a> and <em>Clean Code</em>, page 25.)</p></li>\n<li><p>The code contains lots of magic numbers. Using named constants instead of numbers would make the code more readable and less fragile. If you have to modify their value (for example, you need three-letter, three-digit plates instead of four-letter, three-digit plates) it's easy to forget to do it everywhere. </p></li>\n<li><p>An endless <code>while</code> loop with a <code>return</code> seems more natural and easier to read to me than the <code>do-while</code> loop:</p>\n\n<pre><code>while (true) {\n final String licensePlate = generator.generateLicensePlate();\n if (!isBad(licensePlate)) {\n return licensePlate;\n }\n}\n</code></pre></li>\n<li><p>For the reasons above I'd prefix the classes: <code>RandomLicensePlateGenerator</code>, <code>FilteredLicensePlateGenerator</code> etc.</p></li>\n<li><p>The <code>LicensePlateGeneratorFake</code> class could be omitted if you use a mock library like EasyMock.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T02:34:38.540", "Id": "33053", "Score": "1", "body": "The assignment requires the name of the method to be `licensePlate`. Why professors think teaching their students bad style is beyond me." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T07:34:50.517", "Id": "17709", "ParentId": "17689", "Score": "5" } }, { "body": "<p>While Corbin's answer is great (and I'd cetainly recommend accepting it over this), it buries the key point: your method does two things. This makes testing, understanding, and maintaince harder.</p>\n\n<p>You are supposed to a) generate a licence number, and b) filter out unacceptable ones.</p>\n\n<p>This should properly be split into at least 3 function, 1 to generate, 1 to reject, and 1 that calls the other 2 and only returns the result of the first if not rejected.</p>\n\n<p>At that point you should see what needs testing, what can be tested, and how to do your test.</p>\n\n<p>As for your final question: you fiddle with the process to make the error both frequent and repeatable.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T09:09:50.490", "Id": "17710", "ParentId": "17689", "Score": "3" } }, { "body": "<p>A few small additions:</p>\n\n<ol>\n<li>The Random class is generally made a static field to avoid creating it multiple times.</li>\n<li><p>The letter and number character arrays can be created using a simple method</p>\n\n<pre><code>private char[] getCharsInRange(final char lowerBound, final int size) {\n final char[] result = new char[size];\n\n for (int i = 0; i &lt; size; ++i) {\n result[i] = (char)(lowerBound + i);\n }\n\n return result;\n}\n</code></pre>\n\n<p>Names should be better, but I'm feeling lazy.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-17T02:58:37.710", "Id": "20613", "ParentId": "17689", "Score": "1" } } ]
{ "AcceptedAnswerId": "17690", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T19:49:38.393", "Id": "17689", "Score": "11", "Tags": [ "java", "homework", "random" ], "Title": "Turning an array of words into a random license plate" }
17689
<p>Is there anything what could be improved on this code?</p> <pre><code>def factorial(n: Int, offset: Int = 1): Int = { if(n == 0) offset else factorial(n - 1, (offset * n)) } </code></pre> <p>The idea is to have tail-recursive version of factorial in Scala, without need to define internal function or alias.</p> <p>This one is callable like this:</p> <pre><code>factorial(4) </code></pre> <p>So final solution looks like this:</p> <pre><code>import scala.annotation._ @tailrec def factorial(n: Int, accumulator: Long = 1): Long = { if(n == 0) accumulator else factorial(n - 1, (accumulator * n)) } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:55:28.967", "Id": "28170", "Score": "0", "body": "Not familiar with Scala, but for what it's worth, the slowest part of recursive factorial is the repeated calculations. Make a tree of factorial calls, and you'll see that calls get repeated a lot. (Though how to alleviate this while staying functional, I'm not quite sure.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:57:08.840", "Id": "28171", "Score": "0", "body": "@corbin : yep it's repeated a lot, but making a tree is not a `tail-recursive` approach (more here http://stackoverflow.com/questions/33923/what-is-tail-recursion )" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:59:24.343", "Id": "28172", "Score": "1", "body": "Whoops! You're right. I jumped the gun on that one. For some reason I was thinking that tail recursion reused stackframes (well, in a TCO situation), but still had to make the same calls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T22:02:56.883", "Id": "28173", "Score": "0", "body": "I think, it depends on way it is optimized on platform/jvm level (python, scala, lisp, ...). Anyway it is necesarry for recursion functions, as long stack-trace (call tree) could end up as stack-overflow" } ]
[ { "body": "<p>Looks ok in its basic form, but here are some points to consider:</p>\n\n<ol>\n<li><p>You may want to consider using at least <code>Long</code>, as factorials tend to get large quickly.</p></li>\n<li><p>Whenever you write a function that you believe to be tail-recursive, then do add <code>@tailrec</code> (from scala.annotations) to it. This has two major advantages: First, it corrects your thoughts and tells you immediately, if it isn't tail-recursive although you thought so, and second, it tells everyone else and stops them from making a \"fix\" that causes the function to no longer be tail-recursive. May not be a big deal for such a small one, but in general tail-recursive functions can be more complex and then it's much harder to see at a glance that the function is tail-recursive if you do not annotate it as such.</p></li>\n<li><p>Naming convention: The semantics of what you labelled <code>offset</code> is not really an offset as we would usually think about it. If you say <code>offset</code> most people have a certain meaning in mind that they associate with this term. The traditional meaning that resembles your semantics would be given by the term <code>accumulator</code>. Especially, when writing recursive functions we run into this intermediate-result-variable-thing very often and you will almost always see it referred to as an <code>accumulator</code>, so for clarity's sake you should just name the variable as such.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T06:16:29.030", "Id": "28196", "Score": "0", "body": "Thanks Frank, that helped a lot. I've added final form of function to question tail." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T05:52:34.940", "Id": "17706", "ParentId": "17691", "Score": "8" } } ]
{ "AcceptedAnswerId": "17706", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-18T21:47:43.057", "Id": "17691", "Score": "5", "Tags": [ "recursion", "functional-programming", "scala" ], "Title": "Tail-recursive factorial" }
17691
<p>I've set up some PHP to delete a directory, it's contents, and any subdirectory and its contents... I'm new to PHP so I'm most definitely doing something WRONG or am doing something in the most inefficient way.</p> <p>Looking for some references or suggestion on how to do this better...</p> <p>Using PHP 5.3.8.</p> <p><strong>First Draft</strong></p> <pre><code>if ($handle = opendir($main_dir)) { while (false !== ($entry = readdir($handle))) { $absolute_path = $main_dir.'/'.$entry; if ($entry != "." &amp;&amp; $entry != "..") { chmod($absolute_path, 0755); unlink($absolute_path); //check if any folders exist, then delete files within if (file_exists($absolute_path) &amp;&amp; is_dir($absolute_path)) { if ($child_handle = opendir($absolute_path)) { while (false !== ($child_entry = readdir($child_handle))) { $child_absolute_path = $absolute_path.'/'.$child_entry; if ($child_entry != "." &amp;&amp; $child_entry != "..") { unlink($child_absolute_path); } } closedir($child_handle); } } rmdir($absolute_path); } } closedir($handle); } rmdir($main_dir); </code></pre> <p>how about something like this...</p> <p><strong>Second Draft</strong></p> <pre><code> $dir = "path/to/dir"; chmod($dir, 0755); $di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS); $ri = new RecursiveIteratorIterator($di, RecursiveIteratorIterator::CHILD_FIRST); foreach ( $ri as $file ) { $file-&gt;isDir() ? rmdir($file) : unlink($file); } rmdir($dir); </code></pre> <p>Any thoughts? Much appreciated!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T02:03:51.347", "Id": "28185", "Score": "0", "body": "What version of PHP do you use/can you use? You should tag it if possible as there is a lot of differences between 5.4 and 5.0 in regards to cleanliness of code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T02:14:26.350", "Id": "28186", "Score": "0", "body": "@Steven Im using 5.3.8, I've updated to include." } ]
[ { "body": "<p>Well one way would be to use the Recursive functionality...</p>\n\n<pre><code>chmod($main_dir, 0755) // Not sure why you keep chmodding stuff\n// Recursively loop through directory, starting with the children\n$dir = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($main_dir),RecursiveIteratorIterator::CHILD_FIRST);\n\nforeach($dir as $file) {\n if (in_array($file-&gt;getBasename(), array('.', '..'))) {\n continue; // Skip if it is . or ..\n } elseif ($file-&gt;isDir()) {\n rmdir($file-&gt;getPathname());\n } elseif ($file-&gt;isFile() || $file-&gt;isLink()) {\n unlink($file-&gt;getPathname());\n }\n}\nrmdir($main_dir);\n</code></pre>\n\n<p>Otherwise you could look at <a href=\"https://stackoverflow.com/questions/1334398/how-to-delete-a-folder-with-contents-using-php\">https://stackoverflow.com/questions/1334398/how-to-delete-a-folder-with-contents-using-php</a></p>\n\n<p>Those are both good ways to do it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T02:41:43.830", "Id": "28187", "Score": "0", "body": "Thanks!\nps. I was using chmod cuz I read somewhere something like... 'blah, blah, blah... use chmod to make sure you can access the directory before deleting to avoid errors.'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T03:15:28.250", "Id": "28189", "Score": "0", "body": "What is the purpose of using isLink() ad not just isFile()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T09:58:36.913", "Id": "28212", "Score": "0", "body": "Do you think it is necessary or is it a best practice kinda thing to include isLink() ? What I have read isLink() is only applicable to Windows > Vista." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T02:19:04.200", "Id": "17698", "ParentId": "17696", "Score": "0" } }, { "body": "<pre><code>function empty_dir($dir) {\n $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir),\n RecursiveIteratorIterator::CHILD_FIRST);\n foreach ($iterator as $path) {\n if ($path-&gt;isDir()) {\n rmdir($path-&gt;__toString());\n } else {\n unlink($path-&gt;__toString());\n }\n }\n rmdir($dir);\n}\n</code></pre>\n\n<p>from: <a href=\"http://php.net/manual/en/class.recursivedirectoryiterator.php\" rel=\"nofollow\">http://php.net/manual/en/class.recursivedirectoryiterator.php</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T03:31:38.397", "Id": "28190", "Score": "3", "body": "why are using '$path->__toString()'?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T02:19:15.237", "Id": "17699", "ParentId": "17696", "Score": "1" } }, { "body": "<p>Seen as both of the other answers seem to just be giving you code without much explanation, I thought I'd try and help you understand what they are saying.</p>\n\n<p><strong>Draft 1</strong></p>\n\n<p>I notice that you have found the documentation. Its good to read and use the documentation, but sometimes the code they use really isn't of the best quality. I don't really know what to tell you to remedy this except to always look in multiple places and become familiar with PHP best practices. My first suggestion would be NOT to assign variables inside of statements. Define the variable then check it.</p>\n\n<pre><code>$handle = opendir( $main_dir );\nif( $handle ) {\n //etc...\n}\n</code></pre>\n\n<p>This is counter to how the PHP documentation says to do it, but this is considered best practice. There are a few different reasons for this. First, it becomes much more clear what is being done here because there is no more ambiguity as to whether you actually meant to assign that variable or compare it. Sometimes that is obvious from the context, but sometimes not. Best to avoid the confusion altogether. Second, there is less room for error. If you get in the habit of not assigning variables in a statement you are less likely to accidentally use an assignment when you meant to use a comparison. And third, it requires less parenthesis, which immediately makes it easier to read. Don't believe me? Take a look at that while statement in your code. That's not as bad as it could be, I have seen worse, but the nested parenthesis really does cause eye strain, so much in fact that you may have already noticed something odd about my code. My style is to add spaces between parenthesis. Don't mind this, it is merely my style and not a comment on how \"best\" to write it.</p>\n\n<p>The only time assigning a variable in a statement is \"acceptable\" is when setting up an iterable in a loop.</p>\n\n<pre><code>//most common\nfor( $i = 0; $i &lt; 10; $i++ ) {\n//less common, but still acceptable\nwhile( ($buffer = fgets( $handle, 4096 ) ) !== false) {\n</code></pre>\n\n<p>The second example gets a little iffy, but is still usually acceptable. If you were to try abstracting that variable you would immediately see how much more complex your code would get. You'd have to rewind the initial pointer, manually step through the contents with next and before long you'd realize that the first way was much simpler and much easier to read in comparison. Which is why we still do it. I challenge you to try this out for yourself though. Nothing like seeing this in action to get a full understanding of it. The first example is easier to abstract, and sometimes is, if not starting from zero, but it is also part of the syntax and is considered acceptable. In fact you might get weird looks if you tried to abstract that unnecessarily.</p>\n\n<p>Yoda statements, <code>FALSE == $var</code> instead of <code>$var == FALSE</code>, become unnecessary if you follow the above advice. Yoda statements were initially intended for preventing accidental assignments, because <code>$var = FALSE</code> is valid while <code>FALSE = $var</code> in not. Getting in the habit of not assigning variables in statements means it becomes easier to spot accidental assignments. In some languages this feature has been removed for this very reason, though sadly not in PHP. However, this is a stylistic choice and is entirely up to you. I only mention this because I noticed that this too is from the documentation and I wanted to make sure you understood the reasoning for it and the alternative.</p>\n\n<pre><code>while( FALSE !== ( $entry = readdir( $handle ) ) ) {\n//is the same as\nwhile( ( $entry = readdir( $handle ) ) !== FALSE ) {\n</code></pre>\n\n<p>Let's take a look at the Arrow Anti-Pattern now. Anti-patterns are bad. This particular anti-pattern is easily distinguishable by heavy indentation that brings your code to points, like an arrow, or in extreme cases like a quiver full of arrows (also sometimes referred to as mountainous). Take a look at your code. It is clearly violating this anti-pattern. But how can we fix this?</p>\n\n<p>The easiest way to refactor for this is to return early. This can be expressed by literally returning a value early, or by forcing our code to skip something (this is not the same as goto, never use goto). In loops we can use continue and break to manually manipulate the flow of iteration. For example, if we reverse our if statement we can force the iteration to continue, or skip over an element. This removes a level of indentation from the rest of our code in addition to making it a little more efficient.</p>\n\n<pre><code>if( $entry == '.' || $entry == '..' ) {\n continue;\n}\n</code></pre>\n\n<p>If we found what we were looking for in a loop, we can break or return instead. If we break we only stop the loop and execution continues as if the loop had finished. From this point the last element we looped over is still available, though this could be deceiving because its not always known whether the element we are looking at is the one we want or simply the last element in the array. This is where a return would become useful. If we return from a function, execution stops and returns a value to whichever script called it. If we return from your code execution will just end.</p>\n\n<pre><code>if( $entry == 'found' ) {\n break;\n //or\n return $entry;\n}\n</code></pre>\n\n<p>Sometimes it is also desirable to return in case something went wrong. For instance, in my first suggestion I said to abstract the <code>$handle</code> from the if statement. If we were to reverse that if statement we could issue a return statement in case initializing the handle failed. This would prevent the rest of the code from running.</p>\n\n<pre><code>if( ! $handle ) {\n return FALSE;\n}\n</code></pre>\n\n<p>I believe your procedure for deletion is backwards. You <code>chmod()</code> the file to give you permissions on it, then you immediately delete it, then you finally check if that file is a directory. The file doesn't exist anymore. You've already deleted it. Check if that file is a directory first, then delete it. Though this is just a general bit of advice. Because <code>unlink()</code> also deletes directories and not just files the recursion is implied in the functionality and unnecessary to implement explicitly. However, to help you understand the recursion, I'm going to show you a version that deletes only the files and leaves the directory structure.</p>\n\n<pre><code>if( file_exists( $absolute_path ) &amp;&amp; is_dir( $absolute_path ) ) {\n //loop over new directory\n} else {\n chmod( $absolute_path, 0755 );\n unlink( $absolute_path );\n}\n</code></pre>\n\n<p>Let's take a look at <code>is_dir()</code>. Here is the documentation for this function's return values:</p>\n\n<blockquote>\n <p>Returns <strong>TRUE</strong> if the filename exists and is a directory, <strong>FALSE</strong> otherwise.</p>\n</blockquote>\n\n<p>Therefore, explicitly checking if the <code>file_exists()</code> is unnecessary and redundant. You can remove this function from your statements.</p>\n\n<pre><code>if( is_dir( $absolute_path ) ) {\n</code></pre>\n\n<p>Since we are talking about functions anyways, lets discuss one of the core principles, \"Don't Repeat Yourself\" (DRY). As the name implies, your code should not repeat itself. This is the main problem with your code. It is not recursive, though you are trying to simulate recursion by repeating code, and therefore this would normally not work as expected. You just lucked out. Lets combine what I've already showed you to create a recursive function. Please, do not just copy and paste this. Manually type every line and try to understand how it works first. I have hidden the code in case you wish to try this for yourself first, which I encourage you to do. Reread the above if you need to. Every thing I'm about to reveal I discussed above. Mouse over the block below to reveal it.</p>\n\n<blockquote class=\"spoiler\">\n <p><pre> function recursiveDelete( $path ) {\n $handle = opendir( $path );\n\n if( ! $handle ) {\n return FALSE;\n }\n\n while( ( $entry = readdir( $handle ) ) !== FALSE ) {\n if( $entry == '.' || $entry == '..' ) {\n continue;\n }\n\n $file = \"$path/$entry\";\n\n if( is_dir( $file ) ) {\n recursiveDelete();\n } else {\n chmod( $file, 0755 );\n unlink( $file );\n }\n }\n }</pre></p>\n</blockquote>\n\n<p>There's more to DRY than just recursive functions. There's proper use of variables and loops as well, but going into every way you can keep your code DRY is a bit beyond the scope of this post. If you want a full explanation the first results on Google are likely to be extremely helpful.</p>\n\n<p><strong>Draft 2</strong></p>\n\n<p>There's not really anything here for me to check. As I imagine you probably got this from somewhere. However, I will explain the ternary to you.</p>\n\n<pre><code>$file-&gt;isDir() ? rmdir( $file ) : unlink( $file );\n//is the same as\nif( $file-&gt;isDir() ) {\n rmdir( $file );\n} else {\n unlink( $file );\n}\n</code></pre>\n\n<p>Ternary is a powerful tool. Though some people don't seem to like it much, I am not one of them. If used appropriately it can not only enhance a program's efficiency, but improve its legibility. The ternary shown above is an example of good ternary. When ternary starts making your code illegible or complex, then you should revert to using standard if/else statements. A general rule of thumb is to never nest ternary statements and never use ternary statements that break the 80th column. In case you are confused what that means, a column is the exactly one character, so 80 characters, including spacing.</p>\n\n<p>Hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T16:43:48.143", "Id": "17727", "ParentId": "17696", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T01:56:08.973", "Id": "17696", "Score": "1", "Tags": [ "php" ], "Title": "PHP - Deleting Directory Contents & SubDirectory Contents" }
17696
<p>The below logic is working fine. But is there any way to optimize this logic ?</p> <p>I have a <code>string1, string2,...,stringn</code> and values of each strings are</p> <p><code>string1 = "s1k1-s1k2-s1k3-....-s1kn | s1v1-s1v2-s1v3-....-s1vn";</code></p> <p><code>string2 = "s2k1-s2k2-s2k3-....-s2kn | s2v1-s2v2-s2v3-....-s2vn";</code></p> <pre><code> ............. </code></pre> <p><code>stringn = "snk1-snk2-snk3-....-snkn | snv1-snv2-snv3-....-snvn";</code></p> <p>Now, I want to populate the <code>Dictionary&lt;string, string&gt;()</code> with the key and values as follows.</p> <pre><code>var dict = new Dictionary&lt;string, string&gt;(); dict.Add(s1k1, s1v1); dict.Add(s1k2, s1v2); : : dict.Add(snkn, snvn); </code></pre> <p><strong>Below is my sample code:</strong></p> <pre><code> string string1 = "s1k1-s1k2-s1k3-s1kn|s1v1-s1v2-s1v3-s1vn"; string string2 = "s2k1-s2k2-s2k3-s2kn|s2v1-s2v2-s2v3-s2vn"; string stringn = "snk1-snk2-snk3-snkn|snv1-snv2-snv3-snvn"; var dict = new Dictionary&lt;string, string&gt;(); new List&lt;string&gt; { string1, string2, stringn }.ForEach(str =&gt; { var strSplit = str.Split('|'); var strKeys = strSplit[0].Split('-'); var strValues = strSplit[1].Split('-'); strKeys.Zip(strValues, (key, value) =&gt; new { key, value }).ToList().ForEach(filed =&gt; dict.Add(filed.key, filed.value)); }); </code></pre> <p>Is it possible to optimize this code interms of Speed and Readability.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T03:55:51.533", "Id": "28192", "Score": "2", "body": "Optimize for what? Speed? Memory consumption? Readability?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T09:21:34.223", "Id": "28211", "Score": "0", "body": "-1: this code does not compile, and even if it did it wouldn't do what you say it does." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T17:57:41.603", "Id": "28246", "Score": "0", "body": "Hey Aneves, What is wrong in this post. You didn't understand the problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T18:49:29.587", "Id": "28253", "Score": "0", "body": "Hello @PrasadKanaparthi, welcome to CodeReview. I understood the problem very well. But this is a place to ask for `feedback on a specific _working_ piece of code from your project` - see [the FAQ](http://codereview.stackexchange.com/faq). Code that has gross syntax and algorithm errors is not \"working code\". (I personally accept pseudo-code. Others don't.) After you fixed it your code is still missing at least a `);` at the end and **it still does not fill the dictionary**, but that is good enough for me since you are new around here. I removed the -1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T18:57:16.553", "Id": "28255", "Score": "0", "body": "The problem with the current code is that you're trying to (_very_ wrongly) use `Zip()` to perform side effects (add items to an external dictionary). Not only that, it is never performed because the result of the zipping `temp` is never iterated over which would make it work. However, I would _very strongly_ advise you or anyone from ever doing stuff like that. It will only lead to headaches." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T16:52:14.080", "Id": "28284", "Score": "0", "body": "Hi All, I am new to CR and I just over look all the FAQs. After you guys suggested i read FAQs thoroughly :). Now i have edited my post and corrected my code logic. I really appreciate all your efforts. Thanks" } ]
[ { "body": "<p>If you want to optimize for speed and possibly memory, just use regular loops to build up your dictionary, though it may hurt readability.</p>\n\n<p>The idea is simple, scan the string for keys and values simultaneously. Don't extract substrings until you know what you need. Scan each token until you hit a delimiter and add the corresponding keys and values to your dictionary.</p>\n\n<p>Assuming none of your keys or values do not contain any of your delimiters and everything is well formed and you have the same amount of values as you do keys for every string.</p>\n\n<pre><code>var myStrings = new[]\n{\n \"1-2-3-4-5|a-b-c-d-e\",\n \"10-20-30-40-50|aaa-bbb-ccc-ddd-eee\",\n};\nvar delims = new[] { '-', '|' };\nvar dict = new Dictionary&lt;string, string&gt;();\nforeach (var str in myStrings)\n{\n var sepIndex = str.IndexOf('|');\n\n var keyStart = 0;\n var valueStart = sepIndex + 1;\n while (keyStart &lt; sepIndex)\n {\n // scan for the end of the token\n var keyEnd = str.IndexOfAny(delims, keyStart);\n var valueEnd = keyEnd &lt; sepIndex\n ? str.IndexOfAny(delims, valueStart)\n : str.Length;\n\n // extract and add the tokens\n var key = str.Substring(keyStart, keyEnd - keyStart);\n var value = str.Substring(valueStart, valueEnd - valueStart);\n dict.Add(key, value);\n\n keyStart = keyEnd + 1;\n valueStart = valueEnd + 1;\n }\n}\n</code></pre>\n\n<hr>\n\n<p>For readability, a declarative style works well and LINQ is king, just use it better.</p>\n\n<pre><code>var dict =\n (from str in myStrings\n let split = str.Split('|')\n let keys = split[0].Split('-')\n let values = split[1].Split('-')\n from pair in keys.Zip(values, (key, value) =&gt; new { key, value })\n select pair).ToDictionary(x =&gt; x.key, x =&gt; x.value);\n</code></pre>\n\n<p>As a side note, don't throw things into a list just for the sake of using the <code>ForEach()</code> method, you don't need the overhead of the list just to be able to interate over a collection through that method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T17:58:26.483", "Id": "28247", "Score": "0", "body": "Hey i just given the scenario with my logic. It works perfectly. But i just want to know is there better way to do that interms of speed and readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T18:37:18.487", "Id": "28250", "Score": "2", "body": "@PrasadKanaparthi When I run your code and put a break point after the ForEach statement, the \"dict\" variable is empty." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T04:43:49.480", "Id": "17704", "ParentId": "17697", "Score": "6" } } ]
{ "AcceptedAnswerId": "17704", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T02:13:20.087", "Id": "17697", "Score": "0", "Tags": [ "c#" ], "Title": "How to optimize this C# code" }
17697
<p>Here is some code I wrote in Python / Numpy that I pretty much directly translated from MATLAB code. When I run the code in MATLAB on my machine, it takes roughly 17 seconds. When I run the code in Python / Numpy on my machine, it takes roughly 233 seconds. Am I not using Numpy effectively? Please look over my Python code to see if I'm using Numpy in a non effective manner. All this code is doing is fitting the parameter D (diffusion coefficient) in the heat equation to some synthetically generated data using MCMC method. </p> <pre><code>import numpy as np from numpy import * import pylab as py from pylab import * import math import time def heat(D,u0,q,tdim): xdim = np.size(u0) Z = np.zeros([xdim,tdim]) Z[:,0]=u0; for i in range(1,tdim): for j in range (1,xdim-1): Z[j,i]=Z[j,i-1]+ D*q*(Z[j-1,i-1]-2*Z[j,i-1]+Z[j+1,i-1]) return Z start_time = time.clock() L = 10 D = 0.5 s = 0.03 # magnitude of noise Tmax = 0.2 xdim = 25 tdim = 75 x = np.linspace(0,L,xdim) t = np.linspace(0,Tmax,tdim) dt = t[1]-t[0] dx = x[1]-x[0] q = dt/(dx**2) r1 = 0.75*L r2 = 0.8*L ################################################ ## check the stability criterion dt/(dx^2)&lt;.5 ## ################################################ # Define the actual initial temperature distribution u0 = np.zeros(xdim) for i in range(0,xdim): if(x[i]&gt;=r1 and x[i]&lt;=r2): u0[i] = 1 xDat = range(1,xdim-1) tDat = np.array([tdim]) nxDat = len(xDat) ntDat = 1 tfinal = tdim-1 # synthesize data Z = heat(D,u0,q,tdim) u = Z[xDat,tfinal] # matrix uDat = u + s*randn(nxDat) # MATLAB PLOTTING #figure(1);surf(x,t,Z); hold on; #if ntDat&gt;1, mesh(x(xDat),t(tDat),uDat); #else set(plot3(x(xDat),t(tDat)*ones(1,nxDat),uDat,'r-o'),'LineWidth',3); #end; hold off; drawnow #MCMC run N = 10000 m = 100 XD = 1.0 X = np.zeros(N) X[0] = XD Z = heat(XD,u0,q,tdim) u = Z[xDat,tfinal] oLLkd = sum(sum(-(u-uDat)**2))/(2*s**2) LL = np.zeros(N) LL[0] = oLLkd # random walk step size w = 0.1 for n in range (1,N): XDp = XD+w*(2*rand(1)-1) if XDp &gt; 0: Z = heat(XDp,u0,q,tdim) u = Z[xDat,tfinal] nLLkd = sum(sum( -(u-uDat)**2))/(2*s**2) alpha = exp((nLLkd-oLLkd)) if random() &lt; alpha: XD = XDp oLLkd = nLLkd CZ = Z X[n] = XD; LL[n] = oLLkd; print time.clock() - start_time, "seconds" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-31T13:52:34.893", "Id": "33900", "Score": "0", "body": "Not sure how this works in python, but could you run a kind of profile on the code to see which lines use most computation time?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T05:37:15.730", "Id": "47820", "Score": "1", "body": "I translated this back to Matlab, and ran it on Octave. With that double loop it was very slow, slower than numpy. My guess is that Matlab (probably a newer version) is compiling the loops. The kind of vectorization that classic Matlab required is no longer essential to fast code. Numpy and Octave still require thinking in terms of vector and matrix operations." } ]
[ { "body": "<p>The first obvious thing that jumped out was using nested \"for\" loops to work with array elements. Replace with whole-array arithmetic, and use offset slicing to shift the array (minus one end or the other) </p>\n\n<p>The first and last elements will require special attention, taking a few minutes of development time, but miniscule execution time. </p>\n\n<p>I suspect this alone with will improve your execution speed greatly.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T04:49:58.770", "Id": "17705", "ParentId": "17702", "Score": "2" } }, { "body": "<p>In the <code>heat</code> function, simply vectorizing the inner loop, drops the time from 340 sec to 56 sec, a <strong>6x improvement</strong>. It starts by defining the first column of <code>Z</code>, and calculates the next column from that (modeling heat diffusion). </p>\n\n<pre><code>def heat(D,u0,q,tdim):\n xdim = np.size(u0)\n Z = np.zeros([xdim,tdim])\n Z[:,0]=u0;\n for i in range(1,tdim):\n #for j in range (1,xdim-1):\n # Z[j,i]=Z[j,i-1]+ D*q*(Z[j-1,i-1]-2*Z[j,i-1]+Z[j+1,i-1])\n J = np.arange(1, xdim-1)\n Z[J,i] = Z[J,i-1] + D*q*( Z[J-1,i-1] - 2*Z[J,i-1] + Z[J+1,i-1] )\n return Z\n</code></pre>\n\n<p>some added improvement (<strong>10x speedup</strong>) by streamlining the indexing</p>\n\n<pre><code> Z1 = Z[:,i-1]\n Z[j,i] = Z1[1:-1] + D*q* (Z1[:-2] - 2 * Z1[1:-1] + Z1[2:])\n</code></pre>\n\n<p>Better yet. This drops time to 7sec, a <strong>45x improvement</strong>. It constructs a matrix with 3 diagonals, and applies that repeatedly to the <code>u</code> vector (with a dot product). </p>\n\n<pre><code>def heat(D,u0,q,tdim):\n # drops time to 7sec\n N = np.size(u0)\n dq = D*q\n A = np.eye(N,N,0)+ dq*(np.eye(N,N,-1)+np.eye(N,N,1)-2*np.eye(N,N,0))\n Z = np.zeros([N,tdim])\n Z[:,0] = u0;\n # print u0.shape, A.shape, (A*u0).shape, np.dot(A,u0).shape\n for i in range(1,tdim):\n u0 = np.dot(A,u0)\n Z[:,i] = u0\n return Z\n</code></pre>\n\n<p>Based on further testing and reading, I think <code>np.dot(A,u0)</code> is using the fast <code>BLAS</code> code.</p>\n\n<p>For larger dimensions (here xdim is only 25), <code>scipy.sparse</code> can be used to make a more compact <code>A</code> matrix. For example, a sparse version of <code>A</code> can be produced with</p>\n\n<pre><code>sp.eye(N,N,0) + D * q * sp.diags([1, -2, 1], [-1, 0, 1], shape=(N, N))\n</code></pre>\n\n<p>But there isn't a speed advantage at this small size.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T20:13:19.037", "Id": "30101", "ParentId": "17702", "Score": "15" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T04:40:44.927", "Id": "17702", "Score": "6", "Tags": [ "python", "matlab", "numpy" ], "Title": "Python / Numpy running 15x slower than MATLAB - am I using Numpy effeciently?" }
17702
<p>I'm learning python and I want to model a <a href="http://en.wikipedia.org/wiki/Single-elimination_tournament" rel="noreferrer">single elimination tournament</a> like they use in athletic events like tennis, basketball, etc. The idea would be to insert some meaningful metrics to determine the winner. I've already got a database that I plan to connect to to get the metrics, but I am hoping to find a better way to "process" games in the tournament to move the winner to the next round, and eventually find the tournament winner.</p> <p><img src="https://i.stack.imgur.com/UOMVI.png" alt="16 team tournament"></p> <p>So far this is the best I have come up with, but it doesn't scale (at all easily) to 32, 64, 128 entries &amp; so-on. The "primary key" that I need to retain is the "seed id" (1-16, in this case), which matches the unique identifier in the database, so that I can pull the correct metrics for deciding which entry will win a matchup. Suggestions?</p> <pre><code>## this list represents the round 1 seeding order on the tournament sheet ## this doesnt easily scale to 32, 64, 128 entries teamlist = [1,16,8,9,5,12,4,13,6,11,3,14,7,10,2,15] #In a single elim tournament with a full field, # of games is # of teams-1 totalgames = len(teamlist) - 1 #Set defaults gameid = 0 roundid = 0 nextround = [] #simulate all of the games while gameid &lt; totalgames: if gameid in [8,12,14]: ##this is a manual decision tree, doesn't scale at all #if a new round begins, reset the list of the next round print "--- starting a new round of games ---" teamlist = nextround nextround = [] roundid = 0 #compare the 1st entry in the list to the 2nd entry in the list homeid = teamlist[roundid] awayid = teamlist[roundid + 1] #the winner of the match become the next entry in the nextround list #more realistic metrics could be substituted here, but ID can be used for this example if homeid &lt; awayid: nextround.append(homeid) print str(homeid) + " vs " + str(awayid) + ": The winner is " + str(homeid) else: nextround.append(awayid) print str(homeid) + " vs " + str(awayid) + ": The winner is " + str(awayid) #increase the gameid and roundid gameid += 1 roundid += 2 print "next round matchup list: " + str(nextround) print nextround </code></pre>
[]
[ { "body": "<p>You have two lines marked as \"doesn't scale\".</p>\n\n<p>The initial team list can be obtained from your database table of available teams (select of team details).</p>\n\n<p>The other \"problem line\", is</p>\n\n<pre><code> if gameid in [8,12,14]: ##this is a manual decision tree, doesn't scale at all\n</code></pre>\n\n<p>But that's easily avoided by noticing that the games in a round are always half the previous round, and the initial round is half the number of teams!</p>\n\n<p>In other words, you can do something like (if you include the initial round):</p>\n\n<pre><code>def NewRoundIds( teams_in_tournament ):\n round_ids = []\n game_id = 0\n games_in_next_round = len(teams_in_tournament)/2 #need to count the number of teams_in_tournament list\n while games_in_next_round &gt; 0:\n round_ids += [game_id]\n game_id += games_in_next_round\n games_in_next_round /= 2\n return round_ids\n\nnew_round_game_ids = NewRoundIds( teamlist )\n...\nif gameid in new_round_game_ids:\n # etc\n</code></pre>\n\n<p>== edit ==</p>\n\n<p>This puts it <em>well</em> outside the brief of the site, but it was interesting. The following I think does what you want, <code>generate_tournament(16)</code>. It could do with a bit of tidying up, and it's the sort of thing that will certainly benefit from docstrings and doctests, which I shall leave as a exercise.</p>\n\n<pre><code>import math\n\ndef tournament_round( no_of_teams , matchlist ):\n new_matches = []\n for team_or_match in matchlist:\n if type(team_or_match) == type([]):\n new_matches += [ tournament_round( no_of_teams, team_or_match ) ]\n else:\n new_matches += [ [ team_or_match, no_of_teams + 1 - team_or_match ] ]\n return new_matches\n\ndef flatten_list( matches ):\n teamlist = []\n for team_or_match in matches:\n if type(team_or_match) == type([]):\n teamlist += flatten_list( team_or_match )\n else:\n teamlist += [team_or_match]\n return teamlist\n\ndef generate_tournament( num ):\n num_rounds = math.log( num, 2 )\n if num_rounds != math.trunc( num_rounds ):\n raise ValueError( \"Number of teams must be a power of 2\" )\n teams = 1\n result = [1]\n while teams != num:\n teams *= 2\n result = tournament_round( teams, result )\n return flatten_list( result )\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T14:39:34.257", "Id": "28227", "Score": "0", "body": "Thanks Glenn, excellent suggestions. I will give them a try. Do you have any good suggeestions on how to create the initial \"team list\" without typing it all out? Is there some kind of algorithm that we could identify that would follow the structure of a tourney so I could just insert the team ids? Notice they are not just numbered 1-16 down the lefthand side of the diagram." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T16:28:51.980", "Id": "28235", "Score": "0", "body": "That rather depends on what you meant by \"I've already got a database that I plan to connect to to get the metrics\" - it sounded like you have everything like that in your database. If you want a list of random numbers `teamlist = [i + 1 for i in range( teams_in_tournament )`, `random.shuffle( teamlist )`. Not sure what you mean by the algorithm." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T17:08:38.030", "Id": "28241", "Score": "0", "body": "So, the \"seed id\" (1 through 16) is the \"primary key\" referenced in the database, but not the \"structure\" of the tournament (in regards to 'who plays who'). I do not want a randlom list, either, as in the first round team 1 plays 16, 9v8, etc. In the second round, the winner of team 1/16 needs to play the winner of 9/8, and so on... Make sense?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T22:36:05.667", "Id": "28259", "Score": "0", "body": "It does. Answer edited." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T03:04:57.457", "Id": "28265", "Score": "1", "body": "Wow...That's amazing! I knew there had to be a better way, and you found it. I really appreciate you putting so much thought into your answer. I definitely learned a lot!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T09:34:22.337", "Id": "17713", "ParentId": "17703", "Score": "3" } } ]
{ "AcceptedAnswerId": "17713", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T04:42:51.203", "Id": "17703", "Score": "7", "Tags": [ "python" ], "Title": "Using Python to model a single elimination tournament" }
17703
<p>In my project, they use Hibernate's session the below mentioned way and then save entity objects with in a transaction.</p> <pre><code>Session session = HibernateUtil.getCurrentSession(); session.beginTransaction(); Employee employee = new Employee() ; employee.setName("someName") ; employee.setEmailId ("someId") employee.setID (100000) ; session.saveOrUpdate(employee) ; session.getTransaction().commit(); </code></pre> <p>Now for few functionality I decided to run native SQL. Below is the way i used to run native sql. I wanted to run the queries with-in a transaction and so i decided to write the code the below way</p> <pre><code>String query = "select name from master_employee where id=?" Session session = HibernateUtil.getCurrentSession(); session.beginTransaction(); Connection connection = session.connection(); PreparedStatement psStmt = connection.prepareStatement(query); psStmt.setInt(1,id) ; ResultSet resultSet = psStmt.executeQuery(); // here i will take data from this result set psStmt.close(); resultSet.close() ; // I am not closing the connection object since am taking it from hibernate session // rather i commit hibernate's transaction session.getTransaction().commit(); </code></pre> <p>Is this the right way ?? will the transaction's still be managed ?? taking the connection object from session cannot be managed in to the transaction ????</p> <p>Please tell if there any problems in using this way ??? thanks</p>
[]
[ { "body": "<p>Since <a href=\"http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/querysql.html\" rel=\"nofollow\">Hibernate session provides APIs to run native SQL queries</a>, I would avoid extracting the connection from the session and leave the life cycle management of the Statement, ResultSet used for running native queries, to Hibernate Session itself. There must be some reason why they discourage the use of connection like this, directly and so it is being <a href=\"http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#connection%28%29\" rel=\"nofollow\">deprecated</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T16:20:49.957", "Id": "17726", "ParentId": "17708", "Score": "1" } } ]
{ "AcceptedAnswerId": "17726", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T07:34:37.913", "Id": "17708", "Score": "3", "Tags": [ "java", "hibernate" ], "Title": "Any problems in using hibernate's session.connection() to run native sql" }
17708
<p>I'm trying to improve my coding practices and I was just wondering if (I'm definitely sure there are) there are better ways of doing the following task.</p> <p>I'm rewriting the rent system of the building I live in, which currently (still) uses an Access '97 database. This is <a href="http://resunay.com/rent/schema.jpg" rel="nofollow">the schema</a> that I've constructed and the following code fetches the data to be used in the <a href="http://resunay.com/rent/" rel="nofollow">section just below the nav</a>.</p> <p>I just have a few questions.</p> <ol> <li><p>Am I doing too many queries? I'm pretty sure I cannot get all the information needed in just a single query (I've tried).</p></li> <li><p>Naming conventions, should I be using <code>$query1</code>, <code>$result1</code> etc or $person_query, $result_query. My logic is that, I don't need the resource variable again, why not reuse it? It's not like I create a new <code>$conn</code> each time.</p></li> <li><p>Is there a simpler way of getting data, without using any framework? I'm trying to solidify my own practices first before learning CakePHP. But perhaps CakePHP will force me to do that anyway.</p></li> </ol> <p></p> <pre><code>&lt;?php header('content-type: application/json; charset=utf-8'); //$_POST = json_decode(file_get_contents('php://input')); $host = "127.0.0.1:3306"; $db = "bettenhaus"; $user = "root"; $pass = ""; $rent_types[0] = "Mieter"; $rent_types[1] = "Untermieter"; $rent_types[2] = "Zwischenmieter"; $json_id = $_GET['id']; $conn = new PDO("mysql:host=$host;dbname=$db", $user, $pass, array(PDO::MYSQL_ATTR_INIT_COMMAND =&gt; "SET NAMES utf8")); // get basic info $query = "SELECT people.id, people.surname, people.firstname, people.email, leases.room_id, DATE_FORMAT(leases.in_date, '%e %M %Y') as in_date, DATE_FORMAT(leases.out_date, '%e %M %Y') as out_date, leases.rent_type FROM people, leases WHERE people.id = :json_id AND leases.person_id = :json_id"; $result = $conn-&gt;prepare($query); $result-&gt;bindValue(":json_id", $json_id); $result-&gt;execute(); // prepare to merge $person_info = $result-&gt;fetch(PDO::FETCH_ASSOC); // get lease info $query = "SELECT num as room_num, wg, rent FROM rooms WHERE id = :room_id"; $result = $conn-&gt;prepare($query); $result-&gt;bindValue(":room_id", $person_info['room_id']); $result-&gt;execute(); $room_info = $result-&gt;fetch(PDO::FETCH_ASSOC); // merge two results $all_info = array_merge($person_info, $room_info); $all_info['rent_type'] = $rent_types[$all_info['rent_type']]; // get all bills charged to this tenant $query = "SELECT SUM(amount) as debt FROM money_due WHERE person_id = :json_id"; $result = $conn-&gt;prepare($query); $result-&gt;bindValue(":json_id", $json_id); $result-&gt;execute(); $debt_info = $result-&gt;fetch(PDO::FETCH_ASSOC); // get total amount of money paid into the system by tenant $query = "SELECT sum(money_paid.amount) as sum FROM money_paid, money_due WHERE money_paid.money_for = money_due.id AND money_due.person_id = :json_id"; $result = $conn-&gt;prepare($query); $result-&gt;bindValue(":json_id", $json_id); $result-&gt;execute(); $paid_info = $result-&gt;fetch(PDO::FETCH_ASSOC); // calculate money owed to the house $all_info['balance'] = $paid_info['sum'] - $debt_info['debt']; $conn = null; echo json_encode($all_info); ?&gt; </code></pre>
[]
[ { "body": "<p><strong>Functions!</strong></p>\n\n<p>Functions are what this code needs. You've already started separating your code logically, which is the first step in creating functions. Just look at your comments. You can start by making each commented section its own function. Of course, this isn't the end of it. We still have to make our PDO connection and query parameters available to these functions, and ideally we will want to make them reusable as well, but it will help us get started. I'll do the first one for you.</p>\n\n<pre><code>function getPeople( $conn, $json_id ) {\n $query = \"SELECT people.id, people.surname, people.firstname, people.email, leases.room_id, DATE_FORMAT(leases.in_date, '%e %M %Y') as in_date, DATE_FORMAT(leases.out_date, '%e %M %Y') as out_date, leases.rent_type FROM people, leases WHERE people.id = :json_id AND leases.person_id = :json_id\";\n $result = $conn-&gt;prepare($query);\n $result-&gt;bindValue(\":json_id\", $json_id);\n $result-&gt;execute();\n return $result-&gt;fetch( PDO::FETCH_ASSOC );\n}\n</code></pre>\n\n<p>A function is a reusable script. Each function must have a unique name that should be indicative of its purpose. For instance, the above function sets up a query to get a list of people from a database and then returns the results. Thus its name tells us exactly what it is doing and it should do no more and no less. This is a principle called Single Responsibility. As the name implies, the function has one responsibility. Any additional tasks must be delegated to other functions. The two parameters, <code>$conn</code> and <code>$json_id</code>, are components that it needs to do its task. Instead of fetching these components each time, which is beyond the scope of this function's responsibilities, we inject them into our function via the parameters.</p>\n\n<p>Just like PHP, MySQL and PDO do not care about whitespace. I'm still unfamiliar with the SQL syntax to properly space that out for you, but know that you can add as many newlines and whitespace as you need to make that more legible, in fact I would encourage you to.</p>\n\n<p><strong>Reusing our Functions</strong></p>\n\n<p>So, I created the first function for you. If you went ahead and made the other functions, like I suggested, then you might hate me for this, but they will be unnecessary. It was good practice though. You only need one function here. There is a general programming principle called \"Don't Repeat Yourself\" (DRY). As the name implies, your code should not repeat itself. There are many different ways you can keep your code DRY (variables, loops, and functions to name a few), but we are specifically going to talk about not repeating functionality right now. However, these concepts should be easily transferable to the other aspects of DRY.</p>\n\n<p>How do we know if our code is DRY? If you look at all of those queries, you should begin to notice a pattern. They are all almost identical. This is a clear sign that we can apply the DRY principle. In order to do it with our functions we are going to have to abstract anything that is not exactly the same and inject those properties into our script through some other means. With functions we should do this with the parameters.</p>\n\n<pre><code>function query( $conn, $query, $params ) {\n $result = $conn-&gt;prepare( $query );\n\n foreach( $params AS $key =&gt; $value ) {\n $result-&gt;bindValue( \":$key\", $value );\n }\n\n $result-&gt;execute();\n return $result-&gt;fetch(PDO::FETCH_ASSOC);\n}\n\n//usage\n$params = array(\n ':json_id' =&gt; $json_id\n);\nquery( $conn, $query, $params );\n</code></pre>\n\n<p>As you should be able to see from this, you will no longer need to manually fetch each query, instead you can use this function and pass in the required components. But, as I mentioned above, DRY doesn't stop here. If we were to leave it at this then already our code would be 10 times better, but we are still violating DRY by manually calling our new query function each time we need it. Remember that I mentioned DRY didn't have to be all about functions? Well, how would you handle this? I'll give you a hint, but I'm not going to write this next bit for you.</p>\n\n<p>Mouseover for hint:</p>\n\n<blockquote class=\"spoiler\">\n <p> Try using an array and foreach loop.</p>\n</blockquote>\n\n<p><strong>Bonus</strong></p>\n\n<p>Another thing we can do to help ensure we get the right kind of parameters is to implement something called type hinting. This is a little more advanced and not something you really need to know right now, but simply put, if you add the type of variable you are expecting to get as a parameter, PHP will throw errors and stop execution if any other type is used. This is a good way to ensure our function can do what we are asking of it. For example, if we passed in a non PDO object we should not expect it to be able to use PDO methods, so we could prevent this by explicitly requiring the PDO type.</p>\n\n<pre><code>function getPeople( PDO $conn, $json_id ) {\n</code></pre>\n\n<p>You'll notice that only <code>$conn</code> has been type hinted. This is because <code>$json_id</code> is a scalar type and is unnecessary to type hint due to PHP's loose typing. If that variable happened to be an int and you needed a string you could just treat it as a string and it would work. And vice-versa. Sometimes this is undesirable and you will have to explicitly check for these types, but you can not do this with typehinting. Instead you would have to use one of the <code>is_*()</code> functions. Replace the wildcard with the type of variable you are looking for (int, string, etc...). You don't really need to understand this right now, but it is a good thing to keep in mind.</p>\n\n<p>Another, much more advanced topic, is OOP. Though I tell this to everyone, get proficient with functions and the concepts I mentioned above before trying to tackle OOP. Once you are fluent with functions, then you should take a look at classes and different OOP strategies.</p>\n\n<p><strong>UPDATE</strong></p>\n\n<p>Sorry for the delay in my answer. I'm typically unavailable over the weekend. This is much better, you still have a minor violation of DRY with that second <code>query()</code>, but overall it is much much better. Let's look at a couple things I missed last time and something new you are doing this time.</p>\n\n<p><strong>Connection</strong></p>\n\n<p>This is something I forgot to mention last time, but you should also abstract all of your connection information so that you can set this up to come from anywhere. Remove the following from your PDO instantiation and replace them with variables.</p>\n\n<pre><code>$dsn = \"mysql:host=$host;dbname=$db\";\n$params = array( PDO::MYSQL_ATTR_INIT_COMMAND =&gt; \"SET NAMES utf8\" );\n</code></pre>\n\n<p>The benefit of doing it like this is that you can now abstract all of your connection information to a config file or to any other source to allow for easier extension. The config file would be my suggestion for now as it is fairly simple to implement while still being a pretty powerful tool. I wont go into the specifics on how to implement one here, but a quick Google search should yield immediate results. You can also set up a PHP file with constants to serve as a config file.</p>\n\n<p><strong>Arrays</strong></p>\n\n<p>Another thing I missed was your array. First the <code>$rent_types</code> and now the <code>$queries</code>. Always define your array initially before pushing anything onto it.</p>\n\n<pre><code>$queries = array();\n$queries[ 'general' ] = //etc...\n</code></pre>\n\n<p>Of course, then the better way to do what you are trying to do is to just do it all at once. For instance.</p>\n\n<pre><code>$queries = array(\n 'general' =&gt; /*general SQL*/,\n 'owed' =&gt; /etc...\n);\n</code></pre>\n\n<p>The reason we do this is to avoid accidentally manipulating a preexisting array or string. With an array it probably wont be as noticeable, unless you end up needing that array again elsewhere, but the string should become immediately apparent. Strings can be accessed with array syntax to easier allow for specific character accessing. However, I believe trying to do so with an associative key would cause errors. Likewise, trying to later access a string's contents like an array would yield unexpected results, such as a single letter or NULL. Even if you are 100% sure that you aren't going to have any conflicts, just in case you ever need to extend this later, it is always better to explicitly define it. Besides, you are probably getting a warning initially about how that array is undefined. Make sure your error reporting is turned up so that you can catch these kinds of things.</p>\n\n<p><strong>Variable-Variables</strong></p>\n\n<pre><code>${$label}\n//or\n$$label\n</code></pre>\n\n<p>What you are doing here is called variable-variables. For the most part variable-variables, or variable-functions, should never be used. Assume they are, 99% of the time, a bad idea. There are exceptions (MVC Controllers rendering variables for Views and Factories dynamically accessing unknown functions are pretty common), but this is not one of them. The reason variable-variables are so disliked is because of how easy they are to miss, and thus debug. There is also a security concern, because the information you are typically converting to variables is from userland and thus untrustworthy.</p>\n\n<p>For instance, imagine this scenario: The very first thing you did was load your config file for your database connection, but, for some reason, you had to load variable-variables into scope before connecting. It could have been an accident, or a malicious user, but now your connection variables have been overwritten and break the system, or point to another database altogether. The problems just become bleaker and can get down right ugly.</p>\n\n<p>So, instead of using variable-variables, or variable-functions, what we are going to want to do is either do something with the information immediately, thus creating a temporary generic variable, or do the same thing you are currently doing, only with an array.</p>\n\n<pre><code>${$label} = //etc...\n//becomes\n$query_results[ $label ] = //etc...\n</code></pre>\n\n<p>As you can see, this is almost identical, except we are using a more verbose array instead. There is less security concern and ambiguity here. For instance, now if we have a key that conflicts with a variable in the current scope it wont interact with it in any way. It has been abstracted, or perhaps namespaced, and thus is safer. It also becomes easier to debug. Instead of having variable-variables that could easily hide among the current scope variables, all we have to do is <code>var_dump()</code> the array to peek at its contents. Everything is self-contained.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T21:19:53.627", "Id": "28258", "Score": "0", "body": "Hi, thanks very much for your help. It helped me a great deal. I'm not sure how to reply with code, it says it's too long. I guess I have to 'answer' my own question?\n\n*Actually, it told me to re-edit my original question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T14:47:57.473", "Id": "28347", "Score": "0", "body": "@sanlikestabbies: Yes, typically you will want to edit your question with any updates. Always append or prepend your new content, as you have done, and never delete the original to avoid confusing the context. Sometimes small bits of code can be included in comments by wrapping it in back ticks(tilde key/that squiggly line next to the 1). I have updated my answer to address your other questions, sorry for the delay." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T19:12:44.957", "Id": "17731", "ParentId": "17717", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T12:15:39.973", "Id": "17717", "Score": "3", "Tags": [ "php", "pdo" ], "Title": "Rewriting the rent system of a building" }
17717
<p>I have a form. When I click the <kbd>save</kbd> button, I want to create an object from the data and pass that info to HTML elements on the same page (div.form_content). </p> <p>I decided, instead of creating a variable for each HTML element to create an array of HTML elements. I know the first HTML element is going to contain the first object property, the second html element will contain the second obj property, and so on...</p> <p>What I have done below seems a little repetitive and not very DRY, and I was wondering if someone could recommend a better way. For example, if my form has to grow to 12 input fields, what I am doing now would be pretty clunky. I tried running a loop to prevent the line-by-line assignments, but couldn't figure it out. (By the way, I needed to create an object from the form data because I will need to stringify it to JSON notation to pass to the server, but I got that part.)</p> <pre><code>$('#save').click(function() { var form_Array = $('form').serializeArray(); // Create an Array of HTML elements var el_Array = $('div.form_content').children(); // create empty object var obj = {}; // loop through serialized form object and assign new object keys from this.name and their values from this.value $.each(form_Array, function() { obj[this.name] = this.value; }); // populate the html elements with contents of the newly created object $(el_Array[0]).html(obj.fname); $(el_Array[1]).html(obj.lname); $(el_Array[2]).html(obj.phone); $(el_Array[3]).html(obj.fax); }); </code></pre>
[]
[ { "body": "<p>I'd say give your \"output\" elements a <code>data-*</code> attribute that matches the name of the form value it should contain. For instance:</p>\n\n<pre><code>​&lt;div​​​ class=\"form_content\"&gt;\n &lt;div data-key=\"fname\"&gt;&lt;/div&gt;\n &lt;div data-key=\"lname\"&gt;&lt;/div&gt;\n &lt;div data-key=\"phone\"&gt;&lt;/div&gt;\n &lt;div data-key=\"fax\"&gt;&lt;/div&gt;\n&lt;/div&gt;​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​\n</code></pre>\n\n<p>Then, you can do something like:</p>\n\n<pre><code>$('#save').click(function() {\n var values = $('form').serializeArray(),\n output = $('#values');\n\n $.each(values, function() {\n output.children(\"[data-key='\" + this.name + \"']\").text(this.value);\n });\n});\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/rm7jK/1/\" rel=\"nofollow\">Here's a demo</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T23:45:59.483", "Id": "28263", "Score": "0", "body": "thanks a lot, that worked great...sorry, don't have enough cred to upvote" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T14:25:36.613", "Id": "17722", "ParentId": "17720", "Score": "3" } } ]
{ "AcceptedAnswerId": "17722", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T13:31:23.220", "Id": "17720", "Score": "1", "Tags": [ "javascript", "jquery" ], "Title": "Form data to object to HTML" }
17720
<p>Since I'm learning F# along with functional programming, I managed to implement the rules for Conway's Game of Life. I'm not sure if I can improve some of its parts, though. For example, the <code>neighbours</code> function does an ugly range testing, but I can't think of anything simpler.</p> <pre><code>module Game open System type Cell = | Alive | Dead let amount_neighbours (board: Cell[,]) (pos: int * int) = let range (n: int) (limit: int) = let min = if n &lt; 1 then 0 else n - 1 let max = if n &gt; (limit - 2) then (limit - 1) else n + 1 [min .. max] let x_range = range (fst pos) (Array2D.length1 board) let y_range = range (snd pos) (Array2D.length2 board) List.sum [for x in x_range -&gt; List.sum [for y in y_range -&gt; if board.[x, y] = Alive &amp;&amp; (x, y) &lt;&gt; pos then 1 else 0]] let lifecycle (board: Cell[,]) = Array2D.init (Array2D.length1 board) (Array2D.length2 board) (fun i j -&gt; let neighbours = amount_neighbours board (i, j) match neighbours with | 2 -&gt; board.[i, j] | 3 -&gt; Alive | _ -&gt; Dead) let rec process_game (board: Cell[,]) (n: int) = match n with | x when x &gt; 0 -&gt; printfn "Iteration" printfn "%A" board process_game (lifecycle board) (n - 1) | _ -&gt; 0 [&lt;EntryPoint&gt;] let main args = let board = Array2D.init 5 5 (fun i j -&gt; if i = 2 &amp;&amp; j &gt; 0 &amp;&amp; j &lt; 4 then Alive else Dead) ignore (process_game board 4) 0 </code></pre>
[]
[ { "body": "<p>I thought it would make sense if you created a function <code>alive</code>, which would take care of bounds checking for you. And also simplify the the final expression by using a single sequence expression instead of two like you do.</p>\n\n<p>But I'm not sure it's actually much better than your version:</p>\n\n<pre><code>let amount_neighbours (board: Cell[,]) (pos: int * int) =\n let alive board pos = \n let (x, y) = pos\n if x &lt; 0 || x &gt;= Array2D.length1 board ||\n y &lt; 0 || y &gt;= Array2D.length2 board then\n false\n else\n board.[x, y] = Alive\n\n let vicinity x = seq { x - 1 .. x + 1 }\n\n seq {\n for x in vicinity (fst pos) do\n for y in vicinity (snd pos) do\n if (x, y) &lt;&gt; pos &amp;&amp; alive board (x, y) then\n yield true\n } |&gt; Seq.length\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T19:00:47.997", "Id": "28287", "Score": "0", "body": "Well, this is a good improvement IMO. I'll vote up as soon as I can! Thanks." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T13:11:16.020", "Id": "17749", "ParentId": "17723", "Score": "3" } } ]
{ "AcceptedAnswerId": "17749", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T15:57:11.433", "Id": "17723", "Score": "4", "Tags": [ "f#", "game-of-life" ], "Title": "Conway's Game of Life in F#" }
17723
<p>Basically I have some methods that access the file system and to avoid that in the unit test I have broken those sections out into a protected virtual method. In the Unit Test I then use Moq to setup those protected methods the way I want. I am just curious if I am going about this correctly or is there a better way? Below is an example method I have done this with however I have several places I do this with.</p> <p>Method that gets unit tested: </p> <pre><code>public IEnumerable&lt;ConfigProfile&gt; GetSavedProfiles(string product) { if(string.IsNullOrEmpty(product)) { throw new ArgumentNullException("product"); } string profileDirectory = _factory.GetCustomProfileDirectory(product); List&lt;ConfigProfile&gt; profiles = Enumerable.Empty&lt;ConfigProfile&gt;().ToList(); _logger.Debug("Getting Saved profiles."); IList&lt;FileInfo&gt; files = GetProfilesInDirectory(profileDirectory).ToList(); if (!files.Any()) { _logger.Debug(string.Format("No custom profiles found for {0}.", product)); return profiles; } profiles.AddRange(files.Select(LoadProfile)); return profiles; } </code></pre> <p>Then I have these two protected methods I have taken out and setup in my unit test:</p> <pre><code>protected virtual IEnumerable&lt;FileInfo&gt; GetProfilesInDirectory(string directory) { DirectoryInfo files = new DirectoryInfo(directory); return files.EnumerateFiles("*.ecu"); } </code></pre> <p></p> <pre><code>protected virtual ConfigProfile LoadProfile(FileInfo file) { ConfigProfile profile; using (FileStream stream = new FileStream(file.FullName, FileMode.Open)) { profile = _serializer.DeserializeFromDisk(stream); } return profile; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T17:26:18.717", "Id": "28242", "Score": "0", "body": "Look at http://systemwrapper.codeplex.com for a different approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T17:57:09.280", "Id": "28245", "Score": "0", "body": "Nice that does look very helpful. If you want to create a post I will mark it as my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T18:27:21.597", "Id": "28249", "Score": "1", "body": "As an aside, I would suggest you avoid serializing objects, as can cause problems if you ever need to change assembly versions or even the .NET runtime you use. I've been bitten a number of times by legacy code which does this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T18:47:20.683", "Id": "28252", "Score": "1", "body": "How would you suggest I persist those objects to disk then?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T17:12:54.023", "Id": "142470", "Score": "0", "body": "Serialization is fine in principle, but I'd avoid `BinaryFormatter` in favour of a well defined format based on the public properties of an object. It might be a good idea to use special DTO classes for serialization instead of the model itself." } ]
[ { "body": "<p>Another approach is to use a wrapper for the DirectoryInfo, FileInfo and FileStream. Then your methods can use the wrappers and inject your mocks in the unit tests. Several people have already thought of this and have written the wrappers for you. </p>\n\n<p>The one I like is <a href=\"http://systemwrapper.codeplex.com/\">SystemWrapper</a>. Their <a href=\"http://systemwrapper.codeplex.com/wikipage?title=FileInfo%20Tutorial&amp;referringTitle=Home\">sample</a> page shows some good examples.</p>\n\n<p>Of course, you still have the challenge of refactoring your code to inject the wrappers into your method, since creating a new instance of the wrappers within the code leaves you the same problem. The simpliest approach to injecting wrappers is to pass them in as parameters. But, since the constructor of the wrappers needs information obtained within the method this is more difficult in your case. You may consider breaking your method into several methods in a manner such as this...</p>\n\n<p><em>NOTE: This code will not compile. I am just trying to give you an idea of how to break up the method to make it unit testable. In the end, every method cannot be unit tested. The key is to break it up into small enough methods so as much code as possible is tested.</em></p>\n\n<pre><code>public IDirectoryInfoWrap GetDirectoryInfoWrapper(string product)\n{\n if(string.IsNullOrEmpty(product)) \n { \n throw new ArgumentNullException(\"product\"); \n } \n\n string profileDirectory = _factory.GetCustomProfileDirectory(product); \n return new DirectoryInfoWrap(profileDirectory);\n}\n\npublic IList&lt;FileInfo&gt; GetProfileFiles(IDirectoryInfoWrap di) \n{ \n _logger.Debug(\"Getting Saved profiles.\"); \n\n // NOTE: EnumerateFiles is not in the SystemWrapper so you will have to use an alternative\n IList&lt;FileInfo&gt; files = di.EnumerateFiles(\"*.ecu\").ToList(); \n return files;\n }\n\n// Left for you to do...refactor in a manner so that FileSystem is using the IFileSystemWrap\npublic IEnumerable&lt;ConfigProfile&gt; GetSavedProfiles(IList&lt;FileInfo&gt; files)\n{\n List&lt;ConfigProfile&gt; profiles = Enumerable.Empty&lt;ConfigProfile&gt;().ToList(); \n if (!files.Any()) \n { \n _logger.Debug(string.Format(\"No custom profiles found for {0}.\", product)); \n return profiles; \n } \n\n profiles.AddRange(files.Select(LoadProfile)); \n\n return profiles; \n\n} \n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-03-01T03:29:23.490", "Id": "149025", "Score": "4", "body": "[System.IO.Abstractions](https://github.com/tathamoddie/System.IO.Abstractions) is another option." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T18:24:53.183", "Id": "17729", "ParentId": "17725", "Score": "8" } }, { "body": "<p>Actually you can pass <code>File.Delete</code> as parameter of the function - e.g </p>\n\n<pre><code>private void Method( Action&lt;string&gt; deleteFile)\n</code></pre>\n\n<p>And in Unit Test just do following</p>\n\n<pre><code>Method((file) =&gt; { &lt;VALIDATION&gt; };\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-06-04T00:33:35.007", "Id": "221618", "ParentId": "17725", "Score": "1" } } ]
{ "AcceptedAnswerId": "17729", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T16:18:48.680", "Id": "17725", "Score": "10", "Tags": [ "c#", "unit-testing", "file-system", "moq" ], "Title": "Unit tests for methods that access the file system" }
17725
<p>Please review the following code. Methods <code>getFirsts</code> and <code>getSeconds</code>, both of which are <code>private</code>, return a list of objects which implement <code>CommonInterface</code>. Is this a good or bad design?</p> <pre><code>@Override public final List&lt;? extends CommonInterface&gt; getObjects(final CommonEnum type) { if (type == null) { return new ArrayList&lt;CommonInterface&gt;(); } switch (type) { case FIRST: return getFirsts(); case SECOND: return getSeconds(); default: return null; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T22:41:41.850", "Id": "28260", "Score": "3", "body": "If this list returned through getFirsts or getSeconds are mutable, you have to realize that you are exposing the lists to mutation to any caller of \"getObjects\" (which is public)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T22:46:21.770", "Id": "28261", "Score": "0", "body": "my idea was to expose only one method in the interface and hide the if else/ switch logic in one method, to prevent such statements in other places in the code and to get by the caller the list of appropriate objects only by CommonEnum value. I am asking because I often using such structures so I'm curious the opinions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T04:32:54.440", "Id": "28267", "Score": "2", "body": "Cory's point is that by returning the actual private list you are allowing callers to modify it directly. If this is what you want, perhaps you might want to rethink that part of your design. Also, why is `null` an acceptable value for `type`? It would help to have a concrete example with how you use this idiom." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T06:38:48.650", "Id": "28271", "Score": "0", "body": "@corykendall: I think your comment would be worth an answer." } ]
[ { "body": "<p>It's hard to say anything since it seems rather a pseudo-code. Anyway, two notes which you might find useful:</p>\n\n<ol>\n<li><p>I guess you could replace the switch-case structure with polymorphism. Two useful reading:</p>\n\n<ul>\n<li><em>Refactoring: Improving the Design of Existing Code</em> by <em>Martin Fowler</em>: <em>Replacing the Conditional Logic on Price Code with Polymorphism</em></li>\n<li><a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\">Replace Conditional with Polymorphism</a></li>\n</ul></li>\n<li><p>Are you sure that returning <code>null</code> in the <code>default</code> is fine? I'd consider returning an empty list (as it returns when <code>type == null</code>) or throwing an exception (<code>IllegalStateException</code>, for example) if it's a programming error. (See: <em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T06:36:46.750", "Id": "17744", "ParentId": "17734", "Score": "7" } } ]
{ "AcceptedAnswerId": "17744", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T22:32:43.457", "Id": "17734", "Score": "7", "Tags": [ "java", "design-patterns" ], "Title": "Returning a list of objects" }
17734
<p>The following code should be mostly OK, but I'm trying to avoid any stylistic problems or find anything that I overlooked.</p> <p>The code is an implementation of asynchronous leadership election on a one way ring.</p> <p>Parts of the implementation are a bit unnatural, because it has some forced features.</p> <p><strong>main.cpp</strong></p> <pre><code>#include &lt;iostream&gt; #include "node.h" #include &lt;thread&gt; #include &lt;algorithm&gt; #include &lt;stdexcept&gt; #include &lt;unistd.h&gt; using namespace std; int main() { // initialization reset_sent_messages(); srand(time(NULL)); // prepare the array const unsigned total_nodes = 1000; vector&lt; shared_ptr&lt;Node&gt; &gt; nodes; nodes.reserve(total_nodes); // create nodes, put them into array for (unsigned i = 0; i &lt; total_nodes; ++i) nodes.push_back(make_shared&lt;Node&gt;(i+1)); // shuffle the nodes randomly random_shuffle(nodes.begin(),nodes.end()); // connect the nodes for (unsigned i = 0; i &lt; total_nodes-1; ++i) nodes[i]-&gt;connect(nodes[i+1]); nodes[total_nodes-1]-&gt;connect(nodes[0]); // prepare the futures to store the elected leader information vector&lt; future&lt;int&gt; &gt; leaders; for (auto i : nodes) leaders.push_back(i-&gt;get_leader()); // run the threads with the main node logic for (auto i : nodes) thread([](shared_ptr&lt;Node&gt; node) { node-&gt;logic(); },i).detach(); /* NOTE: * For demonstrational purposes we are using promise&lt;-&gt;future for final * synchronization. This is a very unnatural model. Normaly we wouldn't * detach the threads and use join(). * * Do note that if a thread isn't detached and the thread variable (returned * by thread call) is destroyed, the program will be immediately terminated. * This is due to the fact, that such thread would be effectively leaked. * Not running in detached mode, but incapable of joining the spawn thread. */ // do the final synchronization (so that main doesn't end before the algorithm does) for (unsigned i = 0; i &lt; total_nodes; i++) { if (leaders[i].get() != (int)total_nodes) throw runtime_error("Node didn't correctly detect it's leader."); } // final reports cout &lt;&lt; "Asynchronous run finished." &lt;&lt; endl; cout &lt;&lt; "Total number of sent messages was : " &lt;&lt; sent_messages() &lt;&lt; endl; return 0; } </code></pre> <p><strong>node.h</strong></p> <pre><code>#ifndef NODE_H #define NODE_H #include &lt;queue&gt; #include &lt;mutex&gt; #include &lt;memory&gt; #include &lt;future&gt; #include &lt;atomic&gt; class Node { public: Node(unsigned node_id); /** \brief Put a new message into this nodes message buffer */ void receive_message(int node_id, int distance); /** \brief Put a new message into this nodes message buffer */ void receive_message(const std::pair&lt;int,int&gt;&amp; message); /** \brief Connect this node to a next node in the circle */ void connect(std::shared_ptr&lt;Node&gt; next); /** \brief Node logic */ void logic(); /** \brief Get the leader node id */ std::future&lt;int&gt; get_leader(); private: /** \brief Try to pull one message from the buffer * * Non-blocking operation. */ bool checkout_message(std::pair&lt;int,int&gt;&amp; message); /** \brief Transmit one message to the connected node * * Blocking operation. */ void transmit_message(int node_id, int distance); /** \brief Sub logic for processing the message * * Process the received message * - detection of leader * - detection of transiting state * - trasmition of appropriate messages */ void process_message(int n_id1, int n_id2); /** \brief Sub logic for transiting nodes * * Simple re-trasmit routine. */ void transit_loop_step(); private: std::queue&lt;std::pair&lt;int,int&gt; &gt; p_message_buffer; std::mutex p_message_buffer_lock; std::weak_ptr&lt;Node&gt; p_next; std::mutex p_next_lock; int p_id; bool p_transit; bool p_done; std::promise&lt;int&gt; p_leader; }; extern std::atomic&lt;unsigned&gt; message_count; /** \brief Return count of sent messages */ unsigned sent_messages(); /** \brief Reinitialize the count of sent messages back to zero */ void reset_sent_messages(); #endif // NODE_H </code></pre> <p><strong>node.cpp</strong></p> <pre><code>#include "node.h" #include &lt;thread&gt; #include &lt;iostream&gt; #include &lt;stdexcept&gt; using namespace std; atomic&lt;unsigned&gt; message_count; unsigned sent_messages() { return message_count; } void reset_sent_messages() { message_count = 0; } static mutex cout_lock; // helper routine to output full lines from the algorithm #define atomic_log(x) do { cout_lock.lock(); cout &lt;&lt; x; cout_lock.unlock(); } while(0) Node::Node(unsigned node_id) : p_id(node_id), p_transit(false), p_done(false) { if (node_id == 0) throw range_error("Node id has to be greater than 0."); } void Node::receive_message(const pair&lt;int,int&gt; &amp;message) { // simple blocking implementation p_message_buffer_lock.lock(); p_message_buffer.push(message); p_message_buffer_lock.unlock(); } void Node::receive_message(int node_id, int distance) { receive_message(make_pair(node_id,distance)); } bool Node::checkout_message(std::pair&lt;int,int&gt;&amp; message) { // try to lock the message buffer for this thread // if it's locked, return false and wait a bit using yield if (!p_message_buffer_lock.try_lock()) { this_thread::yield(); return false; } // if we don't have any messages, yield and return false if (p_message_buffer.size() == 0) { p_message_buffer_lock.unlock(); this_thread::yield(); return false; } // we have a message, retrieve it, and remove from buffer message = p_message_buffer.front(); p_message_buffer.pop(); // don't forget to unlock p_message_buffer_lock.unlock(); return true; } void Node::connect(shared_ptr&lt;Node&gt; next) { // simple blocking implementation // only needed if connecting is done asynchronously p_next_lock.lock(); p_next = next; p_next_lock.unlock(); } void Node::transmit_message(int node_id, int distance) { shared_ptr&lt;Node&gt; next; // if the node isn't connected yet, do blocking wait while(1) { p_next_lock.lock(); next = p_next.lock(); if (next) break; p_next_lock.unlock(); this_thread::yield(); } next-&gt;receive_message(node_id,distance); p_next_lock.unlock(); ++message_count; } void Node::process_message(int n_id1, int n_id2) { /* detection of leader * * - trasmit notification message telling other nodes * - set self as leader * - mark algorithm as done */ if (n_id1 == p_id || n_id2 == p_id) { atomic_log("Node [ " &lt;&lt; p_id &lt;&lt; " ] self-declared leader." &lt;&lt; endl); transmit_message(p_id,-1); p_leader.set_value(p_id); p_done = true; } /* detection of transit mode * * - mark the state */ else if (n_id1 &gt; p_id || n_id2 &gt; p_id) { p_transit = true; atomic_log("Node [ " &lt;&lt; p_id &lt;&lt; " ] switched into transit mode." &lt;&lt; endl); } /* if the node is not yet a leader, or in transit mode re-send the base messages */ else { transmit_message(p_id,1); transmit_message(p_id,2); } } void Node::transit_loop_step() { /* single step in transit mode * * - read a single message and re-transmit it to the next node * - if the message is a leader notification, mark the leader node */ pair&lt;int,int&gt; message; if (checkout_message(message)) transmit_message(message.first,message.second); if (message.second == -1) { atomic_log("Node [ " &lt;&lt; p_id &lt;&lt; " ] recognized node [ " &lt;&lt; message.first &lt;&lt; " ] as the leader node." &lt;&lt; endl); p_leader.set_value(message.first); p_done = true; } this_thread::yield(); } void Node::logic() { transmit_message(p_id,1); transmit_message(p_id,2); int message1 = 0, message2 = 0; while (true) { // if the algorithm is done, simply exit the thread if (p_done) return; // if in transit mode, run a single step of transmit logic if (p_transit) { transit_loop_step(); } // if we have two messages, process them else if (message1 != 0 &amp;&amp; message2 != 0) { process_message(message1,message2); message1 = 0; message2 = 0; } // if we don't have two messages, receive new messages else { pair&lt;int,int&gt; message; if (checkout_message(message)) { if (message1 == 0) { message1 = message.first; if (message.second == 2 &amp;&amp; message.first &gt; p_id) transmit_message(message.first,1); } else { message2 = message.first; if (message.second == 2 &amp;&amp; message.first &gt; p_id) transmit_message(message.first,1); } } } this_thread::yield(); } } future&lt;int&gt; Node::get_leader() { return p_leader.get_future(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-06-14T06:37:05.863", "Id": "42585", "Score": "0", "body": "I'm really late here, but I thought I'd chime in and say it looks pretty good in general. I'd consider using a `std::unique_lock` though instead of manually calling `lock()` and `unlock()` on the mutex: eg, `std::unique_lock<std::mutex>(p_message_buffer_lock);`. This guarantees that even in the case of an exception, the `mutex` will be unlocked." } ]
[ { "body": "<p>First, a general observation: you have a fair number of typos in your comments. Although the compiler doesn't check such things, I prefer to think of the comments as an integral part of the code, so even minor typos should be fixed.</p>\n\n<ul>\n<li>Random numbers</li>\n</ul>\n\n<p>Right now, you're using <code>srand()</code> and <code>random_shuffle</code>. Although they were quite new when this question was written, at least if you were doing this today, you'd almost certainly want to use the \"new\" C++11 random number generators and <code>std::shuffle</code> instead.</p>\n\n<ul>\n<li>Locking</li>\n</ul>\n\n<p>In a number of places, you have a pattern of locking, carrying out some action, then unlocking, such as:</p>\n\n<pre><code>void Node::receive_message(const pair&lt;int,int&gt; &amp;message)\n{\n // simple blocking implementation\n p_message_buffer_lock.lock();\n p_message_buffer.push(message);\n p_message_buffer_lock.unlock();\n}\n</code></pre>\n\n<p>For such a case, I'd prefer to use <code>std::lock_guard</code>:</p>\n\n<pre><code>void Node::receive_message(const pair&lt;int, int&gt; &amp;message) { \n std::lock_guard guard(pmessage_buffer_lock);\n p_message_buffer.push(message);\n}\n</code></pre>\n\n<p>This makes the code a little shorter and simpler (not a big deal, but not a bad thing by any means), but much more importantly it adds quite a bit of exception safety. If (for example) <code>p_message_buffer.push()</code> were to throw an exception, your code wouldn't unlock the lock, but this will.</p>\n\n<ul>\n<li>Magic numbers</li>\n</ul>\n\n<p>You have magic numbers sprinkled rather liberally throughout the code. For example:</p>\n\n<pre><code>transmit_message(p_id,1);\ntransmit_message(p_id,2);\n</code></pre>\n\n<p>Until or unless you've looked at <code>transmit_message</code>, it may not be obvious that these are distances. Even if it's only useful from a documentation viewpoint, I'd at least consider creating a type specifically to represent a transmission distance, and probably give it an explicit constructor, so these would look something like:</p>\n\n<pre><code>transmit_message(p_id, hops(1));\ntransmit_message(p_id, hops(2));\n</code></pre>\n\n<p>This seems to me to make the code considerably more self-explanatory, even <code>hops</code> ends up doing essentially nothing other than giving a name/context for the numbers.</p>\n\n<ul>\n<li>shared_ptr</li>\n</ul>\n\n<p>At least as I read things, the ring of nodes doesn't look like a particularly good use-case for <code>std::shared_ptr</code>. In particular, <code>shared_ptr</code> is intended to represent shared ownership. Using <code>shared_ptr</code> basically asserts that each node in the ring <em>owns</em> its successor node, which doesn't seem very accurate. Equally bad, a ring (or cycle in general) is a case where <code>shared_ptr</code> (or reference counting in general) doesn't work correctly. Each item in the cycle has a reference to the next, so every item always has a non-zero reference count (so they never get cleaned up) even when none of them is accessible any more.</p>\n\n<ul>\n<li>Comments redux</li>\n</ul>\n\n<p>One other point about comments: right now it seems to me that the comments are really at too low a level to be particularly useful. Just for an obvious example, at some point I'd like to see an explanation of the actual algorithm this is intended to implement. That might well be only a sentence or two like: `send a message around the ring asking who's the leader. Iff the message arrives back at the originating node without any other node claiming leadership, then that node claims leadership.\"</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-03T16:00:45.760", "Id": "43313", "ParentId": "17736", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T00:08:58.503", "Id": "17736", "Score": "7", "Tags": [ "c++", "c++11", "asynchronous" ], "Title": "Asynchronous leadership election" }
17736
<p>I implemented reversing a linked list in iterative way, just by knowing we need 3 pointers and I have never seen a code before, when I coded. I ran this code and tested it, it works fine. Even for null element and one element. But all the implementations on net have slightly different code. I was just wondering, how my algorithm is.</p> <p>Do you guys see any major concern in my implementation?</p> <pre><code>int reverse(List *l) { if(!l) { printf("List is NULL \n"); return -1; } if(!l-&gt;head) { printf("List is empty \n"); return -1; } Node *prev_node = l-&gt;head; Node *curr_node = l-&gt;head-&gt;next; while(curr_node) { prev_node-&gt;next = curr_node-&gt;next; curr_node-&gt;next = l-&gt;head; l-&gt;head = curr_node; curr_node = prev_node-&gt;next; } return 0; } </code></pre>
[]
[ { "body": "<p>Try this code, it's a bit easier to follow. Also, you define the return type as int, but you're not returning anything meaningful, so you should change the function to void.</p>\n\n<pre><code>void reverse(Node* &amp; node)\n{\n if(!node)\n {\n cerr &lt;&lt; \"The node doesn't exist \\n\" &lt;&lt; endl;\n return;\n }\n\n Node* curr;\n Node* prev = NULL;\n\n while(node != NULL)\n {\n curr = node-&gt;next;\n node-&gt;next = prev;\n prev = node;\n node = curr;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T07:19:48.583", "Id": "28272", "Score": "2", "body": "You needn't to check node in the if block, since you did it in the while loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T08:43:30.450", "Id": "28274", "Score": "1", "body": "Good call. The error message is unnecessary I'd say." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T16:03:01.750", "Id": "28283", "Score": "2", "body": "This code doesn't work. The `node` pointer is passed by value so the caller's copy of the pointer is unchanged. The typical solution is to return the new `head` value (see zdd's answer)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T19:31:20.517", "Id": "28288", "Score": "0", "body": "Yeah that was my bad, forgot to add the by ref." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T06:26:35.520", "Id": "17743", "ParentId": "17741", "Score": "6" } }, { "body": "<p>If you don't care about the origin list, we can use the head of it as the iterator, You should return the new head after reverse, or the new list will lost.\n<img src=\"https://i.stack.imgur.com/MU8yB.png\" alt=\"enter image description here\"></p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nstruct Node\n{\n int data;\n Node* next;\n Node(int value, Node* ptr):data(value), next(ptr){} \n};\n\n// Reverse list and return the new head\nNode* reverse_list(Node* head)\n{\n Node* p = NULL;\n Node* q = head;\n while(q)\n {\n Node* t = q-&gt;next;\n q-&gt;next = p;\n p = q;\n q = t;\n }\n\n return p; // new head\n}\n\nvoid print_list(Node* head)\n{\n Node* t = head;\n while(t)\n {\n printf(\"%d\\n\", t-&gt;data);\n t = t-&gt;next;\n }\n}\n\nvoid main()\n{\n Node* head = new Node(1, NULL);\n Node* p = head;\n for(int i = 2; i &lt; 10; ++i)\n {\n p-&gt;next = new Node(i, NULL);\n p = p-&gt;next;\n }\n print_list(head);\n\n Node* newHead = reverse_list(head);\n print_list(newHead);\n\n getchar();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T07:18:55.510", "Id": "17745", "ParentId": "17741", "Score": "8" } }, { "body": "<p>I would suggest changing the return type to a pointer to the list, and drop all of your error messages -- they aren't relevant. If passed in null, return null.</p>\n\n<p>In general you should seperate your logic from your UI as much as possible -- and this function needs no UI. Even if you consider this a form of error/exception handling, you should not be doing it in this case as there's no reason to allow this code to fail -- you are not allocating new memory, the only thing that can go wrong is not enough stack space, which happens before your code runs.</p>\n\n<p>Elsewhere you may care about whether the list is empty or the pointer to the list is null, but not in the code to reverse the list -- it should be foolproof.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T02:45:27.957", "Id": "17799", "ParentId": "17741", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T05:57:10.987", "Id": "17741", "Score": "13", "Tags": [ "c", "algorithm", "interview-questions", "linked-list" ], "Title": "Reversing a linked list" }
17741
<p>So this is an app I'm working on, and I'd like to get some feedback on it. I'm leaving some key parts out, as I don't want everyone everywhere to have access to the complete code. The main pieces that I would like you guys to look at are still there though.</p> <pre><code>// Does a remote AJAX request that scrapes the URL and parses it function doAjax(url) { $.getJSON(URL, function (data) { if (data.results[0]) { $("#content").html(""); // Reset var number = $(filterData(data.results[0])).find("#gtv_leftcolumn table:gt(1)"); for (var i = 0; i &lt; number.length; i++) { var name = $(filterData(data.results[0])).find("#gtv_leftcolumn table:gt(1) .maintext p:eq(" + i + ")").text(); var type = $(filterData(data.results[0])).find("#gtv_leftcolumn table:gt(1) .trafficbriefs:nth-child(even) p:eq(" + i + ")").text(); // Redacted } if (doAjax) { // Redacted if (number.length === 0) { // Checks to see if there are any elements on the page, and if 0, runs this // Redacted } else { checkFavorite(); var mySearch = $('input#id_search').quicksearch('#content .row', { clearSearch: '#clearsearch' }); mySearch.cache(); console.log("Loaded " + number.length); console.log("Cached"); } } } else { console.log("error"); } }); } function filterData(data) { data = data.replace(/&lt;?\/body[^&gt;]*&gt;/g, ''); data = data.replace(/[\r|\n]+/g, ''); data = data.replace(/&lt;--[\S\s]*?--&gt;/g, ''); data = data.replace(/&lt;noscript[^&gt;]*&gt;[\S\s]*?&lt;\/noscript&gt;/g, ''); data = data.replace(/&lt;script[^&gt;]*&gt;[\S\s]*?&lt;\/script&gt;/g, ''); data = data.replace(/&lt;script.*\/&gt;/, ''); data = data.replace(/&lt;img[^&gt;]*&gt;/g, ''); return data; } // On Load doAjax("http://www.codekraken.com/testing/snowday/wgrz.html"); $("#info").click(showInfo); $(".info").click(closeInfo); $("#reload").click(reaload); $("#clearsearch").click(clearSearchBox); $(".clear").click(clearFavorite); setFavorite(); // You can clear the favorite item you set in setFavorite() function clearFavorite() { localStorage.removeItem("favorite"); localStorage.removeItem("favorite-status"); $(".star-inside").removeClass("favorite"); $(".clear span").text(""); } // Clear search box function clearSearchBox() { $("#id_search").val(""); $('#id_search').trigger('keyup'); } // Show info box function showInfo() { // Redacted } // Close info box function closeInfo() { // Redacted } // Reload AJAX request function reload() { closeInfo(); doAjax("URL"); } // Set favorite item. This enables you to swipe on any .row element, and once it swipes, it sets the row you swipe on as the favorite. Swiping again unfavorites it. I mainly want help on this, as far as cleaning it up. function setFavorite() { var threshold = { x: 30, y: 10 }; var originalCoord = { x: 0, y: 0 }; var finalCoord = { x: 0, y: 0 }; function touchMove() { console.log(event.targetTouches); finalCoord.x = event.targetTouches[0].pageX; changeX = originalCoord.x - finalCoord.x; var changeY = originalCoord.y - finalCoord.y; if (changeY &lt; threshold.y &amp;&amp; changeY &gt; (threshold.y * -1)) { changeX = originalCoord.x - finalCoord.x; if (changeX &gt; threshold.x) { window.removeEventListener('touchmove', touchMove, false); $(document).off("touchmove", ".row"); if ($(event.target).attr("class") === "row-inside") { var element = $(event.target); } if ($(event.target).attr("class") === "row-l") { var element = $(event.target).parent(); } if ($(event.target).attr("class") === "row-r") { var element = $(event.target).parent(); } var text = $(element).find(".row-l").text(); var favstatus = $(element).find(".row-r").text(); var thisStar = $(element).parent().find(".star-inside"); $(element).css("margin-left", "-75px"); if ($(thisStar).hasClass("favorite")) { $(".clear span").text(""); $(thisStar).removeClass("favorite"); localStorage.removeItem("favorite"); localStorage.removeItem("favorite-status"); } else { $(".clear span").text("\"" + text + "\""); localStorage.setItem("favorite", text); localStorage.setItem("favorite-status", favstatus); $(".star-inside").not(thisStar).removeClass("favorite"); $(thisStar).addClass("favorite"); } setTimeout(function () { $(element).css("margin-left", "0px"); }, 500); setTimeout(function () { $(document).on("touchmove", ".row", function () { touchMove(); }); }, 800); } } } function touchStart() { originalCoord.x = event.targetTouches[0].pageX; finalCoord.x = originalCoord.x; } $(document).on("touchmove", ".row", function () { touchMove(); }); $(document).on("touchstart", ".row", function () { touchStart(); }); } // Check favorite set in setFavorite() function checkFavorite() { if (localStorage.getItem("favorite") !== null) { var name = localStorage.getItem("favorite"); var favstatus = localStorage.getItem("favorite-status"); var favstatusSplit = favstatus.substr(2); var favstatusLower = favstatusSplit.toLowerCase(); var string = $(".row-l").text().toLowerCase(); var re = new RegExp(name.toLowerCase(), 'g'); var test = string.match(re); $(".row-l:contains(" + name + ")").parent().parent().find(".star-inside").addClass("favorite"); if (test !== null) { $(".fav_school_inside").text(name + " - " + favstatusLower + "!"); $(".clear span").text("\"" + name + "\""); setTimeout(function () { $(".fav_school").addClass("top"); }, 1000); setTimeout(function () { $(".fav_school").removeClass("top"); }, 6000); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T15:55:17.227", "Id": "28281", "Score": "5", "body": "It'd probably be beneficial if you wrote a few sentences about what the code is supposed to do and/or what you're particularly interested in having reviewed. Also, try running your code through [jshint](http://jshint.com) or [jslint](http://jslint.com). Lastly, for the part about regex'ing HTML, see [this question on SO](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) (if nothing else, just because the answer's funny)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T16:00:45.163", "Id": "28282", "Score": "0", "body": "I love that SO question, but that's partially why I'm here: Is there a better way to do all of this? And I'll include some background for the code..." } ]
[ { "body": "<p>This is not a complete review but one concerning organization aspects only. </p>\n\n<p>The first thing I suggest you do is organize your javascript into objects and classes such. Having a bunch of functions lying around usually is not the best idea as they are really hard to test and mantain after you grow to a few hundred functions. Organizing functions into coherent simple objects is a much better way to deal with javascript application growing.</p>\n\n<p>This series of talks by Douglas Crockford[1] provide an invaluable amount of good stuff regarding javascript.</p>\n\n<p>Also, I can see that you have a lot of DOM manipulation mixed with your app logic. Another good idea is to separate it by using a MVVM framework like Knockout JS[2] where you can leverage it´s binding capabilities leaving the DOM manipulation totally away from your objects. </p>\n\n<p>If you do not want to use a framework like that I suggest at least you use a template engine like handlebars or mustache to deal with HTML building.</p>\n\n<ol>\n<li>YUI talks by Douglas Crockford -> <a href=\"http://yuiblog.com/crockford/\" rel=\"nofollow\">http://yuiblog.com/crockford/</a> </li>\n<li>Knockout JS including live tutorial -> <a href=\"http://learn.knockoutjs.com/\" rel=\"nofollow\">http://learn.knockoutjs.com/</a></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T11:34:38.807", "Id": "17843", "ParentId": "17750", "Score": "3" } }, { "body": "<p>Alright, figure I'll go ahead and say this right off the bat: I am no JS/JQuery guru. However, there were a few things that I saw that you might want to take a look at. This is by no means complete, but hopefully it will help.</p>\n\n<p>You are violating the Arrow Anti-Pattern. This means your code is too heavily indented and should be refactored to remove some of that indentation. For example, the first if statement could be reversed and return early. This would then make an else statement unnecessary thus reducing a whole level of indentation from your entire function.</p>\n\n<pre><code>if( ! data.results[ 0 ] ) {\n console.log( 'error' );\n return;\n}\n\n//rest of code...\n</code></pre>\n\n<p>You can use <code>empty()</code> instead of explicitly clearing a field. This makes it a bit more obvious what you are trying to do wihtout needing comments everywhere trying to explain it.</p>\n\n<pre><code>$( '#content' ).empty();\n</code></pre>\n\n<p>Caching your selectors avoids having to compile them again and again, saving you processing power.</p>\n\n<pre><code>var $filterData = $( filterData( data.results[ 0 ] ) );\nvar number = $filterData.find( '#gtv_leftcolumn table:gt(1)' );\n</code></pre>\n\n<p>I don't know if this next suggestion will actually work, but it seems like it should. If it is possible to <code>.find()</code> from a <code>.find()</code>, in other words chaining finds, then I would try reusing your find results.</p>\n\n<pre><code>var name = number.find( \".maintext p:eq(\" + i + \")\" ).text();\n</code></pre>\n\n<p>I think you can get away with just loosley querying the length instead of explicitly. But that might just be preference.</p>\n\n<pre><code>if( ! number.length ) {\n</code></pre>\n\n<p>I don't like your <code>filterData()</code> function at all. First off, it seems like you should be able to refactor it to avoid redefining the same variable again and again. Second, I'm just not sure I see the point. To me it looks like this is just removing unwanted tags from something. No idea what, but it seems like you should be able to use a selector to chose what part of that document you want without having to regex it. Because I don't know exactly what you are trying to do here I can't make a good suggestion, sorry.</p>\n\n<p>The following is violating the \"Don't Repeat Yourself\" (DRY) Principle. It should be refactored to avoid this. There may be other places that also violate this principle, but this is the first that popped out at me. The first thing that came to mind was to use a switch, but it quickly became apparent that once your abstract the first instance it really only had one other instance. This means you could have gotten away with a single if statement from the beginning. Another problem, not immediately obvious is that <code>element</code> is not always defined. Because you only define it in if statements there is a possibility that it may not be assigned and your script does not gracefully fail to compensate. Either declare a default value, or gracefully return to show an error has occurred. I went with the former.</p>\n\n<pre><code>//original code\nif ($(event.target).attr(\"class\") === \"row-inside\") {\n var element = $(event.target);\n}\nif ($(event.target).attr(\"class\") === \"row-l\") {\n var element = $(event.target).parent();\n}\nif ($(event.target).attr(\"class\") === \"row-r\") {\n var element = $(event.target).parent();\n}\n\n//refactored with default\n//now with multiple uses\nvar element = $( event.target );\nif( element.attr( 'class' ) !== 'row-inside' ) {\n element = element.parent();\n}\n</code></pre>\n\n<p>I think its typically accepted that styling should only be done in CSS. I believe a better way would be to add and/or remove a class to get this same effect.</p>\n\n<pre><code>$(element).css(\"margin-left\", \"-75px\");\n</code></pre>\n\n<p>Part of what I believe tucaz was saying was to do something like this:</p>\n\n<pre><code>$(document).on( {\n 'touchmove' : function () {\n touchMove();\n },\n 'touchstart' : function () {\n touchStart();\n }\n}, '.row' );\n</code></pre>\n\n<p>There's more to his answer, I'm sure, this is just the only part I'm sure of. The above creates an event object that can easily be added to. It also has the added benefit of grouping related functionality. Something you might want to consider is adding namespaces to your events. They already seem to have a pseudo-namespace, but you might want to explicitly declare it. This helps differentiate your custom events from normal ones, while also allowing you to keep track of their purpose.</p>\n\n<pre><code>'touch:move' : function() {\n</code></pre>\n\n<p>This last section is going to be a general blanket statement. You have too few functions for too much functionality. This violates the Single Responsibility Principle. In other words, functions should only do one thing, everything else should be delegated to another function. The functions you do have are bulky and difficult to follow because of this. Adding more functions should help you to make your code more legible and will make it easier to extend this later. This is also key in ensuring your code does not violate DRY.</p>\n\n<p>While I'm sure there are things I missed, I hope some of this helps.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T03:13:43.627", "Id": "28505", "Score": "0", "body": "Just to assuage your doubt: Yup, you can chain `find()` calls all you want. jQuery basically lets you chain any and all of the element selection functions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T13:04:30.223", "Id": "28526", "Score": "0", "body": "@Flambino: Thank you for clearing that up. I meant to try that out at some point yesterday but never got around to it." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T15:16:15.223", "Id": "17845", "ParentId": "17750", "Score": "5" } } ]
{ "AcceptedAnswerId": "17845", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T14:05:57.880", "Id": "17750", "Score": "3", "Tags": [ "javascript", "jquery" ], "Title": "Javascript app review" }
17750
<p>Sparse is probably the wrong word - this is for encoding arrays of booleans where contiguous values tend to be the same. It'd be great to know a proper name for this data structure so I could read about it or use an existing implementation. I already realize I probably ought not to use doctest, and would welcome feedback on this as well. <a href="https://github.com/thomasballinger/bittorrent/blob/74fc610a4a669ee2201ffd0ca70f2d9335e6c367/sparsebitarray.py">github</a></p> <pre><code>""" Sparse (really Frequently Contiguous) Binary Array TODO: bitwise and would be really useful generalize to more than two possible values binary search to find overlapping segments """ class SBA(object): """Sparse BitArray, in which data is represented by ranges &gt;&gt;&gt; s = SBA(20); s &lt;SparseBitArray of length 20, all bits cleared&gt; """ def __init__(self, length): self.length = length self.set_ranges = [] def __len__(self): return self.length def __repr__(self): s = '&lt;SparseBitArray of length %d, ' % self.length if not self.set_ranges: s += 'all bits cleared&gt;' elif self.set_ranges == [(0, self.length)]: s += 'all bits set&gt;' else: s += str(self.set_ranges)+'&gt;' return s def _find_overlapping_ranges(self, start, end): """Returns existing ranges that overlap or touch a new one Returns a tuple of * ranges entirely contained by the new start and end * ranges over or at the edge of the new start and end * the range, if any, that entirely contains the new start and end """ #TODO use binary search instead here edge_overlapping = [] contained_by_new = [] contains_new = None for r_start, r_end in self.set_ranges: if r_end &lt; start or r_start &gt; end: pass elif r_start &lt;= start and r_end &gt;= end: contains_new = (r_start, r_end) break elif r_start &gt;= start and r_end &lt;= end: contained_by_new.append((r_start, r_end)) elif start &lt;= r_start &lt;= end or start &lt;= r_end &lt;= end: edge_overlapping.append((r_start, r_end)) else: raise Exception("Logic Error!") return contained_by_new, edge_overlapping, contains_new def __getitem__(self, key): """Get a slice or the value of an entry &gt;&gt;&gt; s = SBA(20); s[2:6] = True; s &lt;SparseBitArray of length 20, [(2, 6)]&gt; &gt;&gt;&gt; s[2:6] &lt;SparseBitArray of length 4, all bits set&gt; &gt;&gt;&gt; s[4:10] &lt;SparseBitArray of length 6, [(0, 2)]&gt; &gt;&gt;&gt; s[9:14] = True; s[17:19] = True; s &lt;SparseBitArray of length 20, [(2, 6), (9, 14), (17, 19)]&gt; &gt;&gt;&gt; s[2:18] &lt;SparseBitArray of length 16, [(0, 4), (7, 12), (15, 16)]&gt; &gt;&gt;&gt; s[1], s[10] (False, True) """ if isinstance(key, slice): start, step, end = key.start, key.step, key.stop if start is None: start = 0 if end is None: end = len(self) if step not in [None, 1]: raise ValueError("Custom steps not allowed: "+repr(key)) contained_by, edge_overlaps, contains = self._find_overlapping_ranges(start, end) result = SBA(end - start) if contains: result[:] = True for r_start, r_end in contained_by: result.set_ranges.append((r_start - start, r_end - start)) for overlap_start, overlap_end in edge_overlaps: if overlap_end == start or overlap_start == end: pass elif overlap_end &lt; end: result.set_ranges.append((0, overlap_end - start)) elif overlap_start &gt; start: result.set_ranges.append((overlap_start - start, end - start)) else: raise Exception("Logic Error!") return result else: contained_by, edge_overlaps, contains = self._find_overlapping_ranges(key, key+1) if contained_by or contains: return True else: return False def __setitem__(self, key, value): """Sets item or slice to True or False &gt;&gt;&gt; s = SBA(20); s[2:6] = True; s &lt;SparseBitArray of length 20, [(2, 6)]&gt; &gt;&gt;&gt; s[4:10] = True; s &lt;SparseBitArray of length 20, [(2, 10)]&gt; &gt;&gt;&gt; s[3:11] = False; s &lt;SparseBitArray of length 20, [(2, 3)]&gt; &gt;&gt;&gt; s[4:14] = True; s &lt;SparseBitArray of length 20, [(2, 3), (4, 14)]&gt; &gt;&gt;&gt; s[8:11] = False; s &lt;SparseBitArray of length 20, [(2, 3), (4, 8), (11, 14)]&gt; &gt;&gt;&gt; s[5:7] = True; s &lt;SparseBitArray of length 20, [(2, 3), (4, 8), (11, 14)]&gt; &gt;&gt;&gt; s[15:18] = False; s &lt;SparseBitArray of length 20, [(2, 3), (4, 8), (11, 14)]&gt; &gt;&gt;&gt; s[14:16] = False; s &lt;SparseBitArray of length 20, [(2, 3), (4, 8), (11, 14)]&gt; &gt;&gt;&gt; s[14:16] = True; s &lt;SparseBitArray of length 20, [(2, 3), (4, 8), (11, 16)]&gt; &gt;&gt;&gt; s[4:] = True; s &lt;SparseBitArray of length 20, [(2, 3), (4, 20)]&gt; &gt;&gt;&gt; s[:10] = False; s &lt;SparseBitArray of length 20, [(10, 20)]&gt; &gt;&gt;&gt; s[:] = False; s &lt;SparseBitArray of length 20, all bits cleared&gt; &gt;&gt;&gt; s[:] = True; s &lt;SparseBitArray of length 20, all bits set&gt; """ if isinstance(key, slice): start, step, end = key.start, key.step, key.stop if start is None: start = 0 if end is None: end = len(self) if step not in [None, 1]: raise ValueError("Custom steps not allowed: "+repr(key)) contained_by, edge_overlaps, contains = self._find_overlapping_ranges(start, end) if contains: if not value: self.set_ranges.remove(contains) self.set_ranges.append((contains[0], start)) self.set_ranges.append((end, contains[1])) return if value: for overlap_start, overlap_end in edge_overlaps: if overlap_start &lt; start: start = overlap_start self.set_ranges.remove((overlap_start, overlap_end)) elif overlap_end &gt; end: end = overlap_end self.set_ranges.remove((overlap_start, overlap_end)) else: raise Exception("Logic Error!") else: for overlap_start, overlap_end in edge_overlaps: if overlap_start &lt; start: self.set_ranges.remove((overlap_start, overlap_end)) self.set_ranges.append((overlap_start, start)) elif overlap_end &gt; end: self.set_ranges.remove((overlap_start, overlap_end)) self.set_ranges.append((end, overlap_end)) else: raise Exception("Logic Error!") for set_range in contained_by: self.set_ranges.remove(set_range) if value: self.set_ranges.append((start, end)) else: raise ValueError("Single element assignment not allowed") if __name__ == '__main__': import doctest print doctest.testmod() </code></pre>
[]
[ { "body": "<ol>\n<li>Your <code>__repr__</code> function tells the outside world about the implementation of your class. The fact that you are using a particular internal representation of a string shouldn't be exposed even here. I suggest this function should return something of the form <code>SparseBitArray('1111')</code> instead.</li>\n<li><code>_find_overlapping_ranges</code> doesn't seem very useful. Every time it is used, there some tricky to follow logic regarding it afterwards.</li>\n<li>The logic for decoding the slice is duplicated in <code>__getitem__</code> and <code>__setitem__</code>, refactor it into a function</li>\n<li><code>__getitem__</code> doesn't raise IndexError for out of bounds indexes. This would make it iterable.</li>\n<li>Your internal data structure isn't actually the best choice. You store data like [(4, 7), (10, 25)]. Each tuple indicates a range of 1 values. A better approach would actually be to hold [4, 8, 10, 25], where each value indicates a point at which the bitstring changes from 1 to 0 or vice versa.</li>\n</ol>\n\n<p>My reworking of your code:</p>\n\n<pre><code>import bisect\nimport sys\n\nclass SBA(object):\n \"\"\"Sparse BitArray, in which data is represented by ranges\n\n &gt;&gt;&gt; s = SBA(length = 20); s\n SparseBitArray('00000000000000000000')\n \"\"\"\n def __init__(self, length):\n self.length = length\n self.set_ranges = []\n self.changes = []\n def __len__(self):\n return self.length\n def __repr__(self):\n text = ''.join(str(int(x)) for x in self)\n return \"SparseBitArray('%s')\" % text\n\n def _decode_slice(self, key):\n start, end = key.start, key.stop\n if start is None: start = 0\n if end is None: end = len(self)\n if key.step not in [None, 1]: raise ValueError(\"Custom steps not allowed: \"+repr(key))\n\n return start, end\n\n\n def __getitem__(self, key):\n \"\"\"Get a slice or the value of an entry\n\n &gt;&gt;&gt; s = SBA(20); s[2:6] = True; s\n SparseBitArray('00111100000000000000')\n &gt;&gt;&gt; s[2:6]\n SparseBitArray('1111')\n &gt;&gt;&gt; s[4:10]\n SparseBitArray('110000')\n &gt;&gt;&gt; s[9:14] = True; s[17:19] = True; s\n SparseBitArray('00111100011111000110')\n &gt;&gt;&gt; s[2:18]\n SparseBitArray('1111000111110001')\n &gt;&gt;&gt; s[1], s[10]\n (False, True)\n \"\"\"\n if isinstance(key, slice):\n start, end = self._decode_slice(key)\n start_index, end_index = self._indexes(start, end)\n result = SBA(end - start)\n\n if self[start]:\n result.changes.append(0)\n\n result.changes.extend( \n change - start for change in self.changes[start_index:end_index] )\n\n return result\n else:\n if key &gt;= len(self):\n raise IndexError(key)\n\n return bool(bisect.bisect_right(self.changes, key) % 2)\n\n def _indexes(self, start, end):\n start_index = bisect.bisect_right(self.changes, start)\n end_index = bisect.bisect_right(self.changes, end)\n return start_index, end_index\n\n\n def __setitem__(self, key, value):\n \"\"\"Sets item or slice to True or False\n\n &gt;&gt;&gt; s = SBA(20); s[2:6] = True; s\n SparseBitArray('00111100000000000000')\n &gt;&gt;&gt; s[4:10] = True; s\n SparseBitArray('00111111110000000000')\n &gt;&gt;&gt; s[3:11] = False; s\n SparseBitArray('00100000000000000000')\n &gt;&gt;&gt; s[4:14] = True; s\n SparseBitArray('00101111111111000000')\n &gt;&gt;&gt; s[8:11] = False; s\n SparseBitArray('00101111000111000000')\n &gt;&gt;&gt; s[5:7] = True; s\n SparseBitArray('00101111000111000000')\n &gt;&gt;&gt; s[15:18] = False; s\n SparseBitArray('00101111000111000000')\n &gt;&gt;&gt; s[14:16] = False; s\n SparseBitArray('00101111000111000000')\n &gt;&gt;&gt; s[14:16] = True; s\n SparseBitArray('00101111000111110000')\n &gt;&gt;&gt; s[4:] = True; s\n SparseBitArray('00101111111111111111')\n &gt;&gt;&gt; s[:10] = False; s\n SparseBitArray('00000000001111111111')\n &gt;&gt;&gt; s[:] = False; s\n SparseBitArray('00000000000000000000')\n &gt;&gt;&gt; s[:] = True; s\n SparseBitArray('11111111111111111111')\n \"\"\"\n if isinstance(key, slice):\n start, end = self._decode_slice(key)\n start_index, end_index = self._indexes(start, end)\n\n new_changes = self.changes[:start_index]\n\n if bool(len(new_changes) % 2) != value:\n new_changes.append(start)\n\n if bool(end_index % 2) != value:\n new_changes.append(end)\n\n new_changes.extend( self.changes[end_index:] )\n\n self.changes = new_changes\n else:\n raise ValueError(\"Single element assignment not allowed\")\n\nif __name__ == '__main__':\n import doctest\n print doctest.testmod()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T20:47:40.260", "Id": "17819", "ParentId": "17753", "Score": "3" } } ]
{ "AcceptedAnswerId": "17819", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T14:39:15.427", "Id": "17753", "Score": "5", "Tags": [ "python", "array" ], "Title": "Sparse Bitarray Class in Python (or rather frequently having contiguous elements with the same value)" }
17753
Servlet is a Java application programming interface (API) running on the server machine which can intercept on the requests made by the client and can generate/send a response accordingly.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T15:56:20.810", "Id": "17755", "Score": "0", "Tags": null, "Title": null }
17755
JSP (Java Server Pages) is a server side technology used for presentation layer for the web applications. JSP are available on the server machine which allows you to write template text in (the client side languages like HTML, CSS, JavaScript and so on) and interact with backend Java code.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T15:57:18.237", "Id": "17757", "Score": "0", "Tags": null, "Title": null }
17757
<p>I'd love some feedback about this code that I'm editing and shortening now.</p> <pre><code>&lt;?php namespace bbn\cls; class mvc { use \bbn\traits\info; // From \bbn\traits\info. protected static $info=array(); protected static $cli=false; // Is set to null while not routed, then false if routing was unsucessful, and 1 if routing was done. private $is_routed; // Is set to null while not controled, then false if controller was not found, and 1 otherwise. private $is_controled; // The name of the controller. private $dest; // The path to the controller. private $path; // The controller file (with full path) private $controller; // The mode of the output (dom, html, json, txt, xml...) private $mode; // The data model public $data; // The output object public $obj; // The file extension of the view public $ext; // The request sent to the server to get the first controller. public static $original_request; // The first controller to be called at the top of the script. public static $original_controller; // The list of used controllers with their corresponding request, so we don't have to look for them again. public static $known_controllers = array(); // The list of views which have been loaded. We keep their content in an array to not have to include the file again. This is useful for loops. private static $loaded_views = array(); // Mustage templating engine. private static $mustache; // Reference to $appui variable private static $appui; // List of possible outputs with their according file extension possibilities private static $outputs=array('dom'=&gt;'html','html'=&gt;'html','image'=&gt;'jpg,jpeg,gif,png,svg','json'=&gt;'json','pdf'=&gt;'pdf','text'=&gt;'txt','xml'=&gt;'xml','js'=&gt;'js'); /** * List of possible and existing universal controller. * First every item is set to one, then if a universal controller is needed, self::universal_controller() will look for it and sets the according array element to the file name if it's found and to false otherwise. * @var array */ private static $ucontrollers=array('dom'=&gt;1,'html'=&gt;1,'image'=&gt;1,'json'=&gt;1,'pdf'=&gt;1,'text'=&gt;1,'xml'=&gt;1,'js'=&gt;1); // Path to the controllers. private static $cpath='mvc/controllers/'; // Path to the models. private static $mpath='mvc/models/'; // Path to the views. private static $vpath='mvc/views/'; // Path to the outputs. private static $opath='mvc/_output/'; /** * @return void * This function is called once and for all for each request and create a new mustache engine */ private static function init() { if ( !isset(self::$appui) ) { global $appui; self::$appui =&amp; $appui; self::$mustache = new \Mustache_Engine; // Sets the mode, which is the unique (so static) way of final output if ( count(self::$appui-&gt;params) &gt; 0 &amp;&amp; isset(self::$outputs[self::$appui-&gt;params[0]]) ) { self::$appui-&gt;mode = self::$appui-&gt;params[0]; array_shift(self::$appui-&gt;params); } else if ( count(self::$appui-&gt;post) &gt; 0 ) self::$appui-&gt;mode = 'json'; else self::$appui-&gt;mode = 'dom'; self::$original_request = implode('/',self::$appui-&gt;params); } return self::$original_request; } /** * This checks whether an argument used for getting controller, view or model - which are files - doesn't contain malicious content. * * @param string $p The request path &lt;em&gt;(e.g books/466565 or html/home)&lt;/em&gt; * @return bool */ private static function check_path($p) { return ( strpos($p,'./') === false &amp;&amp; strpos($p,'../') === false &amp;&amp; strpos($p,'/') !== 0 ); } /** * This fetches the universal controller for the according mode if it exists. * * @param string $c The mode (dom, html, json, txt, xml...) * @return string controller full name */ private static function universal_controller($c) { if ( !isset(self::$ucontrollers[$c]) ) return false; if ( self::$ucontrollers[$c] === 1 ) self::$ucontrollers[$c] = @file_exists(self::$cpath.$c.'.php') ? self::$cpath.$c.'.php' : false; return self::$ucontrollers[$c]; } /** * Adds the newly found controller to the known controllers array, and sets the original controller if it has not been set yet * * @param string $c The name of the request or how set by the controller * @param file $c The actual controller file ($this-&gt;controller) * @return void */ private static function set_controller($c, $f) { if ( !isset(self::$known_controllers[$c]) ) self::$known_controllers[$c] = $f; if ( is_null(self::$original_controller) &amp;&amp; !empty($c) ) self::$original_controller = $c; } /** * This directly renders content with arbitrary values using the existing Mustache engine. * * @param string $view The view to be rendered * @param array $model The data model to fill the view with * @return void */ public static function render($view, $model) { self::init(); return self::$mustache-&gt;render($view,$model); } /** * This will call the initial routing with the path in appui-&gt;params. * This constructor is chainable * * @param string $path * @return void */ public function __construct($path='') { $this-&gt;route(empty($path) ? self::init() : $path); return $this; } /** * This looks for a given controller in the file system if it has not been already done and returns it if it finds it, false otherwise. * * @param string $p * @return void */ private function get_controller($p) { if ( !$this-&gt;controller ) { if ( !is_string($p) || !is_dir(self::$cpath.$this-&gt;mode) ) return false; if ( isset(self::$known_controllers[$p]) ) { $this-&gt;dest = $p; $this-&gt;controller = self::$known_controllers[$p]; } else if ( file_exists(self::$cpath.$this-&gt;mode.'/'.$p.'.php') ) { $this-&gt;dest = $p; $this-&gt;controller = self::$cpath.$this-&gt;mode.'/'.$p.'.php'; self::set_controller($p,$this-&gt;controller); } else if ( is_dir(self::$cpath.$p) &amp;&amp; file_exists(self::$cpath.$p.'/'.$this-&gt;mode.'.php') ) { $this-&gt;dest = $p; $this-&gt;controller = self::$cpath.$p.'/'.$this-&gt;mode.'.php'; self::set_controller($p); } else return false; } return 1; } /** * This looks for a given controller in the database * * @param string $path The request path &lt;em&gt;(e.g books/466565 or xml/books/48465)&lt;/em&gt; * @return void */ private function fetch_route($path='default') { if ( self::check_path($path) ) { global $bbn; return $bbn-&gt;db-&gt;query(" SELECT route FROM controllers WHERE path LIKE ? AND output LIKE ?", $path, $this-&gt;mode)-&gt;fetchColumn(); } return false; } /** * This will fetch the route to the controller for a given path, using fetch_route() and get_controller() * * @param string $path The request path &lt;em&gt;(e.g books/466565 or xml/books/48465)&lt;/em&gt; * @return void */ private function route($path='') { if ( !$this-&gt;is_routed &amp;&amp; self::check_path($path) ) { $this-&gt;is_routed = 1; if ( strpos($path,'/') !== false ) { $t = explode('/',$path); if ( isset(self::$outputs[$t[0]]) ) { $this-&gt;mode = array_shift($t); $path = implode('/',$t); } } $this-&gt;path = $path; if ( !$this-&gt;mode ) $this-&gt;mode = self::$appui-&gt;mode; $this-&gt;ext = explode(',',self::$outputs[$this-&gt;mode]); $p = false; $fpath = $path; while ( strlen($fpath) &gt; 0 &amp;&amp; !$p ) { if ( $this-&gt;get_controller($fpath) ) return; else if ( $this-&gt;get_controller($this-&gt;fetch_route($fpath)) ) return; else if ( strpos($fpath,'/') === false ) $fpath = ''; else $fpath = substr($this-&gt;path,0,strrpos($fpath,'/')); } $this-&gt;get_controller($this-&gt;fetch_route()); } return false; } /** * This will launch the controller in a new process. * It is publicly launched through check(). In between * * @return void */ private function process() { if ( $this-&gt;controller &amp;&amp; is_null($this-&gt;is_controled) ) { $this-&gt;obj = new \stdClass(); $this-&gt;is_controled = 0; $mvc =&amp; $this; $appui =&amp; self::$appui; call_user_func( function() use ($mvc, $appui) { ob_start(); require($mvc-&gt;controller); $output = ob_get_contents(); ob_end_clean(); if ( isset($mvc-&gt;obj-&gt;error) ) die($mvc-&gt;obj-&gt;error); else if ( !isset($mvc-&gt;obj-&gt;output) ) $mvc-&gt;obj-&gt;output = $output; } ); if ( $this-&gt;data &amp;&amp; is_array($this-&gt;data) &amp;&amp; isset($this-&gt;obj-&gt;output) ) $this-&gt;obj-&gt;output = self::render($this-&gt;obj-&gt;output,$this-&gt;data); if ( $this-&gt;obj ) $this-&gt;is_controled = 1; } return $this; } /** * This will get a view. * * @param string $path * @param string $mode * @return string|false */ private function get_view($path='', $mode='') { if ( $this-&gt;mode &amp;&amp; !is_null($this-&gt;dest) &amp;&amp; self::check_path($path) &amp;&amp; self::check_path($this-&gt;mode) ) { if ( empty($mode) ) $mode = $this-&gt;mode; if ( empty($path) ) $path = $this-&gt;dest; if ( isset(self::$outputs[$mode]) ) { $ext = explode(',',self::$outputs[$mode]); foreach ( $ext as $e ) { if ( @file_exists(self::$vpath.$mode.'/'.$path.'.'.$e) ) return file_get_contents(self::$vpath.$mode.'/'.$path.'.'.$e); else { $t = explode('/',$path); $last = array_pop($t); if ( @file_exists(self::$vpath.$mode.'/'.$path.'/'.$last.'.'.$e) ) return file_get_contents(self::$vpath.$mode.'/'.$path.'/'.$last.'.'.$e); } } } } return false; } /** * This will get the model. * * @params There is no order, but one can put a path (string) or data (array) * @return array|false A data model */ private function get_model() { if ( $this-&gt;dest ) { $args = func_get_args(); foreach ( $args as $a ) { if ( is_array($a) ) $d = $a; else if ( is_string($a) &amp;&amp; self::check_path($a) ) $path = $a; } if ( !isset($path) ) $path = $this-&gt;dest; if ( !isset($d) ) $d = array(); if ( strpos($path,'..') === false &amp;&amp; @file_exists(self::$mpath.$path.'.php') ) { $appui =&amp; self::$appui; $file = self::$mpath.$path.'.php'; $data = $d; return call_user_func( function() use ($appui, $file, $data) { include($file); if ( isset($model) ) return $model; } ); } } return false; } /** * Processes the controller and checks whether it has been routed or not. * * @return bool */ public function check() { $this-&gt;process(); return $this-&gt;is_routed; } /** * Returns the output object. * * @return object|false */ public function get() { if ( $this-&gt;check() &amp;&amp; $this-&gt;is_controled ) return $this-&gt;obj; return false; } /** * Checks if data exists * * @return bool */ public function has_data() { return ( isset($this-&gt;data) &amp;&amp; is_array($this-&gt;data) ) ? 1 : false; } /** * Returns the rendered result from the current mvc if successufully processed * process() (or check()) must have been called before. * * @return string|false */ public function get_rendered() { if ( isset($this-&gt;obj-&gt;output) ) return $this-&gt;obj-&gt;output; return false; } /** * Sets the data. Chainable. Should be useless as $this-&gt;data is public. * * @param array $data * @return void */ public function set_data(array $data) { $this-&gt;data = $data; return $this; } /** * Merges the existing data if there is with this one. Chainable. * * @return void */ public function add_data($data) { if ( !is_array($this-&gt;data) ) $this-&gt;data = $data; else $this-&gt;data = array_merge($this-&gt;data,$data); return $this; } /** * Outputs the result. * * @return void */ public function output() { if ( $this-&gt;check() &amp;&amp; $this-&gt;obj ) { $obj = $this-&gt;obj; $path = self::$opath; $mode = $this-&gt;mode; call_user_func( function() use ($obj,$path,$mode) { include_once($path.$mode.'.php'); } ); } } } ?&gt; </code></pre> <p>Here is the router (<code>index.php</code>), where constants, <code>$bbn</code> and <code>$appui</code> are defined in the includes.</p> <pre><code>&lt;?php include_once('config/cfg.php'); include_once('config/env.php'); include_once('config/vars.php'); include_once('config/custom.php'); if ( defined('BBN_SESS_NAME') &amp;&amp; $appui-&gt;db ) { if ( !isset($_SESSION[BBN_SESS_NAME]) ) include_once('config/session.php'); $bbn-&gt;mvc = new \bbn\cls\mvc(); if ( !$bbn-&gt;mvc-&gt;check() ) die('No controller has been found for this request'); $bbn-&gt;mvc-&gt;output(); } ?&gt; </code></pre> <p>Well, and here's an example on how it works on a whole HTML document. Two views are used: the DOM structure, and a list element that is a part of a multi-level menu with no depth limit.</p> <p>The DOM view:</p> <pre><code>... &lt;/head&gt; &lt;body itemscope itemtype="http://schema.org/WebPage"&gt; &lt;div id="example" class="k-content"&gt; &lt;div id="vertical"&gt; &lt;div id="top-pane" style="overflow:visible; width:100%"&gt; &lt;ul id="menu"&gt;{{{menu_content}}}&lt;/ul&gt; ... </code></pre> <p>The HTML list element view:</p> <pre><code>{{#menus}} &lt;li{{specs}}&gt; {{#icon}} &lt;i class="icon-{{icon}}"&gt;&lt;/i&gt; &amp;nbsp; &amp;nbsp; &amp;nbsp; {{/icon}} {{{title}}} {{#has_menus}} &lt;ul&gt; {{{content}}} &lt;/ul&gt; {{/has_menus}} &lt;/li&gt; {{/menus}} </code></pre> <p>And I have a nested model used by the controller for displaying the menu:</p> <pre><code>array ( 'menus' =&gt; array ( 0 =&gt; array ( 'title' =&gt; 'Hello', 'icon' =&gt; 'cloud', 'has_menus' =&gt; false ), 1 =&gt; array ( 'title' =&gt; '1', 'icon' =&gt; 'user', 'has_menus' =&gt; 1, 'menus' =&gt; array ( 0 =&gt; array ( 'title' =&gt; '11', 'icon' =&gt; 'cloud', 'has_menus' =&gt; false ), 1 =&gt; array ( 'title' =&gt; '12', 'icon' =&gt; 'wrench', 'has_menus' =&gt; false ), 2 =&gt; array ( 'title' =&gt; '13', 'icon' =&gt; 'remove', 'has_menus' =&gt; 1, 'menus' =&gt; array ( 0 =&gt; array ( 'title' =&gt; '131', 'icon' =&gt; 'cloud', 'has_menus' =&gt; false ), 1 =&gt; ... </code></pre> <p>And now here is my controller for the DOM:</p> <pre><code>&lt;?php $mvc-&gt;data = array( 'site_url' =&gt; BBN_URL, 'is_dev' =&gt; BBN_IS_DEV ? 1 : "false", 'shared_path' =&gt; BBN_SHARED_PATH, 'static_path' =&gt; BBN_STATIC_PATH, 'year' =&gt; date('Y'), 'javascript_onload' =&gt; $mvc-&gt;get_view('init','js'), 'theme' =&gt; isset($_SESSION['atl']['cfg']['theme']) ? $_SESSION['atl']['cfg']['theme'] : false ); $tmp = new \bbn\cls\mvc("html/menu"); if ( $tmp-&gt;check() ) $mvc-&gt;data['menu_content'] = $tmp-&gt;get_rendered(); echo $mvc-&gt;get_view('_structure','dom'); ?&gt; </code></pre> <p>Which is calling the controller for the nested menu:</p> <pre><code>&lt;?php if ( !$mvc-&gt;has_data() ) $mvc-&gt;data = $mvc-&gt;get_model(); if ( isset($mvc-&gt;data['menus']) &amp;&amp; is_array($mvc-&gt;data['menus']) ) { foreach ( $mvc-&gt;data['menus'] as $i =&gt; $m ) { $tmp = (new \bbn\cls\mvc("html/menu"))-&gt;set_data($m); if ( $tmp-&gt;check() ) $mvc-&gt;data['menus'][$i]['content'] = $tmp-&gt;get_rendered(); } } echo $mvc-&gt;get_view(); ?&gt; </code></pre> <p>It is working great now! Please let me know the flaws or whatever outrageous mistake or even any advice you might come with about this code.</p> <p>As you can see - if ever you've reached this part! - all the menus look alike and they all use the third menu of the first children. I have tried many combinations, the array is fine at start. It is transformed at some stage when the MVC functions are called within the controller, but I can't figure out now.</p>
[]
[ { "body": "<p>First rewrite you code without the following things:</p>\n\n<ul>\n<li>global</li>\n<li>static</li>\n<li>@</li>\n</ul>\n\n<p>Your code isn't looking an object oriented approach right now. If you can forget the usage of the two mentioned keywords (global is really bad and the static can be a hard question where to use it) we can give you further advice how you can separate in code the functionalities.</p>\n\n<p>I don't know you know this but the PHP is basically a template engine and therefore you don't have to apply any other template angine magic.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T11:59:28.760", "Id": "28308", "Score": "0", "body": "Thanks!\nI use global in 2 methods here: \n- in self::init to provide a global access to the central object of my app ($appui). That gonna remain as is.\n- however, in $this->fetch_route() I use global to get the 2nd database object, and I was thinking of changing that.\nI don't understand what is the problem with statics... Can you elaborate please?\nAbout templates too, because that'd mean everyone using templating engines for php are fools?\nAnd I think my code looks like object oriented, but I'd be glad to know why not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-26T23:57:19.040", "Id": "30398", "Score": "0", "body": "Apologies for my stupid comment. If ever you have a bit of time: http://codereview.stackexchange.com/questions/19043/a-php-mvc-class" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T07:07:14.670", "Id": "17776", "ParentId": "17758", "Score": "3" } }, { "body": "<p>First of all, I'm really impressed that you are using comments. That besing said, in the future, please exclude them. Especially if they account for half of the scrollbar. It is intimidating to those of us trying to answer this, which means less meaningful answers for you. It is also unnecessary as most of us can get by without them. If you MUST have comments to explain your code then your code obviously has something wrong with it. Comments should be used in the public API, interfaces, or abstract classes, not in the code.</p>\n\n<p>Another point I would like to bring up before diving in. Peter gave you some really good advice. Vague, but good all the same. The fact that you shot it down almost immediately worries me. Yes, a better explanation would have been nice, but flat out saying that you aren't going to change something is not very smart. What we are telling you, for the most part, is all VERY good advice that comes from experience. They are suggestions, but not without purpose. Some comments, like those about globals and static, will always be the same. There is never, or almost never in the case of static, a good reason to use them. If there is some reason you must not or can not change something, then you must factor that in while reading a review. But ask why someone said something before just shooting it down.</p>\n\n<hr>\n\n<p><strong>Static in OOP</strong></p>\n\n<p>OOP promotes:</p>\n\n<ul>\n<li>Encapsulization: Properties and methods are scoped and thus unavailable, or only available via namespace or pseudo-namespace.</li>\n<li>Inheritance: Properties and methods are inherited by child classes in order to extend functionality.</li>\n<li>Polymorphism: Properties and methods are adapted during inheritance to extend functionality.</li>\n<li>etc...</li>\n</ul>\n\n<p>Static promotes:</p>\n\n<ul>\n<li>Properties and methods that are similarly scoped, but content that is static and does not change from implementation.</li>\n</ul>\n\n<p>The distinction is subtle, and may be a bit difficult to understand. Especially since I can't think of a good example for it, but static is rarely, if ever, used. In the five years I've been doing this, not that long I suppose, I have never needed static for anything. There are exceptions, but I doubt you will ever need them.</p>\n\n<hr>\n\n<p><strong>Globals in OOP</strong></p>\n\n<p>There is no reason to use a global, ever, but especially not in a class. Globals were replaced by properties.</p>\n\n<pre><code>$this-&gt;$appui;\n//is the same as \nglobal $appui;\n</code></pre>\n\n<p>To prove this, check out this cool constructor.</p>\n\n<pre><code>public function __construct( $appui ) {\n $this-&gt;appui = $appui;\n}\n//or for those assign-by-reference junkies\npublic function __construct( &amp;$appui ) {\n $this-&gt;appui =&amp; $appui;\n}\n</code></pre>\n\n<p>There, no more need for globals. If you need to access it outside of the class, then there are a few different ways to go about it. The first I already showed you with referencing, though I don't suggest it due to lack of legibility. In fact I only mentioned it because you were already doing it. The simplest way is to manually access it from the class scope. Again, not really the best way as you normally don't want to be directly accessing these properties, but a possibility. The final way is to create a getter for it and call that getter as you need it. This final one is the one I'd recommend.</p>\n\n<pre><code>$appui = $mvc-&gt;appui;\n//or\n$appui = $mvc-&gt;getAppui();\n//same as\nglobal $appui;\n</code></pre>\n\n<p>There are quite a few different reasons why globals are considered to be bad. Chief among them is security and lack of legibility. Globals are accessable from any script. So, imagine if you had a <code>$user</code> global with all of the user's credentials. This is a huge security risk. Any script can access this. A private class property, on the other hand, is unavailable outside of that class and therefore is not subject to these issues. Also, globals are not not legible. You have no idea where they could be coming from and they could change at a whim.</p>\n\n<hr>\n\n<p><strong>Review</strong></p>\n\n<p>This actual review is going to be short. I'm usually much more thorough, but as Peter pointed out, this is very difficult to read. Make the suggestions we recommended and post a new question and I'll try and make a more thorough review. At the moment I can't get past the first globals and statics. Sorry for that harsh truth, but there it is.</p>\n\n<hr>\n\n<p><strong>Properties</strong></p>\n\n<p>This is not a functionality suggestion, but one of legibility, which is equally important, if not more so. If you group like properties/methods together and use whitespace to separate them then it will make it much easier to find what you are looking for. For instance:</p>\n\n<pre><code>protected $info;\n//etc...\n\nprivate $is_routed;\n//etc...\n\npublic $data\n//etc...\n</code></pre>\n\n<p>Going along with the above suggestion, you can then also reuse an access modifier. Though I seem to be one of the minority in this regard. So this is subjective.</p>\n\n<pre><code>protected\n /*Also, doccomments*/\n $ifo = array(),\n\n /*are fine here too*/\n $cli = FALSE,\n //etc...\n;\n</code></pre>\n\n<p>That being said, some of these properties would be better as constants. For instance, those path variables. Properties/Variables are \"variable\", they change. A path isn't likely to change, thus it should be declared as a constant. Technically they shouldn't be hard coded into your classes at all, but for the time being I'm just going to suggest you change them to constants. For more on this take a look at: Separation of Concerns (SoC), Inversion of Control (IoC), Dependency Injection (DI).</p>\n\n<hr>\n\n<p><strong>Constructors and Initiators</strong></p>\n\n<p>Because your code is so dependent upon static properties many of its methods must also be static. This also includes your constructor. You can't properly instantiate your class because everything is static. You have to manually check it instead of relying on it. This extermely inhibits your abilities and makes your code repetitive, which violates the \"Don't Repeat Yourself\" (DRY) principle.</p>\n\n<hr>\n\n<p><strong>Another Point For Legibility</strong></p>\n\n<p>Sometimes it is important to abstract information from your statements just to improve legibility. This is especially the case in long statements or statements that have nested braces. Long statements are any that break 80 characters, including whitespace, usually denoted as the 80th column on editors.</p>\n\n<pre><code>$count = count( self::$appui-&gt;params );\n$param = self::$appui-&gt;params[ 0 ];\nif ( $count &gt; 0 &amp;&amp; isset( self::$outputs[ $param ] ) ) {\n</code></pre>\n\n<hr>\n\n<p><strong>Braceless Syntax</strong></p>\n\n<p>PHP inherrently requires braces in its syntax, otherwise you wouldn't have to add them after your statements became longer than one line. To be consistent, and to avoid accidents, it is best to just always add those braces to your statements. This can also make nested statements easier to read.</p>\n\n<pre><code>else if ( count(self::$appui-&gt;post) &gt; 0 ) {\n self::$appui-&gt;mode = 'json';\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Ternary</strong></p>\n\n<p>Ternary statements are a powerful tool. But you should know when to use them. If your statement becomes too long, see above, or to complex, then you should revert to using if/else statements. And above all you should never nest ternary. However, sometimes you can just abstract a portion and that will fix it, but not always. Here's an example:</p>\n\n<pre><code>$file = self::$cpath . $c . '.php';\nself::$ucontrollers[ $c ] = @file_exists( $file ) ? $file : FALSE;\n</code></pre>\n\n<hr>\n\n<p><strong>Error Supressors</strong></p>\n\n<p>As Peter said, don't use the error suppressor <code>@</code>. This is a sure sign of bad code. Do whatever checks you need to do to ensure that those suppressors are unnecessary. Specifically in the above code you were suppressing the warning you get when <code>file_exists()</code> fails. I honestly don't know what would cause this unless the value being passed to it was not a string but an object or array. So you can use <code>is_string()</code> on <code>self::$cpath</code> to determine if you should use it. Do that check before attempting to append on to it.</p>\n\n<pre><code>if( is_string( self::$cpath ) ) {\n</code></pre>\n\n<hr>\n\n<p><strong>Variable-Variables</strong></p>\n\n<p><code>self::$cpath</code> from above is a variable-variable. These are almost as bad as globals. MVC is one of the few frameworks where they are usually considered acceptable, but you are abusing that here.</p>\n\n<hr>\n\n<p><strong>File Exists vs. Is File</strong></p>\n\n<p>If you know the file you are looking for is actually a file and not a directory, use <code>is_file()</code>. If you are not sure, use <code>file_exists()</code>. If you know it's a directory use <code>is_dir()</code>.</p>\n\n<hr>\n\n<p><strong>Return This</strong></p>\n\n<p>When you return <code>$this</code> you are returning the object so that further methods can be chained to it. For instance:</p>\n\n<pre><code>$obj-&gt;meth()-&gt;chain();\n</code></pre>\n\n<p>This is pretty neat, but not typically done. I personally find this rather difficult to read. There are ways of making it better, such as adding new lines and whitespace after each method, but overall, it just seems cluttered. Another thing to note: The constructor can not be chained and already returns the class instance, thus explicitly returning <code>$this</code> is pointless and redundant.</p>\n\n<hr>\n\n<p><strong>PHP as a Template</strong></p>\n\n<p>Peter mentioned that PHP is already a templating language. By this he meant that it is fairly easy to add PHP variables to HTML unobstrusively.</p>\n\n<pre><code>&lt;div id=\"&lt;?php echo $id; ?&gt;\"&gt;&lt;/div&gt;\n//or with short tags\n&lt;div id=\"&lt;?= $id; ?&gt;\"&gt;&lt;/div&gt;\n</code></pre>\n\n<p>I would not suggest using short tags unless your server is using one of the most recent versions of PHP where they are always available, otherwise you will have to make sure your server enables them manually.</p>\n\n<hr>\n\n<p><strong>Conclusion</strong></p>\n\n<p>Resubmit this with Peter's suggested changes and I'll go into more details about your code and some of the principles I talked about and how to apply them. Sorry I can't do more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T02:10:26.547", "Id": "28376", "Score": "0", "body": "Ok, this is already a pretty great answer, thanks a lot. I'll do as you suggest, I'm still quite a newbie with OOP as you can see, and yes I have certainly been wrong with my comment on Peter's answer... Thanks again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T02:22:17.297", "Id": "28377", "Score": "0", "body": "But I'll leave a few comments anyway...\nAs you could notice, my comments are quite big and painfull, and yeah I should have removed them before posting, my bad. It is new for me, I generate documentation with apigen, and it doesn't recognize properties' visibility when they are coma separated - it sets the first one right then all the following properties as public." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T03:16:52.063", "Id": "28379", "Score": "0", "body": "I will think through all this, and write a new question later this week. Thanks for your time" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-26T23:56:27.073", "Id": "30397", "Score": "0", "body": "A bit more than a week later... :) http://codereview.stackexchange.com/questions/19043/a-php-mvc-class" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-12-22T15:08:15.740", "Id": "283459", "Score": "0", "body": "Our team uses static functions inside of model helper classes that require complex sql queries to assist in optimization. Instead of loading a large number of objects into memory in order to run calculations on them, we can do that work in sql in a fraction of the time with a far lower memory cost." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T22:06:54.107", "Id": "17821", "ParentId": "17758", "Score": "2" } } ]
{ "AcceptedAnswerId": "17821", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T17:36:39.990", "Id": "17758", "Score": "2", "Tags": [ "php", "mvc", "template", "url-routing", "mustache" ], "Title": "A PHP MVC working with Mustache (and now nested templates!)" }
17758
<p>My app has a feature that when you click the <kbd>new data</kbd> button, HTML is loaded to the page via ajax. Because I am using AJAX, all events I want to add has to be bound using the <code>on()</code> method.</p> <p>There are 4 <code>on('click')</code> functions that are bound to 4 different HTML elements:</p> <pre><code>// save data $('#container').on( { click: function() { // save code here } }, "a.save_data" ); // cancel data $('#container').on( { click: function() { // cancel code here } }, "a.cancel_data" ); // edit data $('#container').on( { click: function() { // edit code here } }, "a.edit_data" ); // delete data $('#container').on( { click: function() { // delete code here } }, "a.delete_data" ); </code></pre> <p>Each of these functions share multiple jQuery wrappers to select certain elements within the HTML:</p> <pre><code>$(this).closest('div.content_wrap'); $(this).closest('div.Content'); </code></pre> <p><strong>Please note:</strong> The reason I am using selectors such as <code>$(this).closest()</code> is because the user has the ability to add the same HTML multiple times on to the page.</p> <p>First, is there a better way to organize all of the <code>on()</code> functions? Maybe combine them into one object OR create a function?</p> <p>Second, because all 4 functions use the same jQuery wrappers, is there any way to declare them in a variable globally somewhere, so i don't keep retyping them. I wasn't able to figure out how declare variables with <code>$(this)</code> and apply it to more than one function.</p> <p>To me, how I am doing it doesn't seem very DRY and I was wondering if someone can help me better organize this.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T19:41:47.720", "Id": "28289", "Score": "2", "body": "See [this question/answer](http://codereview.stackexchange.com/questions/16483/jquery-multi-functional-event-delegate/16494#16494) (/shameless self-promotion)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T07:44:18.973", "Id": "28305", "Score": "1", "body": "Hey thanks a lot, that was informative...I was able to follow, but wasn't really able to apply it to what I was doing, but I did find a way to set it up so I don't have so much repetitive code...It's under EDIT in my post if you have any additional feedback...Thanks" } ]
[ { "body": "<p>Perhaps something like this? </p>\n\n<pre><code>function manipulateData($action){\n $('#container').on( {\n click: function() {\n switch(action){\n case \"save\" : saveData();\n break;\n case \"delete\" : deleteData();\n }\n }\n }, \"a.\" + action + \"_data\" );\n}\n</code></pre>\n\n<p>Also, see Flambinos comment</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T07:39:46.873", "Id": "28304", "Score": "1", "body": "Hey thanks for taking the time to help...I came up with something similar and posted it in my post under EDIT...My thinking there is, because I am binding 4 different functions to 4 different elements, I just wanted a way to cut back on the repetitive code. What I have done allows me to use the same variables for all events and also allows to write 'click' and 'return false' only once ...Any improvements to this that you know of?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T06:16:54.357", "Id": "17775", "ParentId": "17759", "Score": "1" } }, { "body": "<p>Here's how I'd probably do it (basically, it's the same as in the answer I linked to in the comments, I'm just adding it here for clarity)</p>\n\n<pre><code>var handlers = {\n save_data: function (event, content, wrap) {\n // save code\n },\n\n cancel_data: function (event, content, wrap) {\n // cancel code\n },\n\n edit_data: function (event, content, wrap) {\n // edit code\n },\n\n delete_date: function (event, content, wrap) {\n // delete code\n }\n};\n\n$('#container a').on('click', function (event) {\n var klass = this.className,\n content,\n wrap;\n\n if(typeof handlers[klass] === \"function\") {\n content = $(this).closest(\"div.Content\"),\n wrap = $(this).closest(\"div.content_wrap\");\n handlers[klass].call(this, event, content, wrap);\n }\n\n // you want to always \"absorb\" the click event, you can\n // do so here or in the if-block above\n // event.preventDefault();\n});\n</code></pre>\n\n<p>You can write the handler functions just like you'd write them in your orginal code (i.e. <code>this</code> will refer to the right element, etc.). However, the click event handler will pass along the the <code>content</code> and <code>wrap</code> arguments, so you don't have to have code to select those elements in every handler function.</p>\n\n<p>Of course, if your links have multiple classes, the <code>className</code> trick won't work. That's why I'd advocate (as I do in the answer I linked to) using a <code>data-*</code> attribute if possible.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T06:14:52.153", "Id": "28383", "Score": "0", "body": "Hey thanks for this again, much appreciated...I am actually returning back to this and I had a question...See my code above, I added a new edit...It's just a simple test...I did exactly what you have except I took out the event object, the `if (typeof...)` statement and the call() method...I assume the if statement was just for security sake, but I can't figure out why you need the call function, I was able to run the code without it and get the same results. Also, why did you add the event object?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T06:45:21.413", "Id": "28384", "Score": "0", "body": "Also, I tested this with data being pulled in via ajax and I noticed that without declaring the element I am clicking within the `on()` arguments, the `on()` functionality didn't work, but once I replaced it with `live()`, it did work...Which I know has been deprecated..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T08:03:15.727", "Id": "28393", "Score": "0", "body": "@elgarcon The `typeof` check is there to make sure that the handler actually exists and is a function. If you try `handlers[\"xyz\"]()`, and `handlers[\"xyz\"]` doesn't exist or isn't a function, you'll get an error and JS just stops executing. The point of `call` and passing the event obj, is so the handler functions can be _exactly_ the same as if you added them to the elements the normal way: `this` will be the element the event occurred on, and the 1st argument is the event obj." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T08:11:00.380", "Id": "28394", "Score": "0", "body": "@elgarcon Not sure what you mean by the `on` vs `live` stuff. But if things stop working when you remove things, well, don't remove things. jQuery's `on` function works, so the problem must be on your end. Don't know what else to tell ya." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T11:42:47.237", "Id": "17778", "ParentId": "17759", "Score": "3" } } ]
{ "AcceptedAnswerId": "17778", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T19:20:49.200", "Id": "17759", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Multiple .on() events" }
17759
<p>I want to get my first CSS layout reviewed. First of all, the related HTML code is as follows -</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8" /&gt; &lt;title&gt; Preferences &lt;/title&gt; &lt;script src="options.js"&gt;&lt;/script&gt; &lt;link rel="stylesheet" href="options.css" /&gt; &lt;/head&gt; &lt;body&gt; &lt;h1&gt; Search in New Tab - Preferences &lt;/h1&gt; &lt;form id="preference-form"&gt; &lt;label for="search-engine"&gt; Search Engine &lt;/label&gt; &lt;select id="search-engine"&gt; &lt;option id="google" value="google" selected="selected"&gt; Google &lt;/option&gt; &lt;option id="bing" value="bing"&gt; Bing &lt;/option&gt; &lt;option id="yahoo" value="yahoo"&gt; Yahoo! &lt;/option&gt; &lt;option id="duckduckgo" value="duckduckgo"&gt; DuckDuckGo &lt;/option&gt; &lt;option id="wikipedia" value="wikipedia"&gt; Wikipedia &lt;/option&gt; &lt;/select&gt; &lt;br&gt; &lt;label for="focus-search-tab"&gt; Make the search tab active &lt;/label&gt; &lt;input type="checkbox" value="focus-search-tab" id="focus-search-tab" /&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>I wrote the following CSS file in order to provide satisfactory presentation to the HTML -</p> <pre><code>h1 { width : 40%; background : #eeeeee; box-shadow : 0 0 5px 5px #888; margin-top : 10%; margin-left : 30%; margin-right : 30%; padding-top : 10px; padding-bottom : 10px; text-align : center; font-family : "Arial", "Century Gothic", "Lucida Sans Unicode"; } form { width : 30%; background : #eeeeee; box-shadow: 0 0 5px 5px #888; margin-top : 1%; margin-left : 35%; margin-right : 35%; padding-top : 10px; padding-bottom : 10px; } label { width : 60%; display : inline-block; text-align : right; margin-top : 10px; margin-bottom : 10px; margin-right : 10px; font-family : "Arial"; } </code></pre> <p>The resulting HTML document looks like this:</p> <p><img src="https://i.stack.imgur.com/V75nB.png" alt="screenshot"></p> <p>Basically, I wanted to avoid the use of float property. I felt that I could accomplish the same by using combinations of inline-block property, padding and margins. So, I used that. Was that the right way? Other than that, I would like to know if I did things right. Also, any improvements that make my CSS code better are welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-04T19:28:38.593", "Id": "32225", "Score": "0", "body": "Get rid of the `<br>`" } ]
[ { "body": "<p>I'm no CSS expert, but two things I would change are:</p>\n\n<ul>\n<li>remove unnecessary spaces (indenting and in ' : ').</li>\n<li><p>condense explicit margin-top, margin-left etc (and padding):</p>\n\n<pre><code>h1{\nwidth:40%;\nbackground:#eee;\nbox-shadow:0 0 5px 5px #888;\nmargin:10% 30% 0 30%;\npadding:10px 0 10px;\ntext-align:center;\nfont-family:\"Arial\", \"Century Gothic\", \"Lucida Sans Unicode\";\n}\n\nform{\nwidth:30%;\nbackground:#eee;\nbox-shadow: 0 0 5px 5px #888;\nmargin:1% 35% 35%;\npadding:10px 0 10px;\n}\n\nlabel{\nwidth:60%;\ndisplay:inline-block;\ntext-align:right;\nmargin:10px 10px 10px;\nfont-family:\"Arial\";\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T20:39:00.380", "Id": "28433", "Score": "5", "body": "+1 for condensing items. I have to disagree with the indenting of lines. I find it easier to read and find the different tags within the file with the white space." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T20:57:20.453", "Id": "28435", "Score": "0", "body": "@JeffVanzella, yes it is true. Perhaps indent with a single TAB rather than many spaces (possibly the OP did that)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T21:22:26.050", "Id": "28437", "Score": "0", "body": "That would work, but in VS tab is replaced by spaces ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T06:51:29.150", "Id": "28450", "Score": "0", "body": "@WilliamMorris yes. I am used to a tab indent rather than several spaces. Thanks for the condensation tip, though; it looks better, and saves a lot of lines. I will stick with indentation, though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T06:53:06.230", "Id": "28451", "Score": "0", "body": "However, I was hoping for a review of the code that I have written for CSS - like if my usage of inline-block + margin + padding is better than taking the headache of using float, to achieve the same result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T16:36:25.740", "Id": "29636", "Score": "0", "body": "@JeffVanzella `in VS tab is replaced by spaces` - that is a preference, that has a default value but can be changed to keep tabs." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T19:15:23.880", "Id": "17855", "ParentId": "17764", "Score": "2" } }, { "body": "<p>I think the no fundamental difference using the \"float:left;\" and \"display:inline-block;\". In the first case, we have to clear the output before inserting the new elements that are not on the floated blocks. In the second case we make of inline element inline-block.</p>\n\n<p>Here's another variant:</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;title&gt; Preferences &lt;/title&gt;\n &lt;link rel=\"stylesheet\" href=\"options.css\"&gt;\n&lt;/head&gt;\n\n&lt;body&gt;\n &lt;h1&gt; Search in New Tab - Preferences &lt;/h1&gt;\n &lt;br&gt;\n &lt;form id=\"preference-form\"&gt;\n &lt;label&gt; Search Engine\n &lt;select&gt;\n &lt;option id=\"google\" value=\"google\" selected&gt; Google &lt;/option&gt;\n &lt;option id=\"bing\" value=\"bing\"&gt; Bing &lt;/option&gt;\n &lt;option id=\"yahoo\" value=\"yahoo\"&gt; Yahoo! &lt;/option&gt;\n &lt;option id=\"duckduckgo\" value=\"duckduckgo\"&gt; DuckDuckGo &lt;/option&gt;\n &lt;option id=\"wikipedia\" value=\"wikipedia\"&gt; Wikipedia &lt;/option&gt;\n &lt;/select&gt;\n &lt;/label&gt;\n\n &lt;label&gt; Make the search tab active \n &lt;input type=\"checkbox\" value=\"focus-search-tab\" id=\"focus-search-tab\"&gt;\n &lt;/label&gt;\n &lt;/form&gt; \n &lt;script src=\"options.js\"&gt;&lt;/script&gt;\n&lt;/body&gt;\n&lt;/html&gt;​\n</code></pre>\n\n<p>Styles:</p>\n\n<pre><code>body { text-align: center; }\nh1, form {\n display: inline-block;\n background: #eee;\n box-shadow: 0 0 5px 5px #888;\n font-family: Arial,Helvetica,Garuda,sans-serif;\n}\n\nh1 {\n margin: 10% auto 1%;\n padding: 10px;\n text-align: center;\n}\n\nform {\n margin: 1% auto;\n padding: 10px;\n}\n\nlabel {\n display: block;\n margin: 10px;\n}​\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T16:44:48.200", "Id": "29639", "Score": "1", "body": "There **are** fundamental differences. Just look at this floated thing and imagine the amount of trickery necessary to push all things into place: http://jsfiddle.net/JAyfJ/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T12:04:17.890", "Id": "29692", "Score": "0", "body": "You want to make the transfer of the <label> to a new line? Where, then, <br>? Red border can fix plus one line in css: http://jsfiddle.net/JAyfJ/1/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T12:50:55.437", "Id": "29695", "Score": "0", "body": "1. The `<br>` element [\"br elements must be used only for line breaks that are actually part of the content, as in poems or addresses\".](http://developers.whatwg.org/text-level-semantics.html#the-br-element), and so should not be used to send the label to the new line. 2. USing `overflow: hidden;` in the container is curious, I had not thought of that and cannot find any flaws in it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-15T14:09:54.983", "Id": "29697", "Score": "0", "body": "What about the element `<br>` - I agree. For more semantics then it is logical to make the form elements out of `<p>` tag or wrap them in a separate `<div>`. Because they are not part of paragraph." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-14T16:00:20.793", "Id": "18620", "ParentId": "17764", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T21:17:25.793", "Id": "17764", "Score": "6", "Tags": [ "optimization", "css", "html5" ], "Title": "Review for CSS layout code" }
17764
<p>In the very simple code below I'm illustrating having a master 'App' object with 'Chat' &amp; 'Posts' modules inside.</p> <p>Now, what I'm asking is, in my conscious effort to keep my components loosely coupled and modular, how I can use other functionality in the App object following the modular, decoupled pattern of JS web apps? I.e. imagine if I plucked the 'Chat' object out of the 'App' object and put it inside an 'App1' object, this code would break, so it's tightly coupled with the 'App' object.</p> <p>Can anyone offer any advice on decoupling my code below? </p> <pre><code>​var App = { Utils: { add: function(a,b){ return a + b; } }, Posts: { }, Chat: { init: function(){ console.log(App.Utils.add(1,2)); // 3 }, } } App.Chat.init(); </code></pre>
[]
[ { "body": "<p>Well, your code wouldn't break as long as <code>App.Utils.add()</code> is still around to be called - even if <code>App.Chat.init()</code> becomes <code>SomethingElse.Chat.init()</code>. Of course, if you completely remove <code>App.Utils.add()</code> then, yeah, it'll break.</p>\n\n<p>However, that can really be said of anything. You rely on <code>console.log()</code> too. If that goes away, your code will break.</p>\n\n<p>Point is, your code will inevitably depend on <em>something</em>, so the question then becomes structure: Avoid having low-level functionality depend on higher-level functionality. And your structure is fine in this case. Yes, <code>App.Chat.init()</code> depends on <code>App.Utils.add()</code>, but that function doesn't depend on anything. It certainly doesn't depend on <code>App.Chat.init()</code> existing.</p>\n\n<p>Take, for instance, jQuery or underscore.js. You code may well depend on one or both of those libraries, but they don't depend on your code. Structure your own code similarly: Keep <code>App.Utils</code> generic and low-level (as its name implies), but don't worry about other, higher-level, parts depending on it. Just make sure to include <code>App.Utils</code> if you plan to reuse things that depend on it. Generally speaking the more high-level a chunk of code is, the more dependencies it'll have.</p>\n\n<p>All in all, I think you may be confusing namespacing with coupling. You're using <code>App</code> as your namespace, and putting everything in there. This does not mean the the \"contents\" of <code>App</code> are automatically coupled to each other.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T23:03:13.223", "Id": "17769", "ParentId": "17765", "Score": "4" } }, { "body": "<p>If you have a method on an object that you wish to use on another object, then perhaps <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain\" rel=\"nofollow noreferrer\">prototypal inheritance</a> is for you.</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>var App = {\n Utils: {\n add: function(a,b){\n return a + b;\n }\n },\n Posts: {\n\n },\n Chat: {\n init: function(){\n console.log(App.Utils.add(1,2)); // 3\n },\n\n }\n}\nvar App1 = Object.create(App).prototype = {\n // Utils is not repeated, we just override the Chat.init method\n Chat: {\n init: function(){\n console.log(App.Utils.add(2,2), \"&lt;-- Chat has been decoupled\"); // 4\n },\n\n }\n};\n\nApp.Chat.init();\n\nApp1.Chat.init(); \"&lt;-- Chat has been decoupled\"</code></pre>\r\n</div>\r\n</div>\r\n</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-09T19:41:06.863", "Id": "275439", "Score": "1", "body": "Welcome to Code Review, your first answer looks good, if a bit short on the explanation - n.b. the question looked off-topic to me anyway, sorry about. Enjoy your stay!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-09T19:44:11.860", "Id": "275441", "Score": "0", "body": "Please refrain from answering off-topic questions. It's considered bad form and potentially motivates users to post more off-topic questions (\"we get answers anyway, so why follow the rules?\"). Find more information in the [help/on-topic]." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-09T19:45:32.450", "Id": "275442", "Score": "0", "body": "Don't worry about it in this case though, the question was quite old and not obviously off-topic to new users ;-)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-11-09T19:22:12.407", "Id": "146597", "ParentId": "17765", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T22:11:52.317", "Id": "17765", "Score": "-2", "Tags": [ "javascript" ], "Title": "Keeping my JS decoupled but still use functionality" }
17765
<p>I want to defer the reading of a bitmap to another thread. I'm mainly concerned about concurrency issues since I'm kind of green on that subject, so I would like to know if this code has any potential flaws.</p> <pre><code>public class SomeActivity extends Activity { Bitmap threadBitmap; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); new BitmapTask().execute(); Button button = (Button) findViewById(R.id.button1); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(threadBitmap != null) { // Assume bitmap has loaded and do something with it here } } }); } public class BitmapTask extends AsyncTask&lt;Void, Void, Bitmap&gt; { @Override protected Bitmap doInBackground(Void... params) { Bitmap bitmap = null; InputStream in = null; try { in = getAssets().open("mybitmap.png"); bitmap = BitmapFactory.decodeStream(in); } catch (IOException e) { e.printStackTrace(); } finally { try { if(in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } } return bitmap; } @Override protected void onPostExecute(Bitmap result) { threadBitmap = result; } } } </code></pre>
[]
[ { "body": "<p>I would implement a progress bar to inform the user of the image loading status to eliminate confusion to what it's going on. </p>\n\n<p>Also, you could deactivate the button for as long as the thread is running. And reactivate it in <code>onPostExecute()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T23:19:00.340", "Id": "17770", "ParentId": "17766", "Score": "2" } }, { "body": "<p>When you start reading of a bitmap? </p>\n\n<ol>\n<li><p>If it starting in onCreate, you should use a progress bar while you load resources.</p></li>\n<li><p>If it starting after some user interaction you can use default image for button and set new image in <code>onPostExecute()</code> methods. Your button should be class \ninstance variable of course. </p></li>\n<li><p>And <code>try</code> block inside <code>finally</code> is ugly.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T13:52:32.353", "Id": "28309", "Score": "0", "body": "Ugly, but necessary I guess? How else would you close the InputStream? Thanks for the answer!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T19:06:44.577", "Id": "28359", "Score": "0", "body": "After `BitmapFactory.decodeStream(in);` Why not?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T23:06:30.273", "Id": "28368", "Score": "0", "body": "Well if the `BitmapFactory.decodeStream(in);` throws an exception then `in.close()` won't get called." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T06:45:53.733", "Id": "28385", "Score": "0", "body": "[BitmapFactory.decodeStream](http://developer.android.com/reference/android/graphics/BitmapFactory.html#decodeStream%28java.io.InputStream%29)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T17:07:08.833", "Id": "28483", "Score": "0", "body": "Well I can't argue with facts :) It just seemed natural to me that it would throw an exception if the stream didn't represent a bitmap. Thanks!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T13:37:37.763", "Id": "17779", "ParentId": "17766", "Score": "2" } } ]
{ "AcceptedAnswerId": "17779", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T22:44:00.587", "Id": "17766", "Score": "1", "Tags": [ "java", "android" ], "Title": "Reading a Bitmap from disk on a separate thread on Android" }
17766
<p>I have a string containing around 1 million sets of float/int coords, i.e.:</p> <pre><code> '5.06433685685, 0.32574574576, 2.3467345584, 1,,,' </code></pre> <p>They are all in one large string and only the first 3 values are used. The are separated by 3 commas. The code i'm using right now to read through them and assign them to a list is below:</p> <pre><code> def getValues(s): output = [] while s: v1, v2, v3, _, _, _, s = s.split(',', 6) output.append("%s %s %s" % (v1.strip(), v2.strip(), v3.strip())) return output coords = getValues(tempString) </code></pre> <p>The end results need to be a list of the three floats in each set separated by a space, i.e.: </p> <pre><code> ['5.06433685685 0.32574574576 2.3467345584'] </code></pre> <p>The code I defined above does work for what I want, it just takes much longer than I would like. Does anyone have any opinions or ways I could speed it up? I would like to stay away from external modules/modules i have to download.</p> <p>Btw I don't think it's my computer slowing it down, 32gb ram and 350mb/s write speed, the program that creates the original string does it in about 20 secs, while my code above gets that same string, extracts the 3 values in around 30mins to an hour.</p> <p>P.s. Using python 2.6 if it matters</p> <p><strong>EDIT:</strong> Tried replacing the while loop with a for loop as I did some reading and it stated for loops were faster, it might have shaved off an extra minute but still slow, new code:</p> <pre><code> def getValues(s, ids): output = [] for x in range(len(ids)): v1, v2, v3, _, _, _, s = s.split(',', 6) output.append("%s %s %s" % (v1.strip(), v2.strip(), v3.strip())) return output </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T02:48:05.637", "Id": "28294", "Score": "0", "body": "Could a map perform faster then a for loop? What about multiprocessing.pool.map? Could anyone provide an example that I could apply the above too?" } ]
[ { "body": "<p>How about this?</p>\n\n<pre><code>import random\n\ndef build_string(n):\n s = []\n for i in range(n):\n for j in range(3):\n s.append(random.random())\n for j in range(3):\n s.append(random.randint(0, 10))\n s = ','.join(map(str, s))+','\n return s\n\ndef old_getvalues(s):\n output = []\n while s:\n v1, v2, v3, _, _, _, s = s.split(',', 6)\n output.append(\"%s %s %s\" % (v1.strip(), v2.strip(), v3.strip())) \n return output\n\ndef new_getvalues(s):\n split = s.split(\",\")\n while not split[-1].strip():\n del split[-1]\n outputs = [' '.join(split[6*i:6*i+3]) for i in range(len(split)//6)]\n return outputs\n</code></pre>\n\n<p>I get (using 2.7 here, but I get similar times on 2.6):</p>\n\n<pre><code>In [13]: s = build_string(3)\n\nIn [14]: s\nOut[14]: '0.872836834427,0.151510882542,0.746899728365,1,5,2,0.908901266489,0.92617820935,0.686859068595,1,0,1,0.0773422174111,0.874219587245,0.473976008481,7,9,2,'\n\nIn [15]: old_getvalues(s)\nOut[15]: \n['0.872836834427 0.151510882542 0.746899728365',\n '0.908901266489 0.92617820935 0.686859068595',\n '0.0773422174111 0.874219587245 0.473976008481']\n\nIn [16]: new_getvalues(s)\nOut[16]: \n['0.872836834427 0.151510882542 0.746899728365',\n '0.908901266489 0.92617820935 0.686859068595',\n '0.0773422174111 0.874219587245 0.473976008481']\n\nIn [17]: s = build_string(10001)\n\nIn [18]: old_getvalues(s) == new_getvalues(s)\nOut[18]: True\n</code></pre>\n\n<p>and times of</p>\n\n<pre><code>1000 old 0.00571918487549 new 0.00116586685181\n2000 old 0.0169730186462 new 0.00192594528198\n4000 old 0.0541620254517 new 0.00387787818909\n8000 old 0.240834951401 new 0.00893807411194\n16000 old 3.2578599453 new 0.0209548473358\n32000 old 16.0219330788 new 0.0443530082703\n</code></pre>\n\n<p>at which point I got bored waiting for the original code to finish. And it seems to work nicely on your full case, taking about 2s on my notebook:</p>\n\n<pre><code>In [32]: time s = build_string(10**6)\nCPU times: user 13.05 s, sys: 0.43 s, total: 13.48 s\nWall time: 13.66 s\n\nIn [33]: len(s), s.count(',')\nOut[33]: (51271534, 6000000)\n\nIn [34]: s[:200]\nOut[34]: '0.442266619899,0.54340551778,0.0973845441797,6,9,9,0.849183222984,0.557159614938,0.95352706538,10,7,2,0.658923388772,0.148814178924,0.553198811754,1,0,8,0.662939105945,0.343116945991,0.384742018719,9,'\n\nIn [35]: time z = new_getvalues(s)\nCPU times: user 1.14 s, sys: 0.75 s, total: 1.89 s\nWall time: 1.89 s\n\nIn [36]: len(z)\nOut[36]: 1000000\n\nIn [37]: z[:3]\nOut[37]: \n['0.442266619899 0.54340551778 0.0973845441797',\n '0.849183222984 0.557159614938 0.95352706538',\n '0.658923388772 0.148814178924 0.553198811754']\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T03:55:17.757", "Id": "28295", "Score": "0", "body": "Hm This looks very promising thanks for the respongs, I am having one thing that is a bit odd, every once in a while i get a result like this: '-5.46000003815 \\n\\t\\t\\t\\t\\t\\t\\t\\t6.95499992371 -0.194999933243'\nWhich is why i originally had the strip command in my above code, i see you have it in this too, any idea why it's not stripping?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T03:58:59.930", "Id": "28296", "Score": "1", "body": "`.strip()` only affects the start and the end of a line, not anything in the middle. I only put the `.strip()` in as a safety measure. If you want to get rid of that whitespace (I'm assuming you've read an entire file in), then either `.split()` the string or `.strip()` the individual elements." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T04:06:59.487", "Id": "28297", "Score": "0", "body": "ah ok I'm pretty new to python and wasn't aware of that for the .strip(), they are apparently already in my string, possibly that way from the source, any ideas on how to include a way to remove the newlines and tabs from within the script you provided, i.e without creating to much more inefficiency?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T04:14:03.893", "Id": "28298", "Score": "1", "body": "Probably the fastest would be to add `s = ''.join(s.split())` at the start of `new_getvalues()` -- that will split the string by whitespace and then join it back together. That might seem like it's doing more work, but it's actually faster than `.strip()`-ping each of the elements, because there's only one call to a builtin function. The secret to writing fast Python code is to push as much of the work into the library C code as possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T04:40:16.467", "Id": "28299", "Score": "0", "body": "You sir are truly a gentlemen and a scholar, I can't even believe how much faster it is, seriously (Its a sequence of frames, the last frame = the most data) before i was attempting at half way in the sequence, about 50,000 coords and it was taking 20-30mins, now i did the last frame, 1.5 million coords and it took barely 30 secs! I never realized how much more efficient C code is, very eye opening thank you so much for the time and help, you sir have given me hope for this world :p" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T04:42:59.850", "Id": "28300", "Score": "0", "body": "Just to clarify, I think the bottleneck in your original code was actually the recreation of the string `s` each time through the loop, which is why it showed such superlinear growth with n. But I'm glad to have helped." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T03:39:35.980", "Id": "17774", "ParentId": "17768", "Score": "1" } } ]
{ "AcceptedAnswerId": "17774", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T22:54:22.760", "Id": "17768", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "Python Optimizing/Speeding up the retrieval of values in a large string" }
17768
<p>I was interested in how this code can be improved apart from basic caching. This object creates 'tokens' much like that the iOS mail app and the tag section below.</p> <pre><code>var TokenTime = { assets : { tokenArray : [] }, init : function (){ var self = this; //add event handler $('#friend').on('keyup', function (event) { //test data to make sure its usable self.testData( $(this) , event ); }); }, testData : function ( obj , event ) { var self = this; if ( event.keyCode == 32 || event.keyCode == 13 ) { //create a local variable and store value var token = obj.val().split(' '); //make the array self.arrayMaker( obj, token ); } }, arrayMaker : function ( obj, token ) { var self = this; if( token[0] != "" ) { self.assets.tokenArray.push(token[0]); var html = $('&lt;li&gt;' + self.assets.tokenArray[self.assets.tokenArray.length - 1] + '&lt;span data-num=' + (self.assets.tokenArray.length - 1) + '&gt;x&lt;/span&gt;&lt;/li&gt;'); obj.before(html); obj.val(""); html.on('click', function (e) { $(this).remove(); var test = $(this).find('span').data('num'); }); } else { obj.val(''); } } } TokenTime.init(); </code></pre>
[]
[ { "body": "<p>First of all, there are jQuery plugins out there, that do this for you. <a href=\"http://loopj.com/jquery-tokeninput/\" rel=\"nofollow\">Tokeninput</a>, for example, comes to mind. But if you want to roll your own, by all means do so. I'll continue under that assumption.</p>\n\n<p>So here, in no particular order, are my observations</p>\n\n<ol>\n<li><p>Now, you've hardcoded the <code>#friend</code> selector. A better approach would be passing it as an argument to <code>init()</code>. Makes the code generic and reusable.</p></li>\n<li><p>If you do so, you'll also have to find another solution than the <code>assets.tokenArray</code> array, since that won't work if you're using your code for more than 1 input. (There are other problems, too. More on this later)<br>\nConversely, if you really do only need this for exactly 1 input, there are simpler structures you could use. For instance, just wrapping everything in a function.</p></li>\n<li><p>You're also adding <code>li</code> elements to... well, I don't know exactly, but <strong>it's not valid HTML</strong>. You're inserting the LIs immediately before the input element, which means that either the LIs are not in an OL or UL element (which is invalid), or that the input is in an OL or UL element (which is also invalid). The elements should show up anyway, but you can't be sure how different browsers will react, since one way or another it's not valid markup. I'd suggest passing a 2nd selector/element to <code>init()</code> to specify the element that the LIs should be appended to.</p></li>\n<li><p>You're inserting the token text directly into the HTML string you use to build the LI-elements. This can cause strange behaviour if someone types some HTML in the input field. Probably better to create an empty LI and then add the text using <code>.text()</code>.</p></li>\n<li><p>You have a SPAN element in the LIs, which I would imagine is there to remove the token. However, you're attaching the click-handler to the entire LI. So click anywhere on the token-LI, and the token is deleted. Not sure that's what you're going for.</p></li>\n<li><p>Speaking of, your code seems incomplete when it comes to the removing the token. You have the <code>num</code> data-property on the span, which I imagine is there so you can find the right index in the <code>tokenArray</code> and remove it. However, <strong>this won't work</strong>. For instance, if you add 3 tokens, they'll have <code>num</code> values 0, 1, and 2. So far, so good. If you remove the 2nd token, you'll have 2 tokens left with <code>num</code> values 0 and 2. However, <code>tokenArray</code> only has 2 elements now, numbered 0 and 1, so now you can't properly remove the last token anymore, because its <code>num</code> (2) doesn't correspond to a valid index in the array. And if you add a new token its <code>num</code> will be 2, so you now have 3 LI elements with <code>num</code>s 0, 2, and 2, and the linking between the array and the elements is messed up.<br>\nThe simplest solution is simply to use the LIs themselves <em>as</em> the array. Add their \"raw\" token text as a data property on the LI, and when you need an array of tokens, loop through the LIs, picking out that property (using jQuery's <code>.map()</code>, for example).</p></li>\n<li><p>You're using <code>split()</code> to get rid of spaces, but jQuery has a <code>$.trim()</code> function (\"trim\" being the usual name for a function that removes leading and trailing whitespace) that you can use instead. Of course, you could also just listen for a keydown.</p></li>\n<li><p>You keep declaring a <code>self</code> variable, even when not necessary. Besides, jQuery has a <code>$.proxy()</code> function that you can use to bind your event handler to a certain context.</p></li>\n<li><p>Your naming is a bit off. <code>arrayMaker</code> doesn't make an array, <code>testData</code> doesn't so much test data as it handles an event (and it doesn't actually test/check the token at all). I'd suggest <code>addToken</code> and <code>handleKeyup</code> as more descriptive names.</p></li>\n</ol>\n\n<p><a href=\"http://jsfiddle.net/sKzx2/1/\" rel=\"nofollow\">Here's a demo</a> of how I'd do it. It works for multiple inputs, too. Of course, it should really be a jQuery plugin, but I'll leave that as an exercise to the reader.</p>\n\n<p>Here's the code</p>\n\n<pre><code>// Set up event handlers etc.\nfunction tokenize(input, listElement) {\n // wrap the elements/selectors\n input = $(input);\n listElement = $(listElement);\n\n // event handler to remove a token to the list element\n function removeToken() {\n $(this).parent().remove();\n }\n\n // internal function to add tokens to the list element\n function addToken(text) {\n var item = $(\"&lt;li&gt;&lt;/li&gt;\"),\n removeButton = $(\"&lt;span&gt;X&lt;/span&gt;\");\n\n removeButton.on(\"click\", removeToken);\n\n item.text(text).data(\"token\", text).append(removeButton);\n listElement.append(item);\n }\n\n // attach the keyup event handler\n input.on(\"keyup\", function(event) {\n var token;\n if (event.keyCode == 32 || event.keyCode == 13) {\n token = $.trim(input.val());\n if (token) {\n input.val(\"\");\n addToken(token);\n }\n }\n });\n}\n\n// Get an array of tokens from a list element\nfunction tokens(list) {\n return $(list).children(\"li\").map(function() {\n return $(this).data(\"token\");\n }).toArray();\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T02:35:40.680", "Id": "17773", "ParentId": "17771", "Score": "3" } }, { "body": "<p>You should also wrap your code into a namespace with IIFE to avoid global conflict.</p>\n\n<p>i.e.</p>\n\n<pre><code>(function (token, undefined) {\n token.init = function () {\n var self = this;\n //add event handler\n $('#friend').on('keyup', function (event) {\n //test data to make sure its usable\n self.testData( $(this) , event );\n\n });\n };\n}(window.token = window.token || {}));\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T13:03:02.830", "Id": "28344", "Score": "0", "body": "Your sentence seems to say that an IIFE avoids immediate execution, which is false." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T08:18:58.320", "Id": "28512", "Score": "0", "body": "It's opposite, my bad I should have elaborated it :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T08:49:26.447", "Id": "28514", "Score": "0", "body": "-1: then it should be fixed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T10:16:40.970", "Id": "29088", "Score": "0", "body": "It's fixed now, can you please make up?" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T05:57:48.777", "Id": "17802", "ParentId": "17771", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T23:32:46.973", "Id": "17771", "Score": "4", "Tags": [ "javascript", "jquery" ], "Title": "Tokenizer object" }
17771
<p>Does the code below look correct and efficient for removing duplicates from an unsorted linked list without using extra memory?</p> <p>An object of type Node denotes a LL node. </p> <pre><code>void removeDuplicates() { Node current = head; while(current!=null) { Node prev = current; Node next = current.next; while(next!=null) { if(current.equals(next)) { prev.next = next.next; } else { prev = next; } next = next.next; } current = current.next; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T01:43:53.627", "Id": "28291", "Score": "1", "body": "It seems your method only remove the adjacent duplicate elements. is that the case?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T02:42:21.557", "Id": "28292", "Score": "0", "body": "no i don't intend for it to be that way. Every node is being compared to every NEXT LL node up to the end of the list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T02:45:44.687", "Id": "28293", "Score": "0", "body": "Can you cite some examples of what you are saying" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T07:08:22.210", "Id": "28302", "Score": "1", "body": "OK, take an unsorted list for example, 1->1->2->1->3->2->2->3, you code want to get a result of 1->2->3, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T10:03:52.217", "Id": "28306", "Score": "0", "body": "I think I understand your code now, you are right! but I have another version with a little difference, we can save a pointer, please see my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T22:23:03.903", "Id": "28366", "Score": "0", "body": "For the case you pointed out, it works fine." } ]
[ { "body": "<p>This review is two-fold: once, in case you have to uphold your restriction and then what changes if you allow extra space.</p>\n\n<h2>Review</h2>\n\n<ul>\n<li><p><em>Comments</em>: they are simply missing. You need at least some javadoc, and for non-trivial methods like this some more never hurts. Oh, and skip the usual excuses about how this code is somehow special and doesn't need comments.</p></li>\n<li><p><em>Clarity and Intent</em>: <code>if (current.equals(head))</code> reads like you are comparing the actual nodes, while duplicity is a matter of equal node values. You may have overwritten the <code>equals</code> method accordingly (I assume so for the sake of correctness), but I would prefer to clearly portray your original intent here by comparing the actual values.</p></li>\n<li><p><em>Efficiency and readability</em>: As the answer by zdd points out you could save one pointer, but that's kind of pointless. I prefer your version as its much clearer to a reader what <code>current</code>, <code>prev</code> and <code>next</code> are. However,efficiency is not going to get below <code>O(n^2)</code> with this approach.</p></li>\n</ul>\n\n<h2>Efficiency Improvement</h2>\n\n<p>You said that you need a solution \"without using extra memory\". What you really meant of course is a solution \"with only a constant amount of additional memory\" (your pointers require memory as well after all). What you did not require, however, is that this operation has to leave the list elements' ordering intact. Therefore, a faster approach in <code>O(n log(n))</code> would be to first sort the list (in-place to satisfy the memory requirement), then simply walk through the list comparing only neighbors (another <code>O(n)</code>). While this does not make much difference of course for smaller lists, the memory requirement indicates much larger lists, and then the difference between <code>O(n^2)</code> and <code>O(n log(n))</code> may well be the difference between another problem and a solution.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T13:23:23.647", "Id": "28345", "Score": "0", "body": "Frank thank you for the comments. I skipped writing the equals method but it is intended to compare node equality of data. You mention sorting linked lists. Will it be a merge sort for linked lists ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:36:45.917", "Id": "28348", "Score": "0", "body": "Yes, you would probably use a merge sort, as it suits the linked list nicely. Ideally, you could simply use `Collections.sort`, but that makes a copy, which requires linear memory." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T05:38:56.897", "Id": "17801", "ParentId": "17772", "Score": "4" } }, { "body": "<p>If you use Java, you can use <code>contains</code> method.</p>\n\n<p>Then, if you replace <code>ArrayList</code> by <code>LinkedList</code> in the <a href=\"https://codereview.stackexchange.com/a/17805/15023\">code here</a>, and forget decoration, you can remove duplicate.</p>\n\n<p>Using a temporary additinional <code>List</code> simplify the complexity.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T08:55:51.597", "Id": "17807", "ParentId": "17772", "Score": "2" } } ]
{ "AcceptedAnswerId": "17801", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T00:17:06.870", "Id": "17772", "Score": "6", "Tags": [ "java", "algorithm", "linked-list" ], "Title": "Removing duplicates from an unsorted linked list" }
17772
<p>I'm new to Java and have been through some tutorials and I'm in the next step of checking how I'm doing now. Is there a better way of doing this?</p> <pre><code>import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.Collections; import java.util.Date; import java.util.Vector; import org.apache.log4j.helpers.FileWatchdog; /** * * Simple class that reads in a file - sorts its lines in natural order, * writes it back out to the given filename and adds a timestamp of when it was sorted * * Program will be called with: * * java TestClass &lt;input_filename&gt; &lt;output_filename&gt; * */ public class TestClass { public static void main(String [] args) throws RuntimeException{ boolean OVERWRITE_FILE = true; //get filename from args String inputFilename = args[0]; String outputFilename = args[1]; //check usage if(args.length != 2){ System.out.println("Incorrect number of args"); System.out.println("Correct usage is:"); System.out.println(" java TestClass &lt;input_filename&gt; &lt;output_filename&gt; "); System.exit(-1); } //read in file into collection try { BufferedReader in = new BufferedReader(new FileReader(inputFilename)); Vector fileContents = new Vector&lt;Object&gt;(); while(in.ready()){ fileContents.add(in.readLine()); } //sort the collection in natural order Collections.sort(fileContents); //add timestamp fileContents.add("File Sorted on: "); fileContents.add(new Date()); //write outputFile BufferedWriter out = new BufferedWriter(new FileWriter(outputFilename, OVERWRITE_FILE)); for(int i = 0; i &lt; fileContents.size(); i++){ out.write((String)fileContents.get(i) + "\n"); } //close output file out.close(); } catch (IOException e) { System.out.println("Error while performing IO"); } } } </code></pre>
[]
[ { "body": "<p>Welcome to Code Review.</p>\n\n<p>Before reviewing your code, it needs to be fixed:</p>\n\n<h2>First, make it work...</h2>\n\n<ol>\n<li><p><strong>Usage is never printed</strong> </p>\n\n<p>Your program is supposed to print the usage instructions if the wrong number of parameters ist supplied. Check what happens if you run it without any parameters:</p>\n\n<blockquote>\n <p>Exception in thread \"main\" </p>\n\n<pre><code>java.lang.ArrayIndexOutOfBoundsException: 0\nat codereview.TestClass.main(TestClass.java:30)\n</code></pre>\n</blockquote>\n\n<p>To fix this, you need to check the length of <code>args</code> <em>before</em> accessing <code>args[0]</code> and <code>args[1]</code>.</p></li>\n<li><p><strong>Failure because of unnecessary cast</strong><br>\nIf the correct number of arguments is supplied, your program will fail with the following output:</p>\n\n<blockquote>\n <p>Exception in thread \"main\" </p>\n\n<pre><code>java.lang.ClassCastException: java.util.Date cannot be cast to java.lang.String\nat codereview.TestClass.main(TestClass.java:59)\n</code></pre>\n</blockquote>\n\n<p>This is because you inserted a <code>Date</code> object into your <code>fileContents</code> Vector. Please <strong>thoroughly study generics</strong> as a better understanding of this important topic would have prevented the error.</p>\n\n<p>For now, just remove the cast <code>(String)fileContents.get(i)</code> and test your code. A complete solution is given later in this answer. <em>No, <strong>really</strong> run your code now.</em> You'll see that there is another problem:</p></li>\n<li><p><strong>Sorting is not in the natural order</strong></p>\n\n<p>You are sorting a list of Strings. This means that the sort order will always be <em>alphabetical</em> (1,3,10,12 would be sorted as 1,10,12,3) even though your documentation comments state that the lines are sorted in their <em>natural</em> order. You can't promise to do that without knowing what kind of input they contain. As it currently stands, you should just change your comments.</p></li>\n<li><p><strong>You are appending to the end of the output file</strong><br>\nThe signature of the <code>FileWriter</code> constructor is:</p>\n\n<pre><code>public FileWriter(String fileName, boolean append) throws IOException\n</code></pre>\n\n<p>So your <code>OVERWRITE_FILE</code> is a lie. Rename it to <code>APPEND_FILE</code> and set it to false (a cleaner, completely different solution will be given below).</p></li>\n</ol>\n\n<hr>\n\n<h2>... then, clean it up.</h2>\n\n<h3>General issues</h3>\n\n<ul>\n<li><p>You have several unused imports. Remove them.</p></li>\n<li><p><code>RuntimeException</code> is <em>unchecked</em>, so you should remove <code>throws RuntimeException</code> from <code>main</code>.</p></li>\n<li><p>Your error messages are unhelpful. <code>Error performing IO</code> does not tell the user what went wrong. </p></li>\n</ul>\n\n<h2>Code structure</h2>\n\n<p>Readability, maintainability, reusability: you should strive to achieve these three goals in your code (apart from correctness, of course, which goes above all else). One problem with your code is that <em>everything happens directly inside <code>main</code></em>. You should <em>delegate</em> the bulk of your work into helper methods:</p>\n\n<pre><code>public static void main(String[] args) {\n try\n {\n validateNumberOfArguments(args.length);\n String inputFilename = args[0];\n String outputFilename = args[1];\n List&lt;String&gt; lines = readLinesFrom(inputFilename);\n sortAndAddTimestampTo(lines);\n writeLinesTo(outputFilename, lines);\n }\n catch (IOException e){\n exitBecause(\"Error accessing file\", e);\n }\n}\n</code></pre>\n\n<p>This gives a nice overview of what your code does - similar to article headings in a newspaper or chapters in a book. </p>\n\n<p>Here's the implementation. Your <code>main</code> has been split up into concise methods. Each of them does one thing, so they are easy to understand. </p>\n\n<pre><code>private static void validateNumberOfArguments(int length) {\n if (length != 2) {\n exitBecause(\"Incorrect number of args\", \"Correct usage is:\", \n \"java TestClass &lt;input_filename&gt; &lt;output_filename&gt;\");\n }\n}\n\nprivate static List&lt;String&gt; readLinesFrom(String path) throws IOException {\n return Files.readAllLines(getPath(path), StandardCharsets.UTF_8);\n}\n\nprivate static void sortAndAddTimestampTo(List&lt;String&gt; lines) {\n Collections.sort(lines);\n lines.add(\"File sorted on: \");\n lines.add(new Date().toString());\n}\n\nprivate static void writeLinesTo(String path, List&lt;String&gt; lines) throws IOException {\n Files.write(getPath(path), lines, StandardCharsets.UTF_8);\n}\n\nprivate static Path getPath(String fileName) {\n return new File(fileName).toPath();\n}\n\nprivate static void exitBecause(Object... reasons) {\n for (Object reason : reasons) {\n System.out.println(reason);\n }\n System.exit(-1);\n}\n</code></pre>\n\n<p>Required imports (JRE7):</p>\n\n<pre><code>import java.io.File;\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Path;\nimport java.util.Collections;\nimport java.util.Date;\nimport java.util.List;\n</code></pre>\n\n<p>The error messages will now be a bit more helpful:</p>\n\n\n\n<pre class=\"lang-none prettyprint-override\"><code>Error accessing file\njava.nio.file.NoSuchFileException: input.txt\n</code></pre>\n\n<p>or</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>Error accessing file\njava.io.IOException: The process cannot access the file because it is being used by \nanother process\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T17:34:00.870", "Id": "17782", "ParentId": "17781", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T16:13:03.820", "Id": "17781", "Score": "4", "Tags": [ "java", "sorting", "file" ], "Title": "Sorting file lines in natural order" }
17781
<p>I have an app that has a number ajax requests and instead of writing them all out, I created a plugin that takes options based on the request I am making.</p> <p>I would like the ajax requests to occur when page loads and when the user clicks, mouses over certain buttons.</p> <p>I decided to use the jquery.bind() method to bind the ajax request to what event takes place. But I am running into a problem when the event is 'load' and the jquery selector is $('window') or document.</p> <p>Currently, I put a conditional statement to make it work, but then I have write the same function twice just for the 'load' event like this: </p> <pre><code>(function($) { $.fn.getData = function(options) { var defaults = { eventType : "load", // more default options } var options = $.extend(defaults, options); if (options.eventType == "load") { $.ajax({ // ajax object with options }); } else { return this.bind(options.eventType, function() { $.ajax({ // ajax object with options }); return false; }); } } })(jQuery); </code></pre> <p>So when on my view pages, I call the plugins like this:</p> <pre><code>// for click events $('#selector').getData({ eventType : 'click', // other default options }); // need ajax when page loads $('window').getData({ eventType : 'load', // other default options }); </code></pre> <p>I don't know if there is anyway around writing the function twice and I'm also unsure that it's even good practice to bind event handler to the Window's page load event, but not sure else how to make this plugin flexible to work with browser events like page load and user events like click, mouseover.</p> <p>Any help would be greatly appreciated. Thanks</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T19:14:57.610", "Id": "28422", "Score": "0", "body": "To, hopefully, prevent further close votes: This topic **IS** on topic. The code works, he simply had an issue getting it to that point. Read all the way through the post please." } ]
[ { "body": "<p>Edit: The part below was, I think, me not seeing the forest for all the trees. The issue is quite simply that you're passing the <em>string</em> <code>'window'</code> to jQuery, rather than the <em>object</em> <code>window</code>. So jQuery tries to bind an event listener to a <code>&lt;window&gt;</code> HTML element - which, obviously, does not exist.</p>\n\n<p>What you want, is</p>\n\n<pre><code>$(window).bind(\"load\", function () { .... });\n</code></pre>\n\n<p>or, better:</p>\n\n<pre><code>$(window).on(\"load\", function () { .... });\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$(window).load(function () { .... });\n</code></pre>\n\n<p>or, simply</p>\n\n<pre><code>$(function () { .... });\n</code></pre>\n\n<p>basically, anything other than trying to pass the string <code>'window'</code></p>\n\n<hr>\n\n<p>Actually, the least flexible part of your code are the ajax requests themselves. If the ajax options are hard-coded in the plugin, you still don't have much flexibility; it's the same ajax requests each time. For instance, if you want to load ajax on a scroll event, you still have to edit the plugin to add the ajax request options and/or add an <code>if(options.eventType === \"scroll\")</code>. So you're splitting your code up, but not gaining any real flexibility.</p>\n\n<p>I'd suggest making a simple function that takes an element, an event type, and some ajax options, so you can bind any event to any ajax request. Something like</p>\n\n<pre><code>function bindAjax(element, event, ajaxOptions) {\n ajaxOptions = $.extend({\n // default ajax options, if any\n }, ajaxOptions);\n\n $(element).on(event, function (event) {\n $.ajax(ajaxOptions);\n event.preventDefault();\n });\n}\n\nbindAjax(window, \"load\", { ... });\n</code></pre>\n\n<p>You don't gain <em>that</em> much by doing this, though, compared to \"raw\" jQuery code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T02:37:01.540", "Id": "28337", "Score": "0", "body": "Hey thanks a lot for the response..To your point about having to have an if statement for each new event...That's actually not the case. If I change the event type to mouseover, keyup, etc, I still only need one code block to handle all events...The issue I was running into was when I tried to bind a handler to the Window's page 'load' event. If $('body').bind('load', function() {}); worked, I'd be in business, i would only need one code block to handle all events." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T02:42:15.627", "Id": "28338", "Score": "0", "body": "@elgarcon Not quite sure, I follow you, _but_ I think I found reason you're having trouble with the load-event; you should be using `$(window).bind('load', ...);` - you're quoting `'window'`. You should also be using `.on` rather than `.bind`, by the way. Or `.load`. Or simply `$(function () { ... });`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T20:06:22.673", "Id": "17786", "ParentId": "17784", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T18:25:14.780", "Id": "17784", "Score": "1", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "Ajax plugin that binds to click and page load" }
17784
<p>In my Java program, I need to operate on the sublists a of <code>ArrayList</code> or <code>LinkedList</code> often, like removing a sublist, comparing two sublists.</p> <p>For <code>ArrayList</code> or <code>LinkedList</code>, I didn't find any good APIs to do these. My current implementation is as below. Basically, it takes an input like:</p> <pre><code>u1234 u1236 u1236 u2def u1236 u1236 u2def </code></pre> <p>and outputs the following:</p> <pre><code>u1234 ( ( u1236 ) * u2def ) * </code></pre> <p>Core function:</p> <pre><code>ArrayList&lt;String&gt; toRegex(ArrayList&lt;String&gt; tokenArray) { /* check different length of continuous duplication */ for(int len=1; len&lt;=tokenArray.size()/2; len++) { boolean match = false; /* given a length, scan for duplication */ for(int i=0; i&lt;tokenArray.size()-(2*len-1); i++) { ArrayList&lt;String&gt; first = new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; second = new ArrayList&lt;String&gt;(); for(int j=i; j&lt;i+len; j++) first.add(tokenArray.get(j)); for(int j=i+len; j&lt;i+2*len; j++) second.add(tokenArray.get(j)); if(isSpecial(first)) { /* skip the cases */ continue; } while(isIdentical(first, second)) { match = true; for(int j=i+len; j&lt;i+2*len; j++) tokenArray.remove(i+len); if(i+2*len &gt; tokenArray.size()) break; second.clear(); for(int j=i+len; j&lt;i+2*len; j++) second.add(tokenArray.get(j)); } if(match == true) { tokenArray.add(i, "("); tokenArray.add(i+1+len, ")"); tokenArray.add(i+2+len, "*"); i = i+3+len; match = false; } } } return tokenArray; } </code></pre> <p>Currently, the performance is not good. Could you find the bad design or inappropriate usage of data structures/APIs? What are the good common ways of operating sublists?</p>
[]
[ { "body": "<p>Yes, this doesn't look pretty. Consider converting the list to sets or using RegEx.</p>\n\n<pre><code>ArrayList&lt;String&gt; A = new ArrayList&lt;String&gt;();\nA.add(\"Z\");\nA.add(\"Z\");\nA.add(\"C\");\nA.add(\"X\");\nA.add(\"Z\");\n\nSet&lt;String&gt; set = new HashSet&lt;String&gt;(A);\n\nfor(String temp:set)\n System.out.println(temp); \n</code></pre>\n\n<p>Sublists: </p>\n\n<pre><code>List&lt;String&gt; subList = alist.subList(2, 4);\n</code></pre>\n\n<p>Use retainAll to get intersections:</p>\n\n<pre><code>listOne.retainAll(listTwo) ; \nboolean areEqualNotSamePosition = listeOne.size();\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T19:28:08.257", "Id": "17789", "ParentId": "17788", "Score": "2" } }, { "body": "<pre><code>public static void main(final String[] args) {\n final String[] tabS = \"u1234 u1236 u1236 u2def u1236 u1236 u2def \"\n .split(\" \");\n // The same thing can be done/adapted with a String[]\n final ArrayList&lt;String&gt; al = new ArrayList&lt;&gt;();\n final ArrayList&lt;String&gt; alTmp = new ArrayList&lt;&gt;();\n for (final String s : tabS) {\n al.add(s);\n }\n // removing need to begin by end\n for (int i = al.size() - 1; i &gt;= 0; i--) {\n final String string = al.get(i);\n if (!alTmp.contains(string)) {\n alTmp.add(string);\n } else {\n al.remove(i);\n }\n }\n // inserting decoration if result have 2 or more object\n final int j = al.size();\n final String ending = \")*\";\n if (j &gt; 1) {\n for (int i = 1; i &lt; j; i++) {\n al.add(1, \"(\");\n }\n for (int i = al.size() - 1; i &gt; j; i--) {\n al.add(i, ending);\n }\n al.add(ending);\n }\n System.out.println(al.toString());\n }\n</code></pre>\n\n<p><br>\nOutput :\n<code>[u1234, (, (, u1236, )*, u2def, )*]</code><br>\nYou can use a <code>StringBuilder</code> to remove '<code>'</code>' and make the output as you like.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T08:30:47.830", "Id": "17805", "ParentId": "17788", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T18:39:30.977", "Id": "17788", "Score": "6", "Tags": [ "java", "performance", "linked-list" ], "Title": "Operating sublists efficiently" }
17788
<p>I've written this simple script to force download some files (jpg, mp3, usually those which are loaded in browser by default). I was wondering whether there's any way this could be improved upon, which means:</p> <ul> <li>making it more secure</li> <li>making it use less cpu (filesize(), fopen(), fpassthru() are the usual suspects here)</li> <li>making it simpler maybe</li> </ul> <p>Here it goes:</p> <pre><code>&lt;?php if (!isset($_GET['file'])){ die('no file requested'); } else{ if (substr($_GET['file'], 0, 1) == '.'){ die('trying to leave this directory? :)'); } $path = './'.$_GET['file']; if (file_exists($path) &amp;&amp; is_readable($path)){ $size = filesize($path); header('Content-Type: application/octet-stream'); header('Content-Length: '.$size); header('Content-Disposition: attachment; filename='.$_GET['file']); header('Content-Transfer-Encoding: binary'); $file = fopen($path, 'rb'); fpassthru($file); exit; } } ?&gt; </code></pre> <p>Usage: <code>/?file=sample.jpg</code></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:35:16.017", "Id": "28326", "Score": "1", "body": "Before you start worrying about the microscopic amount of cpu time that filesize() will consume, you should start panicking about how this script lets a malicious user download ANY file on your server for which they know the path. Your substr test is **NOT** sufficient" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:35:16.053", "Id": "28327", "Score": "0", "body": "@MarcB: please, do elaborate (why the substr check isn't enough)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:35:48.620", "Id": "28328", "Score": "2", "body": "`http://example.com?file=/../../../../../../etc/passwd` first char is a `/`, not ., and file path operations will collapse `//` into a single `/`, so you've done nothing to secure things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:36:30.407", "Id": "28329", "Score": "0", "body": "@MarcB: you seem to know the game, why not submit an answer? I'll be happy to upvote and accept it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:37:31.897", "Id": "28330", "Score": "0", "body": "Also, I would check for the ':' (for higher portability) and for encoded 'file://' and other schemes" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T16:39:45.530", "Id": "28331", "Score": "0", "body": "naw, not going to submit it... technically it's not the answer to your question." } ]
[ { "body": "<p>what about just puting a link to that file?</p>\n\n<p>for example:</p>\n\n<pre><code>&lt;a href=\"/file.mp3\"&gt;download file&lt;/a&gt;\n</code></pre>\n\n<p>as far as i know it depends of the user configs if it will download it or use it in the browser</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:35:13.340", "Id": "17791", "ParentId": "17790", "Score": "1" } }, { "body": "<p>Always use <code>===</code> in your comparisons.</p>\n\n<pre><code>if (substr($_GET['file'], 0, 1) == '.'){\n die('trying to leave this directory? :)');\n}\n</code></pre>\n\n<p>Should be:</p>\n\n<pre><code>if (substr($_GET['file'], 0, 1) === '.'){\n die('trying to leave this directory? :)');\n}\n</code></pre>\n\n<p>Also look into other ways to sanitize <code>$_GET['file']</code> properly at the moment I could pass in something like <code>/../</code> and I could access other files.</p>\n\n<p>From the docs you can save on a <code>fopen()</code> call by using <a href=\"http://www.php.net/manual/en/function.readfile.php\" rel=\"nofollow\"><code>readfile()</code></a> instead see <a href=\"http://php.net/manual/en/function.fpassthru.php\" rel=\"nofollow\"><code>fpassthru()</code></a></p>\n\n<p>A better way to use variables in a string is to use <a href=\"http://www.php.net/manual/en/language.types.string.php#language.types.string.parsing.complex\" rel=\"nofollow\"><code>curly syntax</code></a> so this line</p>\n\n<pre><code>header('Content-Disposition: attachment; filename='.$_GET['file']);\n</code></pre>\n\n<p>Would be better as</p>\n\n<pre><code>header(\"Content-Disposition: attachment; filename={$_GET['file']}\");\n</code></pre>\n\n<p>I think that covers the three bullet points :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T16:26:00.713", "Id": "28332", "Score": "0", "body": "There seems to be a problem with my current code anyway. It cannot send big files. Any idea how to resolve this? ``PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 594223105 bytes) in index.php on line 21``" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T17:19:21.127", "Id": "28414", "Score": "0", "body": "The absolute comparison rule is subjective. If you are comparing for the same type as well as value, then yes, the absolute `===` is better. But if all you want is to compare for a pattern, then the loose comparison is fine `==`. Also, \"curly syntax\" is a matter of preference. Both methods are perfectly fine and it is up to the author whether they want to use one over the other. There is no difference except in subjective legibility." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T19:28:21.073", "Id": "28426", "Score": "0", "body": "Not sure I agree on the === vs == argument. If it was down to me I'd never see == in PHP code there's no need for it. Any code that is relying on == to do the comparison is probably a code smell." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T19:36:07.647", "Id": "28427", "Score": "0", "body": "They do essentially the same thing, but their purposes are as I described. Many share your opinion, many don't. That's why I said it was subjective. Here's a related [SO Question/Answer](http://stackoverflow.com/a/80649/1015656) and here's the [official documentation](http://php.net/manual/en/language.operators.comparison.php)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:39:28.493", "Id": "17792", "ParentId": "17790", "Score": "4" } }, { "body": "<p>A small improvement I've spotted, take care to enclose the filename in double quotes to handle the case when file name contains spaces, like so:</p>\n\n<pre><code>header('Content-Disposition: attachment; filename=\"'.$_GET['file'].'\"');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:41:32.897", "Id": "17793", "ParentId": "17790", "Score": "4" } }, { "body": "<p>You should never accept a user to send a <strong>path</strong>, only accept file names as input, only you in the server side will know where directory go to get that file, so use <a href=\"http://php.net/manual/en/function.basename.php\" rel=\"nofollow\">basename()</a> for that:</p>\n\n<pre><code>$_GET['file'] = basename( $_GET['file'] ); //permit only filename\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:51:28.517", "Id": "28333", "Score": "0", "body": "``$_GET['file']`` is expected to be a filename and never a path, yes." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:49:41.590", "Id": "17794", "ParentId": "17790", "Score": "4" } }, { "body": "<p>It's much better to avoid using PHP and allow your web server to manage this. If you're using Apache, the following lines in your .htaccess file will do the trick quite nicely.</p>\n\n<pre><code>AddType application/octet-stream .jpg \nAddType application/octet-stream .mp3\n</code></pre>\n\n<p>This is much less server intensive and more secure.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T00:21:29.083", "Id": "17826", "ParentId": "17790", "Score": "4" } }, { "body": "<p>I agree with most of these other answers, there are just a few things I thought I'd point out.</p>\n\n<p>I would never directly use user input. Always sanitize and validate it. You've already validated, you just need to sanitize. An easy way to do this if your PHP version is >= 5.2 is to use <code>filter_input()</code>.</p>\n\n<pre><code>$file = filter_input( INPUT_GET, 'file', FILTER_SANITIZE_STRING );\n\n$path = \"./$file\";\nif( file_exists( $path ) &amp;&amp; is_readable( $path ) ) {\n //etc...\n header( \"Content-Disposition: attachment; filename=$file\" );\n}\n</code></pre>\n\n<p>You should use <code>is_file()</code> instead of <code>file_exists()</code>. The difference is that the latter doesn't assume its parameter is an actual file and will also return TRUE for directories. However, neither is actually necessary in this context. <code>is_readable()</code> also checks if a file exists, so this is redundant and unnecessary. Just use <code>is_readable()</code>.</p>\n\n<pre><code>if( is_readable( $path ) ) {\n</code></pre>\n\n<p>Depending on the size of these files, imploding the input into an array and iterating over that will allow you to download multiple files, though at this point you will want to offer links to said files instead of automatically generating a save file dialog.</p>\n\n<pre><code>$filestring = filter_input( INPUT_GET, 'file', FILTER_SANITIZE_STRING );\n$files = implode( ',' $filestring );\nforeach( $files AS $file ) {\n //this is where having a function, as Jack mentioned, would be handy\n}\n</code></pre>\n\n<p>My final suggestion. Don't use an if/else statement if you can get away with just using the if. Your if statement returns early, therefore the else statement is implied. There is no need to explicitly use an else statement and force yourself to indent your code unnecessarily. This will help you to avoid the Arrow Anti-Pattern.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T18:58:42.123", "Id": "17854", "ParentId": "17790", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-21T15:31:36.710", "Id": "17790", "Score": "5", "Tags": [ "php" ], "Title": "Is there a better way how to force file download than using this simple PHP script?" }
17790
<p>I am wondering if the code beneath considered as the proper way to achieve the topics stated in the title of the post.</p> <p>I wonder is the best practice for achieving it?</p> <pre><code>var Obj = function() { if (arguments.length) { //do something for (var i in arguments) //iterate over the arguments alert(arguments[i]); } }; Obj.prototype.foo = function() { alert("foo"); return this; }; Obj.prototype.bar = function() { alert("bar"); return this; }; Obj.spam = function() { alert("spam"); }; //varargs constructor var varargs = ["arg1", "arg2"]; new Obj(); new Obj(varargs); new Obj("a", "b", 1, 2.5); //method chaining new Obj().foo().bar(); //static method Obj.spam(); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-20T09:30:41.720", "Id": "28334", "Score": "0", "body": "Why not just use `arguments` from within the function?" } ]
[ { "body": "<p>Answer: Yes, yes, and yes.</p>\n\n<p>Honestly, I'm wondering how else you'd achieve it. The <code>arguments</code> object exists to let you access whatever was passed; <code>return this</code> is really the only way to allow chaining; and the \"static\" method is technically just an object property, and that's the way you define those.</p>\n\n<p>Only things I'd add is that you can easily convert the <code>arguments</code> object - which is \"array-like\" but not actually an array - to a real array by saying <code>[].slice.call(arguments, 0);</code>. Useful for looping, slicing, etc.. And you should always use braces/curly brackets - even if the \"block\" is just 1 line - just good code hygiene. Oh, and when in doubt, use <code>hasOwnProperty()</code> in a <code>for...in</code> loops.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T01:17:37.757", "Id": "17798", "ParentId": "17796", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-19T15:46:52.567", "Id": "17796", "Score": "2", "Tags": [ "javascript" ], "Title": "Javascript - varargs constructors, method chaining, and static methods" }
17796
<h2>Q.</h2> <p>Basically this piece of code appears in my class constructor. It's working, but it seems very confusing. </p> <p>It basically checks if the jQuery library is present locally and if it's not it will try to download it.</p> <p>Is there any way I can improve this? Namely avoiding re-setting vars all the time?</p> <hr> <h2>CODE:</h2> <pre><code>//First we check if JQuery version is correct if ( isset($versionList-&gt;$version) ) { $filePathFull = __DIR__ . '/versions/jquery-' . $version . '.js'; $filePathMin = __DIR__ . '/versions/jquery-' . $version . '.min.js'; $this-&gt;versionLoaded = $version; //Now we check if the JQuery version is installed if ( !file_exists($filePathFull) || !file_exists($filePathMin)) { // They are not installed, so we will try to download and install it if (!self::installVersion($version)) { // Download failed, so we try the defaults $filePathFull = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.js'; $filePathMin = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.min.js'; $this-&gt;versionLoaded = JQuery::DEFAULT_VERSION; } } } else { //Version is incorrect we go with the defaults $filePathFull = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.js'; $filePathMin = __DIR__ . '/versions/jquery-' . JQuery::DEFAULT_VERSION . '.min.js'; $this-&gt;versionLoaded = JQuery::DEFAULT_VERSION; } //This is a redundant check to see if the defaults are installed if ( !file_exists($filePathFull) || !file_exists($filePathMin) ) { // They are not installed, so we will try to download and install it if (!self::installVersion(JQuery::DEFAULT_VERSION)) { //Defaults are not installed so we throw an exception throw new Exception("Nor the version $version or the default version " . JQuery::DEFAULT_VERSION . " could be found or downloaded"); } } </code></pre> <hr> <p>Edit:</p> <h2>MORE DETAILS</h2> <p>A more detailed explanation... </p> <p>As you correctly assumed, this is a "plugin". The plugable system requires wrapped JavaScript libraries in PHP classes that are used for a JS Dependency Manager. The JS Dependency Manager extends <a href="http://getcomposer.org/" rel="nofollow">Composer</a> which constrains how we handle this a bit. We have, however, freedom to chose how we wrap the JS Library.</p> <p><strong>Goals:</strong></p> <ol> <li>Avoidance of library repetition (like having 2 versions of jQuery running which causes weird JS bugs)</li> <li>Automatic update of 3rd party JavaScript (directly from the repository instead of downloading and including them directly)</li> <li>Caching, Minimizing and removal of dead code from JS Scripts through Google Closure Compiler</li> <li>Libraries and scripts dependency management (specially regarding specific library versions such as jquery)</li> </ol>
[]
[ { "body": "<p>Try this, just removed a couple of the repeated code (moved it to a function) and sets minified version or regular version based on a bool variable (getminified), thus you only have filePathFull (no longer have filePathMin):</p>\n\n<pre><code># Set `true` if minified version is preferred.\n// let's assume its in a class somewhere\npublic $getMinified = true;\n\n# DRY\nfunction getFilePath($version){\n $start = __DIR__ . '/versions/jquery-';\n $end = ($someClass-&gt;getMinified == true ? '.min.js' : '.js');\n return $start . $version . $end;\n}\n\n# First we check if JQuery version is correct \nif ( isset($versionList-&gt;$version) ) {\n $filePathFull = getFilePath($version); // DRY\n $this-&gt;versionLoaded = $version;\n\n # Now we check if the JQuery version is installed\n // Why two if statements? Lets just concat the ifs \n if ( !file_exists($filePathFull) &amp;&amp; !self::installVersion($version) ) {\n # Download failed, so we try the defaults\n $filePathFull = getFilePath(JQuery::DEFAULT_VERSION); // DRY\n $this-&gt;versionLoaded = JQuery::DEFAULT_VERSION;\n }\n} else {\n #Version is incorrect we go with the defaults\n $filePathFull = getFilePath(JQuery::DEFAULT_VERSION); // DRY\n $this-&gt;versionLoaded = JQuery::DEFAULT_VERSION;\n}\n\n\n#This is a redundant check to see if the defaults are installed\nif ( !file_exists($filePathFull) ) {\n\n # They are not installed, so we will try to download and install it\n if (!self::installVersion(JQuery::DEFAULT_VERSION)) {\n #Defaults are not installed so we throw an exception\n throw new Exception(\"Nor the version $version or the default version \" . JQuery::DEFAULT_VERSION . \" could be found or downloaded\");\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T17:39:43.610", "Id": "28355", "Score": "0", "body": "Don't you need a `global $getMinified` line in `getFilePath()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T17:47:10.217", "Id": "28356", "Score": "1", "body": "@Flambino: Should probably be a property, though I haven't finished reading this yet." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T18:06:41.703", "Id": "28357", "Score": "0", "body": "Yeah, should be a property. But without knowing what the rest of the class looks like (or if this is even a method within a class)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T18:52:39.993", "Id": "28358", "Score": "1", "body": "Still, the implication that it might be a global scares me DX" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T19:19:24.817", "Id": "28360", "Score": "0", "body": "True...I'll edit it to assume that its in a class somewhere" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T12:35:09.410", "Id": "28406", "Score": "0", "body": "Edited my question to clarify some points. Thanks for your suggestion. The class should provide a \"normal\" jScript and a minified version if exists. If it does not exist, the Plugin Manager with minify it. But which one is used isn't decided here, but rather in the Plugin Manager." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T16:07:18.170", "Id": "28411", "Score": "0", "body": "I don't think (and mseancole and Flambino back me up here if you agree) that this code should go in your construct, but rather be relegated to its own function and have your Plugin Manager set `public $getMinified = true;` or false." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T18:48:12.177", "Id": "28419", "Score": "0", "body": "true. I removed the code from the constructor." } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:50:31.863", "Id": "17812", "ParentId": "17803", "Score": "2" } }, { "body": "<p>Well, you could set this up to use additional methods. You don't have to throw everything into the constructor. This would be a big step in the right direction, at least in as far as OOP and best practice is concerned. This will help you to understand what is going on much easier while also helping you to avoid violating basic OOP principles. For instance:</p>\n\n<p><strong>Single Responsibility</strong></p>\n\n<p>The first principle you are violating, or so it seems, is the Single Responsibility Principle. As the name implies, your classes and methods should be responsible for just one thing, to the exclusion of all others. They can request information from others if necessary, but they should not be aware of how those others work. This principle is typically demonstrated with a function/method, but should also be applied to the classes themselves.</p>\n\n<p>It's hard to tell in this context, because all you provided were the guts, but, judging by the static properties, I would assume you are handling these loading failures for another class. If you are not able to modify the class in question, such as if this were a library, then this functionality should be added to an intermediary, such as a controller, otherwise this really belongs in the JQuery class. Let's continue under the assumption that this is being constructed in said intermediary.</p>\n\n<p><strong>Don't Repeat Yourself</strong></p>\n\n<p>The \"Don't Repeat Yourself\" (DRY) Principle is another of the principles you are violating. As the name implies, your code should not repeat. Typically this is done through functions/methods, but it can also be done with variables/properties and loops, though it is not just confined to this. Keeping your code DRY takes a lot of foresight, but really helps in the long run. So let's take a look at how your code is repeating itself and try to fix this.</p>\n\n<p>This should be fairly obvious. There are two files that are being verifyed and the same things are being done to both files. To paraphrase someone important to DRY (can't remember who, only that it was similar to the Rule of Three): we can either do something once, or do something many times; There is no such thing as doing something only twice. To follow this pearl of wisdom, we can create a method, and then use that method each time we need it. This also follows the Single Responsibility principle because it abstracts the task away from the constructor, whose only job is to instantiate initial values.</p>\n\n<pre><code>public function verifyVersion( $file, $version ) {\n //generalized verification code\n}\n</code></pre>\n\n<p>As the comment says, this method should be generalized for a single file, which can either have a boolean return value or a boolean property it manipulates to show whether verification was a success. It seems like you already have such a property in <code>$versionLoaded</code> so we can use that. Its not exactly a boolean, but it can be used as one so long as its default value is FALSE or NULL.</p>\n\n<pre><code>if( ! $this-&gt;versionLoaded ) {\n throw new Exception(\n \"Neither the version $version nor the default version \"\n . JQuery::DEFAULT_VERSION\n . \" could be found or downloaded\"\n );\n}\n</code></pre>\n\n<p>BTW: I slightly edited your exception because the grammar was bothering me. \"Nor\" is the negative connotation of \"or\" and \"neither\" prefixes a list of negatives. Though I'm not an English major, so you can take that with a grain of salt.</p>\n\n<p>How do we generalize our check? And equally important, how do we do it just once? In your code you were checking if these files exist not once, but twice. If we check it once, and assume that if the version is loaded then the file exists, then we wont need to check it a second time.</p>\n\n<pre><code>if( file_exists( $file ) || self::installVersion( $version ) ) {\n $this-&gt;versionLoaded = $version;\n}\n</code></pre>\n\n<p>That should leave us with one final task. How to check each file. Well, I mentioned that loops were sometimes used in DRY. Here's a pretty good time to use one.</p>\n\n<pre><code>$header = __DIR__ . '/versions/jquery-';\n$default = JQuery::DEFAULT_VERSION;\n\n$files = array(\n $header . $version . '.js',\n $header . $version . '.min.js',\n $header . $default . '.js',\n $header . $default . '.min.js'\n);\n\nforeach( $files AS $file ) {\n $this-&gt;verifyVersion( $file, $version );\n if( $this-&gt;versionLoaded ) {\n return;\n }\n}\n\nthrow new Exception(\n \"Neither the version $version nor the default version \"\n . JQuery::DEFAULT_VERSION\n . \" could be found or downloaded\"\n);\n</code></pre>\n\n<p>Of course, this is still violating the Single Responsibility Principle. This constructor is still doing too much, but I'll leave that up to you to refactor. If you use everything I posted above it should be pretty simple. I'll give you a couple of hints though:</p>\n\n<ul>\n<li>Those files are not violating DRY. You might be thinking that using <code>$header</code> and '.js' repeatedly is a violation, but that is to ensure that our method is as reusable as possible. The only way they might be is by their similar structure, which I can't see refactoring without confusing the issue. Though you might want to try that for yourself.</li>\n<li>I think a pretty good name for this new method might be <code>loadJQuery()</code>.</li>\n</ul>\n\n<p>I hope this helps!</p>\n\n<p><strong>Edit</strong></p>\n\n<p>I forgot about the <code>isset( $versionList-&gt;$version );</code> bit, so the above code will need to be refactored for that as well, but I think the solution should be obvious once that last method is implemented. If you need clarification, let me know.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T12:22:52.120", "Id": "28403", "Score": "0", "body": "Thank you so much for your detailed answer. Like you suspected, this is a plugin. (for more details check my edited question), although we do have some degree of freedom. Right now, each plugin consists of just 1 class that either extends a Generic JSPlugIn class or implements a JSPlugIn interface and should take care of installing itself (and its JScripts) and \"running\" the plugin. Some plugins require detailed installation steps while other don't need any installation (and the install static method remains empty or is simply inherited)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T12:27:54.363", "Id": "28404", "Score": "0", "body": "Like you suggested, we can refactor our plug system and separate these 2 \"responsabilities\". This means, however, each plugin should now contain 2 classes: one for installation and one for \"running\" and due to 3rd party library constrains, each plugin requires a static install method, even if it's empty. So, for some plugins this means implementing an empty class. This was the main reason behind the \"Single Responsibility\" violation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T12:32:53.877", "Id": "28405", "Score": "0", "body": "Regarding the second topic (DRY) your suggestion is, well, excellent. I though for a while how I could refactor and beautify the code... your suggestion is, by far, a lot better. Once again, thank you very much." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T17:44:59.250", "Id": "17814", "ParentId": "17803", "Score": "3" } } ]
{ "AcceptedAnswerId": "17814", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T06:50:17.307", "Id": "17803", "Score": "4", "Tags": [ "php" ], "Title": "Check if the jQuery library is present locally" }
17803
<p>Since asynchronous operations (like <code>Socket</code>'s <code>Begin*</code>-<code>End*</code> pairs and <code>*Async</code> methods) that use <a href="http://msdn.microsoft.com/en-us/library/aa365198%28VS.85%29.aspx" rel="nofollow" title="MSDN | I/O Completion Ports">IOCP</a> under the hood cause the byte array that you use as buffer to be pinned in the memory.</p> <p>So if you create a new byte array everytime you send to, or receive from a socket using IOCP, you're likely to encounter <code>OutOfMemoryException</code>s in your program.</p> <p>One workaround for this is to pool the buffers, and a better one is to create one big byte array and use its parts as buffers. I first saw an implementation of this approach <a href="http://www.codeproject.com/Articles/83102/C-SocketAsyncEventArgs-High-Performance-Socket-Cod" rel="nofollow" title="CodeProject | C# SocketAsyncEventArgs High Performance Socket Code By Stan Kirk">here</a> and I wanted to wrote a simpler one to learn and use in my own projects:</p> <pre><code>public sealed class BufferManager : IDisposable { // Fields private readonly byte[] _Block; private volatile bool _Disposed; private readonly BlockingCollection&lt;int&gt; _FreeSegments; private readonly int _SegmentSize; // Properties public byte[] Block { get { return _Block; } } public int BlockSize { get { return _Block.Length; } } public int BufferSize { get { return _SegmentSize; } } public int FreeBuffers { get { return _FreeSegments.Count; } } // Constructors public BufferManager(int blockSize, int bufferSize) { // These are some helper extensions that take minimum and maximum values. blockSize.ThrowIfOutOfRange(1, paramName: "blockSize"); bufferSize.ThrowIfOutOfRange(1, blockSize, "bufferSize"); // Setting the block size, // So all the bytes will be available according to buffer size. var mod = blockSize % bufferSize; if (mod != 0) blockSize = (blockSize - mod) + bufferSize; // Determining the first byte's index in each segment. var freeSegments = new int[blockSize / bufferSize]; var freeSegment = 0; for (int i = 0; i &lt; freeSegments.Length; i++) { freeSegments[i] = freeSegment; freeSegment += bufferSize; } // Initializing the block and a collection that holds indices to its segments. _Block = new byte[blockSize]; _FreeSegments = new BlockingCollection&lt;int&gt; ( // BlockingCollection uses ConcurrentQueue as default underlaying... // ...collection but since the order is not important, I thought it can... // ...be faster with a ConcurrentBag. new ConcurrentBag&lt;int&gt;(freeSegments), freeSegments.Length ); _SegmentSize = bufferSize; } // Functions public int GetOffset() { // Gets the index of the first byte of a free byte block. // If there is none, it blocks the thread until there is. return _FreeSegments.Take(); } public void FreeOffset(int offset) { // Frees the byte block which starts with offset. _FreeSegments.Add(offset); } public ArraySegment&lt;byte&gt; GetBuffer() { // Gets a free portion of the byte block. // If there is none, it blocks the thread until there is. return ArraySegment.From(Block, GetOffset(), BufferSize); // ArraySegment.From is an extension method to... // ...avoid explicitly specifying generic type parameters. } public void FreeBuffer(ArraySegment&lt;byte&gt; buffer) { // Frees the byte block which starts with buffer.Offset. FreeOffset(buffer.Offset); } public void Dispose() { lock (_FreeSegments) if (_Disposed) return; else _Disposed = true; _FreeSegments.Dispose(); } } </code></pre> <p>It can be used like this:</p> <pre><code>// Initializes a buffer manager with an underlying byte[120] // I specify 100 here but constructor increases it so it can have equal 30-sized segments. var bufferManager = new BufferManager(100, 30); var buffer = bufferManager.Block; var offset = bufferManager.GetOffset(); // Blocks if there is none. var size = bufferManager.BufferSize; someIOCPUsingObject.Receive(buffer, offset, size); // I should call bufferManager.FreeOffset(offset) after I'm done with the received data. // or var segment = bufferManager.GetBuffer(); // Blocks if there is none. someIOCPUsingObject.Receive(segment.Array, segment.Offset, segment.Count); // I should call bufferManager.FreeBuffer(segment) after I'm done with the received data. </code></pre> <p>I chose to block the thread when there is no free portions left until one is freed instead of dynamically allocating more space since these operations <em>usually</em> don't take long and allocating more space seemed risky. I prefer pooling less-sized byte arrays if I need this behavior to creating a buffer manager like this.</p> <ol> <li>Can you detect any flaws in this code? </li> <li>Do you have any suggestions? </li> <li>Do you have any alternatives?</li> </ol>
[]
[ { "body": "<ol>\n<li><pre><code>var mod = blockSize % bufferSize;\nif (mod != 0)\n blockSize = (blockSize - mod) + bufferSize;\n</code></pre>\n\n<p>Wouldn't it be better if the constructor actually accepted <code>bufferCount</code> instead of <code>blockSize</code>, so that you wouldn't have to have this non-obvious logic? Or maybe just throw an exception if <code>blockSize</code> is not divisible by <code>bufferSize</code>.</p></li>\n<li><blockquote>\n <p>I thought it can be faster with a <code>ConcurrentBag</code>.</p>\n</blockquote>\n\n<p>Are you sure about that? <code>ConcurrentBag</code> is optimized for the situation when a thread consumes what it produces, I'm not sure that's the situation you're likely to be in (though you could be). If you're changing the default for performance reasons, you should first make sure it actually makes a difference (you're dealing with IO, that's most likely going to dominate by a lot). And if it does make a difference, you should measure that your version is actually faster, not just make guesses.</p></li>\n<li><p>Consider making <code>GetOffset()</code> and <code>FreeOffset()</code> private. Consumers of your class shouldn't know about its implementation (single block with equally sized buffers). <code>GetBuffer()</code> and <code>FreeBuffer()</code> provide a much better abstraction, and <code>ArraySegment</code> is a <code>struct</code>, so it shouldn't cause a noticeable performance penalty.</p></li>\n<li><p><code>FreeBuffer()</code> should check that the buffer it receives is valid: that it refers to the block (and not some other array) and that it has correct length and offset. The same applies to <code>FreeOffset()</code>, if you decide to keep it public.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T00:22:14.450", "Id": "28373", "Score": "0", "body": "1 - You are so right about buffer count instead of block size, I'll change that. 2- Right again, I just tested it and ConcurrentQueue turned out to be faster. 3 - That was the original idea but since ArraySegment already exposes the buffer array, I saw no harm in exposing them directyly (I still may revert that though, it seems more appropriate). 4 - Agreed, validations _are needed_, I'll add them. Thank you and +1 for this excellent review." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T06:55:00.530", "Id": "28386", "Score": "0", "body": "I added the updated version. In FreeBuffer method, do you have a suggestion on checking the offset?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T11:31:02.040", "Id": "28398", "Score": "0", "body": "That depends on how much performance and code are you willing to sacrifice for being sure about correct usage of your class. I think tracking all used offsets (maybe in a `ConcurrentDictionary`) and using that in validation makes sense. On the other hand, it might be too much code or performance penalty for little benefit for you." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T20:37:29.210", "Id": "17817", "ParentId": "17804", "Score": "4" } }, { "body": "<p>This code does not compile without errors under Visual Studio 2013</p>\n\n<p>These 3 lines of code are in error:</p>\n\n<pre><code>bufferSize.ThrowIfOutOfRange(1, paramName: \"bufferSize\");\n</code></pre>\n\n<p>and </p>\n\n<pre><code>bufferCount.ThrowIfOutOfRange(1, paramName: \"bufferCount\");\n</code></pre>\n\n<p>and</p>\n\n<pre><code>return ArraySegment.From(_Block, index, _BufferSize);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-20T13:19:21.403", "Id": "95804", "Score": "1", "body": "Hello Kevin and welcome to codereview.stackexchange.com. You can get your code formatted as code by indenting it with four spaces (I've gone ahead and done this for you). Also we expect answers to provide help, in your case it would be nice if you explained how to make the code compile cleanly under VS2013. I hope you will enjoy your time with us." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-24T10:27:11.630", "Id": "96453", "Score": "0", "body": "They are extension methods. I stated what they do in the comments above them but didn't feel the need to include their definitions. So, first two `ThrowIfOutOfRange` calls mean: \"if `bufferSize` or `bufferCount` is less than 1, throw an `ArgumentOutOfRangeException`. And the third one can be replaced with `new ArraySegment<byte>(_Block, index, _BufferSize)`." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-20T12:51:09.527", "Id": "54803", "ParentId": "17804", "Score": "0" } } ]
{ "AcceptedAnswerId": "17817", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T07:47:01.597", "Id": "17804", "Score": "8", "Tags": [ "c#", ".net", "array", "memory-management", "asynchronous" ], "Title": "A blocking buffer manager to provide segments of a byte array" }
17804
<p><a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4f2c2e3780aeb" rel="nofollow">This is a problem from Interview Street in Dynamic Programming section</a>.</p> <blockquote> <p><strong>Billboards (20 points)</strong></p> <p>ADZEN is a very popular advertising firm in your city. In every road you can see their advertising billboards. Recently they are facing a serious challenge , MG Road the most used and beautiful road in your city has been almost filled by the billboards and this is having a negative effect on the natural view.</p> <p>On people's demand ADZEN has decided to remove some of the billboards in such a way that there are no more than K billboards standing together in any part of the road.</p> <p>You may assume the MG Road to be a straight line with N billboards.Initially there is no gap between any two adjecent billboards.</p> <p>ADZEN's primary income comes from these billboards so the billboard removing process has to be done in such a way that the billboards remaining at end should give maximum possible profit among all possible final configurations.Total profit of a configuration is the sum of the profit values of all billboards present in that configuration.</p> <p>Given N,K and the profit value of each of the N billboards, output the maximum profit that can be obtained from the remaining billboards under the conditions given.</p> <p><strong>Input description</strong> </p> <p>1st line contain two space separated integers N and K. Then follow N lines describing the profit value of each billboard i.e ith line contains the profit value of ith billboard.</p> <p><strong>Sample Input</strong></p> <pre><code>6 2 1 2 3 1 6 10 </code></pre> <p><strong>Sample Output</strong></p> <pre><code>21 </code></pre> <p><strong>Explanation</strong></p> <p>In given input there are 6 billboards and after the process no more than 2 should be together.</p> <p>So remove 1st and 4th billboards giving a configuration <code>_ 2 3 _ 6 10</code> having a profit of 21. No other configuration has a profit more than 21. So the answer is 21.</p> <p><strong>Constraints</strong></p> <pre><code>1 &lt;= N &lt;= 100,000 (10^5) 1 &lt;= K &lt;= N 0 &lt;= profit value of any billboard &lt;= 2,000,000,000 (2 * 10^9) </code></pre> </blockquote> <p><strong>My solution (psuedocode):</strong></p> <pre><code>Let Profit[i] denote the Profit from ith billboard. (i, j) denotes the range of billboards MaxProfit(i, j) for all (i, j) such that i&lt;=j and i-j+1 &lt;= K is: MaxProfit(i, j) = Profit[i] + Profit[i+1] + ... + Profit[j]; For other (i,j) MaxProfit equals, MaxProfit(i, j) { max = 0; for all k such that i&lt;=k&lt;=j // k denotes that, that position has no billboard { temp = MaxProfit(i, k-1) + MaxProfit(k+1, j); if(temp &gt; max) max = temp; } return max; } </code></pre> <p><strong>Code:</strong></p> <pre><code>#include&lt;stdio.h&gt; #include&lt;stdlib.h&gt; long **DP; long returnValue(long i, long j); int main() { long N, K; scanf("%ld", &amp;N); scanf("%ld" ,&amp;K); DP = (long**) malloc(sizeof(long *) * N); long ARR[N]; long j, z, i=0; for(i=0;i&lt;N;i++) { DP[i] = (long*)malloc(sizeof(long) * N); scanf("%ld", &amp;ARR[i]); } for(i=0;i&lt;N;i++) { long sum=0; for(j=1;j&lt;=K &amp;&amp; (i+j-1)&lt;N;j++) { sum += ARR[i+j-1]; DP[i][i+j-1] = sum; } } for(j=K+1;j&lt;=N;j++) { for(i=0;i&lt;=N-j;i++) { long max = 0; for(z=i;z&lt;=i+j-1;z++) { long temp = returnValue(i, z-1) + returnValue(z+1, i+j-1); if(temp &gt; max) max= temp; } DP[i][i+j-1] = max; } } printf("%ld\n", DP[0][N-1]); for(i=0;i&lt;N;i++) { free(DP[i]); } free(DP); } long returnValue(long i, long j) { if(i&lt;=j) { //printf("%d\n", DP[i][j]); return DP[i][j]; } else return 0; } </code></pre> <p>My solution is of order O(N<sup>2</sup>). So I get TLE and Segmentation fault for larger N. I have already passed 6/10 test cases. I need to pass remaining 4.</p>
[]
[ { "body": "<p>The inputs have to be limited with constraints you have listed, then</p>\n\n<ul>\n<li>use a TreeSet to store the N objects in it </li>\n<li>remove the K first </li>\n<li>print the Set</li>\n</ul>\n\n<p>few lines in Java (no malloc problem, memory managed by JVM): </p>\n\n<ul>\n<li>read the first input</li>\n<li>use String.split() the line,</li>\n<li>use Integer.valueOf(String) to convert</li>\n<li>compare N,K and stop if not correct or if negative</li>\n<li>use a <code>while(&lt;N)</code> for input,</li>\n<li>test limits of input whith <code>if</code> and negative values</li>\n<li>you can use <code>toString()</code> to print the Set, but you have to use a </li>\n<li><code>foreach</code> to sum the result </li>\n<li>print result</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T08:25:24.380", "Id": "17865", "ParentId": "17808", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T13:04:58.990", "Id": "17808", "Score": "8", "Tags": [ "algorithm", "c", "interview-questions" ], "Title": "Billboard challenge algorithm" }
17808
<p>I have a list of dictionaries, with keys 'a', 'n', 'o', 'u'. Is there a way to speed up this calculation, for instance with <a href="http://numpy.scipy.org/" rel="nofollow">NumPy</a>? There are tens of thousands of items in the list.</p> <p>The data is drawn from a database, so I must live with that it's in the form of a list of dictionaries originally.</p> <pre><code>x = n = o = u = 0 for entry in indata: x += (entry['a']) * entry['n'] # n - number of data points n += entry['n'] o += entry['o'] u += entry['u'] loops += 1 average = int(round(x / n)), n, o, u </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:40:02.320", "Id": "28349", "Score": "0", "body": "what are you trying to calculate?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:44:34.283", "Id": "28350", "Score": "0", "body": "@OvedD, an average of all 'a' values and a bunch of sums for the others." } ]
[ { "body": "<p>I'm not sure if there really is a better way to do this. The best I could come up with is:</p>\n\n<pre><code>import itertools\nfrom collections import Counter\n\ndef convDict(inDict):\n inDict['a'] = inDict['a'] * inDict['n']\n return Counter(inDict)\n\naverage = sum(itertools.imap(convDict, inData), Counter())\naverage['a'] = average['a'] / average['n']\n</code></pre>\n\n<p>But I'm still not sure if that is better than what you originally had.</p>\n\n<p><code>Counter</code> is a subclass of <code>dict</code>. You can get items from them the same way you get items from a normal dict. One of the most important differences is that the <code>Counter</code> will not raise an Exception if you try to select a non-existant item, it will instead return 0.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:02:51.863", "Id": "28351", "Score": "0", "body": "Interesting but I don't see how I can replace my code with that. +1 though" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:06:28.850", "Id": "28352", "Score": "0", "body": "I realized after posting this that you wanted to do some multiplication before summing. Ill look into that" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:16:33.677", "Id": "28353", "Score": "0", "body": "Wouldn't that require to access the full list twice instead of once? In that case, it must be slower." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T16:17:39.730", "Id": "28354", "Score": "0", "body": "@AmigableClarkKant Yeah, I just got done editing the question to state that. It is probably slower than what you already have. I'm not sure how much better Counter is (if any) than manually summing." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:59:24.223", "Id": "17811", "ParentId": "17810", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T15:13:17.540", "Id": "17810", "Score": "3", "Tags": [ "python", "optimization" ], "Title": "Optimization of average calculation" }
17810
<p>I'm learning programming and would appreciate any feedback on my code. I've come up with the below code. The logic works fine but the code itself seems rather confusing to me. Are there some patterns I could use to improve this code?</p> <pre><code>// This code snippet handles click events on the Ingredients list (see the image below) $('.items a').click(function (event) { // Remove leading letter from the href id (e.g. id="i15" --&gt; 15) ingr = parseInt((this.id).substring(1)); // Here comes the complicated logic for handling click event // It works well but can it be improved/simplified? if (buy.indexOf(ingr) != -1) { if (weHave.indexOf(ingr) != -1) { if (weNeed.indexOf(ingr) === -1) { weNeed.push(ingr); whIndex = weHave.indexOf(ingr); weHave.splice(whIndex, 1); } } else { if (weNeed.indexOf(ingr) === -1) { weHave.push(ingr); } else { weHave.push(ingr); wnIndex = weNeed.indexOf(ingr); weNeed.splice(wnIndex, 1); } } } else { if (weHave.indexOf(ingr) != -1) { weNeed.push(ingr); whIndex = weHave.indexOf(ingr); weHave.splice(whIndex, 1); } else { if (weNeed.indexOf(ingr) != -1) { weHave.push(ingr); wnIndex = weNeed.indexOf(ingr); weNeed.splice(wnIndex, 1); } else { weNeed.push(ingr); } } } shoplist(); return false; // to prevent the page from scrolling to the top }); </code></pre> <p><strong>EDIT:</strong> Edited the code above and provided more background information below.</p> <p>Here is a simplified picture of the application I'm trying to create:</p> <p><img src="https://i.stack.imgur.com/q29p2.png" alt="enter image description here"></p> <p>Briefly how the application should work:</p> <ul> <li>The idea is to create a shopping list by selecting food and/or ingredients </li> <li>Clicking on a food item will highlight the food item and all necessary ingredients </li> <li>Clicking on already highlighted food item will remove the highlighting from the food item and all necessary ingredients </li> <li>Clicking on an ingredient will highlight the ingredient</li> <li>Clicking on already highlighted ingredient will remove the highlighting from the ingredient</li> </ul> <p>The above is basic logic but here is where it gets complicated. There are couple of scenarios I'm trying to handle in the code above (these are independent scenarios):</p> <ol> <li><p>I click on Spaghetti Bolognese. Necessary ingredients, including onion, get highlighted. Then I click on onion, indicating that I already have this ingredient at home. The highlighting is removed from the onion. Then I click on Pork Stew (which requires onion) but onion shouldn't get highlighted because I have already indicated that I do have an onion at home.</p></li> <li><p>I click on Spaghetti Bolognese. Necessary ingredients, including onion, get highlighted. Then I click on Pork Stew. Pork Stew requires onion too so the onion item stays highlighted. But then I decide I don't want to make Spaghetti Bolognese after all so I unclick it. The onion should stay highlighted because it's required for Pork Stew.</p></li> </ol> <p>So to handle these kind of scenarios I came up with two arrays: <code>weNeed</code> and <code>weHave</code>. </p> <p>Here is a list of inputs/outputs:</p> <ul> <li><code>ingr</code>: integer; clicked ingredient</li> <li><code>buy</code>: unique list of ingredients, concatenation of <code>weNeed</code> + <code>food</code> (<code>food</code> is an array of ingredients coming from the FOOD list; not in the above code)</li> <li><code>weNeed</code>: list of ingredients collected when user clicks on unhighlighted ingredient item</li> <li><code>weHave</code>: list of ingredients collected when user clicks on highlighted ingredient item</li> </ul> <p>P.S. Looking back at my question this has grown into a monster. I'm not sure if the extra information I provided is helpful or even more confusing. I could post the whole code if it helps but something is telling me that dealing with these kind of complex issues on the forum is probably not the right way to do things. I'll be happy for any suggestions.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T19:59:04.747", "Id": "28362", "Score": "2", "body": "You're right, it's confusing. It'd be great if you could write a few lines about what the code's meant to accomplish. Obviously, there are 3 arrays (buy, have, and need) but you're doing some union/intersection/exclusion, but what exactly?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T20:20:14.663", "Id": "28363", "Score": "0", "body": "Right, I'll provide more information and context but it's going to take some time. Right now the whole code is so mess that even I can't make sense of it :/. I would post the whole code here (150 lines) but it's so bad that it's embarrassing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T20:32:14.517", "Id": "28364", "Score": "0", "body": "Well, we only really need to know what the inputs (the 3 arrays) are and what the output is supposed to be; we don't need the entire code necessarily. To me it looks like a shopping list system of some sort, maybe? I'm guessing `ingr` is short for \"ingredient\", and that the code's meant to figure out what needs/doesn't need to be bought (maybe - can't quite figure it out)." } ]
[ { "body": "<p>You have 4 actions, two of which are repeated twice... </p>\n\n<p><strong>Action #1</strong> -- repeated twice</p>\n\n<pre><code>weNeed.push(ingr);\nwhIndex = weHave.indexOf(ingr);\nweHave.splice(whIndex, 1);\n</code></pre>\n\n<p>This action requires that either <code>buy.indexOf(ingr) != -1 &amp;&amp; weHave.indexOf(ingr) != -1 &amp;&amp; weNeed.indexOf(ingr) === -1</code> be <code>true</code>, or that <code>buy.indexOf(ingr) === -1 &amp;&amp; weHave.indexOf(ingr) != -1</code> is <code>true</code>. This can be simplified to <code>weHave.indexOf(ingr) != -1</code> </p>\n\n<p><strong>Action #2</strong> -- repeated twice</p>\n\n<pre><code>weHave.push(ingr);\nwnIndex = weNeed.indexOf(ingr);\nweNeed.splice(wnIndex, 1);\n</code></pre>\n\n<p>This action requires that either <code>buy.indexOf(ingr) != -1 &amp;&amp; weHave.indexOf(ingr) === -1 &amp;&amp; weNeed.indexOf(ingr) != -1</code>\nor <code>buy.indexOf(ingr) === -1 &amp;&amp; weHave.indexOf(ingr) === -1 &amp;&amp; weNeed.indexOf(ingr) != -1</code> be <code>true</code>. This one can be simplified to <code>weHave.indexOf(ingr) === -1 &amp;&amp; weNeed.indexOf(ingr) != -1</code></p>\n\n<p><strong>Action #3</strong></p>\n\n<pre><code>weHave.push(ingr);\n</code></pre>\n\n<p>This action requires that <code>buy.indexOf(ingr) != -1 &amp;&amp; weHave.indexOf(ingr) === -1 &amp;&amp; weNeed.indexOf(ingr) === -1</code> be <code>true</code>.</p>\n\n<p><strong>Action #4</strong></p>\n\n<pre><code>weNeed.push(ingr);\n</code></pre>\n\n<p>This action requires that <code>buy.indexOf(ingr) === -1 &amp;&amp; weHave.indexOf(ingr) === -1 &amp;&amp; weNeed.indexOf(ingr) === -1</code> be <code>true</code>.</p>\n\n<p>That being said, you could structure the logic as follows, and you should end up with the same results. Note that I have not tested this though, so I could have made a mistake... </p>\n\n<pre><code>if( weHave.indexOf(ingr) != -1 )\n{\n weNeed.push(ingr);\n whIndex = weHave.indexOf(ingr);\n weHave.splice(whIndex, 1);\n}\nelse\n{\n if( weNeed.indexOf(ingr) != -1 )\n {\n weHave.push(ingr);\n wnIndex = weNeed.indexOf(ingr);\n weNeed.splice(wnIndex, 1);\n }\n else\n {\n if( buy.indexOf(ingr) != -1 )\n weHave.push(ingr);\n else\n weNeed.push(ingr);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-20T01:10:19.817", "Id": "35229", "Score": "0", "body": "Did this work for you?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T02:14:33.217", "Id": "17829", "ParentId": "17816", "Score": "6" } }, { "body": "<p>Druciferre seems to have found a way to streamline your current code quite nicely (I would add that an \"is-value-x-in-array-y?\" helper function would greatly improve readability, as all the <code>indexOf</code> comparisons make me cross-eyed. A \"remove-x-from-array-y\" function would also help DRY the code), so allow me to suggest a different tack altogether; more rewrite than tweak. Reading your description, here are my suggestions.</p>\n\n<h3>1. Objects for each recipe</h3>\n\n<p>There are plenty of ways to do this, but the simplest, most direct one I can think of is:</p>\n\n<pre><code>var recipes = [\n {\n name: \"Pork stew\",\n ingredients: [\"pork\", \"stew\", \"onion\"]\n },\n {\n name: \"Spaghetti bolognese\",\n ingredients: [\"spaghetti\", \"city of bologna\", \"onion\"]\n },\n // ....\n];\n</code></pre>\n\n<p>(can you tell I don't cook much?)</p>\n\n<p>Anyway, the point is that each recipe \"contains\" its ingredients. A neat logical encapsulation of data.</p>\n\n<h3>2. Use <a href=\"http://underscorejs.org\">underscore.js</a> (or similar, or roll your own) array functions</h3>\n\n<p>Underscore's got some neat array functions. Use 'em. Let's say you have both of the above recipes selected. To get all the ingredients needed, you could do</p>\n\n<pre><code>// concatenate every recipe's ingredients into one array\nvar requiredIngredients = _.reduce(selectedRecipes, function (ingredients, recipe) {\n return ingredients.concat(recipe.ingredients);\n}, []);\nrequiredIngredients = _.uniq(requiredIngredients); // remove duplicates\n</code></pre>\n\n<p><em><strong>Edit</strong> Changed <code>_.map</code> to <code>_.reduce</code> which is what I meant to write first time around, but somehow messed up.</em></p>\n\n<p>Thus, <code>requiredIngredients</code> will be:</p>\n\n<pre><code>[\"pork\", \"stew\", \"onion\", \"spaghetti\", \"city of bologna\"]\n</code></pre>\n\n<p>So now you have an array of all the ingredients needed to cook those two dishes.</p>\n\n<p>Now, let's say you also have an array of ingredients that the user has manually selected and one that contains those that he/she already has (i.e. manually <em>unselected</em>):</p>\n\n<pre><code>var ownedIngredients = [\"onion\", \"olive oil\"];\nvar selectedIngredients = [\"curry\"];\n\n// combine manually selected ingredients with recipe ingredients,\n// and remove duplicates\nvar allIngredients = _.uniq(requiredIngredients.concat(selectedIngredients));\n\n// \"subtract\" unselected ingredients\nvar shoppingList = _.difference(allIngredients, ownedIngredients);\n</code></pre>\n\n<p>And, well, that's pretty much it. When you select a new recipe, re-run that code. When you add/remove an ingredient, re-run that code. With just the above you'd get a shopping list of</p>\n\n<pre><code>[\"pork\", \"stew\", \"spaghetti\", \"city of bologna\", \"curry\"]\n</code></pre>\n\n<p>Of course, this is me taking a stab in the dark, not knowing the rest of your app. But this, to me, seems like a better approach than manually trying to manage arrays element-by-element.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T11:14:33.653", "Id": "28397", "Score": "0", "body": "Thanks for your suggestions! Regarding your point #1, I get a list of ingredients for each recipe via ajax call. I provide the recipe (food) id and the call returns a list of ingredients for the given recipe. Is your suggestion still applicable in this situation? (sorry if my question sounds dumb). Regarding the suggestion #2, I'll definitely check out the underscore.js library. I'm currently using some custom functions for concatenating arrays and returning unique set of values but from what I see underscore.js makes it even simpler." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T12:05:24.130", "Id": "28400", "Score": "0", "body": "@finspin Yes, you should be able to at least \"build your own\" objects in JS. E.g. take ingredients array you get and toss that in an object. Plenty of ways to structure that. The point is mostly to have a logic encapsulation of \"a recipe\" and its ingredients." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T15:52:27.700", "Id": "28410", "Score": "0", "body": "@finspin btw, just corrected some code in my answer - was using `map` where I'd meant to write `reduce`" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T10:19:32.247", "Id": "17841", "ParentId": "17816", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T19:48:46.740", "Id": "17816", "Score": "10", "Tags": [ "javascript", "jquery" ], "Title": "Handling click events on ingredients list" }
17816
<p>Here are some snippets I coded and I would like some feedback on my way of handling this:</p> <p>I have a utility class, as a singleton, that provides me with a method named <code>randomColor</code> which returns a <code>(UIColor*)</code>:</p> <pre><code>-(UIColor*)randomColor { float l_fRandomRedColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f]; float l_fRandomBlueColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f]; float l_fRandomGreenColor = [[MathUtility instance] randomFloatNumberBetweenNumber:0.0f AndNumber:1.0f]; return [UIColor colorWithRed:l_fRandomRedColor green: l_fRandomGreenColor blue: l_fRandomBlueColor alpha: 255]; } </code></pre> <p>Now, I know the object return by this method is <code>autoreleased</code>.</p> <p>I store the returned value in another class and I would like to keep this value for a while, so I proceed like this:</p> <pre><code>[self setMpCurrentPieceColor:[[GraphicsUtility instance] randomColor]]; </code></pre> <p>Which calls the following property:</p> <pre><code>- (void)setMpCurrentPieceColor:(UIColor*)_newColor { [_mpCurrentPieceColor release]; [_newColor retain]; // Make the new assignment. _mpCurrentPieceColor = _newColor; } </code></pre> <p><strong>Question A)</strong></p> <p>My instance variable is released in the dealloc method. Is a the correct way to go?</p> <p><strong>Question B)</strong></p> <p>Now, let's imagine I have an array, like this:</p> <pre><code>UIColor* mBoardColors[WIDTH][HEIGHT]; </code></pre> <p>I want to store the previous instance variable into the array:</p> <pre><code>[mBoardColors[l_iBoardXIndex][l_iBoardYIndex] release]; [_color retain]; mBoardColors[l_iBoardXIndex][l_iBoardYIndex] = _color; </code></pre> <p>Is it correct?</p> <p><strong>Question C)</strong></p> <p>What if I want to move a color from a cell to another (moving, not copying), is it correct to do it like that?</p> <pre><code>[mBoardColors[l_iBoardXIndex][l_iBoardYIndex] release]; mBoardColors[l_iBoardXIndex][l_iBoardYIndex] = mBoardColors[l_iBoardXIndex][l_iBoardYIndex - 1]; mBoardColors[l_iBoardXIndex][l_iBoardYIndex - 1] = nil; </code></pre> <p>Thank in advance for your precious comments and advices!</p>
[]
[ { "body": "<p>Alright, there's a number of simplifications to the Utility Class I'd like to make before I continue:</p>\n\n<p>Your abstraction from <code>arc4random</code> (at least that's what I hope it is), is too expensive to not just use the corresponding C-code directly. You could even make your own method in C, and use the inline qualifier for faster code than calling out to a singleton 3 times for every color. Also, it is never good to name an Objective-C method \"instance\". Singletons usually use a naming convention that makes sense with their overall implementation (i.e. <code>NSFileManager.defaultManager</code>). The following will generate a random <code>double</code> for you between 0 and 1. Not only is it cleaner, but it's cheaper.</p>\n\n<pre><code>#define ARC4RANDOM_MAX 0x100000000\nfloat l_fRandomRedColor = ((double)arc4random() / ARC4RANDOM_MAX);\n</code></pre>\n\n<p><sub>*As an aside, it's also a good idea to use an alpha value of 1.0f, instead of 255, because alpha is also measured on a 0-1 scale</sub></p>\n\n<blockquote>\n <p>Question A)</p>\n \n <p>My instance variable is released in the dealloc method. Is a the\n correct way to go?</p>\n</blockquote>\n\n<p>The rule in ObjC is \"You own it, you destroy it.\" Because <code>mpCurrentPieceColor</code> is an explicitly <code>retain</code>'ed property, you own it. If you were to not destroy <code>mpCurrentPieceColor</code> in <code>-dealloc</code>, then your class would retain a valid reference to it, and it simply would not go away. (memory leak).</p>\n\n<p><sub>*As an aside, switching to ARC will alleviate all of these headaches.</sub></p>\n\n<blockquote>\n <p>Question B)</p>\n \n <p>Now, let's imagine I have an array, like this:</p>\n \n <p>UIColor* mBoardColors[WIDTH][HEIGHT];...</p>\n</blockquote>\n\n<p>So long as you initialize the members of the multi-dimensional array, this is <em>correct</em>, but definitely not optimal. Objective-C has it's own array objects, which free you from having to make these ridiculous memory management decisions, and a dynamic, expandable multidimensional array is as simple as nesting NS(Mutable)Arrays:</p>\n\n<pre><code>[NSMutableArray arrayWithObjects:[NSArray array],[NSArray array],[NSArray array],[NSArray array],..., nil];\n</code></pre>\n\n<p>Not only that, but if you were to decide to expand or contract the board at any time, you could add or remove objects at a whim, and, so long as you release any references to the objects you put into the array, when the main array is released, it will release the sub-arrays, and the sub-arrays will release their objects. It really is quite beautiful.</p>\n\n<blockquote>\n <p>Question C)</p>\n \n <p>What if I want to move a color from a cell to another (moving, not\n copying), is it correct to do it like that?</p>\n</blockquote>\n\n<p>Another beauty of NSArrays is the ability to swap-out objects into a new index of the array, so long as you don't exceed the array's bounds. See the <a href=\"https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/doc/uid/20000138-SW4\" rel=\"nofollow\">\"Replacing Objects\"</a> section of NSMutableArray's documentation. Again, as above, memory management is vastly simplified with an NSArray, than dropping down to a multi-dimensional literal.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-03T16:47:47.453", "Id": "18181", "ParentId": "17818", "Score": "1" } }, { "body": "<p>Your setter looks a little unsafe and could lead to a crash in this case:</p>\n\n<pre><code>[self setMpCurrentPieceColor:_mpCurrentPieceColor];\n</code></pre>\n\n<p>A better version of the setter is synthesized setter, but if you need to change set behavior (add validation, update connected fields etc.) you can use next pattern:</p>\n\n<pre><code>- (void) setMpCurrentPieceColor:(UIColor *)newColor\n{\n if (_color == newColor) return; // No need to do anything if same value transferred\n // Update value\n [_color release];\n _color = newColor;\n [_color retain];\n}\n</code></pre>\n\n<p>Anyway, better use ARC and not fill your mind with memory management</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-13T09:11:09.220", "Id": "18527", "ParentId": "17818", "Score": "1" } } ]
{ "AcceptedAnswerId": "18181", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T20:47:20.820", "Id": "17818", "Score": "3", "Tags": [ "objective-c", "memory-management", "singleton" ], "Title": "Objective-C retain / release snippet" }
17818
<p>I want to implement the flood-fill algorithm for <a href="https://stackoverflow.com/questions/12995378/is-there-a-proper-algorithm-for-detecting-the-background-color-of-a-figure">https://stackoverflow.com/questions/12995378/is-there-a-proper-algorithm-for-detecting-the-background-color-of-a-figure</a>. I did it recursively, but I had a stack-overflow error. No matter - Wikipedia has a spot for a non-recursive, iterative solution.</p> <p>It requires a queue. For school, we're not supposed to use Lists nor the Java Queue class (I don't even know if it does what I think it does, but it doesn't matter - I can't use it).</p> <pre><code>public class QueueOfPixeles { public Pixel[] elements; public int numberOfElements; public QueueOfPixeles() { numberOfElements = 0; elements = new Pixel[1]; } // Next pixel is supposed to return the last pixel element in the queue. // When a pixel element is returned, it will become null in the system. public Pixel nextPixel() { Pixel result = null; for (int i = elements.length - 1; i &gt;= 0 &amp;&amp; result == null; --i) { result = elements[i]; if (result != null) { elements[i] = null; } } return result; } // Adds a new pixel to the queue. // Then, it checks if the capacity of the vector has been reached. public void add(Pixel pixel) { elements[numberOfElements] = pixel; ++numberOfElements; fixVector(); } // If the vector capacity has been reached, create a new vector with all old elements // but with more capacity. private void fixVector() { if (numberOfElements &gt;= elements.length) { Pixel[] newVector = new Pixel[(elements.length * 2) + 1]; for (int i = 0; i &lt; numberOfElements; ++i) { newVector[i] = elements[i]; } elements = newVector; } } } </code></pre> <p><strong>WHAT IS IT SUPPOSED TO DO?</strong></p> <p>You should be able to add pixels to the end of the queue, and get the next pixel by using <code>nextPixel()</code>. When you retrieve the next pixel, it should be removed from the queue automatically.</p> <p><strong>DOES IT WORK?</strong></p> <p>Yes, it seems to be working. I've done a few tests and it has indeed returned all I expected.</p> <p><strong>WHAT'S THE PROBLEM?</strong></p> <p>I'd like to get some feedback about this. I can only use vectors for this project, and I feel there is something rather not-efficient with the way I manage the pixels in the queue (converting the elements to null and just that etc, or asking for more capacity size instead of using the null-spaces I made).</p> <p>What do you think?</p>
[]
[ { "body": "<p>A note on terminology: What you have implemented is usually called a <em>stack</em> rather than a queue, but it can also be called a LIFO (last in, first out) queue, so it's not wrong to call it a queue, only uncommon.</p>\n\n<p>The <code>nextPixel()</code> method is rather inefficient. You keep track of the number of elements in the queue, and you never do anything that allows any array element with an index <code>&gt;= numberOfElements</code> to be anything but <code>null</code>. So instead of starting the search at <code>elements.length - 1</code>, you should start at <code>numberOfElements - 1</code>.</p>\n\n<p>But that still leaves an inconsistency/inefficiency. The <code>add()</code> method doesn't guard against adding <code>null</code>s to the queue, but you never return a <code>null</code> until the queue is empty.</p>\n\n<p>You should either return <code>null</code>s if you accept them to be added to the queue, or, better, I think, guard against <code>null</code>s in <code>add()</code>. So I'd recommend</p>\n\n<pre><code>public void add(Pixel pixel) {\n if (pixel == null) return; // nothing to do\n // pixel isn't null, add it\n elements[numberOfElements] = pixel;\n ++numberOfElements;\n fixVector();\n}\n</code></pre>\n\n<p>and then - also if you decide to return <code>null</code>s if they're added - <code>nextPixel()</code> can simply be</p>\n\n<pre><code>public Pixel nextPixel() {\n // queue empty\n if (numberOfElements == 0) return null;\n // decrement numberOfElements and\n // return the last added Pixel\n return elements[--numberOfElements];\n}\n</code></pre>\n\n<p>In <code>fixVector()</code>, you can probably be a bit more efficient if you use the generic <code>Arrays.copyOf</code> method, but maybe you are not allowed to use that either.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T13:59:59.157", "Id": "28408", "Score": "0", "body": "You can also write ` elements[numberOfElements++] = pixel; ` and remove the next line" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T17:35:52.920", "Id": "28416", "Score": "0", "body": "Note: Wow, the changes made my program like 20 times faster! Now I can handle big images :D. Thanks again." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T01:03:33.847", "Id": "17827", "ParentId": "17823", "Score": "4" } }, { "body": "<p>As Daniel Fisher already mentioned, you're using a Stack. The most basic implementation of this is a single linked list. The down side is that it consumes more memory than an array based implementation. The up side is that it is <strong>much</strong> easier to implement: You don't have to juggle with indexes, you don't have to copy the array content etc.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T14:52:08.023", "Id": "17844", "ParentId": "17823", "Score": "1" } } ]
{ "AcceptedAnswerId": "17827", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T23:11:13.917", "Id": "17823", "Score": "6", "Tags": [ "java" ], "Title": "Vector-based flood-fill algorithm queue class" }
17823
<p>I am trying to learn some Java on my own, and I am tackling some "programming challenge" problems to practice the little I have learnt so far.</p> <p>Could anybody constructively critique this beginner's effort <a href="https://bitbucket.org/robottinosino/topcoder_java/src/2bf27cffa902/src/com/topcoder/srm144/div1/BinaryCode.java?at=default" rel="nofollow">(source on Bitbucket)</a>?</p> <pre><code>public class BinaryCode { public String[] decode(String message) { int messageLength = message.length(); return new String[] { decodeMessage(message, messageLength, 0), decodeMessage(message, messageLength, 1) }; } private String decodeMessage(String encodedMessage, int messageLength, int assumedFirstDigit) { StringBuilder decodedMessage = new StringBuilder(messageLength); int nextDecodedDigit = assumedFirstDigit; for (int i = 0; i &lt; messageLength; i++) { if (nextDecodedDigit != 0 &amp;&amp; nextDecodedDigit != 1) { return "NONE"; } decodedMessage.append(nextDecodedDigit); int encodedDigit = encodedMessage.charAt(i) - '0'; int decodedDigit = decodedMessage.charAt(i) - '0'; nextDecodedDigit = encodedDigit - decodedDigit; if (i &gt; 0) { nextDecodedDigit -= decodedMessage.charAt(i - 1) - '0'; } } int checkValue = decodedMessage.charAt(messageLength - 1) - '0'; if (messageLength &gt; 1) { checkValue += decodedMessage.charAt(messageLength - 2) - '0'; } if (checkValue == encodedMessage.charAt(messageLength - 1) - '0') { return decodedMessage.toString(); } return "NONE"; } } </code></pre>
[]
[ { "body": "<p>These critiques are mostly style and syntax related, and do not address your algorithm (you could probably find the simplest possible algorithm with Google anyway).</p>\n\n<ul>\n<li>make <code>decode</code> and <code>decodeMessage</code> static</li>\n<li><p>explicitly hide the constructor for <code>BinaryCode</code>, e.g.</p>\n\n<pre><code>// hide constructor\nprivate BinaryCode() {}\n</code></pre></li>\n<li>remove unneseccary <code>- 0</code> from <code>encodedDigit</code> and <code>decodedDigit</code> declarations</li>\n<li>let <code>decodeMessage</code> calculate <code>messageLength</code> (fewer parameters are nearly always better)</li>\n<li>avoid using magic numbers and string literals (<code>-1</code>, <code>-2</code>, <code>\"NONE\"</code>, etc...)</li>\n<li><p>create method <code>lastChar</code> and call it instead of <code>messageLength - 1</code> e.g. <code>int checkValue = lastChar(decodedMessage) - '0';</code></p>\n\n<pre><code>private static char lastChar(CharSequence sequence) {\n int lastIndex = sequence.length() - 1;\n return sequence.charAt(lastIndex);\n}\n</code></pre></li>\n<li><p>replace <code>decodedMessage.charAt(messageLength - 2)</code> and <code>decodedMessage.charAt(i - 1)</code> with <code>previouslyDecodedChar</code> e.g.</p>\n\n<pre><code>char previouslyDecodedChar = '\\0';\nfor (int i = 0; i &lt; messageLength; i++) {\n // ...\n if (i &gt; 0) {\n nextDecodedDigit -= previouslyDecodedChar - '0';\n }\n previouslyDecodedChar = decodedMessage.charAt(i);\n}\nint checkValue = lastChar(decodedMessage) - '0';\nif (messageLength &gt; 1) {\n checkValue += previouslyDecodedChar - '0';\n}\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T04:31:15.283", "Id": "29211", "Score": "0", "body": "Thanks very much for your comments. I really appreciated them. `- '0'` is not redundant. The method signatures were mandated by the exercise, and I \"think\" the instantiability is too, so I could not hide the ctor." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T14:09:43.167", "Id": "18317", "ParentId": "17824", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-22T23:54:08.763", "Id": "17824", "Score": "3", "Tags": [ "java", "beginner", "strings", "programming-challenge" ], "Title": "Decoding binary string message" }
17824
<blockquote> <p>Given a string of length n, print all permutation of the given string. Repetition of characters is allowed. Print these permutations in lexicographically sorted order </p> </blockquote> <p>Examples:</p> <p>Input: AB</p> <p>Ouput: All permutations of AB with repetition are:</p> <pre><code> AA AB BA BB </code></pre> <p>Input: ABC</p> <p>Output: All permutations of ABC with repetition are:</p> <pre><code> AAA AAB AAC ABA ... ... CCB CCC </code></pre> <p>The following is my code:</p> <pre><code>void permutate(const string&amp; s, int* index, int depth, int len, int&amp; count) { if(depth == len) { ++count; for(int i = 0; i &lt; len; ++i) { cout &lt;&lt; s[index[i]]; } cout &lt;&lt; endl; return; } for(int i = 0; i &lt; len; ++i) { index[depth] = i; permutate(s, index, depth+1, len, count); } } int main() { string s("CBA"); sort(s.begin(), s.end()); cout &lt;&lt; s &lt;&lt; endl; cout &lt;&lt; "**********" &lt;&lt; endl; int len = s.size(); int* index = new int[len]; int count = 0; permutate(s, index, 0, len, count); cout &lt;&lt; count &lt;&lt; endl; system("pause"); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T17:52:50.960", "Id": "28417", "Score": "0", "body": "Doesn't seem to work. Firstly, the strings are not in lexicographically sorted order, and secondly there are repetitions - eg if `string` = \"AAA\", it prints \"AAA\" 27 times when there is really only 1 permutation. Or did I misunderstand the objective? Also should `string s` be `const string& s` ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T00:17:46.387", "Id": "28444", "Score": "0", "body": "@WilliamMorris, for the case \"AAA\", it's OK to print 27 times. You're right, the strings are not in lexicographically sorted order. I should sort the string at first. Thanks very much" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-06T23:05:47.123", "Id": "36334", "Score": "0", "body": "Removed the C tag, as this is clearly C++." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T03:29:59.180", "Id": "58832", "Score": "0", "body": "Is the question yours, or one you have been asked? \nAre the examples yours, or given as well?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-15T23:17:39.183", "Id": "77186", "Score": "0", "body": "I'm leaving a comment here in case you haven't seen my answer. I've just made a large edit to it." } ]
[ { "body": "<ul>\n<li><p>In case you ever want to just display the string (if you have something like \"AAA\"):</p>\n\n<pre><code>// if a different character from the first is not found\n// std::string::npos corresponds to \"not found\" (or -1)\n\nif (s.find_first_not_of(s.front()) == std::string::npos)\n{\n // inform user that only one permutation exists\n}\n</code></pre></li>\n<li><p>This is a potential loss of data:</p>\n\n<pre><code>int len = s.size();\n</code></pre>\n\n<p><code>size()</code> returns <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/size\" rel=\"nofollow noreferrer\"><code>std::size_type</code></a>, not <code>int</code>. <a href=\"https://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int\">Do not use <code>int</code> for <code>std::string</code> or other STL container sizes</a>. They have their own size types that prevents this very issue. This would be the proper initialization of <code>len</code>:</p>\n\n<pre><code>std::string::size_type len = s.size();\n</code></pre></li>\n<li><p>This is needless and potentially dangerous:</p>\n\n<pre><code>int* index = new int[len];\n</code></pre>\n\n<p>The \"dangerous\" part refers to the fact that <strong><code>delete</code> is never used to free the allocated memory. Always use <code>delete</code> with <code>new</code> where appropriate.</strong></p>\n\n<p>In order to free the memory properly, you would use <code>delete</code> in this way:</p>\n\n<pre><code>delete [] index;\n</code></pre>\n\n<p>But since you're utilizing the STL, instead consider an <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"nofollow noreferrer\"><code>std::vector</code></a>:</p>\n\n<pre><code>std::vector&lt;int&gt; index(s.size());\n</code></pre>\n\n<p>As the memory management is already properly done in <code>std::vector</code>'s implementation, <code>new</code>/<code>delete</code> is not needed here at all. Always try to avoid doing this manually in C++.</p></li>\n<li><p>No need to pass the string's size; it's already part of the implementation. Just use <code>s.size()</code>.</p></li>\n<li><p>With the utilization of the aforementioned <code>std::vector</code> and <code>size()</code>, you should now make <code>depth</code> and the loop counters of <code>std::size_t</code>. This will avoid type-mismatch warnings from comparing <code>size()</code> with an <code>int</code>. <strong>Make sure your compiler's warning flags are high</strong>.</p></li>\n<li><p>Avoid using <code>system(\"PAUSE\")</code> as it is platform-specific and can be imitated by better alternatives such as <code>std::cin.get()</code>. This will ask the user for a console <em>input</em> instead of a <em>keystroke</em>, but that difference shouldn't matter if it means maintaining portability.</p></li>\n</ul>\n\n<p>Final code with applied changes (also tested on <a href=\"http://ideone.com/QmPJZB\" rel=\"nofollow noreferrer\">Ideone</a>):</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;cstddef&gt;\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;vector&gt;\n\nvoid permutate(const std::string&amp; s, std::vector&lt;int&gt;&amp; index, std::size_t depth, int&amp; count)\n{\n if (depth == s.size())\n {\n ++count;\n for (std::size_t i = 0; i &lt; s.size(); ++i)\n {\n std::cout &lt;&lt; s[index[i]];\n }\n std::cout &lt;&lt; \"\\n\";\n return;\n }\n\n for (std::size_t i = 0; i &lt; s.size(); ++i)\n {\n index[depth] = i;\n permutate(s, index, depth+1, count);\n }\n}\n\nint main()\n{\n std::string s(\"CBA\");\n\n if (s.find_first_not_of(s.front()) == std::string::npos)\n {\n std::cout &lt;&lt; \"Only 1 permutation exists\";\n return 0;\n }\n\n std::sort(s.begin(), s.end());\n\n std::cout &lt;&lt; s &lt;&lt; \"\\n**********\\n\";\n\n std::vector&lt;int&gt; index(s.size());\n int count = 0;\n\n permutate(s, index, 0, count);\n\n std::cout &lt;&lt; \"\\nTotal permutations with repetitions: \" &lt;&lt; count;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-30T17:27:12.353", "Id": "29188", "ParentId": "17828", "Score": "8" } }, { "body": "<p>I think it could be improved by not calling the task \"permutations\".\nPermutations are rearrangements. It seems you are mostly producing all combinations.</p>\n\n<p>I refer you to these:</p>\n\n<ul>\n<li><a href=\"http://www.cplusplus.com/reference/algorithm/next_permutation/\" rel=\"nofollow\">http://www.cplusplus.com/reference/algorithm/next_permutation/</a></li>\n<li><a href=\"http://en.wikipedia.org/wiki/Permutation\" rel=\"nofollow\">http://en.wikipedia.org/wiki/Permutation</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T02:36:54.723", "Id": "58825", "Score": "0", "body": "please elaborate, this is for code review. please give a nice review of the code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T03:28:44.723", "Id": "58831", "Score": "1", "body": "Whats to elaborate? Sure I have not give a full review of the code, but correct naming is an important part of coding and I thought qualifies as meaningful feedback. 'Permutation' not only generally means something other than as used in his code, but specifically means something else in C++, due to the standard library function next_permutation. And, btw, when I first looked at his code, one of the first things I wondered is why isnt he using std::next_permutation, and I had to figure out that he isn't doing perumtations. That's work for the next reader that could be avoided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T03:42:50.843", "Id": "58835", "Score": "0", "body": "you put more into a comment explaining why you didn't add more to your answer. point made. explain these things in the answer please. as it stands your answer could have been written in a comment, and looks like a comment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-08T05:33:05.760", "Id": "60694", "Score": "0", "body": "I have actually removed the `std::next_permutation` snippet from my answer. I've realized that it may be best to stick with the OP's permutations with repetition, which the STL function does not perform. Yes, permutations are rearrangements. But the order *does* matter, unlike combinations. I also agree with Malachi: your answer could be more substantial if it explained how the code can *actually* be improved. If that means producing permutations *without* repetition, then that could be explained. These links by themselves are not enough." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T00:37:18.497", "Id": "36024", "ParentId": "17828", "Score": "-4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T01:37:25.807", "Id": "17828", "Score": "11", "Tags": [ "c++", "strings", "recursion", "combinatorics" ], "Title": "Print all permutations with repetition of characters" }
17828
<p>Recently I had the need to make some ajax calls within a MVC 3.0 with Razor and jQuery application. After a bit of trial and error and refactoring it was discovered that a number of different needs were required. These included:</p> <ol> <li>The serverside code would be responsible for creating any redirect urls and we wanted to stick with the inherited controller <em>RedirectToAction()</em> method where possible in our controller actions.</li> <li>We are using jQuery unobtrusive validation and some situations meant that new forms were rendered onto the view via ajax. That meant we needed to ensure those new form fields contained and validated when required.</li> <li>We wanted the flexibility to return html (PartialViews), json or tell the client side it was a redirect and the URL to redirect to (initiated via 1 above).</li> <li>Before page redirects at times we wanted to show div popups such as a Success confirmation. Hence although we were using RedirectToAction() in the backend we wanted the javascript to actually perform the redirect.</li> </ol> <p>With these in place we did a bit of serverside code that ensured we hijacked the <code>RedirectToAction()</code> result and returned a json object instead. I'm fairly happy that code works. What I'm not sure about is the javascript code that I use to perform the result. </p> <p>Some notes:</p> <ol> <li>The <code>$.validator.unobtrusive.parseDynamicContent</code> method will ensure the new html elements are rebound for validation. I did not write that code so have not added it for review.</li> <li>For options 1, 2 and 3 above we didn't want the person writing the ajax to always have to worry about these so esentially wanted them to just be <em>handled</em> so to speak.</li> </ol> <p>I'm definitely pretty raw in the Javascript department so any comments or improvements on the code below would be greatly appreciated.</p> <pre><code>$.ajaxWithRedirect = function (options) { // If dataType wasn't specified in the options, default to 'html' var dataType = (options.dataType !== undefined) ? options.dataType : 'html'; // jQuery AJAX object $.ajax({ // Normal properties type: options.type, url: options.url, data: options.data, dataType: dataType, cache: false, // Global beforeSend wrapper with user defined function beforeSend: function () { // Execute user defined method if (typeof options.beforeSend === 'function') { options.beforeSend(); } }, // Global success wrapper which will redirect if url specified is a json object // with the RedirectUrl tag success: function (data) { var jData; var redirected = false; try { if (data) { jData = $.parseJSON(data); if (jData &amp;&amp; (typeof jData.RedirectUrl !== 'undefined' &amp;&amp; jData != null &amp;&amp; jData.RedirectUrl.length &gt; 0)) { var performRedirect = true; if (typeof options.beforeRedirect !== 'undefined') { // beforeRedirect returns true if the redirect is still to occur otherwise false performRedirect = options.beforeRedirect(jData); } if (performRedirect) { redirected = true; // Using replace based off SO - http://stackoverflow.com/questions/503093/how-can-i-make-a-redirect-page-in-jquery-javascript window.location.replace(jData.RedirectUrl); } } } } catch (e) { // not json } // Execute user defined method if (!redirected) { if ((options.success &amp;&amp; typeof options.success === 'function')) { options.success(data); } // always done after the success to ensure any dyanamic elements have been loaded if (typeof options.dynamicValidation != 'undefined') { $.validator.unobtrusive.parseDynamicContent(options.dynamicValidation); } } }, error: function (xhr, status, err) { if (typeof options.error === 'function') { options.error(xhr, status, err); } if (xhr.status == 400) { alert(err); } } }); }; </code></pre> <p>Example of usage is (Methods such as addUploadTableSpinner just included for examples):</p> <pre><code>$.ajaxWithRedirect({ beforeSend: addUploadTableSpinner(), type: "POST", url: '/MyUrl/Delete' + '?sessionId=' + sessionId, dataType: "html", beforeRedirect: function (data) { closePopup(); // show the user success message showDeleteSuccessfulPopup(data.RedirectUrl); showSuccessfulPopup = false; // don't do the redirect return false; }, success: function (data) { if (data.length == 0) { deleteRow.remove(); } else if (showSuccessfulPopup) { deleteRow.html(data); closePopup(); showDeleteSuccessfulPopup(); } removeUploadTableSpinner(); } }); </code></pre>
[]
[ { "body": "<p>It seems to me that you're duplicating some of what <code>$.ajax()</code> will do for you (such as calling <code>beforeSend</code>) and you're also leaving the door open for using the deferred promise methods (<code>then</code>, <code>done</code>, <code>fail</code>, etc.) that jQuery's XHR object provides.</p>\n\n<p>Here's a version that focusses solely on the redirection (i.e. it doesn't worry about the data type, the validation stuff, or doing its own error handling). It's just a transparent layer on top of the normal <code>$.ajax()</code> function.</p>\n\n<p>The code's below, and <a href=\"http://jsfiddle.net/sPtDb/2/\" rel=\"nofollow\">here's a demo</a></p>\n\n<pre><code>$.ajaxWithRedirect = function (options) {\n \"use strict\";\n\n var deferred = $.Deferred(),\n successHandler,\n xhr;\n\n // force no-cache\n options.cache = false;\n\n // get a copy of the success handler...\n successHandler = options.success;\n\n // ... and replace it with this one\n options.success = function (data) {\n var contentType = xhr.getResponseHeader(\"Content-Type\"),\n performRedirect = true,\n redirectUrl = null,\n args = [].slice.call(arguments, 0),\n json;\n\n // If response isn't there or isn't json,\n // skip all the redirect logic\n if( data &amp;&amp; (/json/i).test(contentType) ) {\n // If json was requested, and json received, jQuery will\n // have parsed it already. Otherwise, we'll have to do it\n if( options.dataType === 'json' ) {\n redirectUrl = data.RedirectUrl;\n } else {\n try {\n json = $.parseJSON(data);\n redirectUrl = json.RedirectUrl;\n } catch(e) {\n // no-op\n }\n }\n\n // check the redirect url\n if( redirectUrl &amp;&amp; typeof redirectUrl === 'string') {\n // Is there a beforeRedirect handler?\n if( typeof options.beforeRedirect === 'function' ) {\n // pass all the arguments to the beforeRedirect handler\n performRedirect = options.beforeRedirect.apply(null, args);\n }\n\n // unless strictly false, go ahead with the redirect\n if( performRedirect !== false ) {\n location.replace(redirectUrl);\n // and stop here. No success and/or deferred handlers\n // will be called since we're redirecting anyway\n return;\n }\n }\n }\n\n // no redirect; forward everything to the success handler(s)\n if( typeof successHandler === 'function' ) {\n successHandler.apply(null, args);\n deferred.resolve.apply(null, args);\n }\n };\n\n // Make the request\n xhr = $.ajax(options);\n\n // Forward the deferred promise method(s)\n xhr.fail(deferred.reject);\n xhr.progress(deferred.notify);\n\n // Replace the ones already on the xhr obj\n deferred.promise(xhr);\n\n return xhr;\n};\n</code></pre>\n\n<p>Point is that you should be able use <code>$.ajaxWithRedirect</code> <em>exactly</em> like you'd use vanilla <code>$.ajax</code>, including all the shiny deferred promise stuff. The only thing it does different from the normal version is set <code>options.cache = false</code>, and that it has a <code>beforeRedirect</code> callback.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T19:04:02.100", "Id": "28488", "Score": "0", "body": "Thanks looks good (I think :)). I'm not sure where the validation re-binding would be plugged in for this though. Would you suggest still creating a wrapper around this to handle that on success, as I've done? The idea is for this stuff to just happen rather than putting it in for every $.ajaxWithRedirect call." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T02:31:51.073", "Id": "28504", "Score": "1", "body": "@dreza Yes, I'd say make a wrapper for that. The point is that the validation code is orthogonal to the redirection code; one does not necessitate or depend on the other. But you can build another layer on top of `ajaxWithRedirect` that takes care of validation, setting `dataType = 'html'` and maybe the error handling too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T04:44:29.720", "Id": "28507", "Score": "0", "body": "Thats great. I will try something and repost as an answer or edit my question when I've sussed it." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T16:16:23.543", "Id": "17889", "ParentId": "17830", "Score": "4" } } ]
{ "AcceptedAnswerId": "17889", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T04:30:02.253", "Id": "17830", "Score": "5", "Tags": [ "javascript", "jquery", "asp.net-mvc-3" ], "Title": "Wrapper for jquery ajax to ensure redirects occur on clientside" }
17830
<p>I'd like a code review on my very simple server application that validates whether the serial number retrieved from the client is a valid one or not. </p> <ol> <li><p>Is there a better way to handle the start/stop on the service? If you look at my Start and Service methods, I'm basically looking at <code>isServerRunning</code> boolean variable and getting the service out of the while loop whenever it has been toggled to false, but this doesn't seem like the ideal approach since the thread is basically paused at <code>listner.AcceptSocket()</code>.</p></li> <li><p>Does this guarantee N:1 connectivity, 1 being the server?</p></li> <li><p>I'm going to set a send/receive timeout on my socket. What is a generally reasonable timeout value to set?</p></li> </ol> <p>I'd also like to hear comments on the overall coding style and any other suggestions on improving this code.</p> <pre><code>public partial class ServerForm : Form { #region Fields private bool isServerRunning = false; private const int CLIENT_LIMIT = 10; private TcpListener listener; #endregion #region Event Handlers private void btnStart_Click(object sender, EventArgs e) { try { int port; if (String.IsNullOrEmpty(txtPort.Text)) { MessageBox.Show(Constant.ERROR_PORT_NUMBER_EMPTY); return; } if (isServerRunning) return; if (!int.TryParse(txtPort.Text, out port)) { MessageBox.Show(Constant.ERROR_PORT_ONLY_INT_ALLOWED); return; } if (port &lt; 0 || port &gt; 65535) { MessageBox.Show(Constant.ERROR_PORT_NUMBER_OUT_OF_RANGE); return; } Start(port); } catch (Exception ex) { LogWriter.WriteExceptionLog(ex.ToString()); } } private void btnStop_Click(object sender, EventArgs e) { if (isServerRunning) { isServerRunning = false; ServerLogWriter("Server Stopped"); } } private void btnClear_Click(object sender, EventArgs e) { try { listBoxLog.Items.Clear(); } catch (Exception ex) { LogWriter.WriteExceptionLog(ex.ToString()); } } #endregion #region Constructor public ServerForm() { InitializeComponent(); } #endregion #region Private Methods private void ServerLogWriter(string content) { string log = DateTime.Now + " : " + content; this.BeginInvoke(new Action(() =&gt; { listBoxLog.Items.Add(log); } )); LogWriter.WriteLog(log, Constant.NETWORK_LOG_PATH); } private void Start(int port) { try { isServerRunning = true; listener = new TcpListener(IPAddress.Parse(LocalIPAddress()), port); listener.Start(); for (int i = 0; i &lt; CLIENT_LIMIT; i++) { Thread t = new Thread(new ThreadStart(Service)); t.IsBackground = true; t.Start(); } ServerLogWriter(String.Format("Server Start (Port Number: {0})", port)); } catch (SocketException ex) { ServerLogWriter(String.Format("Server Start Failure (Port Number: {0}) : {1}",port,ex.Message)); LogWriter.WriteExceptionLog(ex.ToString()); isServerRunning = false; } catch (Exception ex) { LogWriter.WriteExceptionLog(ex.ToString()); isServerRunning = true; } } private void Service() { try { while (isServerRunning) { Socket soc = listener.AcceptSocket(); ServerLogWriter(String.Format("Client Connected : {0}", soc.RemoteEndPoint)); try { Stream s = new NetworkStream(soc); StreamReader sr = new StreamReader(s); StreamWriter sw = new StreamWriter(s); sw.AutoFlush = true; string validation = String.Empty; string serial = sr.ReadLine(); if (ValidateSerial(serial)) { validation = String.Format("Serial Number Validated (Received Serial: {1}) : {0}", soc.RemoteEndPoint, serial); sw.WriteLine("VALIDATE"); } else { validation = String.Format("Invalid Serial Number (Received Serial: {1}) : {0}", soc.RemoteEndPoint, serial); sw.WriteLine("FAILURE"); } ServerLogWriter(validation); s.Close(); } catch (Exception ex) { ServerLogWriter(String.Format("Socket Error: {0}, {1}", soc.RemoteEndPoint, ex.Message)); LogWriter.WriteLog(ex.ToString(), Constant.EXCEPTION_LOG_PATH); } ServerLogWriter(String.Format("End Connection : {0}", soc.RemoteEndPoint)); soc.Close(); } } catch (Exception ex) { LogWriter.WriteExceptionLog(ex.ToString()); } } private string LocalIPAddress() { string localIP = String.Empty; try { IPHostEntry host; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily.ToString() == "InterNetwork") { localIP = ip.ToString(); } } return localIP; } catch (Exception ex) { LogWriter.WriteExceptionLog(ex.ToString()); } return localIP; } #endregion } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-02T10:24:54.870", "Id": "28950", "Score": "0", "body": "For serial number validation, is it not more appropriate to use WCF? have you looked at is as an option?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-19T08:03:49.583", "Id": "58737", "Score": "0", "body": "See the following working example... [C# Socket Sample Program](http://csharp.net-informations.com/communications/csharp-socket-programming.htm) Very simple and good for beginners." } ]
[ { "body": "<p>Without reviewing other aspects, I think you should separate the code so that there's the server itself in its class (or, maybe even better, its own project), and there's the UI.</p>\n\n<p>For instance, you should not show a MessageBox inside a server's code. There are so many reasons for that so I'll just leave this statement as is.</p>\n\n<p>In other words, the server should behave as a black box, returning error codes, or throwing exceptions, or anything else, according to its own API. Mixing the server's code with UI is not a good practice.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T09:17:56.820", "Id": "17839", "ParentId": "17832", "Score": "9" } }, { "body": "<p>You may want to look some other guides/implementations about that:<br>\n<a href=\"http://www.codeproject.com/Articles/83102/C-SocketAsyncEventArgs-High-Performance-Socket-Cod\" rel=\"nofollow noreferrer\">CodeProject | C# SocketAsyncEventArgs High Performance Socket</a><br>\n<a href=\"https://stackoverflow.com/questions/869744/how-to-write-a-scalable-tcp-ip-based-server\">Stack Overflow | How to write a scalable Tcp/Ip based server</a></p>\n\n<p><strong>About your code:</strong> </p>\n\n<ul>\n<li>You should seperate the UI and the server code, so you can be able to use it on a console application or -more likely- a windows service. </li>\n<li><code>TcpListener</code> is a good class that does its job pretty well but if you want something more scalable and customizable, I think it's too <em>high-level</em> for you. For this you should deal with <code>Socket</code> class directly.</li>\n</ul>\n\n<p><em>You should also know,</em><br>\nThere are so many concepts that you should be aware of about TCP and socket programming in general; in order to write a robust, scalable TCP server. You should know about framing protocols, find a good way to handle your buffers, be experienced at asynchronous code and debugging that code.</p>\n\n<p><strong>Edit:</strong> <a href=\"http://nitoprograms.blogspot.com/2009/04/tcpip-net-sockets-faq.html\" rel=\"nofollow noreferrer\">This FAQ page</a> by Stephen Cleary is a really good place to get started.</p>\n\n<p>I suggest you to take a look at the links I mentioned above. They provide some good implementations and explain why they do the things they do in a comprehensive way. Then you can roll your own, avoiding common pitfalls.</p>\n\n<p><strong>Back to your code:</strong> </p>\n\n<ul>\n<li>Creating a new thread for each connection is <strong>brutal</strong>. You should use the asynchronous methods of the TcpListener class. Or you can at least use <code>ThreadPool</code> and the easiest way to do this is using the <code>Task</code> class.</li>\n<li><code>LocalIPAddress()</code> method returns a string that you parse again to an <code>IPAddress</code> object to use. Don't convert it to a string, return it directly as an <code>IPAddress</code>.</li>\n<li><code>AddressFamily</code> is an <code>Enum</code>. You can check whether it is <code>InterNetwork</code> without converting it to a string: <code>ip.AddressFamily == AddressFamily.InterNetwork</code></li>\n<li>Try to use your streams in <code>using</code> blocks or dispose them in <code>finally</code> blocks so you can be sure they're closed even if an exception is thrown in your code.</li>\n<li>Timeout really depends on the client, network and the size of the data you're sending/receiving. Whatever amount of inactive time you think that means \"there's something wrong\" will be a sufficient timeout value.</li>\n</ul>\n\n<p><strong>Nonetheless:</strong><br>\nMy advice is not to continue this and start another after you look into some other implementations like the ones I mentioned. You need a UI independent project that can be referenced by your other applications that need to use (or that need to be) a TCP server.</p>\n\n<p><strong>Edit:</strong> Although I said that <em>you should be able to</em>, it doesn't mean you should have a TCP server in a GUI application. You need a Windows service to run on the background, deal with high amounts of connections and manage the data traffic between itself and its clients. Doing these kinds of operations in a GUI application is usually a bad idea.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T00:09:06.933", "Id": "28443", "Score": "0", "body": "Ok. Thanks for the good answer. The reason why I was mixing GUI code with server code is that one of the requirements imposed on me was to show a log of connection status on the listbox. Any good ideas on how I should handle this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T06:00:40.550", "Id": "28447", "Score": "1", "body": "@l46kok: Is it have to be a ListBox? You can write your logs to a database or a log file and then you can create a GUI application (say, LogViewer) to query and show the logs. You shouldn't keep all the logs in the memory anyway since it will eventually cause your program to throw an OutOfmemoryException and there is the fact that all your logs would be gone when you close the application. For LogViewer, you should get the last N logs depending on your environment. (I don't think a ListBox with millions of items would perform well)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T06:16:35.023", "Id": "28448", "Score": "0", "body": "@ŞafakGür As much as how weird it sounds, yes it has to be a ListBox because that is the requirement imposed on me. The ListBox is automatically cleared out when it reaches a certain number of items, so memory isn't that huge of a problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T06:31:58.450", "Id": "28449", "Score": "0", "body": "@l46kok: Then you can use it in your log viewer. You should be able to see the yesterday's or last month's logs if you want to. So saving the logs somewhere more persistent (like DB or file system) is the way to go. You can use whatever control you wish to show the logs in your log viewer. Think this way: Your TCP server will be running all the time but not everyone will look at its logs every second, constantly. So creating a Windows service for the TCP Server and creating a GUI application that people will run to review logs and close when they're done seems like the right thing to do here." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T09:54:32.287", "Id": "17840", "ParentId": "17832", "Score": "24" } } ]
{ "AcceptedAnswerId": "17840", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T05:13:23.073", "Id": "17832", "Score": "26", "Tags": [ "c#", ".net", "networking" ], "Title": "Implementing a good TCP Socket Server" }
17832
<p>I am trying to write 2 functions, one to read the matrix (2D array) and other one to print it out. So far I have:</p> <pre><code>/* Read a matrix: allocate space, read elements, return pointer. The number of rows and columns are given by the two arguments. */ double **read_matrix(int rows, int cols){ double **mat = (double **) malloc(sizeof(double *)*rows); int i=0; for(i=0; i&lt;rows; i++){ /* Allocate array, store pointer */ mat[i] = (double *) malloc(sizeof(double)*cols); //what to do after?? return mat; } </code></pre> <p>then the print matrix function, not sure if it is correct</p> <pre><code> void print_matrix(int rows, int cols, double **mat){ for(i=0; i&lt;rows; i++){ /* Iterate of each row */ for(j=0; j&lt;cols; j++){ /* In each row, go over each col element */ printf("%f ",mat[i][j]); /* Print each row element */ } }} </code></pre> <p>and here is the main function I am using to run:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; double **read_matrix(int rows, int cols); void print_matrix(int rows, int cols, double **mat); void free_matrix(int rows, double **mat); int main(){ double **matrix; int rows, cols; /* First matrix */ printf("Matrix 1\n"); printf("Enter # of rows and cols: "); scanf("%d %d",&amp;rows,&amp;cols); printf("Matrix, enter %d reals: ",rows*cols); matrix = read_matrix(rows,cols); printf("Your Matrix\n"); /* Print the entered data */ print_matrix(rows,cols,matrix); free_matrix(rows, matrix); /* Free the matrix */ return 0;} </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T08:21:39.823", "Id": "28395", "Score": "2", "body": "Please note that as per the [faq], any code should be working, and actual code from a project rather than pseudo-code or example code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T18:09:44.157", "Id": "28418", "Score": "1", "body": "Note that `scanf` returns the number of values it read. In `scanf(\"%d %d\",&rows,&cols);` it should return 2. If it returns 0 or 1 then the user entered non-numeric data. Subsequent use of `scanf` to read numeric data will fail until the non-numeric data is read or flushed (see `fpurge()`). `scanf` can also return -1 if the input stream is closed." } ]
[ { "body": "<p>It seems OK to me as far as it goes. A couple of suggestions though:</p>\n\n<ol>\n<li><code>read_matrix</code> may be better split up into two functions, one to create it and the other to read the contents from the source, even if the <code>create_matrix</code> function is called from <code>read_matrix</code> - and you need to be aware of the possibility that the allocation may fail.</li>\n<li>On the other hand, you may wish to consider just allocating a single block of size rows*cols of memory, and indexing it via <code>y*rows + x</code> rather than allocating several smaller blocks.</li>\n<li>For 'neatness', you should consider using <code>calloc( number_of_elements, sizeof (double) )</code> instead of <code>malloc</code>, just to give a (possibly) sensible initial value.</li>\n<li><code>print_matrix</code> could do with some layout changes, such that each row is on a separate line, and the corresponding cells line up under each other, something like <code>%10.3f</code> (but would depend on the type of data expected).</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T08:15:21.173", "Id": "17838", "ParentId": "17833", "Score": "5" } }, { "body": "<p>Its fine for what it does.</p>\n\n<p>But you should try and group all the relavant information into a single structure so that you pass it round as one item (this will prevent typing mistakes).</p>\n\n<pre><code>typedef struct TwoDArray\n{\n int cols;\n int rows\n doubel** data;\n} TwoDArray;\n\nTwoDArray* read_TwoDArray(int rows, int cols);\n</code></pre>\n\n<p>Declare one variable per line:</p>\n\n<pre><code>int rows, cols; /* Any industry style guide will force you to split\n this over two lines\n */\n</code></pre>\n\n<p>You are not being payed to conserve vertical space. You are being payed to make the code as readable and maintainable as possible.</p>\n\n<p>You need to pick a brace style and be consistent. There are a couple of styles out there (I can't argue that any one is better than another). So just find a style you like but then by <strong>consistent</strong> when using it:</p>\n\n<pre><code>Stuff /* Lined up Style */\n{\n Plop\n}\n\nStuff { /* K&amp;R up Style */\n Plop\n}\n\nStuff /* indented Style (rarer than the other two) */\n {\n Plop\n }\n</code></pre>\n\n<p>The only thing I would complain about (and its not major) is neatness. Use more white space to break the code into sections. This makes it easier for the reader to group stuff together into logical blocks.</p>\n\n<pre><code>int main()\n{\n double **matrix;\n int row;\n int cols;\n\n printf(\"Matrix 1\\n\");\n printf(\"Enter # of rows and cols: \");\n scanf(\"%d %d\",&amp;rows,&amp;cols);\n\n\n printf(\"Matrix, enter %d reals: \",rows*cols);\n matrix = read_matrix(rows,cols); \n\n\n printf(\"Your Matrix\\n\");\n print_matrix(rows,cols,matrix);\n\n\n free_matrix(rows, matrix);\n\n return 0;\n}\n</code></pre>\n\n<p>Last thing is comments. The comments you add are useless. </p>\n\n<pre><code>free_matrix(rows, matrix); /* Free the matrix */\n</code></pre>\n\n<p>One could even argue worse then useless as the comments over time may stray from the code (or it takes extra work to keep the comments lined up with the work).</p>\n\n<p>The code should explain itself (as it does: the function free_matrix() does not really need any explanation). You should use comments to explain why (or potentially how).</p>\n\n<pre><code>/*\n * read_matrix()\n * Parameters:\n * rows/cols the size of the matrix to be allocated.\n * Returns:\n * A pointer to an a data structure such that \n * the expression M[a][b] to be valid.\n * Where (0 &lt;= a &lt; rows) &amp;&amp; (0 &lt;= b &lt; cols)\n *\n * This structure should be released using the function free_matrix()\n */\ndouble **read_matrix(int rows, int cols){\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T15:40:07.847", "Id": "17847", "ParentId": "17833", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T05:15:49.613", "Id": "17833", "Score": "4", "Tags": [ "c" ], "Title": "Creating an 2D array using pointer/malloc, and then print it out" }
17833
<p>I have a menu, where a user selects one out of 4, and another 2 or 4 options will appear. I used big buttons; a picturebox + label to create the buttons.</p> <p>The 4 main buttons are fixed, but the 4 other buttons depend on the first choice. Text and image will change. I programmed this, but I kinda feel this must be possible more easily.</p> <p>I have 4 structs which contain the image path and label text. like this: (I'll only show with 2, because the rest won't add anything, it is just the same.)</p> <pre><code>private const string _mainButton1 = "ConfigDP"; private const string _mainButton2 = "ConfigADP"; struct ConfigDPSubmenu { public const string _SubMenuBtn1Text = "text submenu 1 button 1"; public const string _SubMenuBtn2Text = "text submenu 1 button 2"; public const string _SubMenuBtn1Img = "DevPortal.png"; public const string _SubMenuBtn2Img = "CustomDevPortal.png"; } struct ConfigADPSubmenu { public const string _SubMenuBtn1Text = "text submenu 2 button 1"; public const string _SubMenuBtn2Text = "text submenu 2 button 2"; public const string _SubMenuBtn1Img = "ADP.png"; public const string _SubMenuBtn2Img = "CustomADP.png"; } </code></pre> <p>Then I have the function where I make the buttons: (it is called when press on the main buttons)</p> <pre><code>private void CreateSubButtons(string sender) { pictureBoxSubBtn3.Image = null; pictureBoxSubBtn4.Image = null; SubBtn3Text.Text = ""; SubBtn4Text.Text = ""; panelSubBtn3.BorderStyle = BorderStyle.None; panelSubBtn4.BorderStyle = BorderStyle.None; switch (sender) { case _mainButton1: SubBtn1Text.Text = ConfigDPSubmenu._SubMenuBtn1Text; SubBtn2Text.Text = ConfigDPSubmenu._SubMenuBtn2Text; pictureBoxSubBtn1.Image = Image.FromFile(ConfigDPSubmenu._SubMenuBtn1Img); pictureBoxSubBtn2.Image = Image.FromFile(ConfigDPSubmenu._SubMenuBtn2Img); panelSubBtn1.BorderStyle = BorderStyle.FixedSingle; panelSubBtn2.BorderStyle = BorderStyle.FixedSingle; break; case _mainButton2: SubBtn1Text.Text = ConfigADPSubmenu._SubMenuBtn1Text; SubBtn2Text.Text = ConfigADPSubmenu._SubMenuBtn2Text; pictureBoxSubBtn1.Image = Image.FromFile(ConfigADPSubmenu._SubMenuBtn1Img); pictureBoxSubBtn2.Image = Image.FromFile(ConfigADPSubmenu._SubMenuBtn2Img); panelSubBtn1.BorderStyle = BorderStyle.FixedSingle; panelSubBtn2.BorderStyle = BorderStyle.FixedSingle; break; } } </code></pre>
[]
[ { "body": "<p>A couple of points that may help you.</p>\n\n<ol>\n<li><p>When you see yourself copy and pasting or writing duplicated code, consider refactoring. I could only see one difference in your code in the case statements. You could move all that to a method and pass in the necessary struct. Even further, once you have done this you will see further code duplication you could probably further refactor into seperate methods.</p></li>\n<li><p>I'm not sure about having exposed fields on the struct start with _. You might want to read <a href=\"https://stackoverflow.com/questions/1618316/naming-convention-in-c-sharp\">Jon Skeets Answer</a> on stack overflow.</p></li>\n<li><p>I would probably consider removing your struct and using a single class. Then I would create 4 instances of that class with the values required. I might even consider populating the text for those from a resource file.</p></li>\n<li><p>I'm not really sure on this, but in old versions (Vb 6....) you could create controls which were arrays of each other. So instead of panelSubBtn1, panelSubBtn2 etc you would just have panelSubBtn and reference it by panelSubBtn[0] etc If this was possible you could seriously simplify your code. I'll let you figure that out though...</p></li>\n</ol>\n\n<p>These are a few quick things which may or may not help.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T07:45:13.377", "Id": "28387", "Score": "0", "body": "Thank you for the answer! 1. I've tried to create a variable but I can not call Variable._SubMenuBtn1Text; Where I use the value of Variable in stead of the name Variable. Is there a way to do so? 2. I preffer _ for constant data, but as I see it is not recommended; I'll change that :). 3. I think a class is nicer because you can place that somewhere else? Placing text in a resource file would be nice, I've thought about that. But as I am still learning I'll pass that to a new project. 4. I'll check that out! Idk whether it works on C#." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T07:53:07.093", "Id": "28388", "Score": "1", "body": "4. I've found an artilcle on [this](http://msdn.microsoft.com/en-us/library/aa289500(v=vs.71).aspx) topic. I'll rewrite my code using that!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T19:16:39.183", "Id": "28423", "Score": "1", "body": "I don't see any public *methods* in the question. And the public constant fields are not so public, because they are in a private `struct` inside another type." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T20:41:51.200", "Id": "28434", "Score": "0", "body": "@svick ah good point. more of a typo although I would still stand by renaming thefields to not having the _" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T09:04:51.897", "Id": "28456", "Score": "0", "body": "@svick Yea, would be better to make them private I guess. no need for public." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T07:36:53.190", "Id": "17835", "ParentId": "17834", "Score": "7" } }, { "body": "<p>dreza has some great comments, but I would go further and change the structs to classes that inherit from interfaces.</p>\n\n<p>I'll start with the design.</p>\n\n<p>First you could create an interface that represents button information.</p>\n\n<pre><code>public interface IButtonInformation\n{\n string Text{ get; }\n string ImageFileName\n}\n</code></pre>\n\n<p>Then an interface that represents the possible statuses.</p>\n\n<pre><code>public interface IFormStatus\n{\n IButtonInformation Button1 { get; }\n IButtonInformation Button2 { get; }\n}\n</code></pre>\n\n<p>You can now create concrete classes:</p>\n\n<pre><code>public class DPButton1 : IButtonInformation\n{\n private const string TextString = \"text submenu 1 button 1\";\n private const string ImageFileNameString = \"StreamitDevPortal.png\";\n\n public string Text { get { return TextString ; } }\n public string ImageFileName{ get { return ImageFileNameString; } }\n}\n\n\n// Do the same for all 4 possible states.\n</code></pre>\n\n<p>And create the statuses</p>\n\n<pre><code>public class ConfigDPStatus : IFormStatus\n{\n public IButtonInformation Button1 { get; private set;\n public IButtonInformation Button2 { get; private set;\n\n public ConfigADPStatus()\n {\n Button1 = new DPButton1();\n Button2 = new DPButton2();\n }\n}\n\n// Rinse and repeat for ADP Status\n</code></pre>\n\n<p>Now your CreateSubButtons looks like this:</p>\n\n<pre><code>private const IDictionary&lt;string, IFormStatus&gt; ButtonStatuses = new Dictionary&lt;string, IFormStatus&gt;\n {\n {MainButton1, new ConfigDPStatus()},\n {MainButton2, new ConfigADPStatus()},\n }\n\nprivate void CreateSubButtons(string sender)\n{\n if (!ButtonStatuses.ContainsKey(sender)\n {\n throw new ApplicationException(\"Unknown sender\");\n }\n\n FormatButtons(ButtonStatuses[sender]);\n}\n\nprivate void FormatButtons(IFormStatus status)\n{\n SubBtn1Text.Text = status.Button1.Text;\n SubBtn2Text.Text = status.Button2.Text;\n pictureBoxSubBtn1.Image = Image.FromFile(status.Button1.ImageFileName);\n pictureBoxSubBtn2.Image = Image.FromFile(status.Button1.ImageFileName);\n}\n</code></pre>\n\n<p>You'll notice I didn't clear the controls as you did, I don't think that is necessary as you are just re-assigning them right away anyway.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T19:19:12.707", "Id": "28424", "Score": "0", "body": "Why do you have the string constants as `const` fields? Wouldn't it be better to inline them? (E.g. `public string Text { get { return \"text submenu 1 button 1\"; } }`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T20:26:06.157", "Id": "28431", "Score": "1", "body": "I guess my thinking was to create only one version of the string that will be referenced where ever it is used. I guess it comes from working on an API that get hundreds of hits a second. Also, see http://stackoverflow.com/questions/1707959/is-there-a-runtime-benefit-to-using-const-local-variables. Short answer from what I understand: by putting it in a const, you are telling the compiler \"This is never going to change\" so it can be optimized properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T08:41:56.037", "Id": "28454", "Score": "0", "body": "I use the `const` always for static data I.E: Texts, names of resources (images) or in switch/case structures I always define the cases in `const` to gain better readability and more flexibility. Especially when you use them at more places" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T08:55:09.613", "Id": "28455", "Score": "0", "body": "Thank you for the answer! I've posted what I created, and am wondering why it is better/more efficient/better readable to use an interface for each button, 2 classes for each button, a dictionary, and two functions to update the buttons. Seems quite a lot to me. Could you please explain why you suggest/advise this, or when it usefull to use this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T15:28:40.873", "Id": "28471", "Score": "1", "body": "My thought process was to limit the number of parameters in any given function. On average, I try and keep it to two, three in extreme cases. Anything more than that and it gets confusing. I also think doing it this way more portrays the intent/design of the application. I also used interface / class combination so you can do your button assignments in a single method. I used the dictionary to eliminate a possibly huge if/else or switch statement. And if you look at it, it's only one class for each button. There is one class that is shared through all of them." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T16:36:05.460", "Id": "17849", "ParentId": "17834", "Score": "3" } }, { "body": "<p>I didn't see this covered in other peoples' answers, so I thought I'd mention one thing. Your <code>struct</code>s with <code>const</code>s are all right by me:</p>\n\n<pre><code>struct ConfigDPSubmenu\n{\n public const string _SubMenuBtn1Text = \"text submenu 1 button 1\";\n public const string _SubMenuBtn2Text = \"text submenu 1 button 2\";\n public const string _SubMenuBtn1Img = \"StreamitDevPortal.png\";\n public const string _SubMenuBtn2Img = \"CustomDevPortal.png\";\n}\nstruct ConfigADPSubmenu\n{\n public const string _SubMenuBtn1Text = \"text submenu 2 button 1\";\n public const string _SubMenuBtn2Text = \"text submenu 2 button 2\";\n public const string _SubMenuBtn1Img = \"StreamitADP.png\";\n public const string _SubMenuBtn2Img = \"CustomADP.png\";\n}\n</code></pre>\n\n<p>However, they are instantiatable as such:</p>\n\n<pre><code>var c1 = new ConfigDPSubmenu();\nvar c2 = new ConfigADPSubmenu();\n</code></pre>\n\n<p>which semantically makes no sense. In order to take care of that, convert them to <code>static</code> <code>class</code>es:</p>\n\n<pre><code>static class ConfigDPSubmenu\n{\n public const string _SubMenuBtn1Text = \"text submenu 1 button 1\";\n public const string _SubMenuBtn2Text = \"text submenu 1 button 2\";\n public const string _SubMenuBtn1Img = \"StreamitDevPortal.png\";\n public const string _SubMenuBtn2Img = \"CustomDevPortal.png\";\n}\nstatic class ConfigADPSubmenu\n{\n public const string _SubMenuBtn1Text = \"text submenu 2 button 1\";\n public const string _SubMenuBtn2Text = \"text submenu 2 button 2\";\n public const string _SubMenuBtn1Img = \"StreamitADP.png\";\n public const string _SubMenuBtn2Img = \"CustomADP.png\";\n}\n</code></pre>\n\n<p>You shouldn't lose any sort of performance or functionality by that conversion.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-29T18:44:23.807", "Id": "18057", "ParentId": "17834", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T07:13:32.617", "Id": "17834", "Score": "10", "Tags": [ "c#", "strings" ], "Title": "Creating submenus with buttons" }
17834
<p>I have this class whose code I pasted in full. The <code>CredentialsManager</code> class is not shown here as all it does is return the DB connection variables.</p> <p>Can be improved or is this is OK as I've written it? Namely, I'm interested if it's OK to have a private variable <code>mysqli</code> populate inside the function <code>openConnection()</code> or if I should have done that in the constructor.</p> <p>I'm pretty confident it would be a bad thing to have the same code for opening a connection in each function of the class, which is why I've put the connection opening code in a function itself.</p> <pre><code>&lt;?php class Logger { // private variables private $_host; private $_database; private $_username; private $_password; private $_mysqli; // public functions public function __construct() { $credientials = CredentialsManager::GetCredentials(); $this-&gt;_host = $credientials['host']; $this-&gt;_database = $credientials['database']; $this-&gt;_username = $credientials['user']; $this-&gt;_password = $credientials['pass']; } public function RecordLog($log){ if ($this-&gt;openConnection()){ if (!($stmt = $this-&gt;_mysqli-&gt;prepare("INSERT INTO logz (log) VALUES (?)"))) { echo "Prepare failed: (" . $this-&gt;_mysqli-&gt;errno . ") " . $this-&gt;_mysqli-&gt;error; } if (! $stmt-&gt;bind_param("s", $log)){ echo "Binding failed: (". $stmt-&gt;errno .") " . $stmt-&gt;error; } if (! $stmt-&gt;execute() ){ echo "Execute failed: " . $stmt-&gt;error; } if ($stmt-&gt;affected_rows &gt; 0) return true; else return false; } else return false; } // private functions private function openConnection() { $this-&gt;_mysqli = new mysqli($this-&gt;_host, $this-&gt;_username, $this-&gt;_password, $this-&gt;_database); if ($this-&gt;_mysqli-&gt;connect_errno) { echo "Failed to connect to MySQL: " . $this-&gt;_mysqli-&gt;connect_error; return false; } return true; } } ?&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T16:09:03.473", "Id": "28412", "Score": "0", "body": "That's not how you spell credentials? Anyways, I'm looking at the code now, will post an answer after I go through it." } ]
[ { "body": "<p>\"I'm pretty confident it would be a bad thing to have the same code for opening a connection in each function of the class, that's why I've put the connection opening code in a function itself.\"</p>\n\n<ul>\n<li>That would be correct when possible, practice DRY: Don't Repeat Yourself</li>\n</ul>\n\n<p>\"Namely, I'm interested if it's OK to have a private variable mysqli populate inside the function openConnection() or should I have done that in the constructor?\"</p>\n\n<ul>\n<li><p>Nope, its okay the way you did it, but you can call openConnection() in the construct instead of in each function that uses it.</p>\n\n<p>\n\n<pre><code>// private variables\n# You don't need the comment above...it's not a functional comment\nprivate $_host;\nprivate $_database;\nprivate $_username;\nprivate $_password;\nprivate $_mysqli; \n\n// public functions\n# Again, not a good comment. \npublic function __construct(){\n $credentials = CredentialsManager::GetCredentials();\n $this-&gt;_host = $credentials['host'];\n $this-&gt;_database = $credentials['database'];\n $this-&gt;_username = $credentials['user'];\n $this-&gt;_password = $credentials['pass']; \n if (!$this-&gt;openConnection())\n echo \"Connection failed.\";\n}\n\n/**\n * How come there's no comment here? Add a function description here\n * \n * @return true or false if....\n */\npublic function RecordLog($log){\n if (!( $stmt = $this-&gt;_mysqli-&gt;prepare(\"INSERT INTO logz (log) VALUES (?)\") )) {\n echo \"Prepare failed: (\" . $this-&gt;_mysqli-&gt;errno . \") \" . $this-&gt;_mysqli-&gt;error;\n }\n\n if (! $stmt-&gt;bind_param(\"s\", $log)){\n echo \"Binding failed: (\". $stmt-&gt;errno .\") \" . $stmt-&gt;error;\n }\n\n if (! $stmt-&gt;execute() )\n echo \"Execute failed: \" . $stmt-&gt;error;\n }\n\n if ($stmt-&gt;affected_rows &gt; 0)\n return true;\n else\n return false;\n}\n\n\n// private functions\n# Comment above not needed\n/**\n * Let's make a useful descriptive comment here\n * \n * @return false if mysqli fails, true if connection is successful \n */ \nprivate function openConnection(){\n $this-&gt;_mysqli = new mysqli($this-&gt;_host, $this-&gt;_username, $this-&gt;_password, $this-&gt;_database);\n if ($this-&gt;_mysqli-&gt;connect_errno) {\n echo \"Failed to connect to MySQL: \" . $this-&gt;_mysqli-&gt;connect_error;\n return false;\n } \n\n return true;\n}\n</code></pre>\n\n<p>}</p></li>\n</ul>\n\n<p>Code looks good to me otherwise. Wait until others weigh in though. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T16:20:54.037", "Id": "17848", "ParentId": "17842", "Score": "2" } }, { "body": "<p>The first suggestion I would like to make is for you to become familiar with Inversion of Control (IoC) and Dependency Injection (DI). These two principles state that dependencies should not be hardcoded into your classes, but should be \"injected\" into them. This ensures that your class does not become dependent upon a single entity and can thus be extended. This is most commonly combined with type hinting.</p>\n\n<p>Type hinting ensures that a parameter is of the proper type, otherwise PHP will terminate execution of the script with an error. You can use the class you are expecting, or you can instead use a parent class or interface so that any similar class can be used, thus making it more extensible. I will demonstrate using the former as I don't know if there is a parent class or interface to use.</p>\n\n<pre><code>public function __construct( CredentialsManager $credentials ) {\n //etc...\n}\n\n//usage\n$log = new Logger( CredentialsManager::GetCredentials() );\n</code></pre>\n\n<p>You should also become aware of the Arrow Anti-Pattern. Through it you learn that unnecessarily indented code is bad. To illustrate this they usually show code that comes to peaks to form an arrow. The easiest way to refactor your code to avoid this anti-pattern is to return early. For example, if we reverse your first if statement in your <code>RecordLog()</code> method we can return early thus making the else statement unnecessary and removing an entire level of indentation from that method.</p>\n\n<pre><code>if( ! $this-&gt;openConnection() ) {\n return FALSE;\n}\n\n//etc...\n</code></pre>\n\n<p>Speaking of that else statement. PHP inherently requires braces, otherwise you would not be forced to add them after your statements reached more than one line. Adding them helps ensure no mistakes are made and keeps your code consistent. I would strongly recommend adding braces, even if you think they are unnecessary.</p>\n\n<pre><code>else {\n return FALSE;\n}\n</code></pre>\n\n<p>Always avoid assigning variables in statements. There are quite a few reasons for this:</p>\n\n<ul>\n<li>They are extremely difficult to debug. I actually missed this the first time through and thought you were using globals.</li>\n<li>They decrease legibility. Usually they increase line length and make statements more complex.</li>\n<li>There is usually no way for the reader, or your IDE, to determine if this was done accidentally. Therefore it is fairly easy to accidentally assign a value to a variable when you actually meant to compare it.</li>\n</ul>\n\n<p>There are exceptions to this rule, such as when setting up an iterator, but typically this should be avoided.</p>\n\n<pre><code>//common\nfor( $i = 0; $i &lt; $count; $i++ ) {\n//not as common, but fine\nwhile( ( $buffer = fgets( $handle, 4096 ) ) !== false ) {\n//as it should be\n$stmt = $this-&gt;_mysqli-&gt;prepare( 'INSERT INTO logz (log) VALUES (?)' );\nif( ! $stmt ) {\n</code></pre>\n\n<p>When you want a boolean return value that reflects a boolean state of what you are comparing, you can simply return the comparison and skip the unnecessary if/else structure.</p>\n\n<pre><code>return $stmt-&gt;affected_rows &gt; 0;\n</code></pre>\n\n<p>Your <code>RecordLog()</code> method violates the Single Responsibility Principle. This principle states that your methods should do one thing and delegate everything else. Instead you have this method doing everything. A better way to rewrite this is to call the logger whenever an error is encountered and pass that error to it. Instead you are calling the logger to perform the functionality that might produce errors in order to catch them. This is backwards.</p>\n\n<pre><code>if( ! $this-&gt;performAction() ) {\n $this-&gt;RecordLog( $error );\n}\n</code></pre>\n\n<p>Expanding upon this concept, and those mentioned previously, our classes should be equally singular. It may not be as obvious, but your logger should really only be concerned with logging the errors, not with the how of it. If you instead inject the database into this class, then that database can change without needing to modify the logger. So you should be able to go from using a MySQLi database to PDO or any other database without needing to modify this class. Though this is more advanced and I wouldn't suggest trying to tackle this until you are more comfortable with the rest.</p>\n\n<pre><code>$log = new Logger( $mysqli );\n$log = new Logger( $pdo );\n</code></pre>\n\n<p>The way you are currently connecting to your database restarts the connection every time <code>RecordLog()</code> is called. This is bad. You only need one connection per instance of the class. Creating it in the constructor ensures this. In fact, since you are not reusing any of those connection properties, you could probably get away with <code>openConnection()</code> BEING the constructor. If you just directly apply the credentials then declaring them as properties will become unnecesary.</p>\n\n<pre><code>$this-&gt;_mysqli = new mysqli(\n $credientials[ 'host' ],\n $credientials[ 'user' ],\n $credientials[ 'pass' ],\n $credientials[ 'database' ]\n);\n</code></pre>\n\n<p>If you take my advice about that <code>RecordLog()</code> method, then you can \"log\" the connection error from the constructor as well, thus making your code more uniform.</p>\n\n<pre><code>if( $this-&gt;_mysqli-&gt;connect_errno ) {\n $this-&gt;RecordLog(\n \"Failed to connect to MySQL: \"\n . $this-&gt;_mysqli-&gt;connect_error\n );\n}\n</code></pre>\n\n<p>So, something you should begin to notice from all of these suggestions is that your class now doesn't do much. You have a constructor and a logger. The constructor is a wrapper for the MySQLi class' constructor and as such can be abstracted out. This leaves just the logger method, and if we look at what this is doing, then we can also determine that this is unnecessary. Assuming you are planning on modifying this functionality to do more than just echo the error, then that leaves just the one method. This is not enough to justify a class. A function yes, but not a class. I would say forgo the class and just use PHP's MySQLi class directly. Extending, or in this case, pseudo extending, a class is unnecessary unless you are planning on doing something DRASTIC with that extension. Just creating a connection is not enough. However, it is a good start to trying to understand OOP concepts.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T21:53:53.053", "Id": "28438", "Score": "0", "body": "Excellent walk through of the code. I learned something too :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T07:22:56.240", "Id": "28452", "Score": "0", "body": "You gave me quite a lot to study on, but thank you for that!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T13:41:41.003", "Id": "28466", "Score": "0", "body": "`otherwise PHP will terminate execution` - that's not my experience, it will emit a notice though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T14:07:11.517", "Id": "28467", "Score": "0", "body": "@Jack: Then you probably don't have your error reporting turned on high enough. Though that shouldn't make a difference. Directly from the PHP documentation [\"Failing to satisfy the type hint results in a catchable fatal error.\"](http://php.net/manual/en/language.oop5.typehinting.php)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T16:56:30.827", "Id": "17851", "ParentId": "17842", "Score": "5" } } ]
{ "AcceptedAnswerId": "17851", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T07:58:26.350", "Id": "17842", "Score": "3", "Tags": [ "php", "object-oriented", "mysqli", "logging" ], "Title": "Logger class for logging connections" }
17842
<p>I'd like to know whether having different variables for the src (source) and dst (destination) of an OpenCV function will have an effect on the processing time. I have two functions below that does the same thing.</p> <pre><code>public static Mat getY(Mat m){ Mat mMattemp = new Mat(); Imgproc.cvtColor(m,mMattemp,Imgproc.COLOR_YUV420sp2RGB); Imgproc.cvtColor(mMattemp,mMattemp, Imgproc.COLOR_RGB2HSV); Core.inRange(mMattemp, new Scalar(20, 100, 100), new Scalar(30, 255, 255), mMattemp); return mMattemp; } </code></pre> <p>VERSUS</p> <pre><code>public static Mat getY(Mat m){ Mat mMattemp_rgb = new Mat(); Mat mMattemp_hsv = new Mat(); Mat mMattemp_ir = new Mat(); Imgproc.cvtColor(m,mMattemp_rgb,Imgproc.COLOR_YUV420sp2RGB); Imgproc.cvtColor(mMattemp_rgb,mMattemp_hsv, Imgproc.COLOR_RGB2HSV); Core.inRange(mMattemp_hsv, new Scalar(20, 100, 100), new Scalar(30, 255, 255), mMattemp_ir); return mMattemp_ir; } </code></pre> <p>Which of the two is considered best-practice? What is the advantage of one over the other?</p>
[]
[ { "body": "<p>Just looking over the two functions, I would probably say the first function is a better practice. It's shorter (meaning it's more maintainable), it uses fewer variables (which can cause less confusion), and does the same thing as the second function. Overall the advantage is that the first function is just shorter.</p>\n\n<p>In terms of speed/efficiency (if I had to guess), it looks like the first function would also be a bit faster as well (though not by very much at all). To know for sure which one is faster, test the function calls with OpenCV's methods <code>double getTickCount()</code> and <code>double getTickFrequency()</code>.</p>\n\n<p><code>getTickCount</code> gives you the <strong>number of clock cycles</strong> after a certain event, e.g., after machine is switched on. </p>\n\n<pre><code>A = getTickCount() // number of clock cycles from beginning (for example, 100)\ngetY(image) // do whatever process you want\nB = getTickCount() // number of clock cycles from beginning (for example, 150)\n\nC = B - A // number of clock cycles for processing (150-100 = 50)\n</code></pre>\n\n<p>Now you want to know how many seconds are these clock cycles. For that, you want to know how many seconds a single clock takes, i.e. <code>clock_time_period</code>. If you find that, simply multiply by 50 to get total time taken.</p>\n\n<p>For that, OpenCV gives second function, <code>getTickFrequency()</code>. It gives you <strong>frequency</strong>, i.e. <strong>how many clock cycles per second</strong>. You take its reciprocal to get time period of clock.</p>\n\n<pre><code>time_period = 1/frequency.\n</code></pre>\n\n<p>Now you have <code>time_period</code> of one clock cycle, multiply it with 50 to get total time taken in seconds.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T04:37:24.933", "Id": "40599", "ParentId": "17846", "Score": "7" } }, { "body": "<p>You can try to separate the two scalars objects in an pre-created shared instance in order to use a unique space on memory and only one execution of the Scalar's constructor. Like this:</p>\n\n<pre><code>private static firstScalar = new Scalar(20, 100, 100);\nprivate static secondScalar = new Scalar(30, 255, 255);\n\npublic static Mat getY(Mat m){\n Mat mMattemp = new Mat();\n Imgproc.cvtColor(m,mMattemp,Imgproc.COLOR_YUV420sp2RGB);\n Imgproc.cvtColor(mMattemp,mMattemp, Imgproc.COLOR_RGB2HSV);\n Core.inRange(mMattemp, firstScalar, secondScalar, mMattemp);\n return mMattemp;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-20T18:15:45.733", "Id": "74313", "ParentId": "17846", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-23T15:32:02.840", "Id": "17846", "Score": "10", "Tags": [ "java", "performance", "android", "opencv" ], "Title": "OpenCV Mat processing time" }
17846
<p><strong>Preamble</strong></p> <p>I am trying to learn JavaScript by writing code and looking up documentation, one problem at a time. I am already familiar with several "dynamic" languages, so I'm hoping to be productive quickly. This may not be the perfect way to learn the language, but I don't have the time to pick up a book right now.</p> <p>The following code works, but feels much more like clumsy Python than proper JavaScript. I commented the code as much as I can, so understanding it shouldn't be very difficult.</p> <p>Can you please show me how to do this in a "better" JS way?</p> <p><sub>Note that I run this outside of the browser using Node.js if that makes any difference</sub></p> <p><strong>Exercise</strong></p> <p><em>(Adapted from <a href="http://www.cs.sfu.ca/SeminarsAndEvents/ACM/120922/probC.pdf" rel="nofollow">Problem C of the first qualifier of the ACM Programming Contest of 2012/2013</a>).</em></p> <p>Let's consider a set of Arrays (A1, A2, A3, ... ,An) of variable sizes. All the elements in these arrays are integers. All the arrays are sorted in an ascending order.</p> <p>A sandwich is a set of indices (i1, i2, i3, ..., in) such as:</p> <p><code>A1[i1] &lt;= A2[i2] &lt;= A3[i3] &lt;= .. &lt;= An[in]</code> where <code>&lt;=</code> is the inequality sign for "lesser than or equal"</p> <p>For example, consider the following arrays:</p> <pre><code>A1 = [1, 5, 7, 10] A2 = [2, 6, 6, 8, 12] A3 = [4, 5, 9] </code></pre> <p>Here are some examples of valid sandwiches of the above set:</p> <ul> <li><code>(0, 0, 0)</code> Because 1 &lt;= 2 &lt;= 4 </li> <li><code>(1, 3, 2)</code> Because 5 &lt;= 8 &lt;= 9</li> </ul> <p>Given a set of arrays given as input, write a program that will calculate the number of valid sandwiches.</p> <p>You are free to format your input in any way you want, and use any language you want. If your language of choice has a builtin function that does this (or something close enough), avoid using it.</p> <p><strong>Code</strong></p> <pre><code>/* * A is an array of ints. * * Returns true if the input array is sorted in an ascending order. * */ function sorted_ascend(A) { for (var i=0; i&lt;A.length-1; ++i) { if (A[i] &gt; A[i+1]) { return false; } } return true; } /* * A is a set of arrays * ind is a list of indices * * This function will return true if ind is a sandwich to the set A * It does so by verifying that the following list is sorted: * * # List comprehension in a Python-fashion * [ A[i][ind[i]] for i in range(0, len(A)) ] * */ function is_sandwich (A, ind) { if (ind.length !== A.length) { return false; } var l = []; for (var i=0; i&lt;ind.length; ++i){ l.push(A[i][ind[i]]); } return sorted_ascend(l); } /* * face is an object * times is an integer * * repeat ``face'' on an array, ``times'' times * e.g., array.repeat_push("hello", 3) pushes "hello" 3 times. * * I use this function to initialize an array with a 0 repeated avariable number of times. * Is there a better way to do this? * */ function repeat_face (face, times) { l = []; for (var i=0; i&lt;times; ++i) { l.push(face); } return l; } /* * ind is an array of indices * ref is array holding the max values for each cell * * The function returns true if each element of ind is lesser than its equivalent in ref * It returns false otherwise */ function valid_ind(ind, ref) { if (ind === undefined || ind.length !== ref.length) { return false; } for (var i=0; i&lt;ref.length; ++i) { if (ind[i] &gt;= ref[i]) { return false; } } return true; } /* * ind is an array holding the previous value. * ref is a reference array, holding the max value for each cell. * * Starting with the rightmost cell, increment the value of ind until reaching the maximum * defined in ref. Once the maximum is reached, reset to 0 and increment the cell on the left. * * Do this recursively until all the cells reach their maximum. * Then return undefined, to mark the end of the generation process. * */ function incr_ind(ind, ref) { carry = 1; for (var i=ref.length-1; i&gt;=0; --i) { ind[i] += carry; carry =0; if (ind[i] &gt;= ref[i]) { ind[i] = 0; carry = 1; } } return (carry === 0) ? ind : undefined; } /* * A is a set of arrays * * Generate the valid lists of indices lexicographically * i.e., * {{0, 0, ..., 0}, {0, 0, ..., 1}, ..., {0, 0, ..., |An|}, * {0, 0, ..., 1, 0}, {0, 0, ..., 1, 1}, ..., {|A0|, |A1|, ..., |An|}} * * */ function all_indices(A) { // replace each array in A by its length // this is used to control the max value of each cell // in the indices array. lengths_set = A.map(function (x) { return x.length;}); // initial indice array is [0, 0, 0, ..., 0] ind = repeat_face(0, A.length); // this array will hold all the valid indices. indices = []; // as long as the ind list is valid, append it to indices and increment. while (valid_ind(ind, lengths_set)) { indices.push(ind.slice()); ind = incr_ind(ind, lengths_set); } return indices; } /* * array_set is an array containing all the input arrays. * * Bruteforcing: Generate all the possible indices then filtering according * to the is_sandwich() test. */ function sandwiches(array_set) { return all_indices(array_set).filter(function(x) { return is_sandwich(this, x); }, array_set); } // main function (function () { A1 = [1, 5, 7, 10]; A2 = [2, 6, 6, 8, 12]; A3 = [4, 5, 9]; S = sandwiches([A1, A2, A3]); console.log(S); console.log(S.length); })(); </code></pre> <p>And here's the output I get:</p> <pre><code>[ [ 0, 0, 0 ], [ 0, 0, 1 ], [ 0, 0, 2 ], [ 0, 1, 2 ], [ 0, 2, 2 ], [ 0, 3, 2 ], [ 1, 1, 2 ], [ 1, 2, 2 ], [ 1, 3, 2 ], [ 2, 3, 2 ] ] 10 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T04:14:29.183", "Id": "28445", "Score": "2", "body": "Haven't gone over your code in detail, but I've noticed quite a few implied globals in your functions; i.e. variables you haven't declared with a `var` keyword, like `l` in `repeat_face`. Without the `var` declaration, `l` will be defined in the global scope, which could bite you later." } ]
[ { "body": "<p>Probably the biggest problem is that you forget <code>var</code> keywords every now and then. In JavaScript, these are <strong>required</strong> or the variable will implicitly be global. Yes, your program will execute, but you'll end up with a bunch of global variables you didn't expect. Bad.</p>\n\n<p>Since you're a Python person it's probably expected that you'll omit a few <code>var</code>s every now and then. To prevent it, run your scripts in \"strict mode\": put the <em>string</em> <code>\"use strict\";</code> (with quotes) at the top of your program or any functions you want it to apply to. In strict mode, omitting a <code>var</code> keyword is an error.</p>\n\n<p>I went through and I think I caught all the missing <code>var</code>s.</p>\n\n<pre><code>function repeat_face (face, times) {\n var l = [];\n\nfunction incr_ind(ind, ref) {\n var carry = 1;\n\nfunction all_indices(A) {\n // replace each array in A by its length\n // this is used to control the max value of each cell \n // in the indices array.\n var lengths_set = A.map(function (x) {\n return x.length;});\n\n // initial indice array is [0, 0, 0, ..., 0]\n var ind = repeat_face(0, A.length);\n\n // this array will hold all the valid indices.\n var indices = [];\n\n// main function\n(function () {\n\n var A1 = [1, 5, 7, 10], // Note the comma: In JS, you can merge consecutive var statements like I've done here. It's generally considered good style.\n A2 = [2, 6, 6, 8, 12],\n A3 = [4, 5, 9],\n S = sandwiches([A1, A2, A3]);\n</code></pre>\n\n<p>Other minor things:</p>\n\n<p>In JavaScript we usually use camelCase instead of underscored_names, however there is a significant minority that use underscores. Since you're from Python, where underscores is the preferred style, feel free to continue that. Just know that when you see other people's code, camelCase is quite a bit more popular.</p>\n\n<p>A very common pattern in JavaScript is the <a href=\"http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth\" rel=\"nofollow noreferrer\">module pattern</a>. Essentially what this involves is wrapping all your code in an <a href=\"https://stackoverflow.com/questions/8228281/what-is-this-construct-in-javascript\">immediately-invoked function expression</a>, and returning what you want to \"export\" to calling code. This helps cut down on globals. So your code would look like:</p>\n\n<pre><code>// File: utils.js\nwindow.utils = (function () {\n // Define repeat_face, incr_ind, all_indices, etc, everything except your main function.\n\n return {\n repeat_face: repeat_face,\n incr_ind: incr_ind,\n // etc\n };\n})();\n\n// File: main.js\n(function (utils) {\n // Do your main logic\n})(utils);\n</code></pre>\n\n<p>A similar form of this is the AMD (Asynchronous Module Definition) pattern which has become quite popular recently. You might want to learn about it, as it has a bunch of advantages over the module pattern (which it basically is an improved version of). See for example <a href=\"http://requirejs.org/docs/whyamd.html\" rel=\"nofollow noreferrer\">http://requirejs.org/docs/whyamd.html</a>. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T16:57:38.290", "Id": "28482", "Score": "1", "body": "I would add, that you (@rahmu) could also look into [CoffeeScript](http://coffeescript.org). It compiles to JavaScript, but is very much inspired by Python (and Ruby and even Haskell) in terms of syntax. Personally speaking, I love it, but you do still need to know a fair amount of JavaScript since that's what it actually is. But it's much nicer to write." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T19:23:05.883", "Id": "28491", "Score": "0", "body": "+1 to CoffeeScript. It's indentation based like Python so it should feel very familiar to you @rahmu." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T05:09:57.293", "Id": "17862", "ParentId": "17858", "Score": "3" } } ]
{ "AcceptedAnswerId": "17862", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T00:03:30.577", "Id": "17858", "Score": "2", "Tags": [ "javascript", "algorithm", "programming-challenge", "combinatorics" ], "Title": "Counting the ways to pick increasing sequences from sorted arrays" }
17858
<p>Title: Identifying equivalent lists</p> <p>I am using lists as keys, and therefore want to identify equivalent ones.</p> <p>For example,</p> <pre><code>[0, 2, 2, 1, 1, 2] [4, 0, 0, 1, 1, 0] </code></pre> <p>are 'equivalent' in my book. I 'equivalify' the list by checking the list value with the highest count, and set that to 0, then the next highest count to 1, and so on and so forth. It's done with this code below, which does the job properly but is fairly slow - and I am wondering if there is a way of doing the same job yet I haven't seen it yet.</p> <pre><code>for key in preliminary_key_list: key = list(key) # convert from immutable tuple to mutable list i = 0 translation = {} counts = [[j, key.count(j)] for j in set(key)] counts_right = [j[1] for j in counts] for count in set(key): translation[counts[counts_right.index(max(counts_right))][0]] = i counts_right[counts_right.index(max(counts_right))] = 0 i += 1 for i in range(len(key)): key[i] = translation[key[i]] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T14:51:48.873", "Id": "28469", "Score": "0", "body": "Could it be the case that there are multiple values with the same count? E.g. `[0, 1, 1, 2, 2, 3, 3, 3]`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T07:21:13.493", "Id": "28509", "Score": "0", "body": "@DSM Yes it happens. However, to optimise that would be a smaller optimisation than what I'm currently looking for, which is 'how to speed up all key translations'. I will come back to this one after I've optimised the main process" } ]
[ { "body": "<p>You can do things slightly differently - instead of manually sorting, you can use the standard library sort() function. Below I've modified things slightly for convenience, but using it, <code>timeit</code> originally gave 16.3 seconds for 10^6 iterations and now gives 10.8 seconds.</p>\n\n<pre><code>def equivalify( preliminary_key_list ):\n ret = []\n for key in preliminary_key_list:\n key = list(key) # convert from immutable tuple to mutable list\n\n translation = {}\n counts = [[key.count(j), j] for j in set(key)]\n counts.sort( reverse = True )\n for idx, ( cnt, val ) in enumerate( counts ):\n translation[ val ] = idx\n for i,k in enumerate( key ):\n key[i] = translation[ k ]\n ret += [key]\n return ret\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T08:38:59.313", "Id": "17867", "ParentId": "17859", "Score": "0" } }, { "body": "<pre><code>for key in preliminary_key_list:\n key = list(key) # convert from immutable tuple to mutable list\n</code></pre>\n\n<p>You don't need to do this. Rather then creating a modifiable list, just use the tuple and construct a new tuple at the end</p>\n\n<pre><code> i = 0\n translation = {}\n counts = [[j, key.count(j)] for j in set(key)]\n</code></pre>\n\n<p>This should be a list of tuples, not a list of lists. </p>\n\n<pre><code> counts_right = [j[1] for j in counts]\n\n for count in set(key): \n</code></pre>\n\n<p>Use <code>for i, count in enumerate(set(key)):</code> to avoid having to manage i yourself.</p>\n\n<p>You use <code>set(key)</code> twice, which will force python to do work twice. Also, there is no guarantee you'll get the same order both times. </p>\n\n<pre><code> translation[counts[counts_right.index(max(counts_right))][0]] = i\n counts_right[counts_right.index(max(counts_right))] = 0\n</code></pre>\n\n<p>These lines are really expensive. <code>max</code> will scan the whole list checking for the highest value. <code>.index</code> will then rescan the list to find the index for the value. \nThen you do the whole thing over again on the next line!</p>\n\n<p>You'd do far better as @GlenRogers suggests to sort by the counts. </p>\n\n<pre><code> i += 1\n\n for i in range(len(key)):\n key[i] = translation[key[i]]\n</code></pre>\n\n<p>Here using a comprehension would be better (I think):</p>\n\n<pre><code> key = tuple(translation[item] for item in key)\n</code></pre>\n\n<p>Here is how I'd write the code:</p>\n\n<pre><code>ret = []\nfor key in preliminary_key_list:\n counts = sorted(set(key), key = lambda k: -key.count(k) )\n translation = { val: idx for idx, val in enumerate(counts) }\n ret.append([translation[k] for k in key])\nreturn ret\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T11:31:47.447", "Id": "28519", "Score": "0", "body": "It's certainly a lot faster and it's concise as well. Makes me wonder how you get to that level where you know how to do it. Your explanation was good too. Thanks Winston" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T12:24:54.287", "Id": "17880", "ParentId": "17859", "Score": "3" } } ]
{ "AcceptedAnswerId": "17880", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T02:28:51.793", "Id": "17859", "Score": "2", "Tags": [ "python" ], "Title": "Identifying equivalent lists" }
17859
<p>The Model is simple: a <code>Player</code> class with three attributes: <code>first_name</code>, <code>last_name</code>, and <code>team_id</code>.</p> <p>I'm just trying to get a handle on TDD for what will expand into a much more robust API. Here is my first stab at the integration/controller specs for REST actions on the API.</p> <p>I haven't seen a lot of concrete examples of RSpec and API tests, so feedback is very welcome.</p> <p>I'm using Rabl in my views for rendering the JSON Responses.</p> <pre><code>describe Api::V1::PlayersController do render_views before do @player1 = FactoryGirl.create(:player, first_name: "Joe", last_name: "Smith", team_id: 1) @player2 = FactoryGirl.create(:player, first_name: "Bob", last_name: "Jones", team_id: 2) @player3 = FactoryGirl.create(:player, first_name: "Peter", last_name: "Wilson", team_id: 3) end describe "#index" do before do get :index, :format =&gt; :json end it "should retrieve status code of 200" do response.response_code.should == 200 end it "should retrieve license header" do response.header["X-LS-License"].should == "All Rights Reserved" end it "should retrieve application name header" do response.header["X-LS-Application"].should == "league-server" end it "should retrieve records-returned header" do response.header["X-LS-Records-Returned"].should be_present end it "should retrieve a content-type of json" do response.header['Content-Type'].should include 'application/json' end it "should retrieve list of players" do players = Player.all players.count.should == 3 response.body.should include(@player1.id.to_s) response.body.should include(@player2.id.to_s) response.body.should include(@player3.id.to_s) response.body.should include('Joe Smith') response.body.should include('Bob Jones') response.body.should include('Peter Wilson') end end describe "#show" do before do get :show, id: @player1.id, :format =&gt; :json end it "should retrieve status code of 200" do response.response_code.should == 200 end it "should retrieve application name header" do response.header["X-LS-Application"].should == "league-server" end it "should retrieve license header" do response.header["X-LS-License"].should == "All Rights Reserved" end it "should retrieve records-returned header" do response.header["X-LS-Records-Returned"].should == "1" end it "should retrieve a content-type of json" do response.header['Content-Type'].should include 'application/json' end it "should retrieve a single player" do player = Player.where id: @player1.id player.count.should == 1 response.body.should include(@player1.id.to_s) response.body.should include('Joe Smith') end end describe "#create" do before do request_payload = { player: { first_name: "Buck", last_name: "Carradine", team_id: "1", junk: "trunk" } } post :create, request_payload end it "should retrieve status code of 200" do response.response_code.should == 200 end it "should retrieve application name header" do response.header["X-LS-Application"].should == "league-server" end it "should retrieve license header" do response.header["X-LS-License"].should == "All Rights Reserved" end it "should retrieve records-returned header" do response.header["X-LS-Records-Returned"].should == "1" end it "should retrieve a content-type of json" do response.header['Content-Type'].should include 'application/json' end it "should retrieve a single player" do response.body.should include('Buck Carradine') end it "should not add extraneous attributes" do response.body.should_not include('junk') end end describe "#update" do before do request_payload = { player: { first_name: "Buck", last_name: "Carradine", team_id: "1" } } put :update, { id: @player1.id }.merge(request_payload) end it "should retrieve status code of 200" do response.response_code.should == 200 end it "should retrieve application name header" do response.header["X-LS-Application"].should == "league-server" end it "should retrieve license header" do response.header["X-LS-License"].should == "All Rights Reserved" end it "should retrieve records-returned header" do response.header["X-LS-Records-Returned"].should == "1" end it "should retrieve a content-type of json" do response.header['Content-Type'].should include 'application/json' end it "should retrieve a single player" do response.body.should include('Buck') response.body.should_not include('Joe') end end describe "#delete" do before do delete :destroy, id: @player1.id end it "should retrieve status code of 200" do response.response_code.should == 200 end it "should retrieve application name header" do response.header["X-LS-Application"].should == "league-server" end it "should retrieve license header" do response.header["X-LS-License"].should == "All Rights Reserved" end it "should retrieve records-returned header" do response.header["X-LS-Records-Returned"].should == "0" end it "should retrieve a content-type of json" do response.header['Content-Type'].should include 'application/json' end it "should retrieve a single player" do response.body.should include('Player deleted') end end end </code></pre>
[]
[ { "body": "<p>This looks pretty okay to me. I don't see why you have multiple header data tests though, I would assume they are all generated through the same piece of code, so you should either remove redundant tests to DRY up your specs, or if you are not using the same bit of code to generate the headers refactor that instead. </p>\n\n<p>Regarding your initial question, I do not feel that API testing is any different that any other request and controller testing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-09T23:13:43.457", "Id": "18428", "ParentId": "17860", "Score": "2" } }, { "body": "<p>You might consider replacing this:</p>\n\n<pre><code>it \"should retrieve status code of 200\" do\n response.response_code.should == 200\nend\n</code></pre>\n\n<p>with</p>\n\n<pre><code>it { response.response_code.should == 200 }\n</code></pre>\n\n<p>I find that very simple code checks are better done with the second form to eliminate duplication when you're reading the test.</p>\n\n<p>It's helpful to review this occasionally. Something good is added frequently.</p>\n\n<p>Quote from <a href=\"https://github.com/rspec/rspec-expectations\" rel=\"nofollow\">https://github.com/rspec/rspec-expectations</a></p>\n\n<blockquote>\n <p>One-liners</p>\n \n <p>The one-liner syntax supported by rspec-core uses should even when\n config.syntax = :expect. It reads better than the alternative, and\n does not require a global monkey patch:</p>\n \n <p>describe User do it { should validate_presence_of :email } end</p>\n</blockquote>\n\n<p>This is another helpful reference: <a href=\"https://www.relishapp.com/rspec/rspec-rails/v/2-13/docs/controller-specs\" rel=\"nofollow\">https://www.relishapp.com/rspec/rspec-rails/v/2-13/docs/controller-specs</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-24T06:34:01.793", "Id": "35584", "Score": "2", "body": "You could also make `response` the subject, and thus write `its(:response_code) { should == 200 }`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-24T04:57:16.663", "Id": "23072", "ParentId": "17860", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T02:43:09.963", "Id": "17860", "Score": "3", "Tags": [ "ruby", "ruby-on-rails", "api", "rspec" ], "Title": "RSpec integration tests for a simple Rails API" }
17860
<p>I know there are other Python wiki API classes out there. I'm writing this one because I don't need all the bells and whistles, no edits, no talks, etc. I just need to be able to search for titles and get the wiki markup.</p> <p>Any advice or suggestions or comments or a review or anything really.</p> <pre><code># -*- coding: utf-8 -*- import urllib2 import re import time import sys from urllib import quote_plus, _is_unicode try: import json except: import simplejson as json def enum(*sequential, **named): enums = dict(zip(sequential, range(len(sequential))), **named) return type('Enum', (), enums) class Wiki: def __init__(self, api=None): if api == None: self.api = "http://en.wikipedia.org/w/api.php" else: self.api = api return """A HTTP Request""" def downloadFile(self, URL=None): """ URL - The URL to fetch """ opener = urllib2.build_opener() opener.addheaders = [('User-agent', 'Mozilla/5.0')] responce = opener.open(URL) data = responce.read() responce.close() return data.decode(encoding='UTF-8',errors='strict') """Search the wiki for titles""" def search(self, searchString): results = [] if (searchString != u""): encoded_searchString = searchString if isinstance(encoded_searchString, unicode): encoded_searchString = searchString.encode('utf-8') url = self.api + "?action=query&amp;list=search&amp;format=json&amp;srlimit=10&amp;srsearch=" + urllib2.quote(encoded_searchString) rawData = self.downloadFile(url) object = json.loads(rawData) if object: if 'query' in object: for item in object['query']['search']: wikiTitle = item['title'] if isinstance(wikiTitle, str): wikiTitle = wikiTitle.decode(encoding='UTF-8',errors='strict') results.append(wikiTitle) return results """Search for the top wiki title""" def searchTop(self, searchString): results = self.search(searchString) if len(results) &gt; 0: return results[0] else: return u"" """Get the raw markup for a title""" def getPage(self, title): # Do the best we can to get a valid wiki title wikiTitle = self.searchTop(title) if (wikiTitle != u""): encoded_title = wikiTitle if isinstance(encoded_title, unicode): encoded_title = title.encode('utf-8') url = self.api + "?action=query&amp;prop=revisions&amp;format=json&amp;rvprop=content&amp;rvlimit=1&amp;titles=" + urllib2.quote(encoded_title) rawData = self.downloadFile(url) object = json.loads(rawData) for k, v in object['query']['pages'].items(): if 'revisions' in v: return v['revisions'][0]['*'] return u"" </code></pre>
[]
[ { "body": "<p>An obvious one that jumps out at me is this:</p>\n\n<pre><code>class Wiki:\n def __init__(self, api=None):\n if api == None:\n self.api = \"http://en.wikipedia.org/w/api.php\"\n else:\n self.api = api\n return\n</code></pre>\n\n<p>Can be simplified to this:</p>\n\n<pre><code>class Wiki:\n def __init__(self, api=\"http://en.wikipedia.org/w/api.php\"):\n self.api = api\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T10:23:57.390", "Id": "17872", "ParentId": "17861", "Score": "3" } }, { "body": "<pre><code>class Wiki:\n def __init__(self, api=\"http://en.wikipedia.org/w/api.php\"):\n self.api = api\n return\n</code></pre>\n\n<p>This return does nothing</p>\n\n<pre><code> \"\"\"A HTTP Request\"\"\"\n def downloadFile(self, URL=None):\n</code></pre>\n\n<p>Python convention is to use <code>lowercase_with_underscores</code> for method names</p>\n\n<pre><code> \"\"\" \n URL - The URL to fetch\n \"\"\"\n opener = urllib2.build_opener()\n opener.addheaders = [('User-agent', 'Mozilla/5.0')]\n</code></pre>\n\n<p>Why are you pretending to be Mozilla?</p>\n\n<pre><code> responce = opener.open(URL)\n</code></pre>\n\n<p>Response is spelled wrong</p>\n\n<pre><code> data = responce.read()\n responce.close()\n return data.decode(encoding='UTF-8',errors='strict')\n</code></pre>\n\n<p>This whole function should probably be a free function, not a method.</p>\n\n<pre><code> \"\"\"Search the wiki for titles\"\"\"\n def search(self, searchString):\n</code></pre>\n\n<p>Parameters by convention should be named <code>lowercase_with_underscore</code> </p>\n\n<pre><code> results = []\n if (searchString != u\"\"):\n</code></pre>\n\n<p>No need for the <code>(</code> and <code>)</code>. Also you can just do: <code>if searchString:</code></p>\n\n<pre><code> encoded_searchString = searchString\n</code></pre>\n\n<p>Why?</p>\n\n<pre><code> if isinstance(encoded_searchString, unicode):\n encoded_searchString = searchString.encode('utf-8')\n url = self.api + \"?action=query&amp;list=search&amp;format=json&amp;srlimit=10&amp;srsearch=\" + urllib2.quote(encoded_searchString)\n rawData = self.downloadFile(url)\n object = json.loads(rawData)\n</code></pre>\n\n<p>I'd combine these two lines</p>\n\n<pre><code> if object:\n</code></pre>\n\n<p>In what circumstance will this be false? If that happens you should probably do something besides pretend that nothing happened.</p>\n\n<pre><code> if 'query' in object:\n for item in object['query']['search']:\n wikiTitle = item['title']\n if isinstance(wikiTitle, str):\n wikiTitle = wikiTitle.decode(encoding='UTF-8',errors='strict')\n results.append(wikiTitle)\n return results\n\n\n \"\"\"Search for the top wiki title\"\"\"\n def searchTop(self, searchString):\n results = self.search(searchString)\n if len(results) &gt; 0:\n return results[0]\n else:\n return u\"\"\n</code></pre>\n\n<p>Do you really want an empty string if your result wasn't found? You should probably throw an exception here. Returning an empty string will just make failures hard to trace.</p>\n\n<pre><code> \"\"\"Get the raw markup for a title\"\"\"\n def getPage(self, title):\n # Do the best we can to get a valid wiki title\n wikiTitle = self.searchTop(title)\n\n if (wikiTitle != u\"\"):\n encoded_title = wikiTitle\n if isinstance(encoded_title, unicode):\n encoded_title = title.encode('utf-8')\n url = self.api + \"?action=query&amp;prop=revisions&amp;format=json&amp;rvprop=content&amp;rvlimit=1&amp;titles=\" + urllib2.quote(encoded_title)\n rawData = self.downloadFile(url)\n object = json.loads(rawData)\n\n for k, v in object['query']['pages'].items():\n if 'revisions' in v:\n return v['revisions'][0]['*']\n return u\"\"\n</code></pre>\n\n<p>Don't default to stupid defaults. If you can't get the requested page throw an error with as much detail as possible, don't just throw me an empty string.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T13:43:49.513", "Id": "17961", "ParentId": "17861", "Score": "2" } } ]
{ "AcceptedAnswerId": "17961", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T04:15:46.467", "Id": "17861", "Score": "2", "Tags": [ "python", "beginner", "classes" ], "Title": "Wiki API getter" }
17861
<p>for now I'm using:</p> <pre><code>int connect(const String&amp; address, int port) { struct sockaddr_in servAddr; struct hostent* host; /* Structure containing host information */ /* open socket */ if((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) &lt; 0) return ERROR; //TODO: gethostbyname is obsolete. if((host = (struct hostent*) gethostbyname(address)) == 0) return ERROR; memset(&amp;servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = inet_addr(inet_ntoa(*(struct in_addr*)(host -&gt; h_addr_list[0]))); servAddr.sin_port = htons(port); if(::connect(handle, (struct sockaddr*) &amp;servAddr, sizeof(servAddr)) &lt; 0) return ERROR; return OK; } </code></pre> <p>this procedure but everytime I compile it I'm getting:</p> <p>socket.cpp:(.text+0x374): warning: gethostbyname is obsolescent, use getnameinfo() instead.</p> <p>getname info is still being confusing stuff for me. here is my try to implement it:</p> <pre><code>struct sockaddr_in servAddr; struct hostent *host; /* Structure containing host information */ /* open socket */ if ((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) &lt; 0) return ERROR; memset(&amp;servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = inet_addr(address.ptr()); servAddr.sin_port = htons(port); char servInfo[NI_MAXSERV]; if ( ( host = (hostent*) getnameinfo( (struct sockaddr *) &amp;servAddr ,sizeof (struct sockaddr) ,address.ptr(), address.size() ,servInfo, NI_MAXSERV ,NI_NUMERICHOST | NI_NUMERICSERV ) ) == 0) return ERROR; if (::connect(handle, (struct sockaddr *) &amp;servAddr, sizeof(servAddr)) &lt; 0) return ERROR; </code></pre> <p>-- yes <strong>this doesn't work</strong> :(</p> <p>Maybe I should use getaddrinfo instead? </p> <p><code>getaddrinfo(hostname, NULL, &amp;hints, &amp;res)</code> - can I use it alike gethostbyname? but where is host actually here? hints?</p> <p>Working recode based on answer:</p> <pre><code>int Socket::connect(const String&amp; address, int port) { struct sockaddr_in servAddr; /* open socket */ if((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) &lt; 0) return ERROR; //gethostbyname by getaddrinfo replacement addrinfo hints = {sizeof(addrinfo)}; hints.ai_flags = AI_ALL; hints.ai_family = PF_INET; hints.ai_protocol = 4; //IPPROTO_IPV4 addrinfo* pResult = NULL; int errcode = getaddrinfo(address, NULL, &amp;hints, &amp;pResult); if(errcode != 0) return ERROR; memset(&amp;servAddr, 0, sizeof(servAddr)); servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = *((uint32_t*) &amp; (((sockaddr_in*)pResult-&gt;ai_addr)-&gt;sin_addr)); servAddr.sin_port = htons(port); if(::connect(handle, (struct sockaddr*) &amp;servAddr, sizeof(servAddr)) &lt; 0) return ERROR; return OK; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T17:15:16.030", "Id": "28484", "Score": "0", "body": "Not a code review question. Code posted her is expected to be working, but needing improvements." } ]
[ { "body": "<p>This works for me:</p>\n\n<pre><code>int connect2(const CStringA&amp; address, int port) {\n struct sockaddr_in servAddr;\n /* open socket */\n SOCKET handle;\n if((handle = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) &lt; 0)\n return ERROR;\n //gethostbyname by getaddrinfo replacement\n ADDRINFO hints;\n ZeroMemory(&amp;hints, sizeof(hints));\n hints.ai_flags = AI_ALL;\n hints.ai_family = PF_INET;\n hints.ai_protocol = IPPROTO_IPV4;\n ADDRINFO* pResult = NULL;\n int errcode = getaddrinfo((LPCSTR)address, NULL, &amp;hints, &amp;pResult);\n if(errcode != 0)\n return ERROR;\n memset(&amp;servAddr, 0, sizeof(servAddr));\n servAddr.sin_family = AF_INET;\n servAddr.sin_addr.S_un.S_addr = *((ULONG*)&amp;(((sockaddr_in*)pResult-&gt;ai_addr)-&gt;sin_addr));\n servAddr.sin_port = htons(port);\n if(::connect(handle, (struct sockaddr*) &amp;servAddr, sizeof(servAddr)) &lt; 0)\n return ERROR;\n return OK;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T09:06:23.813", "Id": "28457", "Score": "0", "body": "Works now \\o/ w/o warnings. added recode to question, thank you." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T08:25:55.563", "Id": "17866", "ParentId": "17863", "Score": "3" } } ]
{ "AcceptedAnswerId": "17866", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T06:39:46.530", "Id": "17863", "Score": "1", "Tags": [ "c++" ], "Title": "Socket connect realization: gethostbyname or getnameinfo" }
17863
<p>I've written a BST implementation and would like a code review and any suggestions on how to make it better.</p> <pre><code>#include&lt;iostream.h&gt; #include&lt;conio.h&gt; #include&lt;stack&gt; #include&lt;queue&gt; #ifndef BINSTREE #define BINSTREE using namespace std; typedef int valuetype; /*struct Node{ valuetype data; Node* left; Node* right; }; */ class Node{ public: valuetype data; Node* left; Node* right; Node(); Node(valuetype); }; //OK class BST{ Node* findNodebyvalue(valuetype); Node* findparentforNode(valuetype); Node* findrightnode(Node*); void inorder(Node*); void postorder(Node*); void preorder(Node*); public: Node* root; Node* current; public: BST(); void insert(valuetype); void remove(valuetype); void traverse(); valuetype retrieve(); void custom_print(); }; //constructor1 Node::Node(){ left=right=NULL; } //constructor2 Node::Node(valuetype val){ data=val; left=right=NULL; } //constructor BST::BST(){ root=current=NULL; } //insert a node with value val in tree void BST::insert(valuetype val){ if(root==NULL) root = new Node(val); else{ Node* p =findNodebyvalue(val); if(p==0) { //cout&lt;&lt;"fine1"; Node* parent=root; if (p != root) parent = findparentforNode(val); if(val&gt;parent-&gt;data) parent-&gt;right=new Node(val); else parent-&gt;left=new Node(val); } //cout&lt;&lt;"fine2"; } } //remove the node if value is val void BST::remove(valuetype val){ Node* p = findNodebyvalue(val); if(p!=0){ //if both of child of node are null(leaf node) if(p-&gt;left==NULL&amp;&amp;p-&gt;right==NULL){ if(p!=root){ Node* parent= findparentforNode(val); if(val&lt;parent-&gt;data) parent-&gt;left=NULL; else parent-&gt;right=NULL; } else root=NULL; delete (p); } //if only left child is not null else if(p-&gt;left!=NULL&amp;&amp;p-&gt;right==NULL){ if(p!=root){ Node* parent=findparentforNode(val); if(val&lt;parent-&gt;data) parent-&gt;left=p-&gt;left; else parent-&gt;right=p-&gt;left; } else root=NULL; delete (p); } //if only right child is not null else if(p-&gt;left==NULL&amp;&amp;p-&gt;right!=NULL){ if(p!=root){ Node* parent=findparentforNode(val); if(val&lt;parent-&gt;data) parent-&gt;left=p-&gt;right; else parent-&gt;right=p-&gt;right; } else root=NULL; delete (p); } //if both child are not null else{ Node* righty=findrightnode(p-&gt;left); Node* parent=findparentforNode(righty-&gt;data); p-&gt;data=righty-&gt;data; if(parent!=p) parent-&gt;right=righty-&gt;left; else p-&gt;left=righty-&gt;left; } } } //fins node with a value key Node* BST::findNodebyvalue(valuetype key){ Node* p =root; while((p!=NULL)&amp;&amp;(p-&gt;data!=key)){ if(key&lt;p-&gt;data)p=p-&gt;left; else p=p-&gt;right; } return p; } //find parent of a node with value key Node* BST::findparentforNode(valuetype key){ Node* p =root; Node* q=0; while((p!=NULL)&amp;&amp;(p-&gt;data!=key)){ q=p; if(key&lt;p-&gt;data)p=p-&gt;left; else p=p-&gt;right; } return q; } //finds the most right of a node p(means immediate succesor of p in inorder representation) Node* BST::findrightnode(Node* p){ Node* righty=p; while(righty-&gt;right!=NULL) righty=righty-&gt;right; return righty; } //inorder void BST::inorder(Node* p){ if(p!=NULL){ inorder(p-&gt;left); cout&lt;&lt;p-&gt;data&lt;&lt;" "; inorder(p-&gt;right); } } //postorder void BST::preorder(Node* p){ if(p!=NULL){ cout&lt;&lt;p-&gt;data&lt;&lt;" "; preorder(p-&gt;left); preorder(p-&gt;right); } } //postorder void BST::postorder(Node* p){ if(p!=NULL){ postorder(p-&gt;left); postorder(p-&gt;right); cout&lt;&lt;p-&gt;data&lt;&lt;" "; } } void BST::traverse(){ cout&lt;&lt;"Preorder: "; preorder(root); cout&lt;&lt;endl&lt;&lt;"Inorder: "; inorder(root); cout&lt;&lt;endl&lt;&lt;"PostOrder: "; postorder(root); cout&lt;&lt;endl; } //to print tree hightwise i.e. all nodes at h1, then all nodes at h2, then at h3 void BST::custom_print(){ //Node* temp; if(root==NULL) return; queue&lt;Node*&gt; Q; Q.push(root); //Q.push(NULL); while(!Q.empty()){ current=Q.front(); cout&lt;&lt;current&lt;&lt;" "; Q.pop(); Q.push(current-&gt;left); Q.push(current-&gt;right); } } #endif int main() { BST tree; tree.insert(10); tree.insert(2); tree.insert(4); tree.insert(12); tree.insert(23); tree.traverse(); tree.custom_print(); getch(); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T07:35:43.823", "Id": "28453", "Score": "1", "body": "replace `void custom_print(){` with `void custom_print();` in your class declaration" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T10:15:05.950", "Id": "28461", "Score": "0", "body": "Fixed typo: It now compiles and runs (as expected)." } ]
[ { "body": "<p>This is an old deprecated header don't use it:</p>\n\n<pre><code>#include&lt;iostream.h&gt;\n\n// modern C++ standard headers have dropped the '.h' part\n// It is also more visually pleasing to add a space after include\n#include &lt;iostream&gt;\n</code></pre>\n\n<p>This is non standard (MS-DOS specific)</p>\n\n<pre><code>#include&lt;conio.h&gt;\n\n// You only use it to get the program to pause before exiting.\n// So you can use some more standard compliant code to do the same thing\n// See below for details (but just drop the header)\n</code></pre>\n\n<p>You seem to have header guards in a source file. Only add these to the header file (I assume this is because of pasting into website). Also they should surround everything in the file (include the #include).</p>\n\n<pre><code>#ifndef BINSTREE\n#define BINSTREE\n</code></pre>\n\n<p>Don't do this:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>It brings everything from standard into the global namespace. This is a problem especially if other people include your header file. The reason std is short so it is not a problem prefixing things with std:: .</p>\n\n<p>Delete all commented out code.</p>\n\n<pre><code>/*struct Node{\n valuetype data;\n Node* left;\n Node* right;\n};\n*/\n</code></pre>\n\n<p>It has no place in your code. If you want to remember old code then use version control software. There is lots of free stuff around. A very popular one nowadays is <code>git</code>. You can even host you repos for free on <code>github.com</code>.</p>\n\n<p>Not much point in using a class if everything is public. If you are just using it is a property bag (ie no methods and all the code is in BST) then you can use struct as an indication that this type is not that important.</p>\n\n<pre><code>class Node{\n public:\n valuetype data;\n Node* left;\n Node* right;\n Node();\n Node(valuetype);\n}; \n</code></pre>\n\n<p>Remove useless comments.</p>\n\n<pre><code>//OK\n</code></pre>\n\n<p>The <code>Node</code> class should probably be a private internal member of BST. Are <code>root</code> and <code>current</code> really public (i think you just have not tidied up your code). More visual clues about the layout would be nice. I indent members more that <code>public:</code> and <code>private:</code> to make sure the sections stand out. An extra empty line would not hurt either.</p>\n\n<pre><code>class BST{\n Node* findNodebyvalue(valuetype);\n Node* findparentforNode(valuetype);\n Node* findrightnode(Node*);\n void inorder(Node*);\n void postorder(Node*);\n void preorder(Node*);\n public:\n Node* root;\n Node* current;\n public:\n BST();\n void insert(valuetype);\n void remove(valuetype);\n void traverse();\n valuetype retrieve();\n void custom_print();\n};\n</code></pre>\n\n<p>Your class contain RAW pointers (ie not smart pointers). These are owned by the class. Thus you should use RAII to manage them. In this example you just leak memory. But if you had add destructors to clean up the memory then you would not have been following the rule of 3 which would have caused problems if you had made any copies.</p>\n\n<p>So you need to add the following methods to your class:</p>\n\n<pre><code>~BST(); // Clean up allocated memory.\nBST(BST const&amp; rhs); // Correctly make a deep copy.\nBST&amp; operator=(BST const&amp; rhs); // Correctly do an assignment.\n // Look up copy and swap idiom.\n</code></pre>\n\n<p>Use initializer list in the constructor (and comments like that are usless I can see they are constructors). Comments should be used to explain the how (or why) code is doing what it does. The code should itself be self documenting (ie use good variable and method names that explain what is happening).</p>\n\n<pre><code>Node::Node()\n : left(NULL)\n , right(NULL)\n{}\n\nNode::Node(valuetype val)\n : left(NULL)\n , right(NULL)\n , data(val)\n{}\n\nBST::BST()\n : root(NULL)\n , current(NULL)\n{}\n</code></pre>\n\n<p>Not a very useful comment. </p>\n\n<pre><code>//insert a node with value val in tree\n</code></pre>\n\n<p>I should hope it inserts a value it is after called insert(). More useful would be notes of any pre/post conditions etc.</p>\n\n<pre><code>void BST::insert(valuetype val){\n if(root==NULL)\n root = new Node(val);\n else{ // K&amp;R Style brace here\n Node* p =findNodebyvalue(val);\n if(p==0)\n { // Aligned brace style here.\n\n // Remove commented out code.\n // Or use some form of logging infrastructure you\n // can turn on at a more abstract level.\n //cout&lt;&lt;\"fine1\";\n\n // More white space in the code to break sections up\n // would also be nice.\n Node* parent=root;\n if (p != root)\n parent = findparentforNode(val);\n\n // Not a fan of this style of if it makes the code hard to read\n // Always consistently using braces can keep you out of trouble.\n if(val&gt;parent-&gt;data) parent-&gt;right=new Node(val);\n else parent-&gt;left=new Node(val);\n\n // Putting the statement on the same line as the condition\n // makes it hard when stepping through with a de-bugger.\n // If there was no else you would not be able to tell if the\n // condition fired so split up the lines a bit.\n\n // At a push if you really wanted to save space\n if (val&gt;parent-&gt;data)\n {parent-&gt;right =new Node(val);}\n else {parent-&gt;left =new Node(val);}\n\n // Personally I would use\n if (val&gt;parent-&gt;data)\n {\n parent-&gt;right =new Node(val);\n }\n else\n {\n parent-&gt;left =new Node(val);\n }\n\n // Or K&amp;R style\n if (val&gt;parent-&gt;data) {\n parent-&gt;right =new Node(val);\n }\n else {\n parent-&gt;left =new Node(val);\n }\n\n }\n //cout&lt;&lt;\"fine2\";\n }\n}\n</code></pre>\n\n<p>Not a fan of your brace style it is sloppy. This makes code hard to read and maintain. Also you use several different brace styles in your code. Pick a style and be consistent in its usage.</p>\n\n<p>Looks like the code is correct.<br>\nSeems like you are mixing in tabs and spaces (which has made the indentation fail). When posting to websites it is usually a good idea to replace all tabs with spaces. Within your own code make sure you consistently use tabs and spaces (which is better is a religious war I am not going to get into).</p>\n\n<p>Also you should start adding some white space to make the code more readable.</p>\n\n<pre><code>//Example:\nif(p-&gt;left==NULL&amp;&amp;p-&gt;right==NULL){\n\n// Why not make it easy to read:\nif ((p-&gt;left == NULL) &amp;&amp; (p-&gt;right == NULL)) {\n</code></pre>\n\n<p>There seems like there is a lot of repeated code here (<code>BST::remove()</code>) that can be factored out.</p>\n\n<p>If I were to write this I would start with a recursive delete.</p>\n\n<pre><code>void BST::remove(valuetype val)\n{\n root = removeValue(root, val);\n}\nNode* BST::removeValue(Node* node, valuetype val)\n{\n if (val &lt; node.data)\n {\n node.left = removeValue(node.left, val);\n return node;\n }\n else\n {\n node.right = removeValue(node.right, val);\n return node;\n }\n\n return unlinkNode(node, val);\n }\n Node* unlinkNode(Node* node, valuetype val)\n {\n Node* result = NULL;\n\n // We have found the node we want to remove.\n if ((node.left == NULL) &amp;&amp; (node.right == NULL))\n {\n delete node;\n // Will return NULL\n }\n else if (node.right == NULL)\n {\n result = node.left;\n delete node;\n }\n else if (node.left == NULL)\n {\n result = node.right;\n delete node;\n }\n else\n {\n result = node;\n\n // This is complicated.\n // You should definately have a comment that explains the algorithm\n // that you are using here.\n Node* righty = findrightnode(node-&gt;left);\n Node* parent = findparentforNode(righty-&gt;data);\n\n node-&gt;data=righty-&gt;data;\n\n if(parent != node) {\n parent-&gt;right=righty-&gt;left;\n }\n else {\n node-&gt;left=righty-&gt;left;\n }\n // You forgot to delete righty\n delete righty;\n }\n return result;\n}\n</code></pre>\n\n<p>In <code>findNodebyvalue()</code><br>\nAgain more white space needed.<br>\nAgain tabs/space problem.<br>\nI would replace the if with a trinary operator.</p>\n\n<pre><code>//fins node with a value key\nNode* BST::findNodebyvalue(valuetype key)\n{\n Node* p =root;\n while((p != NULL) &amp;&amp; (p-&gt;data != key))\n {\n p = (key &lt; p-&gt;data) ? p-&gt;left : p-&gt;right;\n }\n return p;\n}\n</code></pre>\n\n<p>In <code>findparentforNode()</code><br>\nAgain more white space needed.<br>\nAgain tabs/space problem. </p>\n\n<p>In your printing functions. Rather than serialize to std::cout. You should probably pass a reference to a stream onto which you want to serialize the tree.</p>\n\n<p>The method custom print should probably be re-named <code>breadth first print</code>.</p>\n\n<pre><code>int main()\n{\n// Horrible indent.\nBST tree;\ntree.insert(10);\ntree.insert(2);\ntree.insert(4);\ntree.insert(12);\ntree.insert(23);\ntree.traverse();\ntree.custom_print();\n\n// Wait for user to hit key.\ngetch();\n\n// Can be replaced with:\nstd::string line;\nstd::getline(std::cin, line);\n\n// Main is special.\n// If you don't return a value the compiler plants a `return 0;` for you.\n// Thus if your app is not going to report any errors to the OS it is \n// more usual to not add this. Adding this is a sign that your application\n// can fail.\nreturn 0;\n\n// Currently the BST tree leaks memory here.\n// You need to add a destructor.\n// If you add a destructor you will need to add the other methods\n// to make sure you obey the rule of three.\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T11:27:11.180", "Id": "17878", "ParentId": "17864", "Score": "23" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T07:13:57.780", "Id": "17864", "Score": "8", "Tags": [ "c++", "tree", "binary-search" ], "Title": "Binary search tree implementation in C++" }
17864
<p>I have a timer that is only supposed to tick between x and x on weekdays.</p> <p>I have used the following implementation.</p> <pre><code> void tmrMain_Tick(object sender, EventArgs e) { if (!(DateTime.Now.DayOfWeek == DayOfWeek.Saturday || DateTime.Now.DayOfWeek == DayOfWeek.Sunday)) { if ((IsTimeOfDayBetween(DateTime.Now, new TimeSpan(8, 0, 0), new TimeSpan(18, 0, 0)))) { if (pnlAssembly.Visible == true) { cmdShed.PerformClick(); } else if (pnlShed.Visible == true) { cmdServices.PerformClick(); } else if (pnlWeb.Visible == true) { cmdAssembly.PerformClick(); } } } } static bool IsTimeOfDayBetween(DateTime time, TimeSpan startTime, TimeSpan endTime) { if (endTime == startTime) { return true; } else if (endTime &lt; startTime) { return time.TimeOfDay &lt;= endTime || time.TimeOfDay &gt;= startTime; } else { return time.TimeOfDay &gt;= startTime &amp;&amp; time.TimeOfDay &lt;= endTime; } } </code></pre> <p>Is this the way to go?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T13:31:47.533", "Id": "28465", "Score": "4", "body": "Ditch the `== true` bits. It's redundant. For example, `if (pnlAssembly.Visisble) {` is more idiomatic as it's already a Boolean expression and reads more naturally." } ]
[ { "body": "<p>I would use immediate returns to reduce the nesting of the first function.</p>\n\n<p>I would extract the constants out.</p>\n\n<p>I would also consider extracting to a method the logic of whether or not to do the actions.</p>\n\n<pre><code>private readonly TimeSpan StartTime = new TimeSpan(8, 0, 0);\nprivate readonly TimeSpan EndTime = new TimeSpan(18, 0, 0);\nprivate void tmrMain_Tick(object sender, EventArgs e) {\n if (DateTime.Now.DayOfWeek == DayOfWeek.Saturday\n || DateTime.Now.DayOfWeek == DayOfWeek.Sunday\n || !IsTimeOfDayBetween(DateTime.Now, StartTime, EndTime)\n ) {\n return;\n }\n if (pnlAssembly.Visible == true) {\n cmdShed.PerformClick();\n } else if (pnlShed.Visible == true) {\n cmdServices.PerformClick();\n } else if (pnlWeb.Visible == true) {\n cmdAssembly.PerformClick();\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T11:07:55.347", "Id": "28463", "Score": "0", "body": "Thanks for your answer. Just 1 note - TimeSpan cannot be declared const" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T10:49:51.727", "Id": "17876", "ParentId": "17869", "Score": "4" } }, { "body": "<p>Here is another alternative...</p>\n\n<pre><code>private void tmrMain_Tick(object sender, EventArgs e) \n{ \n if (ShouldRunNow())\n PerformClick();\n} \n\nprivate void PerformClick()\n{\n if (pnlAssembly.Visible)\n cmdShed.PerformClick(); \n\n else if (pnlShed.Visible) \n cmdServices.PerformClick(); \n\n else if (pnlWeb.Visible)\n cmdAssembly.PerformClick(); \n}\n\nprivate bool ShouldRunNow()\n{\n TimeSpan startTime = new TimeSpan(8, 0, 0); \n TimeSpan endTime = new TimeSpan(18, 0, 0);\n DateTime now = DateTime.Now;\n\n // Only run Saturday and Sunday\n if (now.DayOfWeek != DayOfWeek.Saturday &amp;&amp; now.DayOfWeek != DayOfWeek.Sunday)\n return false;\n\n // Only run between the specified times.\n if (endTime == startTime )\n return true; \n\n if (endTime &lt; startTime) \n return now.TimeOfDay &lt;= endTime || now.TimeOfDay &gt;= startTime; \n\n return now.TimeOfDay &gt;= startTime &amp;&amp; now.TimeOfDay &lt;= endTime; \n}\n</code></pre>\n\n<p>Couple notes:<br/>\nI think this is what ANeves meant by \"would also consider extracting to a method the logic of whether or not to do the actions\" but not sure so I decided to show it. By putting the entire decision tree in a method you have self documenting code (the \"if (ShouldRunNow())\" describes what you are trying to do without needing comments). </p>\n\n<p>Eliminating \"else\" statements makes your code more readable (IMHO)</p>\n\n<p>I personnally think using brackets when there is only one statement makes your code less readable as well. Of course, this is my own opinion and I even have people at my workplace that disagree with this. I will let the readers decide :)</p>\n\n<p>Since the ShouldRunNow method is private then it doesn't hurt to not pass in the parameters. And putting them directly in the method will make them easier to find. This is not a big deal either way but just another alternative.</p>\n\n<p><b>Update</b>\nChanged code based on feedback in comments</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T16:00:04.797", "Id": "28476", "Score": "0", "body": "Great answer. I would change ShouldRunNow() to ShouldNotRunNow(). As @ANeves this will allow immediate return and not nest the important logic in the method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T16:42:25.880", "Id": "28481", "Score": "1", "body": "I'm not a fan of NOT logic, but your point is a good one. I suppose the line could read \"if (!ShouldRunNow())\" so that at least the method code does not read \"backwards\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T18:28:02.533", "Id": "28485", "Score": "0", "body": "You can't have `readonly` locals. Also, when you're saving `DateTime.Now` to a local, you should use it in the day checks too. And `Now` is a property, not a method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T17:04:47.603", "Id": "28540", "Score": "0", "body": "@svick ahh you caught me. Guess I did not do a very good job hiding the fact that I wrote this in NotePad. :) Thanks for your feedback." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T14:32:30.173", "Id": "17883", "ParentId": "17869", "Score": "6" } } ]
{ "AcceptedAnswerId": "17883", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T09:11:22.077", "Id": "17869", "Score": "5", "Tags": [ "c#", "winforms", "timer" ], "Title": "Timer Tick Event only to execute at specific time" }
17869
<p>I've written a thread safe, persistent FIFO for <code>Serializable</code> items. The reason for reinventing the wheel is that we simply can't afford any third party dependencies in this project and want to keep this really simple. </p> <p>The problem is it isn't fast enough. Most of it is undoubtedly due to reading and writing directly to disk but I think we should be able to squeeze a bit more out of it anyway. Any ideas on how to improve the performance of the 'take'- and 'add'-methods?</p> <pre><code>/** * &lt;code&gt;DiskQueue&lt;/code&gt; Persistent, thread safe FIFO queue for * &lt;code&gt;Serializable&lt;/code&gt; items. */ public class DiskQueue&lt;ItemT extends Serializable&gt; { public static final int EMPTY_OFFS = -1; public static final int LONG_SIZE = 8; public static final int HEADER_SIZE = LONG_SIZE * 2; private InputStream inputStream; private OutputStream outputStream; private RandomAccessFile file; private FileChannel channel; private long offs = EMPTY_OFFS; private long size = 0; public DiskQueue(String filename) { try { boolean fileExists = new File(filename).exists(); file = new RandomAccessFile(filename, "rwd"); if (fileExists) { size = file.readLong(); offs = file.readLong(); } else { file.writeLong(size); file.writeLong(offs); } } catch (FileNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } channel = file.getChannel(); inputStream = Channels.newInputStream(channel); outputStream = Channels.newOutputStream(channel); } /** * Add item to end of queue. */ public void add(ItemT item) { try { synchronized (this) { channel.position(channel.size()); ObjectOutputStream s = new ObjectOutputStream(outputStream); s.writeObject(item); s.flush(); size++; file.seek(0); file.writeLong(size); if (offs == EMPTY_OFFS) { offs = HEADER_SIZE; file.writeLong(offs); } notify(); } } catch (IOException e) { throw new RuntimeException(e); } } /** * Clears overhead by moving the remaining items up and shortening the file. */ public synchronized void defrag() { if (offs &gt; HEADER_SIZE &amp;&amp; size &gt; 0) { try { long totalBytes = channel.size() - offs; ByteBuffer buffer = ByteBuffer.allocateDirect((int) totalBytes); channel.position(offs); for (int bytes = 0; bytes &lt; totalBytes;) { int res = channel.read(buffer); if (res == -1) { throw new IOException("Failed to read data into buffer"); } bytes += res; } channel.position(HEADER_SIZE); buffer.flip(); for (int bytes = 0; bytes &lt; totalBytes;) { int res = channel.write(buffer); if (res == -1) { throw new IOException("Failed to write buffer to file"); } bytes += res; } offs = HEADER_SIZE; file.seek(LONG_SIZE); file.writeLong(offs); file.setLength(HEADER_SIZE + totalBytes); } catch (IOException e) { throw new RuntimeException(e); } } } /** * Returns the queue overhead in bytes. */ public synchronized long overhead() { return (offs == EMPTY_OFFS) ? 0 : offs - HEADER_SIZE; } /** * Returns the first item in the queue, blocks if queue is empty. */ public ItemT peek() throws InterruptedException { block(); synchronized (this) { if (offs != EMPTY_OFFS) { return readItem(); } } return peek(); } /** * Returns the number of remaining items in queue. */ public synchronized long size() { return size; } /** * Removes and returns the first item in the queue, blocks if queue is empty. */ public ItemT take() throws InterruptedException { block(); try { synchronized (this) { if (offs != EMPTY_OFFS) { ItemT result = readItem(); size--; offs = channel.position(); file.seek(0); if (offs == channel.size()) { truncate(); } file.writeLong(size); file.writeLong(offs); return result; } } return take(); } catch (IOException e) { throw new RuntimeException(e); } } /** * Throw away all items and reset the file. */ public synchronized void truncate() { try { offs = EMPTY_OFFS; file.setLength(HEADER_SIZE); size = 0; } catch (IOException e) { throw new RuntimeException(e); } } /** * Block until an item is available. */ protected void block() throws InterruptedException { while (offs == EMPTY_OFFS) { try { synchronized (this) { wait(); file.seek(LONG_SIZE); offs = file.readLong(); } } catch (IOException e) { throw new RuntimeException(e); } } } /** * Read and return item. */ @SuppressWarnings("unchecked") protected ItemT readItem() { try { channel.position(offs); return (ItemT) new ObjectInputStream(inputStream).readObject(); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T08:32:31.753", "Id": "28458", "Score": "0", "body": "So why can't you afford 3rd party dependencies? It's actually simpler to use them in a case like this. Performance tuning and error handling for I/O is... hard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T09:58:18.823", "Id": "28460", "Score": "0", "body": "Yeah I know it's hard, been there done that. I have no choice right here though and solving problems is what programming is all about." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T08:50:13.827", "Id": "28515", "Score": "0", "body": "Any ideas on how to get rid of the ObjectStream instantiations in add() / readItem()?" } ]
[ { "body": "<p>The problem is that you are always seeking. This slows you down very much on a conventional hard disk. The solution is to only append to a file and do compaction later. Such data structures are called journals. See <a href=\"https://github.com/sbtourist/Journal.IO\" rel=\"nofollow\">Journal.IO</a> for more details.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T09:57:18.387", "Id": "28459", "Score": "0", "body": "Am not :) add() appends at eof, take() picks the first non-taken from the start and compaction happens whenever defrag() is called. If you add or take several items in a row the seeks shouldn't make a difference as it's already in the right place." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T09:27:39.257", "Id": "17871", "ParentId": "17870", "Score": "0" } }, { "body": "<p>A few random notes:</p>\n\n<ol>\n<li><p>It does not seem completely thread-safe. The <code>offs</code> field sometimes is read outside any <code>synchronized</code> block.</p>\n\n<blockquote>\n <p>[...] synchronization has no effect unless both read and write operations are synchronized.</p>\n</blockquote>\n\n<p>From <em>Effective Java, 2nd Edition, Item 66: Synchronize access to shared mutable data</em>.</p></li>\n<li><p>I'd consider using separate file for every item and one for the meta information (list of the name of the corresponding files).</p></li>\n<li><p>If you don't use checked exceptions and rethrow every exception catching <code>Exception</code>s directly would be simpler. </p>\n\n<pre><code>} catch (ClassNotFoundException e) {\n throw new RuntimeException(e);\n} catch (IOException e) {\n throw new RuntimeException(e);\n}\n</code></pre>\n\n<p>The following is very similar (not exactly the same):</p>\n\n<pre><code>} catch (Exception e) {\n throw new RuntimeException(e);\n}\n</code></pre></li>\n<li><p>I'd prefer concurrency utilities to <code>wait</code> and <code>notify</code>. (<em>Effective Java, 2nd Edition, Item 69</em>) A <code>Semaphore</code> might be a good choice here.</p></li>\n<li><pre><code>public ItemT getSomething() {\n block();\n\n synchronized (this) {\n if (queue if not empty) {\n return readItem();\n }\n }\n return getSomething();\n}\n</code></pre>\n\n<p>Instead of the above recursive structure I'd use a loop. The recursion might cause <code>StackOverflowError</code>s. </p>\n\n<pre><code>public ItemT getSomething() {\n block();\n\n while (true) {\n synchronized (this) {\n if (queue if not empty) {\n return readItem();\n }\n }\n }\n}\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T08:43:55.223", "Id": "28513", "Score": "0", "body": "1. Thanks, missed that one.\n\n2. I'm afraid separate files for each item won't scale to hundreds of thousands of items. Maybe one file for headers and one for data would be a good compromise?\n\n3. It's not that I want to catch everything, I want to catch everything the code is throwing right now.\n\n4. I tried changing to a semaphore and it works like before but wait()/notify() is a simpler construct and better fit as I don't really need multiple permits. Care to elaborate on why you prefer the Semaphore?\n\n5. You're right of course, thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T11:20:12.063", "Id": "28516", "Score": "0", "body": "@trialcodr: 2. Another idea: you could use separate folders (one folder for every 100 file). 3: Semaphore seemed the most suitable from the concurrency framework, I've not thought too much about this. Effective Java is very convincing about not using wait/notify." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T11:54:30.800", "Id": "28522", "Score": "0", "body": "The problem with separate files and folders is that you normally would require more seeking as there is a different position on the disk for every file/folder and the file system data needs to be updated. There was a good discussion on the HornetQ Journal and why this is fast. But I can't find it at the moment." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-26T12:08:10.843", "Id": "28573", "Score": "0", "body": "Just for the record, I did a quick test of splitting the file into two. One for the book keeping and one for data. I was very surprised to find that it was actually slower than the naive single file solution. That might change when/if the data file grows really big though." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T19:20:19.960", "Id": "17896", "ParentId": "17870", "Score": "3" } }, { "body": "<p>A big performance killer in your code is the use of <code>\"rwd\"</code> mode to open the file. The <code>\"d\"</code> forces every write to be synchronously written on the physical disk.</p>\n\n<p>A quick benchmark gives me a <strong>500x speed improvement</strong> just by removing the <code>\"d\"</code> in your code. I did a profiling of your code, and it appears that the majority of the time is spent in the <code>writeLong</code> function. This is because <code>writeLong</code> internally calls <code>write</code> eight times, and each time a physical write is performed !</p>\n\n<p>You should remove this <code>\"d\"</code> mode and insert flushing instructions at strategic places. I think <code>FileChannel.force(false)</code> is the right method for that. Adding this instruction in <code>add</code>, <code>take</code> and <code>defrag</code> gives me a <strong>12x speed improvement</strong> compared to the original code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-01-23T14:49:12.720", "Id": "20824", "ParentId": "17870", "Score": "4" } }, { "body": "<p>In addition to the great points by palacsint and barjak I have a few things to consider.</p>\n\n<p>There are two ways you could increase the concurrency. The only thing that must be serialized is the head/tail pointer update.</p>\n\n<blockquote>\n <p>This assumes that the order in which items are written to and read from the disk does not need to match the order in which the calls to <code>add</code> and <code>take</code> occur. This seems to be the case given the structure as it is now.</p>\n</blockquote>\n\n<p>First, serialize in parallel, no pun intended. Each thread can perform its own object serialization without making the other threads wait.</p>\n\n<p>Here's how <code>add</code> would look:</p>\n\n<pre><code>add ( ItemT item )\n serialize item to a byte array\n lock file\n write byte count\n write bytes\n update size\n</code></pre>\n\n<p>It's been a long time since I played with NIO, and I never used it in a real project, but I'm pretty sure it provides facilities for efficiently copying between <code>ByteBuffer</code>s. You can see I've added a byte count to each item. This is so you can know how many bytes to read from the file and advance the pointer.</p>\n\n<p>Second, let the I/O subsystem decide how best to order the seek/read/write steps by moving the read/write of the byte arrays outside synchronization. Since you've already serialized the object during <code>add</code>, you know exactly how many bytes to read/write and advance the pointers.</p>\n\n<p>Now <code>add</code> is maximally concurrent:</p>\n\n<pre><code>add ( ItemT item )\n serialize item to byte array\n insert entry size in front of byte array\n lock tail pointer\n advance tail pointer by entry size\n write entry\n</code></pre>\n\n<p>You can avoid byte shuffling by inserting a <code>0</code> for the size before serializing instead of performing an insertion after calculating the size. The key is that \"write entry\" should be an atomic \"append byte buffer to file\" operation which again I believe NIO provides.</p>\n\n<p>Here are some random notes I made while reading the code:</p>\n\n<ol>\n<li><p>Do you have to instantiate new object input/output streams every time? Depending on how expensive this is, you may want to store them in a <code>ThreadLocal</code>, especially when using the byte arrays above.</p></li>\n<li><p>You are seeking twice for every operation which could have a large cost if the block containing the header is far from the head/tail of the queue. Could you tolerate writing the size of the queue less frequently or in a separate thread? Are you writing to disk for fault tolerance or because it might grow too large to fit in memory? If the latter, keep it in memory only and write it when the application terminates or every <em>x</em> operations.</p></li>\n<li><p>Why do you need <code>EMPTY_OFFS</code>? Can you use <code>HEADER_SIZE</code> as the initial offset for an empty queue?</p></li>\n<li><p>Abbreviating <code>offset</code> to <code>offs</code> is terribad! It looks like the plural form of <code>off</code> and doesn't add any value. Pay those extra two keystrokes for clarity and call it exercise if you need an excuse. :)</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-24T17:28:30.433", "Id": "24312", "ParentId": "17870", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T07:58:54.403", "Id": "17870", "Score": "5", "Tags": [ "java", "multithreading", "recursion", "queue", "reinventing-the-wheel" ], "Title": "Optimizing a thread safe Java NIO / Serialization / FIFO Queue" }
17870
<p>I was trying to solve the Median challenge at Interviewstreet.com.</p> <p>I wasn't able to pass most of the test cases. But according to my understanding my code should work fine.</p> <p>Here is the question: <a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4fcf919f11817" rel="nofollow">https://www.interviewstreet.com/challenges/dashboard/#problem/4fcf919f11817</a></p> <p>Here is my code:</p> <pre><code> /* Sample program illustrating input and output */ import java.util.*; class Solution{ public static void main( String args[] ){ // helpers for input/output Scanner in = new Scanner(System.in); int N; N = in.nextInt(); String s[] = new String[N]; int x[] = new int[N]; ArrayList&lt;Integer&gt; items=new ArrayList&lt;Integer&gt;(); float result[]=new float[N]; //int itemindex=-1; for(int i=0; i&lt;N; i++){ s[i] = in.next(); x[i] = in.nextInt(); switch(s[i].charAt(0)) { case 'r': if(items.size()&lt;=1) { result[i]=-1; } else { items.remove((Integer)x[i]); int itemindex=items.size(); Collections.sort(items); if((itemindex)%2==0) { result[i]=(float) ((items.get((itemindex/2))+items.get(((itemindex)/2)-1))/2.0); } else { result[i]=items.get((itemindex-1)/2); } } break; case 'a': items.add(x[i]); int itemindex=items.size(); Collections.sort(items); if((itemindex)%2==0) { result[i]=(float)((items.get((itemindex/2))+items.get(((itemindex)/2)-1))/2.0); } else { result[i]=items.get((itemindex-1)/2); } break; } } for(int j=0;j&lt;N;j++) { if(result[j]==-1) { System.out.println("Wrong!"); } else { if((result[j]*10)%10==0) { System.out.println((int)(result[j])); } else { System.out.println(result[j]); } } } } } </code></pre> <p>I would highly appreciate if someone could help me find out the test cases which will fail for my code.</p> <p>Thanks.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T03:23:42.177", "Id": "28506", "Score": "0", "body": "I see that you were redirected here by someone on Stackoverflow. This question actually belongs there though. CR is intended for code that the poster believes to be correct. (Actually, I see that is has 4 close votes on stackoverflow -- that's probably because the question is very broad. Posting a problem statement, posting a chunk of code, and asking for someone to debug it is a bit of a large task and not really the aim of SO or CR. Typically when asking a question on SO, you should have already debugged yourself and know a specific question.)" } ]
[ { "body": "<ol>\n<li><p>The following is duplicated, you could extract it out a method:</p>\n\n<pre><code>int itemindex = items.size();\nCollections.sort(items);\nif (itemindex %2 == 0) {\n result[i]=(float)((items.get((itemindex/2))+items.get(((itemindex)/2)-1))/2.0);\n} else {\n result[i]=items.get((itemindex-1)/2);\n}\n</code></pre></li>\n<li><p><code>ArrayList&lt;...&gt;</code> reference types should be simply <code>List&lt;...&gt;</code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n\n<pre><code>List&lt;Integer&gt; items = new ArrayList&lt;Integer&gt;();\n</code></pre></li>\n</ol>\n\n<p>Three bugs:</p>\n\n<ol>\n<li><p>Input:</p>\n\n<pre><code>2\na 214748367\na 214748365\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>2.14748368E8\n2.14748368E8\n</code></pre></li>\n<li><p>Input:</p>\n\n<pre><code>2\na 2147483647\na 2147483645\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>2147483647\n-2\n</code></pre></li>\n<li><p>Processing the output of the following code takes more than the allowed 5 seconds:</p>\n\n<pre><code>for (int i = 100000; i &gt; 0; i--) {\n System.out.println(\"a \" + i);\n}\n</code></pre></li>\n</ol>\n\n<p>Some useful reading:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency\">Why not use Double or Float to represent currency?</a></li>\n<li><em>Effective Java, 2nd Edition, Item 48: Avoid float and double if exact answers are required</em></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T20:23:28.890", "Id": "28492", "Score": "1", "body": "+1 you have two important notes so I prefer to add a third point with a comment here instead of giving a partial answer: There is also a mistake in calculating \"Wrong!\". it is done by checking if the list is empty or has a single item. according to the challenge it should be done if the number is not in the list." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T20:43:27.330", "Id": "28493", "Score": "1", "body": "@A.J.: Thanks! I think you should write it as an answer. I'd upvote it and it would improve our [answer ratio](http://area51.stackexchange.com/proposals/11464/code-review) too." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T20:13:29.753", "Id": "17899", "ParentId": "17874", "Score": "0" } }, { "body": "<p>An additional point to the ones mentioned by @palacsint is the check for the object removal:\naccording to the challenge:</p>\n\n<blockquote>\n <p>If the operation is remove and the number x is not in the list, output\n \"Wrong!\" in a single line</p>\n</blockquote>\n\n<p>your code does not check for that: here is what you have:</p>\n\n<pre><code>if(items.size()&lt;=1)\n {\n result[i]=-1;\n }\nelse .....\n</code></pre>\n\n<p>You are marking wrong when the list has a single item or is empty. Obviously this is not what the challenge requires. Therefore, you should discard this \"if\" block and only check the return value from the remove on the list:</p>\n\n<pre><code>boolean ok= items.remove((Integer)x[i]);\nif (!ok){\n result[i]=-1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T21:39:54.343", "Id": "17904", "ParentId": "17874", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T10:31:46.337", "Id": "17874", "Score": "1", "Tags": [ "java" ], "Title": "Interview street Median challenge" }
17874
<p>I've been using the following user agent Regular Expression to detect mobile devices, but I recently came across a few resources that listed a whole host of mobile user agents that I had not heard of before.</p> <p>Whilst my agent check is only the first step in the detection process - I also have some JavaScript as a fallback - I would like for it to contain the majority of <em>currently</em> undisputed mobile "keywords" so as to optimise the user experience for those handsets. I would also like to keep things as future-proof as possible, but this can only ever be argued with good reasoning and not <em>set-in-stone</em>.</p> <p>The core of the regexp follows - please note the user agent string has had it's white-space removed. The check is also specifically case dependent.</p> <p><em>Please ignore the newlines; they are for formatting only.</em></p> <pre><code>/i[Pp]hone|[Mm]obile[Ss]afari|[Ww]indowsCE|[Ww]indows[Pp]hone| IE[Mm]obile|[Oo]pera[Mm]ini|[Oo]pera[Mm]obi|[Bb]lack[Bb]erry| [^A-Z]RIM[^A-Z]|[Ss]ony[Ee]ricsson|[Nn]okia|[^A-Z]MIB[^A-Z]/ </code></pre> <p>These are the extra edge-case agents that I've found out about:</p> <pre><code>/[Ss]kyfire|[Tt]ea[Ss]hark|[Nn]et[Ff]ront|[Mm]inimo| [Ii]ris|[Ff]ennec|[Dd]oris|[Ss]eries60|BOLT|[Bb]lazer/ </code></pre> <p>Does anyone have any further suggestions, or possible keywords to remove, that could cause false positives?</p> <p>For example, I do not include Samsung or Android for the precise reasons that they are not unique to mobile agents. I'd rather let agents through to the JavaScript that I'm unsure about.</p> <p>As a second note, many user-agents report as <em>Like Something</em> - i.e. <em>Like Mobile Safari</em> - should I filter these out of the equation, or if something is reporting this; is it also likely to be a mobile device.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-11T01:07:36.983", "Id": "29423", "Score": "0", "body": "Any reason not to use a case-insensitive flag to avoid all the `[Aa]` character classes? Additionally, it would seem to me that you could simply surround the branching in `\\b` word-boundary \"characters\", or put the `[^a-z]` classes there. E.g. `/\\b(iphone|mobile| ... |nokia|mib)\\b/i`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-25T02:29:39.857", "Id": "101551", "Score": "0", "body": "It is better to detect *features* than devices, for example using [CSS media queries](http://css-tricks.com/css-media-queries/) to cater for small screens, or [jQuery UI Touch Punch](http://touchpunch.furf.com/) to handle touch events. The most important question is WHY you want to detect a mobile user. What will you do differently for them?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-06T00:38:14.383", "Id": "101601", "Score": "0", "body": "Take a look at http://detectmobilebrowsers.com. You can download scripts in almost any language, including PHP, and take a look at the regex voodoo. Also be sure to provide a link to the non-mobile version so that the user can choose to go to the full site should they choose to do that or if the detection fails." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T21:30:26.310", "Id": "101602", "Score": "0", "body": "+1 Thanks for the info, however their regex voodoo - whilst seemingly rather inclusive - is also rather cryptic. I would have a hard time justifying the reasons behind each particular check to the server team I'm working alongside. Although looking at the regexp has raised a good point because I have no idea what my client expects to happen with Kindle devices ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T02:25:00.970", "Id": "101603", "Score": "0", "body": "The site I linked uses the [WURFL](http://wurfl.sourceforge.net/) database. You can download the database, pick and choose which user agents you want to support. You will have to do all the regex voodoo yourself though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-08T09:22:08.107", "Id": "101604", "Score": "0", "body": "Yeah, I recently came across WURFL and also read about their new license preventing people from breaking it up and using it in an unlicensed way. Whilst I could probably do such a thing and not be found out, I don't agree with ignoring licenses and would rather develop my own solution. It is a useful link however to others who may find this." } ]
[ { "body": "<p>First of all I guess your first step of the detection process is processed <strong>server side</strong> because you said there is a fallback which is processed by JavaScript.\nTherefore I guess you only perform a <strong>HTTP User-Agent</strong> check so far.</p>\n<h2>Suggestion BlackBerry</h2>\n<p>I would recommend to add also a check of the <a href=\"http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html\" rel=\"nofollow noreferrer\">Accept request header</a> to your first step of detection.</p>\n<p>In one of my recent projects I ran into trouble cause the HTTP User-Agent detection of <strong>BlackBerry</strong> failed in some cases. For these casees I had to add an Accept request header check which looks for <code>/vnd.rim/</code>.\nI didn't find out much about the background why it happens. I only know some BlackBerry browsers try to emulate IE or Firefox.</p>\n<h3>Example</h3>\n<p>Taken from the <a href=\"http://www.blackberry.net/go/mobile/profiles/uaprof/8120/4.3.0.rdf\" rel=\"nofollow noreferrer\">BlackBerry 8120 device specification document</a>: <code>application/vnd.rim.html</code></p>\n<h2>Suggestion J2ME Devices</h2>\n<p>Clients using this technology might be quite rare but to be sure you could include another RegEx for <code>midp</code> to cover all kind of MIDP devices.</p>\n<h2>Question</h2>\n<p>I know they're dead but I think there are still some around. What about Palm and webOS devices?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-07T21:35:32.353", "Id": "29203", "Score": "0", "body": "+1 Thanks for the good points, and pointing out that I had totally missed to state server side, my bad :) you are correct in your assumptions. I had not considered the `Accept request header` at all, I shall do some research..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-11-05T15:40:26.737", "Id": "18253", "ParentId": "17879", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-24T12:14:31.667", "Id": "17879", "Score": "2", "Tags": [ "regex", "mobile" ], "Title": "Mobile user agent check" }
17879