body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>Is there any way to improve this code? It looks a bit ugly for me.</p> <pre><code>if($url_chunks_num == 1) { $this-&gt;controller = $this-&gt;pageData[0]; } elseif($url_chunks_num == 2) { $this-&gt;controller = $this-&gt;pageData[0]; $this-&gt;action = $this-&gt;pageData[1]; } elseif($url_chunks_num &gt; 2) { $this-&gt;controller = $this-&gt;pageData[0]; $this-&gt;action = $this-&gt;pageData[1]; $this-&gt;values = array_slice($this-&gt;pageData, 2); } </code></pre> <p>I thought about nested conditions, but this option is ugly as well.</p>
[]
[ { "body": "<p>There seems to be some code repetition. Perhaps this could be improved like this:</p>\n\n<pre><code>if ($url_chunks_num &gt;= 1)\n $this-&gt;controller = $this-&gt;pageData[0];\nif ($url_chunks_num &gt;= 2)\n $this-&gt;action = $this-&gt;pageData[1];\nif ($url_chunks_num &gt; 2)\n $this-&gt;values = array_slice($his-&gt;pageData, 2);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>if ($url_chunks_num &gt;= 1) {\n $this-&gt;controller = $this-&gt;pageData[0];\n if ($url_chunks_num &gt;= 2)\n $this-&gt;action = $this-&gt;pageData[1];\n if ($url_chunks_num &gt; 2)\n $this-&gt;values = array_slice($his-&gt;pageData, 2);\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T23:29:53.443", "Id": "12913", "ParentId": "12912", "Score": "7" } }, { "body": "<p>I agree with luiscubal about restructuring the code (with the one minor difference that I would use braces), however, I think you could make something a bit cleaner with <a href=\"http://us2.php.net/array_shift\">array_shift</a>.</p>\n\n<pre><code>$this-&gt;controller = array_shift($this-&gt;pageData);\n$this-&gt;action = array_shift($this-&gt;pageData);\n$this-&gt;values = $this-&gt;pageData;\n</code></pre>\n\n<p>This is functionally equivalent to the code luiscubal posted, though his does not define defaults. (The two strings would default to <code>NULL</code> and then <code>$this-&gt;values</code> would default to <code>array()</code>.)</p>\n\n<p>This does change $this->pageData though, so if you need to keep that data around (which is implied by it being a property), you'll need to either use luiscubal's approach or create a temporary copy.</p>\n\n<hr>\n\n<p>Since the array is small, and PHP is typically copy-on-write, making a copy shouldn't be an issue, however, if you're worried, you could take a non-direct route to basically have the same amount of copying as the if trees have:</p>\n\n<pre><code>$this-&gt;values = $this-&gt;pageData;\n$this-&gt;controller = array_shift($this-&gt;values);\n$this-&gt;action = array_shift($this-&gt;values);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T00:04:04.150", "Id": "12915", "ParentId": "12912", "Score": "7" } }, { "body": "<p>I'd do it just how Corbin suggested, but the above is still valid. You could also check out <code>list()</code> and, if <code>$pageData</code> were associative with keys of the same title you could use variable variables. Disclaimer: I do not advise the use of variable variables, merely pointing it out for completeness.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T06:09:50.207", "Id": "20831", "Score": "1", "body": "this would behave differently from the original code, for example if `$url_chunks_num == 0`. In your code the line `$this->controller = $this->pageData[0];` will be executed, while in the original it will not." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T13:16:41.207", "Id": "20866", "Score": "0", "body": "@nadirs: You are quite right, can't believe I missed that. I'll remove the code snippet, as I can't make that look any better with the added constraint. However, I'll leave the answer up for the rest is still relevant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T20:19:29.513", "Id": "20903", "Score": "0", "body": "List requires you to know that the elements exist. And variable variables would have the same problem. -1 isn't me though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T21:27:58.617", "Id": "20908", "Score": "0", "body": "Its actually -2. However, the issue with list can be fixed by checking its length and appending elements onto it so that it has the right default amount, even if those are empty. I'll probably just end up deleting this post as it appears that it is not going over well -.-" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T04:44:22.887", "Id": "12919", "ParentId": "12912", "Score": "1" } }, { "body": "<p>this should look better.</p>\n\n<pre><code>if ($url_chunks_num&gt;0)\n $this-&gt;controller = $this-&gt;pageData[0];\nif($url_chunks_num &gt; 1)\n $this-&gt;action = $this-&gt;pageData[1];\nif($url_chunks_num &gt; 2) {\n $this-&gt;values = array_slice($this-&gt;pageData, 2);\n</code></pre>\n\n<p>but also using a switch statement should be nicer... i do not know if it works, should be tested...</p>\n\n<pre><code>switch ($url_chunks_num) {\n default:\n $this-&gt;values = array_slice($this-&gt;pageData, 2);\n case 2:\n $this-&gt;action = $this-&gt;pageData[1];\n case 1:\n $this-&gt;controller = $this-&gt;pageData[0];\n case 0:\n break;\n}\n</code></pre>\n\n<p>as you do not use breaks in cases it shold work like it is in your structure.</p>\n\n<p>last exit before bridge : you should test it esp. for syntax errors.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T07:50:26.760", "Id": "20838", "Score": "1", "body": "The switch syntax is correct, as is the logic (I believe). I must say though, I always avoid switch statements that fall through, and the way `default` is structured irks me a little. Definitely creative though! +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T10:04:21.433", "Id": "20854", "Score": "0", "body": "well using if's in this piece of code is just bad in terms of optimization... and yes i know this is just some web application, and yes i am obsessive ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T20:21:41.023", "Id": "20904", "Score": "0", "body": "I would be surprised if there's even a 1 us difference (probably even less than that)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T06:22:14.247", "Id": "12921", "ParentId": "12912", "Score": "2" } } ]
{ "AcceptedAnswerId": "12915", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T22:57:24.697", "Id": "12912", "Score": "3", "Tags": [ "php", "url-routing" ], "Title": "Setting controller, action, and values based on the number of URL chunks" }
12912
<pre><code>count = 0 def merge_sort(li): if len(li) &lt; 2: return li m = len(li) / 2 return merge(merge_sort(li[:m]), merge_sort(li[m:])) def merge(l, r): global count result = [] i = j = 0 while i &lt; len(l) and j &lt; len(r): if l[i] &lt; r[j]: result.append(l[i]) i += 1 else: result.append(r[j]) count = count + (len(l) - i) j += 1 result.extend(l[i:]) result.extend(r[j:]) return result unsorted = [10,2,3,22,33,7,4,1,2] print merge_sort(unsorted) print count </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T07:12:44.690", "Id": "20833", "Score": "0", "body": "Do you mean it to be a simple code review? Or is there any specific aspect of the code that you would like reviewed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T07:16:05.713", "Id": "20834", "Score": "0", "body": "I just want the code to be minimalistic and also readable... so if there is any improvement in that aspect then I would definitely like some positive criticism." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T09:56:28.700", "Id": "20853", "Score": "0", "body": "The code doesn't work as expected: change unsorted -> u_list" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-18T08:14:34.127", "Id": "198165", "Score": "1", "body": "Some of the following suggestions make the error of using pop(0). Unlike pop(), which pops the last element and takes O(1), s.pop(0) gives O(n) runtime (rearranging the positions of all other elements). This breaks the algorithmic O(nlogn) concept and turns the runtime to O(n^2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-19T05:56:02.943", "Id": "198323", "Score": "0", "body": "Added my own version for codereview here: http://codereview.stackexchange.com/questions/107928/inversion-count-via-divide-and-conquer" } ]
[ { "body": "<p>Rather than a global count, I would suggest using either a parameter, or to return a tuple that keeps the count during each recursive call. This would also assure you thread safety.</p>\n\n<pre><code>def merge_sort(li, c):\n if len(li) &lt; 2: return li \n m = len(li) / 2 \n return merge(merge_sort(li[:m],c), merge_sort(li[m:],c),c) \n\ndef merge(l, r, c):\n result = []\n</code></pre>\n\n<p>Since l and r are copied in merge_sort, we can modify them without heart burn. We first reverse the two lists O(n) so that we can use <em>s.pop()</em> from the correct end in O(1) (Thanks to @ofer.sheffer for pointing out the mistake).</p>\n\n<pre><code> l.reverse()\n r.reverse()\n while l and r:\n s = l if l[-1] &lt; r[-1] else r\n result.append(s.pop())\n</code></pre>\n\n<p>Counting is separate from the actual business of merge sort. So it is nicer to move it to a separate line.</p>\n\n<pre><code> if (s == r): c[0] += len(l)\n</code></pre>\n\n<p>Now, add what ever is left in the array</p>\n\n<pre><code> rest = l if l else r\n rest.reverse()\n result.extend(rest)\n return result\n\n\nunsorted = [10,2,3,22,33,7,4,1,2]\n</code></pre>\n\n<p>Use a mutable DS to simulate pass by reference.</p>\n\n<pre><code>count = [0]\nprint merge_sort(unsorted, count)\nprint count[0]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-18T08:12:34.617", "Id": "198163", "Score": "0", "body": "Unlike pop(), which pops the last element and takes O(1), s.pop(0) gives O(n) runtime (rearranging the positions of all other elements). This breaks the algorithmic O(nlogn) concept and turns the runtime to O(n^2)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-18T23:02:03.943", "Id": "198284", "Score": "0", "body": "Thank you, I did not realize that. Since it is a major problem, would you like to make an answer of your own (I will note your comment in my answer, and point to yours if you do that)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-19T06:00:39.847", "Id": "198324", "Score": "0", "body": "I added my own version for code review here: http://codereview.stackexchange.com/questions/107928/inversion-count-via-divide-and-conquer - I used a loop over k values (subarray). For each of them I run \"A[write_index]=value\" which is O(1)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T18:13:23.393", "Id": "12956", "ParentId": "12922", "Score": "7" } } ]
{ "AcceptedAnswerId": "12956", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T06:29:05.900", "Id": "12922", "Score": "9", "Tags": [ "python", "homework", "mergesort" ], "Title": "Inversion count using merge sort" }
12922
<p>I'm building an option panel for a Wordpress theme. I'm just learning PHP and I wonder if there is any better (shorter) way to generate the social media links. Here's what I came up with and even tho it works, I think there are cleaner way to write it</p> <pre><code>&lt;ul&gt; &lt;?php if ( of_get_option('mm_sm_vimeo') ) { ?&gt; &lt;li&gt; &lt;a href="&lt;?php echo of_get_option('mm_sm_vimeo'); ?&gt;"&gt;&lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/socials/ico_vimeo.png" alt="Vimeo"/&gt;&lt;/a&gt;&lt;span&gt;Vimeo&lt;/span&gt; &lt;/li&gt; &lt;?php } ?&gt; &lt;?php if ( of_get_option('mm_sm_gplus') ) { ?&gt; &lt;li&gt; &lt;a href="&lt;?php echo of_get_option('mm_sm_gplus'); ?&gt;"&gt;&lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/socials/ico_gplus.png" alt="Google Plus"/&gt;&lt;/a&gt;&lt;span&gt;Google Plus&lt;/span&gt; &lt;/li&gt; </code></pre> <p>Etc... etc... over 20 times.</p> <p>Maybe a loop or something? The problem is that I have a different Option name for each and I don't know how to handle it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:05:30.447", "Id": "20845", "Score": "0", "body": "Your code is scrambled, plesse edit it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:09:04.827", "Id": "20846", "Score": "0", "body": "Yes, there is a better way to write this, and yes, it would involve a loop. Is this the answer you're looking for?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:09:19.257", "Id": "20847", "Score": "5", "body": "wordpress and clean doesn't come together..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:20:55.203", "Id": "20848", "Score": "0", "body": "...but wordpress doesn't force you to switch back and forth between html and php rather than embedding html in php in html." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:38:43.493", "Id": "20849", "Score": "0", "body": "You should combine these options into one option. you can put an array in `add_option` and retrieve that array in `get_option`" } ]
[ { "body": "<p>You could take the common bits out into a function:</p>\n\n<pre><code>&lt;?php\nfunction my_thing($name, $title) {\n if ( of_get_option(\"mm_sm_$name\") ) {\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php echo of_get_option(\"mm_sm_$name\"); ?&gt;\"&gt;&lt;img src=\"&lt;?php echo get_template_directory_uri(); ?&gt;/images/socials/ico_&lt;?php echo $name ?&gt;.png\" alt=\"&lt;?php echo $title ?&gt;\"/&gt;&lt;/a&gt;&lt;span&gt;&lt;?php echo $title ?&gt;&lt;/span&gt;\n &lt;/li&gt;\n &lt;?\n }\n}\n\nmy_thing('vimeo', 'Vimeo');\nmy_thing('gplus', 'Google Plus');\n?&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:15:33.343", "Id": "12929", "ParentId": "12927", "Score": "2" } }, { "body": "<p>You can just refactor it.</p>\n\n<pre><code>&lt;?php $data = array('vimeo' =&gt; 'vimeo', 'gplus' =&gt; 'Google Plus'); ?&gt;\n&lt;ul&gt;\n&lt;?php foreach($data as $key=&gt;$val){\nif ( of_get_option('mm_sm_'.$key) ) { ?&gt;\n&lt;li&gt;\n&lt;a href=\"&lt;?php echo of_get_option('mm_sm_'.$key); ?&gt;\"&gt;&lt;img src=\"&lt;?php echo get_template_directory_uri(); ?&gt;/images/socials/ico_&lt;?php echo $key ?&gt;\" alt=\"&lt;?php echo $val; ?&gt;\"/&gt;&lt;/a&gt;&lt;span&gt;&lt;?php echo $val; ?&gt;&lt;/span&gt;\n&lt;/li&gt;\n&lt;?php } \n}?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p><strong>Note:</strong> Here the key point is the <code>$data</code> array. populate it and the loop will do the rest. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:17:04.123", "Id": "12931", "ParentId": "12927", "Score": "0" } }, { "body": "<p>You can define the data array and iterate through its elements:</p>\n\n<pre><code>&lt;ul&gt;\n&lt;?php\n$data = array(\n array('name' =&gt; 'Vimeo', 'option' =&gt; 'mm_sm_vimeo', 'icon' =&gt; 'ico_vimeo.png'),\n array('name' =&gt; 'Google Plus', 'option' =&gt; 'mm_sm_gplus', 'icon' =&gt; 'ico_gplus.png'),\n // other elements go here in the same format\n);\n\nforeach($data as $item) {\n if (of_get_option($item['option'])) {\n ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?= of_get_option($item['option'])?&gt;\"&gt;&lt;img src=\"&lt;?= get_template_directory_uri() ?&gt;/images/socials/&lt;?= $item['icon'] ?&gt;\" alt=\"&lt;?= $item['name'] ?&gt;\"/&gt;&lt;/a&gt;&lt;span&gt;&lt;?= $item['name'] ?&gt;&lt;/span&gt;\n &lt;/li&gt;\n &lt;?php\n }\n}\n?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>Or using templates and without explicit iterating:</p>\n\n<p>\n\n<pre><code>$data = array(\n array('name' =&gt; 'Vimeo', 'option' =&gt; 'mm_sm_vimeo', 'icon' =&gt; 'ico_vimeo.png'),\n array('name' =&gt; 'Google Plus', 'option' =&gt; 'mm_sm_gplus', 'icon' =&gt; 'ico_gplus.png'),\n);\n\nfunction printItem($item)\n{\n if (!of_get_option($item['option'])) {\n return;\n }\n $template = '&lt;li&gt;\n &lt;a href=\"%s\"&gt;&lt;img src=\"%s/images/socials/%s\" alt=\"%s\"/&gt;&lt;/a&gt;&lt;span&gt;%s&lt;/span&gt;\n &lt;/li&gt;';\n echo sprintf($template, of_get_option($item['option']), get_template_directory_uri(), $item['icon'], $item['name'], $item['name']);\n}\n\nfunction printData($data) {\n echo '&lt;ul&gt;';\n array_walk($data, 'printItem');\n echo '&lt;/ul&gt;';\n}\n\nprintData($data);\n</code></pre>\n\n<p>Anyway, main idea is not to duplicate some code 20 times, use data source (like array in this example) and iterate through its elements.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:20:13.020", "Id": "12932", "ParentId": "12927", "Score": "1" } }, { "body": "<p>I'm not familiary with wordpress so i can only give you some hints\nregarding the style of mixing php and html.\nUse the templating style of php. It will look a lot cleaner:</p>\n\n<pre><code>&lt;ul&gt;\n &lt;?php if ( of_get_option('mm_sm_vimeo') ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php echo of_get_option('mm_sm_vimeo'); ?&gt;\"&gt;&lt;img src=\"&lt;?php echo get_template_directory_uri(); ?&gt;/images/socials/ico_vimeo.png\" alt=\"Vimeo\"/&gt;&lt;/a&gt;&lt;span&gt;Vimeo&lt;/span&gt;\n &lt;/li&gt;\n &lt;?php endif; ?&gt;\n\n &lt;?php if ( of_get_option('mm_sm_gplus') ): ?&gt;\n &lt;li&gt;\n &lt;a href=\"&lt;?php echo of_get_option('mm_sm_gplus'); ?&gt;\"&gt;&lt;img src=\"&lt;?php echo get_template_directory_uri(); ?&gt;/images/socials/ico_gplus.png\" alt=\"Google Plus\"/&gt;&lt;/a&gt;&lt;span&gt;Google Plus&lt;/span&gt;\n &lt;/li&gt;\n &lt;?php endif; ?&gt;\n&lt;/ul&gt;\n</code></pre>\n\n<p>as for loops:</p>\n\n<pre><code>&lt;?php foreach($container as $var): ?&gt;\n &lt;html /&gt;\n&lt;?php endforeach; ?&gt;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:23:13.190", "Id": "20850", "Score": "0", "body": "i like this way cleaner" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:21:07.380", "Id": "12933", "ParentId": "12927", "Score": "0" } }, { "body": "<p>Very similar to a number of the answers already here. However, none are using heredoc and I think in this case it is cleaner because of all the variables you are trying to pass to HTML, especially on that one line.</p>\n\n<pre><code>$template_directory = get_template_directory_uri();\n$options = array(\n 'vimeo' =&gt; 'Vimeo',\n 'gplus' =&gt; 'Google Plus',\n //etc...\n);\n?&gt;\n\n&lt;ul&gt;\n\n&lt;?php\nforeach( $options AS $option =&gt; $name ) {\n $link = of_get_option( \"mm_sm_$option\" );\n\n echo &lt;&lt;&lt;HTML\n &lt;li&gt;\n &lt;a href=\"$link\"&gt;\n &lt;img src=\"$template_directory/images/socials/ico_$option.png\" alt=\"$name\"/&gt;\n &lt;/a&gt;\n &lt;span&gt;$name&lt;/span&gt;\n &lt;/li&gt;\n\nHTML;\n}\n?&gt;\n\n&lt;/ul&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T13:56:59.637", "Id": "12950", "ParentId": "12927", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T08:04:42.537", "Id": "12927", "Score": "1", "Tags": [ "php" ], "Title": "Generating social media links" }
12927
<p>I am running a Markov Chain Monte Carlo algorithm for updating a density distribution. There is a specific section of my code which tries to fill a very large matrix <code>thetha.mh</code> (of dimension 5000x2x60). the following code snippet is trying to fill the first dimension of my matrix, but the specific operation in second line of the loop is taking too much time.</p> <p>Does anybody know of a better way to improve the efficiency of this operation?</p> <pre><code>fhatt=kde(x=theta.mh[m1:m,s,t-1], h=hpi(theta.mh[m1:m,s,t-1])) p2=function(thetax) dkde(thetax, fhatt) fhatd=kde(x=deltat.mh[m1:m,s,t-1], h=hpi(deltat.mh[m1:m,s,t-1])) p3=function(deltatx) dkde(deltatx, fhatd) # P1 and P2 are two distribution updated from the previous values of tetha.mh through kernel density estimation h1=function(thetax) log(p1(y[s,t],thetax)*p2(thetax)) # h1 is the the logarithm of the multiplication of p1 and p2 (laplace form estimate) for(i1 in 2:5000) { thetas=rnorm(1,theta.mh[i1-1,s,t],stheta[i1,s,t]) r1[i1,s,t]=exp(h1(thetas)-h1(theta.mh[i1-1,s,t])) if (r1[i1,s,t]&gt;runif(1)) theta.mh[i1,s,t]=thetas else { theta.mh[i1,s,t]=theta.mh[i1-1,s,t] } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T00:13:17.830", "Id": "20858", "Score": "0", "body": "What do you mean by \"too much time\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T00:35:27.347", "Id": "20859", "Score": "0", "body": "It would help if you provide a reproducible example (code that I can paste directly into my console and run)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T01:12:03.517", "Id": "20860", "Score": "0", "body": "other generic comments include compiling your function, moving anything out of the loop that you can, and consider using `Rcpp` and `inline` to rewrite in C++ depending on your wizard skills" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T03:01:04.687", "Id": "20861", "Score": "0", "body": "How did you pre-allocate your matrix?" } ]
[ { "body": "<p>The functions you use (kde, dkde, hpi, ...) do not seem to be standard R functions and you are not very explicit on your exact data structur, so it's hard to help. Could you provide more info on that (packages used, ...)?</p>\n\n<p>What I think to realize though - but correct me if I'm wrong - is the following. When substituting <code>h1</code> in the second line of your loop with its function body, you could simplify the function and get rid of all exp and log, which should speed up your script at least a bit:</p>\n\n<pre><code> exp( h1(thetas) - h1(theta.mh[i1-1,s,t]) )\n--&gt; exp( log(p1(...)*p2(...)) - log(p1(...)*p2(...)))\n--&gt; exp(log(p1(...)*p2(...))) / exp(log(p1(...)*p2(...)))\n--&gt; p1(...)*p2(...) / p1(...)*p2(...)\n</code></pre>\n\n<p>that means, what your second line actually computes is:</p>\n\n<pre><code>p1(y[s,t],thetas)*p2(thetas) / p1(y[s,t],theta.mh[i1-1,s,t])*p2(theta.mh[i1-1,s,t])\n</code></pre>\n\n<p>I hope that is of some use to you...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T00:38:58.860", "Id": "12936", "ParentId": "12935", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T23:53:50.260", "Id": "12935", "Score": "3", "Tags": [ "matrix", "r" ], "Title": "Updating a density distribution" }
12935
<p>I have the following dataset</p> <pre><code>kkk&lt;-data.frame(days=1:100,positive=rbinom(100,1,0.05)) </code></pre> <p>Over the monitoring period of 100 days, if an event occurs then for that day <code>kkk$positive==1</code> else <code>kkk$positive==0</code></p> <p>The following function, samples <code>k=s.freq=1:12</code> number of times <code>j=s.length=1:30</code> consecutive elements from the sample space and checks if at least in one of the samples an event was recorded. The sample space consists of all possible <code>j</code> consecutive combinations of <code>kkk$days</code>. The elements of the sample space are overlapping. Before each of the <code>k=s.freq=1:12</code> samples, the sample space is reevaluated and elements that have common days with the sampled element are removed before the next sampling occurs (for the total of <code>k</code> samplings).</p> <pre><code>my.sampling&lt;-function(days, status, s.length, s.freq, iter){ start&lt;-Sys.time() #build the data frame ddd&lt;-data.frame(days=days, positive=status) #length of each sample j&lt;-s.length #Buld the sample space monitor.ss&lt;-matrix(nrow=dim(ddd)[1]-j+1, ncol=j+1) n.row&lt;-dim(ddd)[1]-j+1 #Create the elements of sample space: each row of the monitor.ss is an element of the sample space for (i in 1:j){ monitor.ss[,i]&lt;-i:(n.row-1+i) } rm(i) #adds if the each of the possible samples of the sample space at least one event was observed or not monitor.ss[,j+1]&lt;-apply(monitor.ss,1,function(x) { r.low&lt;-range(x,na.rm=T)[1] r.high&lt;-range(x,na.rm=T)[2] return(as.numeric(sum(ddd$positive[r.low:r.high])&gt;0))}) #Build the initial sample space as data frame sampling.start&lt;-data.frame(monitor.ss) suc.list&lt;-rep(NA, iter) #Initiate a vector to keep track of successes #Now the sampling takes place for (i in 1:iter) { #for each iteration sampling.start&lt;-data.frame(monitor.ss) k&lt;-s.freq #number of samples drawn from the sample space k.t=0 #controller to break the while loop suc&lt;-0 while (k.t&lt;=k | dim(sampling.start)[1]&gt;0) { #breaks the while loop if k reaches the specified limit (k=s.freq) or if the reduction of the sample space (see below) does not leave any elements in the sample space s&lt;-sampling.start[sample(nrow(sampling.start),1),] #samples the first trial suc&lt;-suc+s[1,j+1] #adds up if there is a success or not ( a tleast one event in the sample was observed) sampling.start &lt;- sampling.start[apply(sampling.start, 1, function(x) !any(x %in% as.numeric(s[,1:j]))),] #sample space reduction: Elements of the sample space that intersect with the sample that was just selected are removed from the sample space before the next sampling occurs k.t&lt;-k.t+1 #controller for the wile loop } suc.list[i]&lt;-(suc/k.t) } print(Sys.time()-start) message("") #hist(suc.list, breaks=sqrt(iter)) return(suc.list) } </code></pre> <p>For example:</p> <pre><code>my.sampling(kkk$days, kkk$positive, s.length=3, s.freq=5, iter=300) </code></pre> <p>My problem is that the function requires about 100msec for each iteration and I need to run this function about 100.000 times with at least 1000 iterations each time. I have used preallocation of the vectors and apply to speed things up, however its still too slow. </p> <p>Parallel processing is applicable to my problem as I can split the data on which the function will have to run on multiple cores, however if my calculations are right I need about 120 days of processing pro CPU core. </p> <p>Is this possible to reduce the run time of the function? I have tried cpmfun but without much improvement. Otherwise I have to resort to some type of AWS EC2 solution. </p> <p>Thanks a lot</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T17:24:44.933", "Id": "20862", "Score": "2", "body": "You can, for one, replace that entire allocation of `monitor.ss` where you are \"building sample space\" with this single line: \n\n `monitor.ss <- embed(1:dim(ddd)[1], j)[ , j:1]`. I haven't been able to follow your problem description, however." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T17:38:26.690", "Id": "20863", "Score": "1", "body": "Nice @DWin, However that loop doen't take any time. His main problen is in the last loop. I couldn't follow either." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T22:26:38.237", "Id": "20864", "Score": "0", "body": "Thanks @DWin. However as Iselzer writes this parts does not consume significant CPU time. I also think the last part is the most CPU intensive. The most important part of the sampling is the reevaluation and reduction of the sample space (the while loop) before the next consecutive sampling. Any ideas if the function or this part can get faster?" } ]
[ { "body": "<p>This question is probably not appropriate for stackoverflow, since it requires mainly code review.</p>\n\n<p>First of all, there is a logics problem with your while loop. Changing <code>|</code> to <code>&amp;</code> reduces the number of loops considerably.</p>\n\n<p>Furthermore you should not use dataframes, if you can use a matrix.</p>\n\n<pre><code>my.sampling1&lt;-function(days, status, s.length, s.freq, iter){\n start&lt;-Sys.time()\n\n #build the data frame\n ddd&lt;-data.frame(days=days, positive=status)\n\n#length of each sample\n j&lt;-s.length\n\n#Buld the sample space\n monitor.ss&lt;-matrix(nrow=dim(ddd)[1]-j+1, ncol=j+1)\n n.row&lt;-dim(ddd)[1]-j+1\n\n #Create the elements of sample space: each row of the monitor.ss is an element of the sample space\n for (i in 1:j){\n monitor.ss[,i]&lt;-i:(n.row-1+i)\n }\n rm(i)\n\n\n #adds if the each of the possible samples of the sample space at least one event was observed or not\n monitor.ss[,j+1]&lt;-apply(monitor.ss,1,function(x) {\n r.low&lt;-range(x,na.rm=T)[1]\n r.high&lt;-range(x,na.rm=T)[2]\n return(as.numeric(sum(ddd$positive[r.low:r.high])&gt;0))}) \n\n\nsuc.list&lt;-rep(NA, iter) #Initiate a vector to keep track of successes\n\n #Now the sampling takes place\n\n k&lt;-s.freq #number of samples drawn from the sample space\n for (i in 1:iter) { #for each iteration\n\n #do not convert to data.frame\n sampling.start&lt;-monitor.ss\n\n k.t=0 #controller to break the while loop\n suc&lt;-0\n\n #use &amp; to stop the loop if one condition is not fullfilled, second condition changed because a matrix is used instead of a data.frame\n while (k.t&lt;=k &amp; !is.null(nrow(sampling.start))) { #breaks the while loop if k reaches the specified limit (k=s.freq) or if the reduction of the sample space (see below) does not leave any elements in the sample space\n #set.seed(k.t*i) #use set.seed to test if results are identical\n s&lt;-sampling.start[sample(nrow(sampling.start),1),] #samples the first trial\n suc&lt;-suc+s[j+1] #adds up if there is a success or not ( a tleast one event in the sample was observed)\n sampling.start &lt;- sampling.start[apply(sampling.start, 1, function(x) !any(x %in% as.numeric(s[1:j]))),] #sample space reduction: Elements of the sample space that intersect with the sample that was just selected are removed from the sample space before the next sampling occurs\n k.t&lt;-k.t+1 #controller for the wile loop\n }\n\n suc.list[i]&lt;-(suc/k.t)\n\n }\n print(Sys.time()-start)\n message(\"\")\n #hist(suc.list, breaks=sqrt(iter))\n return(suc.list)\n}\nkkk&lt;-data.frame(days=1:100,positive=rbinom(100,1,0.05)) \nres1&lt;-my.sampling1(kkk$days, kkk$positive, s.length=3, s.freq=5, iter=20)\n</code></pre>\n\n<p>This is already faster. To make it even more efficient, I would try to avoid apply inside the loop (could an algebraic operation be used instead?) and try to vectorize. Furthermore you can tidy up. There are some unnecessary assignments inside the function.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T11:52:34.497", "Id": "12938", "ParentId": "12937", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-21T17:05:00.247", "Id": "12937", "Score": "2", "Tags": [ "performance", "r" ], "Title": "Speed up a sampling function" }
12937
<p>I have a question about lock upgrading.Specifically what bothers me is between readlock.unlock() and following writelock.lock()... I am providing a nearly complete implementation for a sample cache.I just omitted actual loading of cached data from database. </p> <p>I appreciate if you can review the code and share your thoughts. I tried to express my concern in the java comments . My question is how to correctly synchronize in order to avoid rechecking the cache in load cache.</p> <pre><code>import java.util.*; import java.util.concurrent.*; import java.util.concurrent.locks.*; public class JavaRanchSampleCache { private ConcurrentHashMap&lt;String, ReentrantReadWriteLock&gt; refreshLocks = new ConcurrentHashMap&lt;String, ReentrantReadWriteLock&gt;(); private ConcurrentHashMap&lt;String, HashMap&lt;String, String&gt;&gt; cacheData = new ConcurrentHashMap&lt;String, HashMap&lt;String, String&gt;&gt; (); public HashMap&lt;String, String&gt; getCachedData(String cacheKey) { ReentrantReadWriteLock lock = refreshLocks.get(cacheKey); if(lock==null) { lock=new ReentrantReadWriteLock(); ReentrantReadWriteLock previous=refreshLocks.putIfAbsent(cacheKey, lock); if(previous!=null)//null means no previous lock object,first time usage lock=previous; } //we have a safe lock at this point try { lock.readLock().lock();//read the cached item for correspoding cacheKey HashMap&lt;String, String&gt; cachedItem=cacheData.get(cacheKey); if(cachedItem==null)//it is not cached yet.Load to cache on first request { cachedItem=loadItemExpensive(cacheKey); } return cachedItem;//return the cached item. } finally { lock.readLock().unlock(); } } private HashMap&lt;String, String&gt; loadItemExpensive(String cahceKey) { ReentrantReadWriteLock lock = this.refreshLocks.get(cahceKey); HashMap&lt;String, String&gt; cachedItem=null; try { /*these two lines are for lock upgrading * BUT what happens if another thread interacts between line1 and line2 * I mean after the readlock is relased,some OTHER thread might gain the writelock * before this thread and perform loaddata and update cache operation. * So should I check the cache once more to see if some other thread * has updated the cache? I 'feel' that I should,but it is ugly,i need some clever way. */ lock.readLock().unlock();//line1 lock.writeLock().lock();//line2 /*omitted load data from some expensive store such as database or remote server*/ return cachedItem; } finally { lock.readLock().lock();//writelock owner can grant readlock immediately. lock.writeLock().unlock();//lock released } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T16:34:51.413", "Id": "20867", "Score": "0", "body": "From the javadoc: \"Reentrancy also allows downgrading from the write lock to a read lock, by acquiring the write lock, then the read lock and then releasing the write lock. However, upgrading from a read lock to the write lock is not possible.\" So you need to find a way..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T17:21:18.730", "Id": "20868", "Score": "0", "body": "Actually i am aware of this. I can easily write an if statement to check cacheData hashmap for existance however i was asking for best practise-pattern for this scenario." } ]
[ { "body": "<p>Your fears are valid. Once you let go of the lock, all bets are off. When you get the write lock, you <em>will</em> need to check if another thread has mutated the cache. Don't think of it as \"ugly\"; think of it as \"correct\". Continue to use comments to explain what you're doing and why you're doing it.</p>\n\n<p>In a nutshell, a read/write lock can't support both upgrading and downgrading. Multiple locks must always be acquired in the same order (in this case, write then read), otherwise a deadly embrace can occur. So when going the other way (read then write), you <em>must</em> let go of the lock, at which point any decisions you made based on current state must be reconsidered.</p>\n\n<p>But there are other options, depending on the details of your situation.</p>\n\n<p>One is to always a get a write lock in anticipation of needing to make a modification and downgrading to a read lock if the data's already there. This is probably not what you want, especially if the majority of operations are read-only, as it will lead to lock contention and poor response times under load.</p>\n\n<p>Other options might involve allowing multiple threads to (redundantly) perform the expensive load, and acquiring the write lock just at the moment of insertion to the table. Or it might be appropriate to just blindly overwrite the existing entry (in this last case, all you would really need is ConcurrentHashMap) . It all depends on the scenario what you're willing to tolerate. </p>\n\n<p>Hope this helps.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T17:33:44.070", "Id": "12940", "ParentId": "12939", "Score": "4" } }, { "body": "<p>This is an old question, but here's both a solution to the problem, and some background information.</p>\n\n<p>If you need to safely acquire a write lock without first releasing a read lock, take a look at a different type of lock instead, a <em>read-write-<strong>update</em></strong> lock.</p>\n\n<p>I've written a ReentrantReadWrite_Update_Lock, and released it as open source under an Apache 2.0 license <a href=\"http://code.google.com/p/concurrent-locks/\" rel=\"nofollow noreferrer\">here</a>. I also posted details of the approach to the JSR166 <a href=\"http://cs.oswego.edu/pipermail/concurrency-interest/2013-July/011621.html\" rel=\"nofollow noreferrer\">concurrency-interest mailing list</a>, and the approach survived some back and forth scrutiny by members on that list.</p>\n\n<p>The approach is pretty simple, and as I mentioned on concurrency-interest, the idea is not entirely new as it was discussed on the Linux kernel mailing list at least as far back as the year 2000. Also the .Net platform's <a href=\"http://msdn.microsoft.com/en-us/library/system.threading.readerwriterlockslim.aspx\" rel=\"nofollow noreferrer\">ReaderWriterLockSlim</a> supports lock upgrade also. So effectively this concept had simply not been implemented on Java (AFAICT) until now.</p>\n\n<p>The idea is to provide an <em>update</em> lock in addition to the <em>read</em> lock and the <em>write</em> lock. An update lock is an intermediate type of lock between a read lock and a write lock. Like the write lock, only one thread can acquire an update lock at a time. But like a read lock, it allows read access to the thread which holds it, and concurrently to other threads which hold regular read locks. The key feature is that the update lock can be upgraded from its read-only status, to a write lock, and this is not susceptible to deadlock because only one thread can hold an update lock and be in a position to upgrade at a time.</p>\n\n<p>This supports lock upgrade, and furthermore it is more efficient than a conventional readers-writer lock in applications with <em>read-before-write</em> access patterns, because it blocks reading threads for shorter periods of time.</p>\n\n<p>Example usage is provided on the <a href=\"http://code.google.com/p/concurrent-locks/\" rel=\"nofollow noreferrer\">site</a>. The library has 100% test coverage and is in Maven central.</p>\n\n<p>Note there is a similar question <a href=\"https://stackoverflow.com/questions/464784/java-reentrantreadwritelocks-how-to-safely-acquire-write-lock\">here</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-13T12:01:27.303", "Id": "31231", "ParentId": "12939", "Score": "3" } } ]
{ "AcceptedAnswerId": "12940", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-20T16:31:54.357", "Id": "12939", "Score": "2", "Tags": [ "java", "locking", "concurrency" ], "Title": "ReentrantReadWriteLock lock upgrade method" }
12939
<p>I'm working on my way to write most efficient, reusable and robust code, and this is why I'd like to receive some support. I've written a datetimepicker script that allows datetime chosing, and a shortcut button that will subtract from higher date (the right input) a variable number of minutes:</p> <p>Is there a way to simplify my code even more?</p> <pre><code>&lt;form&gt; &lt;input type="text" name="poczatek" id="od" /&gt; &lt;input type="text" name="koniec" id="do" /&gt; &lt;input type="button" value="10" class="odejmijCzas"/&gt; &lt;input type="button" value="20" class="odejmijCzas"/&gt; &lt;input type="button" value="30" class="odejmijCzas"/&gt; &lt;/form&gt; </code></pre> <p><strong>JavaScript</strong></p> <pre><code>dateTimeFormat = new Object(); dateTimeFormat.dwucyfrowa = function(m) { return m &lt; 10 ? '0' + m : m; } dateTimeFormat.format = function(date) { return date.getFullYear() + '-' + dateTimeFormat.dwucyfrowa(date.getMonth() + 1) + '-' + dateTimeFormat.dwucyfrowa(date.getDate()) + ' ' + dateTimeFormat.dwucyfrowa(date.getHours()) + ':' + dateTimeFormat.dwucyfrowa(date.getMinutes()); } $(document).ready(function() { inputOd = $("#od"); inputDo = $("#do"); inputOd.add(inputDo).datetimepicker({ changeMonth: 'true' }); currentTime = new Date(); inputOd.add(inputDo).val(dateTimeFormat.format(currentTime)); $('.odejmijCzas').click(function() { odejmijCzas($(this).attr('value')); }); }); function odejmijCzas(liczbaMinut) { czasDo = new Date(inputDo.val()); roznicaCzasu = czasDo.getTime() - liczbaMinut * 1000 * 60; czasOd = new Date(); czasOd.setTime(roznicaCzasu); inputOd.val(dateTimeFormat.format(czasOd)); }​ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T07:31:08.047", "Id": "20883", "Score": "0", "body": "Are you having a problem with your code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T07:31:24.933", "Id": "20884", "Score": "0", "body": "no it's working fine, but i'm wondering if i can shorten it even more" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T07:32:51.243", "Id": "20885", "Score": "0", "body": "Well this is programming question, i want to know if i can make the code shorter" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T07:33:45.590", "Id": "20886", "Score": "2", "body": "one great way to improve it - is not to use Polish for variable names" } ]
[ { "body": "<p>A quick review:</p>\n\n<p><strong>High Level Overview</strong></p>\n\n<p>This code is okay except for 2 major items: you are not declaring your variables, making them escape all scope. And you use non-English variable names and function names, not every developer speaks Polish, though we should all understand English.</p>\n\n<p><strong>Naming</strong></p>\n\n<ul>\n<li>English is the one true language for naming, please find English equivalents for <code>odejmijCzas</code>, <code>roznicaCzasu</code> etc.</li>\n</ul>\n\n<p><strong>Idioms and Custom</strong></p>\n\n<ul>\n<li>Do not use <code>= new Object();</code>, use <code>= {}</code></li>\n</ul>\n\n<p><strong>Scope</strong></p>\n\n<ul>\n<li>You must declare everything with <code>var</code>, <code>let</code>, or <code>const</code></li>\n<li>I would declare <code>dateTimeFormat</code> and <code>odejmijCzas</code> inside <code>$(document).ready(function() {</code> to keep the namespace clean </li>\n</ul>\n\n<p><strong><a href=\"http://jshint.com/\" rel=\"nofollow noreferrer\">JSHint.com</a></strong></p>\n\n<ul>\n<li>Consider using <a href=\"http://jshint.com/\" rel=\"nofollow noreferrer\">http://jshint.com/</a> to perfect your code, most of these items were found by this tool as well</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-11T16:51:01.737", "Id": "152364", "ParentId": "12951", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-05-21T07:27:31.803", "Id": "12951", "Score": "1", "Tags": [ "javascript", "jquery", "datetime" ], "Title": "Datetimepicker script" }
12951
<p>I am trying to compose an illustrative example which shows how to implement move semantics on an object that will be stored in a <code>vector</code>.</p> <p>Please consider the following code, which is my illustrative example so far. It is designed to be a canonical, pedantically correct implementation of an object that implements move semantics, does not implement copy semantics, and can be stored in a <code>vector&lt;&gt;</code> (Where T is Moveable, below). How did I do?</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;vector&gt; #include &lt;list&gt; #include &lt;algorithm&gt; #include &lt;memory&gt; #include &lt;iterator&gt; using namespace std; class Moveable { public: string foo_; string bar_; Moveable(Moveable&amp;&amp; rhs) : foo_(std::move(rhs.foo_)), bar_(std::move(rhs.bar_)) {} // move construction Moveable(const string&amp; foo) : foo_(foo) {}; // convert construction Moveable&amp; operator=(Moveable&amp;&amp; rhs) // move assignment { foo_ = std::move(rhs.foo_); bar_ = std::move(rhs.bar_); return * this; } private: Moveable(const Moveable&amp;); // not defined, not copy-constructible Moveable&amp; operator=(const Moveable&amp;); // not defined, not copy-assignable Moveable(); // not defined, not default constructible }; Moveable generate_it() { static string foo ; if( foo.empty() || foo[0] == 'z' ) foo.insert(0, 1, 'a'); else foo[0]++; return foo; } int main() { typedef vector&lt;Moveable&gt; Moveables; Moveables v; generate_n(back_inserter(v), 1024, &amp;generate_it); cout &lt;&lt; v.size() &lt;&lt; endl; string target = "zzz"; auto that = find_if(v.begin(), v.end(), [target](const Moveables::value_type&amp; it) -&gt; bool { return it.foo_ == target; }); if( that != v.end() ) v.erase(that); sort(v.begin(), v.end(), [](const Moveables::value_type&amp; lhs, const Moveables::value_type&amp; rhs) -&gt; bool { return lhs.foo_ &gt; rhs.foo_; }); cout &lt;&lt; v.size() &lt;&lt; endl; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T17:18:48.853", "Id": "20896", "Score": "0", "body": "I had posted another question very similar to this, but deleted it and replaced it with this one. The other question had used `unique_ptr` which ultimately was orthogonal to what I was really going for." } ]
[ { "body": "<ul>\n<li><p>One small error: Mark the move constructor as <code>noexcept</code>, otherwise <a href=\"https://stackoverflow.com/q/10127603/1968\">there are situations where it won’t be used</a>. The linked case is different since the class has a copy-constructor, yet I can imagine that there are still situations where it matters, especially since your copycon isn’t deleted, just private and undefined.</p></li>\n<li><p>Why is the destructor virtual? If the example is supposed to be minimal then this might be distracting.</p></li>\n<li><p>In <code>generate_it</code>:</p>\n\n<pre><code>return std::move(Moveable(foo));\n</code></pre>\n\n<p>The <code>std::move</code> here is redundant, since you are returning a temporary. What’s more, the explicit constructor call is redundant too, since the constructor isn’t marked as <code>explicit</code>. Just <code>return foo;</code> will do.</p></li>\n<li><p>The <code>find_if</code> call could be replaced by vanilla <code>find</code>, using temporary construction again:</p>\n\n<pre><code>auto that = find(v.begin(), v.end(), target);\n</code></pre></li>\n<li><p>Finally, in the <code>sort</code> call, why aren’t the arguments declared <code>const&amp;</code>? Granted, makes the line even longer as it stands this is inconsistent with the const-correctness illustrated in the <code>find_if</code> call.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:35:19.910", "Id": "21157", "Score": "0", "body": "+1: various replies. 1) The destructor was an artifact of my testing durig development. Since its implementation was trivial, and the tor was public, I've removed it entirely." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:38:41.047", "Id": "21158", "Score": "0", "body": "2) `noexcept` is not supported by MSVC10. Sad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:40:33.137", "Id": "21159", "Score": "0", "body": "3) Fixed `generate_it` 4) fixed `sort` call. These were simply part of the harness, but it's important that the whole thing is correct." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T12:37:37.287", "Id": "12972", "ParentId": "12954", "Score": "6" } } ]
{ "AcceptedAnswerId": "12972", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T17:17:48.227", "Id": "12954", "Score": "7", "Tags": [ "c++", "c++11" ], "Title": "Canonical Implementation of Move Semantics" }
12954
<p>I took a base from <a href="http://www.webdeveloper.com/forum/showthread.php?t=161951" rel="nofollow">here</a> and built on it. You call the function with <code>onkeypress</code> (hence live changing).</p> <p>The function gives output like this for domestic numbers:</p> <blockquote> <p>(123) 456–7890</p> </blockquote> <p>When the numbers pass the above character limit (13), the function outputs international numbers like this:</p> <blockquote> <p>+12 (345) 678-9012</p> </blockquote> <p>It doesn't handle backspacing elegantly (reformatting), which is on my to-do list. I'm looking for feedback on how to improve.</p> <pre><code> var mask = function(content) { var val = content.value.split(''); if (val.length &gt; 13) { tel = '+' } else {tel = '('} for(var i=0; i&lt; val.length; i++) { if(val[i] == '+'){ val[i]=''; } if(val[i] =='('){ val[i]=''; } if(val[i]==')'){ val[i]=''; } if(val[i]==' '){ val[i]=''; } if(val[i]=='-'){ val[i]=''; } } for(var i=0; i&lt;val.length; i++){ if (i==3){ if (val.length&gt;13) { val[i]= ' (' + val[i]; } else { val[i]=val[i]+') '; } } if (i==7){ if (val.length&gt;13) { val[i]= val[i] + ') '; if (val[i+2] == '–') { val[i+2]=''; val[i+5]='–' } } } if(i==8 &amp;&amp; val[i+1] != '–'){ if (val.length &lt;= 13) { val[i]=val[i]+'–'; } } tel=tel+val[i]; } content.value=tel; }; </code></pre>
[]
[ { "body": "<p><a href=\"http://www.regular-expressions.info/\" rel=\"nofollow\">Regular expressions</a> are a quicker way to get it done. Here's a naïve implementation that's (I believe) functionally equivalent to yours:</p>\n\n<pre><code>var mask = function (content) {\n var val = content.value.replace(/[^\\d]/g, ''); // Remove anything that's not a digit\n if( val.length &lt;= 10 ) { // US number\n content.value = val.replace(/^(\\d{3})(\\d{3})(\\d*)$/, '($1) $2-$3');\n } else { // Other\n content.value = val.replace(/^(\\d{2})(\\d{3})(\\d{3})(\\d*)$/, '+$1 ($2) $3-$4');\n }\n};\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/qZGGF/1/\" rel=\"nofollow\">Here's a live demo</a></p>\n\n<p>But this is far, far from perfect. There are many, many things to consider.</p>\n\n<p>For starters, non-US numbers aren't necessarily longer than US ones. My own number is just 8 digits (or 10, if you count the country digits - or 12 if you use \"00xx\" instead of \"+xx\" for the country code). So if I wrote my phone number (as I normally would) as \"+xx xx xx xx xx\", it'd be formatted as a US number - which it isn't. If I wrote \"00xx xx xx xx xx\", I'd get \"+00 ...\", which is also wrong since it's an invalid country code.</p>\n\n<p>On top of that, there's <a href=\"http://en.wikipedia.org/wiki/Local_conventions_for_writing_telephone_numbers\" rel=\"nofollow\">a ton of different local conventions</a> for how to write phone numbers.</p>\n\n<p>Point is that you can't go by the phone-number-length alone.</p>\n\n<p>Regardless of how far you want to go with it, though, regular expressions will come in handy. <a href=\"http://gskinner.com/RegExr/\" rel=\"nofollow\">Here's a nice interactive reg exp demo/tester</a> to get you started.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T01:11:41.730", "Id": "12963", "ParentId": "12958", "Score": "3" } } ]
{ "AcceptedAnswerId": "12963", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T21:12:17.760", "Id": "12958", "Score": "4", "Tags": [ "javascript", "formatting" ], "Title": "Liveupdate phone number forms and test for international numbers" }
12958
<p>Recently me and colleague had a discussion about the following piece of code (simple bool function that checks if string is a number, <code>+1000</code> not allowed, <code>-1000</code>, <code>1234</code> ... allowed). </p> <p>He felt that it was hackish, while I thought it was nice, clean and elegant (since it uses STL, not hand made loops).<br> So is this a judgement call or one of us is wrong? Is this code elegant or hack?</p> <pre><code> bool validate(const std::string&amp; m) { if (m.empty()) return false; return m.end() == find_if(*m.begin() == '-'? ++m.begin() : m.begin(), m.end(), not1(ptr_fun(isdigit))); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T21:40:54.917", "Id": "20909", "Score": "0", "body": "[Don't cross post](http://stackoverflow.com/questions/11163638/is-this-code-elegant-or-hack#comment14643018_11163638)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T20:30:50.127", "Id": "20911", "Score": "2", "body": "It's not elegant if it has code for special cases (that's part of *my* definition of elegant)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T20:31:16.110", "Id": "20912", "Score": "2", "body": "For somebody unfamiliar with stl, this is unreadable. Simple for loop is easy, and understood by anybody" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T20:31:19.207", "Id": "20913", "Score": "3", "body": "It seems pretty darn hard to read to me... I would never do so many things in one statement." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T20:35:04.830", "Id": "20914", "Score": "3", "body": "@elmes: Even for somebody *extremely* familiar with STL, this is damned hard to read." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T20:41:34.197", "Id": "20916", "Score": "0", "body": "I don't see anything wrong with your approach (i.e. I would find it unsurprising), but apparently I'm the odd one out here..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T21:33:55.580", "Id": "20918", "Score": "0", "body": "@ildjam - yeah, like I said I consider it very elegant. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T00:41:03.713", "Id": "20931", "Score": "2", "body": "I have nothing against the algorithms. But would be better if you did not try and do it in one line. One list does not equal elegant. Easy to read (at a glance) equal elegant." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T10:16:53.563", "Id": "20935", "Score": "0", "body": "@elmes Irrelevant. Someone unfamiliar with STL doesn’t count for anything. But there are other objections to the code. That it doesn’t work, for instance …)." } ]
[ { "body": "<p>I had to really look at your code and think about what it was doing before I figured it out. That tells me that this code is not elegant by my definition of \"elegant\". My definition of elegant is something like,</p>\n\n<blockquote>\n <p>Easy to understand, easy to maintain, efficient in execution, robust.</p>\n</blockquote>\n\n<p>I would suggest something like this as a start:</p>\n\n<pre><code>if( m.empty() )\n return false;\n\nstring::iterator start = m.begin();\nif( *start == '-' )\n ++start;\n\nif( m.end() == find_if( start, m_end(), not1(ptr_fun(isdigit)) ))\n return true;\nelse\n return false;\n</code></pre>\n\n<p>Not much caring for the use of <code>find_if</code>, I'd refine it to:</p>\n\n<pre><code>if( m.empty() )\n return false;\n\nstring::size_type pos = 0;\nif( m[0] == '-' )\n pos = 1;\n\nif( m.find_first_not_of(\"0123456789\", pos) == m.end() )\n return true;\nelse\n return false;\n</code></pre>\n\n<p>I find this to be much more elegant than the 1-liner you wrote. It's more code, sure. But it is exceedingly simple to understand and maintain. You found a bug yourself just by brain-compiling it. That's what code should look like.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T22:04:25.250", "Id": "20922", "Score": "2", "body": "if i compiled and ran in my head correctly second transformation returns true for \"42-1729\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T22:45:24.590", "Id": "20924", "Score": "0", "body": "@NoSenseEtAl: Edited, please take a look." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T22:58:52.663", "Id": "20926", "Score": "2", "body": "i guess you also need to remove minus from find_first_not_of, but it is just a minor thing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T23:32:16.683", "Id": "20928", "Score": "0", "body": "@NoSenseEtAl: Done." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T10:17:25.903", "Id": "20936", "Score": "2", "body": "`if (…) return true; else return false;` is a *huge* antipattern in my book." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T14:24:20.507", "Id": "20947", "Score": "1", "body": "`return ( m.find_first_not_of(\"0123456789\", pos) == m.end() );` would be preferable, imho." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T08:27:37.367", "Id": "21015", "Score": "0", "body": "I personally don't like the `find_first_not_of(\"0123456789\")`. Though I can't actually think of a situation were this would not work correctly, it makes me have a nagging suspicion that there is some corner case (maybe with locals) that may fail. I would prefer the use something standard that actually checks to see if the whole value is a number (like strtol)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-18T16:59:58.503", "Id": "212028", "Score": "0", "body": "`( m.find_first_not_of(\"0123456789\", pos) == m.end() )` gives me a compile time error: \"Invalid operands to binary expression\". This one is good: `( m.find_first_not_of(\"0123456789\", pos) == string::npos )`" } ], "meta_data": { "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T21:44:18.680", "Id": "12960", "ParentId": "12959", "Score": "4" } }, { "body": "<p>I think in this case, pretty much pure C does the job as well as anything:</p>\n\n<pre><code>bool check_num(std::string const &amp;in) {\n char *end;\n\n strtol(in.c_str(), &amp;end, 10);\n return !in.empty() &amp;&amp; *end == '\\0';\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T08:32:28.297", "Id": "21017", "Score": "1", "body": "Corner case is that std::string allows '\\0' within the string. Unlikely to fail but not foolproof." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T07:40:28.997", "Id": "12966", "ParentId": "12959", "Score": "2" } }, { "body": "<p>If you insist on using <code>find_if</code> (fine by me), and not mutating variables (fine by me as well!), your code still suffers from three deficiencies:</p>\n\n<ol>\n<li>Too much happening in a single statement. <em>Separate</em>.</li>\n<li>Why <code>*m.begin()</code> instead of <code>m.front()</code> or even <code>m[0]</code>?</li>\n<li><code>++</code> first and foremost mutates a value. <code>++m.begin()</code>, even though it compiles, smells, since we discard the mutated value and just use the value returned by the expression. <em>This</em> definitely qualifies as a hack.</li>\n</ol>\n\n<p>But since <code>string::iterator</code> is a random-access iterator, you can just write <code>+ 1</code>. In cases where that doesn’t work, there’s now <a href=\"http://en.cppreference.com/w/cpp/iterator/next\" rel=\"nofollow\"><code>std::next</code></a> which calls <code>std::advance</code> internally and returns the modified result.</p>\n\n<pre><code>bool validate(const std::string&amp; m) \n{\n if (m.empty()) \n return false;\n\n auto begin = m[0] == '-' ? std::next(m.begin()) : m.begin();\n return find_if(begin, m.end(), not1(ptr_fun(is_digit))) == m.end();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T13:58:30.387", "Id": "20943", "Score": "0", "body": "@3. what variable, string or it returned by m.begin()? Afaik it modifies iterator, so it is legit. std::string s=\"C++11\";\n ++s.begin();\n ++s.begin();\n ++s.begin();\n char c=*s.begin();\n assert (c='S');" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T14:08:19.983", "Id": "20944", "Score": "0", "body": "@NoSenseEtAl I take that objection back partially. However, the operation is still not really meaningful, since `++` *modifies* its argument. But we discard that modified value, since it’s a temporary. This still works since prefix `++` also *returns* the modified value but it’s still not an entirely meaningful operation – the side-effect was just ignored." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T14:10:37.657", "Id": "20945", "Score": "0", "body": "still I dont get your objection, that temporary lives long enough to be used as input param (begin iterator for find_if). So to make it clear is it a stye or correctness objection?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T14:15:53.593", "Id": "20946", "Score": "0", "body": "@NoSenseEtAl It’s an objection of style, *not* of correctness (it was initially, but that was my mistake, because the style confused me)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T14:29:34.697", "Id": "20948", "Score": "0", "body": "Ah, just noticed you posted an answer, going for the sane return nonetheless. `if (…) return true; else return false;` made me chuckle." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:34:36.127", "Id": "20955", "Score": "0", "body": "I'd use `auto const begin = m.begin() + (m[0] == '-');`, maybe add a conditional if I didn't want to abuse the implicit conversion to int." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T21:53:00.123", "Id": "20978", "Score": "0", "body": "@AntonGolov Spot-on: I’m against using the implicit `bool <=> int` conversion. Apart from that, adding 1 is of course a good solution (see answer) – I wanted to showcase the general case that also works for non-random-access iterators." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T08:22:37.343", "Id": "21014", "Score": "0", "body": "@AntonGolov: Yep I agree that lines readability can improved with your technique. But I am with Konrad and don;t like the implicit bool -> int conversion. So: `begin = m.begin() + (m[0] == '-') ? 1 : 0;`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T09:35:41.073", "Id": "21021", "Score": "0", "body": "I confess that I do like the implicit conversion to `int`, as long as it's clearly demarcated by parentheses. But then, I'm also very used to the Iverson bracket which I've found to be *incredibly* useful. I think I would prefer an explicit conversion to the conditional, though." } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T10:26:24.940", "Id": "12968", "ParentId": "12959", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-22T21:31:50.903", "Id": "12959", "Score": "4", "Tags": [ "c++", "stl" ], "Title": "Checking if a string is a number with STL" }
12959
<p>I am new to MVC and Zend, so I have little idea what I am doing at the moment, but here is my question.</p> <p>The following code is my get method for an API I am attempting to build in order to learn both. It works as is, but given the sparsity of code I have seen in example methods, and the fact that Zend seems to do a lot for you, is there a better way of doing this? The code is something I cobbled together because the tutorial that I was walking through forgot to add the get method code.</p> <pre><code>public function getAction() { // action body // Is there a better way to get the id from the URL? $this-&gt;_getAllParams(); $request = $this-&gt;_request-&gt;getParams(); if (array_key_exists($request['id'], $this-&gt;_todo)){ $return[] = array($request['id'] =&gt; $this-&gt;_todo[$request['id']]); }else{ // error code here or call some error method? // do I do error coding here or send a message to some handler/helper? } echo Zend_Json::encode($return); } </code></pre> <p>Essentially this will take a URL and pass json encode information that is currently stored in an array, i.e:</p> <pre><code>http://restapi.local/api/1 </code></pre> <p>Will display:</p> <pre><code>[{"1":"Buy milk"}] </code></pre> <p>The routing takes place in the bootstrap:</p> <pre><code>class Bootstrap extends Zend_Application_Bootstrap_Bootstrap { public function _initRoutes() { $front = Zend_Controller_Front::getInstance(); $router = $front-&gt;getRouter(); $restRoute = new Zend_Rest_Route($front); $router-&gt;addRoute('default', $restRoute); } } </code></pre> <p>Below is the full ApiController.php:</p> <pre><code>class ApiController extends Zend_Controller_Action { public function init() { /* Initialize action controller here */ $this-&gt;_helper-&gt;viewRenderer-&gt;setNoRender(true); $this-&gt;_todo = array ( "1" =&gt; "Buy milk", "2" =&gt; "Pour glass of milk", "3" =&gt; "Eat cookies" ); } public function indexAction() { // action body echo Zend_Json::encode($this-&gt;_todo); } public function getAction() { // action body $this-&gt;_getAllParams(); $request = $this-&gt;_request-&gt;getParams(); if (array_key_exists($request['id'], $this-&gt;_todo)){ $return[] = array($request['id'] =&gt; $this-&gt;_todo[$request['id']]); } echo Zend_Json::encode($return); } public function postAction() { // action body $item = $this-&gt;_request-&gt;getPost('item'); $this-&gt;_todo[count($this-&gt;_todo) + 1] = $item; echo Zend_Json::encode($this-&gt;_todo); } public function putAction() { // action body } public function deleteAction() { // action body } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T08:15:26.973", "Id": "20933", "Score": "0", "body": "Can't comment on the Zend stuff since I don't quite understand what's going on here, but the first thing that jumps out at me is that it's possible for your encode call to act on a non-existing variable. (Also, I suspect that it should be returned instead of echo'd.) Can you post the entire class? I'm a bit confused about what `_todo` is." } ]
[ { "body": "<p>By using Zend_Rest_Route you are on a good way. I wouldn't recommend making it the default route though, as I had trouble when using MVC-stuff which required additional params not specified in the route, e.g. for a paginator. You could also <a href=\"http://framework.zend.com/manual/1.11/en/zend.controller.router.html#zend.rest.route_config\" rel=\"nofollow\">move the routing-configuration to your application.ini</a> to keep your Bootstrap-class clean.</p>\n\n<p>I recommend simplifying your <code>getAction()</code> by using:</p>\n\n<pre><code>$id = $this-&gt;getRequest()-&gt;getParam('id', null);\n$id = $this-&gt;_request-&gt;getParam('id');\n</code></pre>\n\n<p>Both are identical, but I prefer using the get-methods in case I use them to override the handling of the underlying class-property (in this case <code>$this-&gt;_request</code>). The second argument specifies the default value to be used, if the param is not set (by default this is null).</p>\n\n<p>edit: Also, instead of</p>\n\n<pre><code>$this-&gt;_todo[count($this-&gt;_todo) + 1] = $item;\n\n$this-&gt;_todo[] = $item;\n</code></pre>\n\n<p>this will automatically append $item to $this->_todo, even if the variable is not yet initialized.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T22:53:49.673", "Id": "20980", "Score": "0", "body": "Thanks, I should have looked deeper into the $this->getRequest()->getParam(). That is a much simpler way, and makes checking for errors simpler as well." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:52:15.493", "Id": "12988", "ParentId": "12964", "Score": "2" } } ]
{ "AcceptedAnswerId": "12988", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T04:47:09.727", "Id": "12964", "Score": "3", "Tags": [ "php", "api", "url-routing", "zend-framework" ], "Title": "Zend Framework getAction method" }
12964
<p>I have a working script that I wrote in Python which for e-mail messages that consist only of a plain text part + an HTML part, discards the HTML and keeps only the plain text part.</p> <p>The script is not exactly elegant and, as can be seen from the code, it smells like it is C (in particular, I simulate the use of bitmasks) and I am not exactly satisfied with some points of it.</p> <p>I know that the script has some issues (like code duplication and the hack mentioned above), but I don't know the idiomatic Pythonic way of writing it and I would appreciate <em>any</em> kind of criticism to improve it in any way to make the code elegant.</p> <pre><code>#!/usr/bin/env python # -*- coding: utf-8 -*- """ Author: Rogério Theodoro de Brito &lt;rbrito@ime.usp.br&gt; License: GPL-2+ Copyright: 2010-2012 Rogério Theodoro de Brito drop-alternatives is a simple Python script for those who hate emails in HTML and who prefer their inbox to have as many messages in pure text as feasible. This script is generally meant to be run as a filter with procmail or some other mail delivery agent. It tries to be moderately conservative and only act when things are moderately safe: * If the message is `multipart` and has a `text/plain` and a `text/html` part, keep the `text/plain` part only. * In all other cases keep the message intact. """ import email import email.message def compose_message(orig, body): """ Create new message with headers from `orig` and body from `body`. * `orig`: The original message. * `body`: The body that we want the new message to have. * Returns a new message. `compose_message` creates a new message with most of the fields from `orig`, with fields from `body` (if any) and with the payload of `body`. The fields excluded from `orig` are the following: * `content-length` * `content-type` * `lines` * `status` """ wanted = email.message.Message() wanted.set_payload(body.get_payload()) unwanted_fields = ["content-length", "content-type", "lines", "status"] # The dictionaries `orig` and `body` have only headers as their items. for field in unwanted_fields: del orig[field] for k, v in orig.items(): wanted[k] = v for k, v in body.items(): wanted[k] = v return wanted def sanitize(msg): """ Given an RFC-2822 message `msg`, generate its 'sanitized' version. * `msg`: The message to be sanitized. * Returns a sanitized version of `msg`. `sanitize` tries to be moderately conservative and only act when things are moderately safe: * If the message is multipart and has a `text/plain` and a `text/html` part, keep the `text/plain` part only. * In all other cases keep the message intact. """ if not msg.is_multipart(): return msg # 'composition' is a bitmask containing the kind of the parts TEXTPLAIN = 1 # text/plain TEXTHTML = 2 # text/html MISCPARTS = 4 # anything else composition = 0 text_taken = False for part in msg.walk(): if (part.get_content_maintype() == "multipart" or part.get_content_type() == "message/external-body" or part.get_payload() == ""): continue elif part.get_content_type() == "text/plain": if not text_taken: text_taken = True body = part composition |= TEXTPLAIN else: # if we are seeing a second text/plain part, stop throwing # things composition |= MISCPARTS break elif part.get_content_type() == "text/html": composition |= TEXTHTML else: composition |= MISCPARTS if composition == (TEXTPLAIN + TEXTHTML) or composition == TEXTPLAIN: return compose_message(msg, body) else: return msg if __name__ == "__main__": import sys res = sanitize(email.message_from_file(sys.stdin)) print res.as_string(unixfrom=False), </code></pre>
[]
[ { "body": "<p>I think the code is quite fine as it is. Some small notes:</p>\n\n<pre><code>if composition == (TEXTPLAIN + TEXTHTML) or composition == TEXTPLAIN:\n</code></pre>\n\n<p>Just to make sure: this code tests that <code>TEXTPLAIN</code> is set and that <code>MISCPARTS</code> is <em>not</em> set. I would make that explicit, otherwise this code is hard to understand (in particular, it’s easy to miss that <code>MISCPARTS</code> mustn’t be set):</p>\n\n<pre><code>if (composition &amp; TEXTPLAIN) != 0 and (composition &amp; MISCPARTS) == 0:\n</code></pre>\n\n<p>If you’re not happy with bit operations, you can a <code>set</code> instead.</p>\n\n<pre><code>composition = set()\n\n# …\n\nif TEXTPLAIN in composition and MISCPARTS not in composition:\n</code></pre>\n\n<p>… and define <code>TEXTPLAIN</code> etc. as simple consecutive constants rather than bitmasks.</p>\n\n<p>This is more pythonic certainly, but I actually find the use of bit masks entirely appropriate here.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T15:58:37.837", "Id": "21032", "Score": "0", "body": "Thanks, @Konrad. I thought that the bitfields would be condemned in python, but as you mention right now, they even feel a bit natural. BTW, in C I would use an enum for the constants. Is there any Pythonic idiom with the same \"flavour\" as C's enums?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T12:22:09.787", "Id": "12970", "ParentId": "12967", "Score": "3" } }, { "body": "<p>Your code is fine as it is, and there isn't much I can recommend. However, I believe that this may profit from being made into a class.</p>\n\n<pre><code>#!/usr/bin/env python\nimport email\nimport email.message\n\nclass MyMail:\n unwanted_fields = [\"content-length\", \"content-type\", \"lines\", \"status\"]\n\n def __init__(self, fp):\n self.res = self.sanitize(email.message_from_file(fp))\n\n def display(self):\n print self.res.as_string(unixfrom=False)\n\n def compose_message(self, orig, body):\n wanted = email.message.Message()\n wanted.set_payload(body.get_payload())\n\n # The dictionaries `orig` and `body` have only headers as their items.\n for field in self.unwanted_fields: del orig[field]\n for k, v in orig.items() + body.items(): wanted[k] = v\n\n return wanted\n</code></pre>\n\n<p>Your code does not really care about <code>text/html</code> mime, other than to skip it. Other than that, it cares that <code>text/plain</code> is seen only once. This seemed to be an overkill for bit fiddling. Removing that,</p>\n\n<pre><code> def sanitize(self, msg):\n if not msg.is_multipart(): return msg\n\n compose = False\n text_taken = False\n\n for part in msg.walk():\n if (part.get_content_maintype() == \"multipart\" or\n part.get_content_type() == \"message/external-body\" or\n part.get_content_type() == \"text/html\" or\n part.get_payload() == \"\"):\n continue\n elif part.get_content_type() == \"text/plain\" and not text_taken:\n body = part\n compose = True\n text_taken = True\n # if we are seeing a second text/plain part, stop throwing\n # things\n else: return msg\n\n return self.compose_message(msg, body) if compose else msg\n\nif __name__ == \"__main__\":\n import sys\n s = MyMail(sys.stdin)\n s.display()\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T08:46:22.703", "Id": "21020", "Score": "1", "body": "I’m not sure I agree. While this looks OK and conventional, there’s this great talk arguing that you should [*Stop Writing Classes*](http://pyvideo.org/video/880/stop-writing-classes). It makes a lot of good points. Well, it could be argued that the presence of `display` makes a class here worthwhile. Anyway, +1." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T16:10:48.543", "Id": "21033", "Score": "0", "body": "Thanks for analysing my code and concluding that it is not utter terrible. :) I think that, as with @Konrad, I will still keep the code outside of a class (I may change my mind in the future), but I will adopt your absense of bitfields. Your solution is more elegant, IMVHO." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T04:19:33.100", "Id": "13000", "ParentId": "12967", "Score": "2" } } ]
{ "AcceptedAnswerId": "12970", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T09:04:48.460", "Id": "12967", "Score": "4", "Tags": [ "python", "email" ], "Title": "Script to drop HTML part of multipart/mixed e-mails" }
12967
<p>For reasons unknown I've recently taken up generating word squares, or more accurately <a href="http://en.wikipedia.org/wiki/Word_square#Double_word_squares" rel="nofollow">double word squares</a>. Below you can see my implementation in Python, in about 40 lines. The code uses this <a href="http://github.com/causes/puzzles/raw/master/word_friends/word.list" rel="nofollow">word list</a>. It takes around 10ms for dim=2 (2x2 word squares) and around 13 seconds for dim=3 (3x3 squares). For dim=4 it explodes to something like 3.5 hours in cpython, and causes a MemoryError in pypy. For dim=20 and dim=21 it returns 0 solutions in a few seconds, but for dim=18 and dim=19 it causes a MemoryError in both pypy and cpython.</p> <p>So, I am looking for improvements that will allow me to explore values of dim >4, but also to explore ways of solving the MemoryErrors for the values &lt;20. Small improvements of a few %, improvements in how things are expressed, as well as large improvements in the algorithm are all welcome.</p> <pre><code>import time start = time.clock() dim = 3 #the dimension of our square posmax = dim**2 #maximum positions on a dim*dim square words = open("word.list").read().splitlines() words = set([w for w in words if len(w)==dim]) print 'Words: %s' % len(words) prefs = {} for w in words: for i in xrange(0,dim): prefs[w[:i]] = prefs.get(w[:i], set()) prefs[w[:i]].add(w[i]) sq, options = ['' for i in xrange(dim)], {} for i in prefs: for j in prefs: options[(i,j)] = [(i+o, j+o) for o in prefs[i] &amp; prefs[j]] schedule = [(p/dim, p%dim) for p in xrange(posmax)] def addone(square, isquare, position=0): if position == posmax: yield square else: x,y = schedule[position] square2, isquare2 = square[:], isquare[:] for o in options[(square[x], isquare[y])]: square2[x], isquare2[y] = o for s in addone(square2, isquare2, position+1): yield s print sum(1 for s in addone(sq, sq[:])) print (time.clock() - start) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T14:36:13.857", "Id": "21148", "Score": "0", "body": "Would you like to find all word squares or just the first one?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T08:04:05.923", "Id": "21199", "Score": "0", "body": "it's currently geared towards finding all squares. Finding one would be acceptable if all wasn't feasible." } ]
[ { "body": "<p>Am working on a few minor improvements, but I think the major saving to be had is in removing the line </p>\n\n<pre><code>square2, isquare2 = square[:], isquare[:]\n</code></pre>\n\n<p>Instead, do</p>\n\n<pre><code>sofar = square[x], isquare[y]\nfor o in options[sofar]:\n square[x], isquare[y] = o\n for s in addone(square, isquare, position+1):\n yield s\nsquare[x], isquare[y] = sofar\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:33:23.047", "Id": "20953", "Score": "0", "body": "great idea Paul! Gave a nice ~10% boost." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T14:52:40.600", "Id": "12977", "ParentId": "12974", "Score": "4" } }, { "body": "<pre><code>import time\nstart = time.clock()\n\ndim = 3 #the dimension of our square\nposmax = dim**2 #maximum positions on a dim*dim square\n</code></pre>\n\n<p>Python convention is to have constants be in ALL_CAPS</p>\n\n<pre><code>words = open(\"word.list\").read().splitlines()\n</code></pre>\n\n<p>Actually, a file iterates over its lines so you can do <code>words = list(open(\"words.list\"))</code></p>\n\n<pre><code>words = set([w for w in words if len(w)==dim])\n</code></pre>\n\n<p>I'd make it a generator rather then a list and combine the previous two lines</p>\n\n<pre><code>print 'Words: %s' % len(words)\n</code></pre>\n\n<p>It is generally preferred to do any actual logic inside a function. Its a bit faster and cleaner</p>\n\n<pre><code>prefs = {}\nfor w in words:\n</code></pre>\n\n<p>I'd suggest spelling out <code>word</code></p>\n\n<pre><code> for i in xrange(0,dim):\n prefs[w[:i]] = prefs.get(w[:i], set())\n prefs[w[:i]].add(w[i])\n</code></pre>\n\n<p>Actually, you can do <code>prefs.setdefault(w[:i],set()).add(w[i])</code> for the same effect.</p>\n\n<pre><code>sq, options = ['' for i in xrange(dim)], {}\n</code></pre>\n\n<p>You can do <code>sq, options = [''] * dim, {}</code> for the same effect</p>\n\n<pre><code>for i in prefs: \nfor j in prefs:\n options[(i,j)] = [(i+o, j+o) \n for o in prefs[i] &amp; prefs[j]]\n\nschedule = [(p/dim, p%dim) for p in xrange(posmax)]\n</code></pre>\n\n<p>This can be written as <code>schedule = map(divmod, xrange(posmax))</code></p>\n\n<pre><code>def addone(square, isquare, position=0):\n#for r in square: print r #prints all square-states\n</code></pre>\n\n<p>Don't leave dead code as comments, kill it!</p>\n\n<pre><code>if position == posmax: yield square\n</code></pre>\n\n<p>I'd put the yield on the next line, I think its easier to read especially if you have an else condition</p>\n\n<pre><code>else:\n x,y = schedule[position]\n square2, isquare2 = square[:], isquare[:]\n</code></pre>\n\n<p>In the one line you don't have a space after the comma, in the next line you do. I suggest always including the space.</p>\n\n<pre><code> for o in options[(square[x], isquare[y])]:\n square2[x], isquare2[y] = o\n for s in addone(square2, isquare2, position+1):\n yield s\n\nprint sum(1 for s in addone(sq, sq[:]))\n\nprint (time.clock() - start)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:36:35.023", "Id": "20956", "Score": "0", "body": "minor corrections - \nschedule = map(divmod, xrange(POS_MAX), [DIM]*POS_MAX)\n\nalso, list(open(\"words.list\")) included the \\n at the end of each word which needed some working around. In the end I fif it in 65 chars precisely:\n\nwords = set(w[:-1] for w in open(\"words.list\") if len(w)==DIM+1)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:59:07.207", "Id": "20958", "Score": "1", "body": "@AlexandrosMarinos, ok, my baew. I'd use `[divmod(x, DIM) for x in xrange(POS_MAX)]` I'd also use `w.strip()` instead of `w[:-1]` but that only IMO." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T19:51:50.317", "Id": "20962", "Score": "0", "body": "w.strip() is cleaner, but it'd take me over the 65 char limit.. choices, choices :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T19:54:00.490", "Id": "20963", "Score": "0", "body": "@AlexandrosMarinos, 65 char limit?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T19:58:41.587", "Id": "20965", "Score": "0", "body": "On line length.. I try to keep them under 65 chars so I don't write too complex 1-liners" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:04:21.057", "Id": "20966", "Score": "2", "body": "@AlexandrosMarinos, for what its worth: the official python style guide recommends a limit of 79 characters." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:05:04.027", "Id": "20967", "Score": "0", "body": "Good to know! Don't know how I got 65 stuck in my head.." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T16:53:31.903", "Id": "12980", "ParentId": "12974", "Score": "4" } }, { "body": "<p>I tried a different schedule, it made a very small difference to the time though!</p>\n\n<pre><code>schedule = [(b-y,y)\n for b in range(DIM*2)\n for y in range(min(b+1, DIM))\n if b-y&lt; DIM]\n\nassert len(schedule) == POSMAX\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T19:54:25.337", "Id": "20964", "Score": "0", "body": "schedules are so fascinating.. I've tried a few, but the timing remains roughly the same. I do have a suspicion that a good schedule could make a difference, but I also fear that they make no difference. I was thinking of trying to generate random schedules then time them and see if anything strange comes up, or even do some genetic algos to discover interesting schedules if the random stuff points to significant gains.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T11:38:41.747", "Id": "21024", "Score": "0", "body": "so bizarre.. schedule = [tuple(reversed(divmod(x, DIM))) for x in xrange(POS_MAX)] (effectively the basic schedule but with x and y reversed) seems to be the best performing schedule on a 3x3 out of 24 possibilities. It is a slight improvement on the order of 100ms but for the life of me can't figure out why." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T18:41:39.130", "Id": "12984", "ParentId": "12974", "Score": "0" } }, { "body": "<p>We fill column by column with the current schedule. I tried adding a check whether we're going to be able to put anything in the next row before filling the rest of the column, but it results in a slight slowdown. </p>\n\n<pre><code>if x+1 &lt; DIM and len(FOLLOWSBOTH[(square[x+1], transpose[y])]) == 0:\n continue\n</code></pre>\n\n<p>I am still tempted to think that something like this but more thorough could still save time: checking not just this one spot, but everything remaining in the row and the column, to ensure that there are compatible letters. That needs a new, more complex data structure though!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:40:50.817", "Id": "20970", "Score": "0", "body": "maybe a 'deadends' dictionary, so we can check (square[x+1], transpose[y]) in deadends would speed this up? off to try it I am." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T21:00:30.247", "Id": "20974", "Score": "0", "body": "wait. I think this wouldn't offer anything with the normal schedule, since square[x+1] is always '', and therefore it comes down to options[transpose[y]], which is always something, if you've gotten that far. Have I missed something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T21:09:24.167", "Id": "20975", "Score": "0", "body": "deadends idea doesn't improve time at all.." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:21:44.683", "Id": "12987", "ParentId": "12974", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T13:25:58.417", "Id": "12974", "Score": "3", "Tags": [ "python" ], "Title": "Word Square generation in Python" }
12974
<p>After becoming interested in various bits of functional programming provided by non-functional languages, I've recently decided to start learning Haskell. As I'm fairly experienced with conventional imperative programming languages, I decided to make my "hello world" something a little more complex - an implementation of gradient descent with 2 variables.</p> <p>The idea with this code is that you fill in the training set for the algorithm in the code, and then run the code something similar to this:</p> <pre><code>descentFunc = singleDescend trainingSet 0.1 deltas = descend descentFunc ( 100, 1 ) 100000 </code></pre> <p>Where <code>0.1</code> is the learning rate (referred to as <code>lr</code> in the code) <code>100000</code> is the number of iterations for the loop, and <code>( 100, 1 )</code> is an initial guess for the coefficients.</p> <p>The actual code that's running is below. As I'm entirely new to Haskell, I was wondering whether code such as this is acceptable? And whether there's any obvious idioms I'm missing/misusing or any glaring style errors I've made.</p> <p>Any comments on my implementation of the algorithm are welcome also.</p> <pre><code>import Data.List trainingSet = [ (1.0,10.0),(2.0,20.0),(3.0,30.0),(4.0,40.0) ] hypothesis (d1,d2) x = d1 + (d2 * x) squareDiff d (x,y) = diff * diff where diff = ( hypothesis d x ) - y costFunc ts d = scaleFactor * sum squares where scaleFactor = 1.0 / (2 * genericLength ts) squares = map (squareDiff d) ts diff d (x,y) = (hypothesis d x) - y descendTheta thetaFunc deltaFunc ts lr deltas = deltaFunc deltas - (scaleFactor * sum scaledDiffs) where scaleFactor = lr / genericLength ts diffs = map (diff deltas) ts scaledDiffs = map (\(x,y) -&gt; x * thetaFunc y) $ zip diffs ts descendThetaZero = descendTheta (\_ -&gt; 1) fst descendThetaOne = descendTheta (fst) snd singleDescend ts lr deltas = (thetaZero,thetaOne) where thetaZero = descendThetaZero ts lr deltas thetaOne = descendThetaOne ts lr deltas descend func deltas i | i == 0 = deltas | otherwise = descend func ( func deltas ) ( i - 1 ) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T23:27:13.293", "Id": "21696", "Score": "0", "body": "would you please consider accepting my answer - or do you still have questions" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T10:43:31.690", "Id": "21931", "Score": "0", "body": "@epsilon'εⳆ2'halbe Sorry, i'm actually just having a difficult time deciding *who* to accept. I'm not convinced that code-review lends itself very well to selecting single answer. I will make a decision shortly though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T21:12:30.337", "Id": "21953", "Score": "0", "body": "sorry i wrote this comment wen no other answer was there - of course choose the answer most helpful to you" } ]
[ { "body": "<p>one obvious change would be to add type signatures,\ni additionally introduced some type synonyms to distinguish between all those <code>Doubles</code>. A bit explanation could be done towards the algorithm - I don't know what it actually want to achieve. I am no programmer so the non understanding comes quite often.</p>\n\n<p>Next thing is it seems <code>costFunc</code> is never used - why is it there?</p>\n\n<p>and I've replaced <code>genericLength</code> by length and converting the result - as the library says length is faster.</p>\n\n<pre><code>type TrainData = [(Double,Double)]\ntype LearnRate = Double\ntype DeltaPair = (Double,Double)\n\ntrainingSet :: TrainData\ntrainingSet = [ (1.0,10.0),(2.0,20.0),(3.0,30.0),(4.0,40.0) ]\n\nhypothesis :: DeltaPair -&gt; Double -&gt; Double\nhypothesis (d1,d2) x = d1 + (d2 * x)\n\ncostFunc :: TrainData -&gt; DeltaPair -&gt; Double\ncostFunc ts d = scaleFactor * sum squares\n where scaleFactor = 1.0 / (2 * fromIntegral (length ts))\n squares = map (square . diff d) ts\n square x = x * x\n\ndiff :: DeltaPair -&gt; (Double, Double) -&gt; Double\ndiff d (x,y) = hypothesis d x - y\n\n\ndescendTheta :: ((Double, Double) -&gt; Double) -&gt; (DeltaPair -&gt; Double) -&gt; TrainData -&gt; LearnRate -&gt; DeltaPair -&gt; Double\ndescendTheta thetaFunc deltaFunc ts lr deltas =\n deltaFunc deltas - (scaleFactor * sum scaledDiffs)\n where scaleFactor = lr / fromIntegral (length ts)\n diffs = map (diff deltas) ts\n scaledDiffs = map (\\(x,y) -&gt; x * thetaFunc y) $ zip diffs ts\n\ndescendThetaZero :: TrainData -&gt; LearnRate -&gt; (Double, Double) -&gt; Double\ndescendThetaZero = descendTheta (const 1) fst\n\ndescendThetaOne :: TrainData -&gt; LearnRate -&gt; (Double, Double) -&gt; Double\ndescendThetaOne = descendTheta fst snd\n\nsingleDescend :: TrainData -&gt; LearnRate -&gt; DeltaPair -&gt; DeltaPair\nsingleDescend ts lr deltas = (thetaZero, thetaOne)\n where thetaZero = descendThetaZero ts lr deltas\n thetaOne = descendThetaOne ts lr deltas\n\ndescend :: (DeltaPair -&gt; DeltaPair) -&gt; DeltaPair -&gt; Int -&gt; DeltaPair\ndescend f deltas i\n | i &lt; 0 = error \"no negative numbers\"\n | i == 0 = deltas\n | otherwise = descend f (f deltas) (i-1)\n\nmain :: IO ()\nmain = print (descend descendFunc (100, 1) 10000)\n where descendFunc = singleDescend trainingSet 0.1\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T17:27:09.420", "Id": "12982", "ParentId": "12975", "Score": "4" } }, { "body": "<p>Welcome to haskell, Your code is quite good for a beginner, I have only peripheral recommendations on your style.</p>\n\n<pre><code>import Test.HUnit\nimport Data.List\nimport Control.Arrow\n</code></pre>\n\n<p>As @epsilon 'εⳆ2' halbe suggested below, use type signatures to define your functions first, this would help you avoid obvious errors.</p>\n\n<pre><code>type DeltaPair = (Double, Double)\ntype PairFunc = DeltaPair -&gt; Double\n\ntrainingSet = [(1.0,10.0),(2.0,20.0),(3.0,30.0),(4.0,40.0)]\n</code></pre>\n\n<p>The classes in <code>Control.*</code> are often very useful. These are just your functions that have been modified a little bit. This may seem like overkill to you, but as a beginner, you would profit tremendously if you internalize the functions in the <code>Control.*</code> space. At the very least, understand the functions used here. (I would certainly recommend your definition of the diff over this, but the point here is one of demonstration.)</p>\n\n<pre><code>diff :: DeltaPair -&gt; DeltaPair -&gt; Double\ndiff d = uncurry (-) . first (flip hypothesis d)\n where hypothesis x = uncurry (+) . first (* x)\n</code></pre>\n\n<p>The scaleDiffs can be written in two ways, one by recognizing that it is actually a <code>zipWith</code> and the other, using the functions in <code>Control.Arrow</code> to manipulate the pair. The second gets you a pointfree form. Use which ever you feel comfortable with, but understand both.</p>\n\n<p>I have replaced genericLength with <code>fromIntegral . length</code> because it seems from your training set that the set is not very large. If that is not the case, change it back to <code>genericLength</code></p>\n\n<pre><code>descendTheta :: PairFunc -&gt; PairFunc -&gt; [DeltaPair] -&gt; Double -&gt; DeltaPair -&gt; Double\ndescendTheta thetaFunc deltaFunc ts lr deltas = deltaFunc deltas - sSum\n where scaleFactor = lr / fromIntegral (length ts)\n -- scaledDiffs ts = zipWith (\\x y -&gt; x * thetaFunc y) (diffs ts) ts\n scaledDiffs ts = map (uncurry (*) . second thetaFunc) $ zip (diffs ts) ts\n diffs = map (diff deltas)\n sSum = scaleFactor * sum (scaledDiffs ts)\n</code></pre>\n\n<p>It is often hard to decide which definitions go on the top level. A good rule of thumb is to see if the function being defined can be reused elsewhere. If they can't then they probably are better of as sub definitions under a where clause.</p>\n\n<pre><code>singleDescend :: [DeltaPair] -&gt; Double -&gt; DeltaPair -&gt; DeltaPair\nsingleDescend ts lr deltas = (fn descendThetaZero, fn descendThetaOne)\n where fn f = f ts lr deltas\n descendThetaZero = descendTheta (const 1) fst\n descendThetaOne = descendTheta fst snd\n</code></pre>\n\n<p>We should always be on the look out for general functions. These help us tremendously in refactoring the code. Here is one such function.</p>\n\n<pre><code>napply :: Int -&gt; (c -&gt; c) -&gt; c -&gt; c\nnapply n = ((!! n) .) . iterate\n\ndescend :: (DeltaPair -&gt; DeltaPair) -&gt; DeltaPair -&gt; Int -&gt; DeltaPair\ndescend = flip . flip napply\n\ndeltas n = descend descentFunc (100, 1) n\n where descentFunc = singleDescend trainingSet 0.1\n</code></pre>\n\n<p>A few unit tests</p>\n\n<pre><code>tests = TestList [\n TestLabel \"1\" test1,\n TestLabel \"2\" test2,\n TestLabel \"3\" test3\n ]\n\ntest1 = TestCase $ assertEqual \"A1\" (100.0, 1.0) (deltas 0)\ntest2 = TestCase $ assertEqual \"A1\" (92.25,-17.25) (deltas 1)\ntest3 = TestCase $ assertEqual \"A1\" (89.8375,-19.875) (deltas 2)\ntt = runTestTT tests \n</code></pre>\n\n<p>These two does not seem to be used any where</p>\n\n<pre><code>{-\nsquareDiff :: Num a =&gt; (a, a) -&gt; (a, a) -&gt; a\nsquareDiff = ((^ 2) .) . diff\n\ncostFunc :: Fractional a =&gt; [(a, a)] -&gt; (a, a) -&gt; a\ncostFunc ts d = scaleFactor * sum squares\n where scaleFactor = 1.0 / (2 * fromIntegral (length ts))\n squares = map (squareDiff d) ts\n-}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:54:54.797", "Id": "12998", "ParentId": "12975", "Score": "4" } }, { "body": "<p>This was the simplest rewrite of your code that I could come up with:</p>\n\n<pre><code>{-# LANGUAGE UnicodeSyntax #-}\n\nimport Data.List\n\ntrainingSet = [(1, 10), (2, 20), (3, 30), (4, 40)]\n\nhypothesis (δ1, δ2) x = δ1 + δ2 * x\n\ndiff δs (x, y) = hypothesis δs x - y\n\naverage xs = realToFrac (sum xs) / genericLength xs\n\ndescendθ θFunc ts lr δs = lr * average (map (\\t -&gt; diff δs t * θFunc t) ts)\n\nnext ts lr δs@(δ0, δ1) = (δ0', δ1')\n where δ0' = δ0 - descendθ (\\(x, y) -&gt; 1) ts lr δs\n δ1' = δ1 - descendθ (\\(x, y) -&gt; x) ts lr δs\n\ndescend f δs i = iterate f δs !! i\n</code></pre>\n\n<p>Some general comments:</p>\n\n<p>You don't need to put <code>.0</code>s on your numeric literals to indicate they are <code>Doubles</code> like you would in C. A type signature will suffice.</p>\n\n<p>I used the unicode syntax extension for greek variable names to make it easier on my eyes.</p>\n\n<p>Your <code>descend</code> function is just <code>iterate</code> in disguise.</p>\n\n<p>Your variable naming in your <code>descendTheta</code> function was incredibly confusing, since you name your output variables theta, even thought they are basically the same as your input variables, which you named delta. I decided to name them both delta for consistency, leaving theta only to refer to the projection of the data set that you are descending on.</p>\n\n<p>Your <code>scaledDiffs</code> function was incredibly awkward and a round-about way to do what essentiallyw as a single <code>map</code> and <code>average</code>. Unfortunately, the <code>average</code> function is not in the Haskell standard library, but the definition I included in the code is the most general version and will type-check for anything you would want to average.</p>\n\n<p>Your training set and learning rate are constant over the entire run, so you could actually improve the above code even more by using the <code>Reader</code> monad to thread those variables through your code without explicit parameter-passing. If you don't know what the <code>Reader</code> monad is, just ask and I will update this post with a demonstration of it. It's very easy to use.</p>\n\n<p>Also, I disagree that you must put type signatures on your code. For application code that only you will maintain, using type signatures is mostly a matter of style. For libraries, though, or code other people have to maintain, I would strongly recommend type signatures.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T05:36:57.123", "Id": "21053", "Score": "0", "body": "Very nice and elegent implementation. You could replace ` (\\(x, y) -> 1)` with `const 1` and `(\\(x, y) -> x)` with `fst` otherwise +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T13:47:18.087", "Id": "21065", "Score": "0", "body": "@blufox Yeah, I wrote it that way to document what those two functions were doing by using the same variable names as the training set data, because it was difficult for me to understand at first." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T00:45:15.867", "Id": "13032", "ParentId": "12975", "Score": "3" } } ]
{ "AcceptedAnswerId": "12998", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T13:27:49.533", "Id": "12975", "Score": "4", "Tags": [ "haskell" ], "Title": "Simple Gradient Descent Algorithm In Haskell" }
12975
<p>I think I have correctly implemented <a href="http://en.wikipedia.org/wiki/Powerset" rel="nofollow">Powerset</a> in Clojure.</p> <pre><code>(use '(clojure set)) (defn powerset [input result] (if (nil? (first input)) (concat result #{}) (set (reduce concat (for [x input] (let [set-of-x #{x} input-no-x (set (remove set-of-x input)) next-result (union result (set (list input set-of-x input-no-x)))] (powerset input-no-x next-result))))))) </code></pre> <p>Of course I'm interested in how a library function could make the above a one-liner, but I'm also interested in how the above code could be made more idiomatic.</p> <ol> <li><code>(if (nil? (first input))</code> feels wrong.</li> <li>Using the <code>let</code> block to replicate imperative calculations. Acceptable?</li> <li>Could I use <code>-&gt;&gt;</code> to make the following line more readable? <code>(union result (set (list input set-of-x input-no-x)))</code> </li> <li>I'm not using <code>recur</code> as I got the "recur must be in the tail position" compiler error. </li> </ol> <p><strong>EDIT</strong> Removed <code>(loop)</code> from originally-posted version. - I had erroneously copy-pasted code after I had already commenced attempting to introduce loop/recur (tail recursion). How use loop/recur in this function?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T03:36:55.847", "Id": "21010", "Score": "0", "body": "Feedback from @stevelknievel on twitter: use if-let" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T07:45:24.890", "Id": "21013", "Score": "1", "body": "Library that does the job: [`math.combinatorics/subsets`](https://github.com/clojure/math.combinatorics/blob/master/src/main/clojure/clojure/math/combinatorics.clj#L81)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T14:55:37.233", "Id": "21069", "Score": "0", "body": "And it's part of Clojure Contrib." } ]
[ { "body": "<p>A couple of random comments on your code:</p>\n\n<ul>\n<li><p>it doesn't parse correctly, I guess the closed paren right after <code>loop</code> bindings is misplaced. I couldn't run it even after fixing that.</p></li>\n<li><p>why do you need a second input parameter? I would expect the signature to only have the input set as parameter</p></li>\n<li><p><code>(if (nil (first input)) then else)</code> is more idiomatically written (note the inversion of the then-else branches) <code>(if (seq input) else then)</code></p></li>\n<li><p><code>input-no-x</code> can be obtained in a simpler way: <code>(let [input-no-x (disj input x)])</code></p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T14:58:05.887", "Id": "21070", "Score": "0", "body": "Fixed the code - I had copy-pasted a late attempt at introducing `loop` \\ `recur` - which didn't work (want to do this). Regarding the second parameter - it's an accumulator for the recursive call, so another improvement is that the function could be overloaded." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T08:06:21.060", "Id": "13002", "ParentId": "12979", "Score": "3" } }, { "body": "<p>I know this is an old question, but see the explanation here for a much simpler way:</p>\n\n<p><a href=\"http://www.ecst.csuchico.edu/~amk/foo/csci356/notes/ch1/solutions/recursionSol.html\" rel=\"nofollow\">http://www.ecst.csuchico.edu/~amk/foo/csci356/notes/ch1/solutions/recursionSol.html</a></p>\n\n<p>Code (from <a href=\"https://gist.github.com/796299\" rel=\"nofollow\">https://gist.github.com/796299</a> )</p>\n\n<pre><code>(defn powerset [ls]\n (if (empty? ls) '(())\n (union (powerset (next ls))\n (map #(conj % (first ls)) (powerset (next ls))))))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-10T20:10:40.023", "Id": "139754", "Score": "2", "body": "You should save `(powerset (next ls))` in a variable rather than computing it twice. :)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-03T19:10:57.543", "Id": "19269", "ParentId": "12979", "Score": "2" } } ]
{ "AcceptedAnswerId": "13002", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T15:33:46.237", "Id": "12979", "Score": "8", "Tags": [ "clojure" ], "Title": "Powerset in Clojure" }
12979
<p>I'm training a bit with C, and I'm trying to build a bit array. I would like to have some comments about my code, because I'm not sure that it's the best way to do it.</p> <pre><code>// BAL.c #include &lt;assert.h&gt; #include &lt;limits.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; #include "BAL.h" #define BAL_Mask(n) (1 &lt;&lt; ((n) % CHAR_BIT)) #define BAL_Convert(n) ((n) / CHAR_BIT) void BAL_And(BAL_Array *p, BAL_Array *q) { assert(p != NULL); assert(q != NULL); for (size_t i = 0; i &lt; p-&gt;nBits; ++i) p-&gt;pBits[i] &amp;= q-&gt;pBits[i]; } _Bool BAL_Any(BAL_Array *p) { assert(p != NULL); for (size_t i = 0; i &lt; p-&gt;nBits; ++i) { if (BAL_Get(p, i) != 0) return 1; } return 0; } _Bool BAL_Compar(BAL_Array *p, BAL_Array *q) { assert(p != NULL); assert(q != NULL); if (p-&gt;nSize != q-&gt;nSize) return 0; for (size_t i = p-&gt;nBits; i &gt; 0; --i) { if (BAL_Get(p, i) != BAL_Get(q, i)) return 0; } return 1; } size_t BAL_Count(BAL_Array *p) { assert(p != NULL); size_t n = 0; for (size_t i = 0; i &lt; p-&gt;nBits; ++i) { if (BAL_Get(p, i) != 0) ++n; } return n; } void BAL_End(BAL_Array *p) { assert(p != NULL); free(p-&gt;pBits); free(p); } inline unsigned char BAL_Get(BAL_Array *p, size_t i) { assert(p != NULL); assert(i &lt;= p-&gt;nBits); return p-&gt;pBits[BAL_Convert(i)] &amp; BAL_Mask(i); } inline size_t BAL_GetSize(BAL_Array *p) { assert(p != NULL); return p-&gt;nBits; } BAL_Array * BAL_Init(size_t n) { assert(n &gt; 0); BAL_Array *p = malloc(sizeof *p); assert(p != NULL); p-&gt;nSize = BAL_Convert(n + CHAR_BIT - 1); p-&gt;pBits = calloc(p-&gt;nSize, 1); p-&gt;nBits = n; return p; } BAL_Array * BAL_Load(const char *s) { assert(s != NULL); size_t size = strlen(s); BAL_Array *pRet = BAL_Init(size); for (size_t i = 0; i &lt; size; ++i) { if (s[i] == '1') BAL_Set(pRet, i); } return pRet; } void BAL_LShift(BAL_Array *p, size_t m) { assert(p != NULL); for (size_t i = 0; i &lt; p-&gt;nBits; ++i) { p-&gt;pBits[i] &gt;&gt;= m; p-&gt;pBits[i] |= BAL_Get(p, i + 1) ? 1 : 0; } } void BAL_Not(BAL_Array *p) { assert(p != NULL); for (size_t i = 0; i &lt; p-&gt;nBits; ++i) p-&gt;pBits[i] = ~p-&gt;pBits[i]; } void BAL_Or(BAL_Array *p, BAL_Array *q) { assert(p != NULL); assert(q != NULL); for (size_t i = 0; i &lt; p-&gt;nBits; ++i) p-&gt;pBits[i] |= q-&gt;pBits[i]; } void BAL_Print(BAL_Array *p, unsigned char *pOut, size_t nMax) { assert(p != NULL); assert(pOut != NULL); size_t i; for (i = 0; i &lt; p-&gt;nBits &amp;&amp; i &lt; nMax; ++i) pOut[i] = BAL_Get(p, i) ? '1' : '0'; pOut[i] = '\0'; } inline void BAL_Reset(BAL_Array *p, size_t i) { assert(p != NULL); assert(i &lt;= p-&gt;nBits); p-&gt;pBits[BAL_Convert(i)] &amp;= ~BAL_Mask(i); } void BAL_RShift(BAL_Array *p, size_t m) { assert(p != NULL); for (size_t i = 0; i &lt; p-&gt;nSize; ++i) { p-&gt;pBits[i] &lt;&lt;= m; p-&gt;pBits[i] |= BAL_Get(p, i + 1) ? 1 : 0; } } inline void BAL_Set(BAL_Array *p, size_t i) { assert(p != NULL); assert(i &lt;= p-&gt;nBits); p-&gt;pBits[BAL_Convert(i)] |= BAL_Mask(i); } void BAL_Xor(BAL_Array *p, BAL_Array *q) { assert(p != NULL); assert(q != NULL); for (size_t i = 0; i &lt; p-&gt;nBits; ++i) p-&gt;pBits[i] ^= q-&gt;pBits[i]; } </code></pre> <p>Header file :</p> <pre><code>// BAL.h #ifndef BAL_H #define BAL_H typedef struct { unsigned char *pBits; size_t nSize; size_t nBits; } BAL_Array; void BAL_And (BAL_Array *, BAL_Array *); _Bool BAL_Any (BAL_Array *); _Bool BAL_Compar (BAL_Array *, BAL_Array *); size_t BAL_Count (BAL_Array *); void BAL_End (BAL_Array *); unsigned char BAL_Get (BAL_Array *, size_t); size_t BAL_GetSize (BAL_Array *); BAL_Array *BAL_Init (size_t); BAL_Array *BAL_Load (const char *); void BAL_LShift (BAL_Array *, size_t); void BAL_Not (BAL_Array *); void BAL_Or (BAL_Array *, BAL_Array *); void BAL_Print (BAL_Array *, unsigned char *, size_t); void BAL_Reset (BAL_Array *, size_t); void BAL_RShift (BAL_Array *, size_t); void BAL_Set (BAL_Array *, size_t); void BAL_Xor (BAL_Array *, BAL_Array *); #endif /* BAL_H */ </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T20:54:37.660", "Id": "20971", "Score": "2", "body": "Sorry, I don't have the time to write a full review but I have one thing to say. Assertions are not a replacement for error checking. As these functions are being exported, you should not be using `assert` here. You should come up with a mechanism to indicate an error. Make your `void` methods return `int` (or `_Bool` in your case) returning `\"true\"` when successful or `\"false\"` on failure. Come up with an \"error code\" to indicate what problem comes up or something similar if you want to convey that information to the programmer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T08:30:53.363", "Id": "21016", "Score": "0", "body": "Assertions are useful here, because I'm not in the production phase. But I'm going to delete them soon. Thanks anyway for your comment." } ]
[ { "body": "<p>Quite clean implementation, but some remarks:</p>\n\n<ol>\n<li><p>The header shouldn't compile. It references <code>size_t</code>, but doesn't include stdlib.h.</p></li>\n<li><p>BAL_Any can be faster if you just compare the characters in the pBits array to zero, you don't need to check each individual bit. Same with BAL_Compar.</p></li>\n<li><p>Any particular reason why you denied BAL_Compar that last 'e'?</p></li>\n<li><p><code>strlen</code> is unsafe. Consider adding a size argument to BAL_Load so the user is responsible for passing the right size. This also enables the use of BAL_Load with substrings.</p></li>\n<li><p>Do you want BAL_Load to make \"1000\" from, say, \"1337\" and \"1ABC\"? </p></li>\n<li><p>As Jeff Mercado already said, asserts aren't the best way for error handling, especially for errors the caller didn't cause. Checking for null pointers is ok, but your BAL_Init and BAL_Load should return NULL if an error occured. That way, the caller can at least try to recover.</p></li>\n<li><p>I'm missing a BAL_Toggle.</p></li>\n<li><p>You should consider moving the struct definition into the implementation file. You only use pointers to it, so you can just as well make it opaque. That way, you can change the implementation (i.e. struct-layout) of the array without having to recompile everything that included the header.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T23:55:31.597", "Id": "12994", "ParentId": "12981", "Score": "6" } }, { "body": "<p>Unless I'm misreading something (and there's a very good chance that I am), there's quite a nasty overflow:</p>\n\n<pre><code>void\nBAL_And(BAL_Array *p, BAL_Array *q)\n{\n assert(p != NULL);\n assert(q != NULL);\n\n //p-&gt;nSize is the number of bytes allocated (as shown in the calloc call)\n //and p-&gt;nBits is the number of bits present\n //So unless p-&gt;nBits == p-&gt;nSize this is an overflow\n for (size_t i = 0; i &lt; p-&gt;nBits; ++i)\n p-&gt;pBits[i] &amp;= q-&gt;pBits[i];\n}\n</code></pre>\n\n<hr>\n\n<p>Also, there's an optimization opportunity in a lot of places if you're willing to make your code ugly in a few places. For example, in <code>BAL_Compar</code>, the individual bits only need to be compared for the last <code>unsigned char</code>. For all other <code>unsigned char</code> you can just compare them directly and save a bit of arithmetic.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:18:02.303", "Id": "12997", "ParentId": "12981", "Score": "3" } }, { "body": "<p>Here:</p>\n\n<pre><code>void\nBAL_And(BAL_Array *p, BAL_Array *q)\n{\n assert(p != NULL);\n assert(q != NULL);\n\n for (size_t i = 0; i &lt; p-&gt;nBits; ++i)\n p-&gt;pBits[i] &amp;= q-&gt;pBits[i];\n}\n</code></pre>\n\n<p>here:</p>\n\n<pre><code>void\nBAL_Xor(BAL_Array *p, BAL_Array *q)\n</code></pre>\n\n<p>and here:</p>\n\n<pre><code>void\nBAL_Or(BAL_Array *p, BAL_Array *q)\n</code></pre>\n\n<p>Here if p and q have different nSizes, and p is the bigger one, than you read from an unallocated memory/rest of the q struct.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T01:02:16.237", "Id": "13409", "ParentId": "12981", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T17:07:10.217", "Id": "12981", "Score": "6", "Tags": [ "c", "bitwise" ], "Title": "Managing a bit array" }
12981
<p>How can I improve my remove function? Could someone also give me a solid explanation of the <code>free()</code> function?</p> <p>Here is my remove function:</p> <pre><code>void removeData(void *data, struct accList *theList) { if(theList-&gt;head == NULL) //nothing can be deleted return; else if(theList-&gt;head == theList-&gt;tail) //there is only one element in the list { free(theList-&gt;head); theList-&gt;head = theList-&gt;tail = NULL; } else if(data == theList-&gt;head-&gt;data) //the node to be deleted is the head { struct accListNode *temp = theList-&gt;head; free(theList-&gt;head); theList-&gt;head = temp; theList-&gt;head-&gt;next = temp-&gt;next; } else if(data == theList-&gt;tail-&gt;data) //the node to be deleted is the tail { struct accListNode *cur; for(cur = theList-&gt;head; cur-&gt;next-&gt;next != NULL; cur = cur-&gt;next); theList-&gt;tail = cur; free(cur-&gt;next); cur-&gt;next = NULL; } else //the node to be deleted is any other node { struct accListNode *cur; for(cur = theList-&gt;head; cur != NULL; cur = cur-&gt;next) { if(cur-&gt;data == data) //this is the node we must delete from theList { struct accListNode *temp = cur-&gt;next-&gt;next; free(cur-&gt;next); cur-&gt;next = temp; break; } } } } </code></pre>
[]
[ { "body": "<p>First, about <code>free()</code>. If you need memory, you call <code>malloc()</code> and it will give you a pointer that points to a block of memory that is yours now. The OS will (hopefully) take care that no one else will use this memory. But, as with all resources, be it sockets, open files or threads, you will have to relinquish this memory at one time. At the latest, when your application exits. Better, before that, ideally the moment you don't need it anymore. And that's what <code>free()</code> is for. That pointer you got from <code>malloc()</code>? Give it to <code>free()</code> and you're telling the OS that you're done with this particular block of memory. This will allow other programs to reutilize the memory and keeps your memory footprint small. However, that means that you shouldn't use this memory yourself again. The mean thing is that using the memory anyway might not crash your application right away. That's why it's always a good idea to set a pointer to <code>NULL</code> right after freeing it. That way, if you try to use this pointer again, it will crash directly, making it more obvious where the error is.</p>\n\n<p>If you don't free memory you allocated, it's a memory leak. Especially if this happens periodically, it can be a real problem, because the longer your program runs, the more memory it consumes. Memory it doesn't use, but other programs might need. So always free your memory. Use tools like valgrind to check for leaks and other problems.</p>\n\n<p>Now, to your function. I spotted one little error:</p>\n\n<pre><code>struct accListNode *temp = theList-&gt;head;\nfree(theList-&gt;head);\ntheList-&gt;head = temp; // Does nothing\ntheList-&gt;head-&gt;next = temp-&gt;next; // Potential crash\n</code></pre>\n\n<p>I think the first line should read</p>\n\n<pre><code>struct accListNode *temp = theList-&gt;head-&gt;next;\n</code></pre>\n\n<p>Otherwise, the third line does nothing (it's just the first line in reverse) and the fourth will sooner or later lead to a crash because you're accessing free'd memory.</p>\n\n<p>Then, there's the second case, where there's only one element in the list. Are you sure you want to remove that element without first checking if it's actually the data that was requested to be removed?</p>\n\n<p>And a small optimization in the last case:</p>\n\n<pre><code>for(cur = theList-&gt;head-&gt;next; cur != theList-&gt;tail; cur = cur-&gt;next)\n</code></pre>\n\n<p>You've already established that the data to remove isn't in the tail or head, so you don't need to check them again.\nThe rest is just stylistic:</p>\n\n<pre><code>if(theList-&gt;head == NULL)\n return;\n</code></pre>\n\n<p>Even if it's only one line, it's good practice to put braces around it:</p>\n\n<pre><code>if(theList-&gt;head == NULL) {\n return;\n}\n</code></pre>\n\n<p>Also, you use <code>struct accList</code> a lot. You can make a typedef like so:</p>\n\n<pre><code>typedef struct accList accList\n</code></pre>\n\n<p>It looks a little weird, but after that, you can replace all your <code>struct accList</code> with just <code>accList</code>. To better distinguish it from a variable name, I also recommend renaming it to <code>AccList</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T23:25:00.513", "Id": "12992", "ParentId": "12990", "Score": "5" } }, { "body": "<p>I find it easier when working with hierarchical data structures that the functions you write should be written recursively to make your job as simple as possible. These types lends themselves well for such methods.</p>\n\n<p>The typical structure for such methods will usually have this form:</p>\n\n<ol>\n<li><p>For operations that alter the structure (i.e., add or remove items), it will accept an object to modify and return the modified item. The modified item may or may not be the same exact object that was passed in, depending on the operation you're doing and the state of the object (more on that later). You might be thinking your function does something like this: search through a list to remove an object. Instead, you should be thinking of your functions like this: given a list, return a list that has an object removed from the list.</p></li>\n<li><p>They will be recursive usually doing some operation on the first object in the collection and recursively be called on the rest. The recursion is what drives the code so you generally would not have loops going through the collection. That's not to say you will <em>never</em> have loops, you might have loops going through a <em>subset</em> of the collection, just not the <em>whole</em> collection.</p></li>\n<li><p>Being recursive, the function will perform different actions depending on the state of the object so you'll usually have a set of <code>if</code>/<code>else</code> statements (or if possible, <code>switch</code>). Ideally there'd be only 2-4 different conditions at most. The key is that the conditions should be as general as possible. i.e., have cases for an empty collection, one item and more than one item; don't have cases for an empty collection, one item, two items, three items, four, five, etc.</p></li>\n</ol>\n\n<p>As a side note, you should have separate functions defined to perform the different node manipulations. e.g., functions to create/initialize a new node, to destroy a node, etc. You will need to perform these operations a lot so there you should minimize the amount of copy/pasting to do these.</p>\n\n<p>Though this is C, you should follow C naming conventions. You shouldn't use <code>camelCase</code>, but rather <code>underscore_separated_words</code> (I don't know if there's a name for this convention). I'd recommend naming functions in this form: <code>[type name]_[operation]</code>.</p>\n\n<p>Personally, I'd create <code>typedef</code>s for your types rather than using raw <code>struct</code>s, makes things easier to use and cleaner IMHO.</p>\n\n<p>To rewrite your remove function to follow this form, it would look more like this:</p>\n\n<pre><code>typedef struct _acc_list_node {\n struct _acc_list_node *next;\n void *data;\n} *acc_list_node;\ntypedef struct _acc_list {\n acc_list_node head;\n} *acc_list;\n\n/* you should have a corresponding acc_list_node_create() function */\nstatic void acc_list_node_destroy(acc_list_node node)\n{\n free(node);\n}\n\n/* this is the actual (\"private\") implementation */\nstatic acc_list_node acc_list_node_remove(acc_list_node root, void *data)\n{\n acc_list_node tail;\n\n /* the list is \"empty\", no changes to be made */\n if (root == NULL)\n {\n return root;\n }\n\n /* current node has the data, remove (omit) it */\n if (root-&gt;data == data)\n {\n tail = root-&gt;next;\n acc_list_node_destroy(root);\n return tail;\n }\n\n /* current node does not contain the data, remove data from the tail (if possible) */\n root-&gt;next = acc_list_node_remove(root-&gt;next, data);\n\n return root;\n}\n\nvoid acc_list_remove(acc_list list, void *data)\n{\n if (list == NULL || data == NULL)\n return;\n list-&gt;head = acc_list_node_remove(list-&gt;head, data);\n}\n</code></pre>\n\n<hr />\n\n<p>The <code>free()</code> function is just a function that frees (\"deletes\") dynamically allocated memory (memory that was requested from the runtime by a program when running). You will usually see it in conjunction with <code>malloc()</code> or <code>calloc()</code> (functions that request memory from the runtime).</p>\n\n<p>Think of it this way, functions like <code>malloc()</code> allow you to ask the operating system for some memory. You're free to do whatever you want with that memory for the lifetime of your program. When you're done with that memory, you'd use <code>free()</code> to give that memory back to the operating system.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T23:52:20.150", "Id": "20983", "Score": "1", "body": "+1. A lot of good points, but I strongly disagree with \"Generally when working with hierarchical data structures, the functions you write should be written recursively to make your job as simple as possible.\" In the case of a linked list, recursive versions will be of equal simplicity to iterative versions with worse performance. I think recursive algorithms should only be used when a non-recursive one does not exist or if the non-recursive one is significantly more complicated. Just my $.02 though, I suppose :)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:00:08.927", "Id": "20987", "Score": "0", "body": "My point there was that if you can think in terms of recursive functions, it will make writing your code easier and much more succinct. Iterative code in comparison tends to be a bit more complicated, often with the same blocks of code, just more of it. That and also blame it on my exposure to using and writing functional code in functional languages, a lot of my code tends to be like this. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T08:38:08.003", "Id": "21018", "Score": "0", "body": "`acc_list_node_destroy` can be reduced to a single line because [`free` accepts `NULL` pointers](http://en.cppreference.com/w/c/memory/free) (and does nothing). I.e. the check is redundant. (But it should still be a separate function because the fact that it calls `free` is an implementation detail.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-03T10:55:31.843", "Id": "105906", "Score": "0", "body": "the name of the convention you suggest as alternative to `CamelCase` is `snake_case` :)" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T23:39:34.530", "Id": "12993", "ParentId": "12990", "Score": "2" } }, { "body": "<p>At least in my opinion, the explicit checks for the head or tail being the one you want to remove is pretty much a waste of time and effort. </p>\n\n<p>I'd just walk through the list until you find the correct data or hits the end of the list. I'm also a bit worried about the way you're currently doing comparisons -- you're comparing the address of the data you're searching for to the address of the data in the node. To work reasonably, you normally want to compare the data at the locations, rather than the addresses at which they happen to be stored. To do this, I'd add a field to your structure to say how long its data is.</p>\n\n<pre><code>typedef struct accList acc_list;\n\nvoid remove_data(void *data, size_t len, acc_list *list) {\n while (list != NULL &amp;&amp; memcmp(data, list-&gt;data, len)\n list=list-&gt;next;\n if (list != NULL) {\n acc_list *temp = list-&gt;next;\n free(list-&gt;data);\n list-&gt;data = temp-&gt;data;\n free(temp);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T08:41:39.590", "Id": "21019", "Score": "0", "body": "Better yet, make the check generic (i.e. pass a comparer function pointer, like `qsort` does)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T13:00:02.907", "Id": "21027", "Score": "0", "body": "@Jerry Coffin The reason why I check for the head and tail is because my linked-list has head and tail fields. Thus when the head or tail of the list is removed I need to change the head or tail of the list to the right node." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T13:00:21.063", "Id": "21028", "Score": "0", "body": "@Jerry Coffin. Is there still away around this?" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T05:51:08.603", "Id": "13001", "ParentId": "12990", "Score": "1" } } ]
{ "AcceptedAnswerId": "12992", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T21:24:21.063", "Id": "12990", "Score": "2", "Tags": [ "c", "linked-list" ], "Title": "Linked list remove() and free()" }
12990
<p>I've seen plenty of examples and questions on how to do this, but the issue is that they all rely on a massive database on the server-side. I figured I could try to move that to the client-side. Here's what I have:</p> <pre><code>(function() { var data, pos, read, write, fcnt, tcnt, i, forums, threads, l, fid, id, t, allunread, post; data = {forum:{},thread:{}}; if( localStorage[USERID+'.forumhistory']) { data = JSON.parse(localStorage[USERID+'.forumhistory']); } switch(FORUM_READ.mode) { // in the initialisation, FORUM_READ is an object with: // mode: "index" for the list of forums, "forum" for an individual forum // "thread" for an individual thread. case "forum": threads = document.querySelectorAll('.f_thread'); // each thread element has a "data-id" attribute indicating the thread's ID // and a "data-ts" attribute indicating the timestamp of the most recent post l = threads.length; fid = FORUM_READ.id; for( i=0; i&lt;l; i++) { id = threads[i].getAttribute("data-id"); data.thread[fid] = data.thread[fid] || {}; data.thread[fid][id] = data.thread[fid][id] || data.forum[fid] || DATE; if( threads[i].getAttribute("data-ts")*1000 &gt; data.thread[fid][id]) { threads[i].cells[0].children[0].src = "/img/misc/f_unread.gif"; } else delete data.thread[fid][id]; } data.forum[fid] = DATE; allunread = true; for( i in data.thread[fid]) { allunread = false; break; } if( allunread) { delete data.thread[fid]; } // Fall through to deal with subforums case "index": forums = document.querySelectorAll('.f_forum'); // similarly to threads, forums have "data-id" and "data-ts" attributes l = forums.length; for( i=0; i&lt;l; i++) { id = forums[i].getAttribute("data-id"); data.forum[id] = data.forum[id] || DATE; if( forums[i].getAttribute("data-ts")*1000 &gt; data.forum[id]) forums[i].cells[0].children[0].src = "/img/misc/f_unread.gif"; } break; case "thread": // the last post, #f_post, has a "data-ts" attribute giving its timestamp post = document.getElementById('f_post').getAttribute("data-ts")*1000; fid = FORUM_READ.forum; id = FORUM_READ.id; if( data.thread[fid] &amp;&amp; data.thread[fid][id] &amp;&amp; data.thread[fid][id] &lt; post) { data.thread[fid][id] = post; } break; } localStorage[USERID+'.forumhistory'] = JSON.stringify(data); })(); </code></pre> <p>Now, as far as I can tell this works. However, I haven't really been able to test much due to not having anyone else who can test for me (sometimes working alone sucks...). So I'm hoping that someone here will be able to spot any errors in my logic.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T22:11:23.330", "Id": "20979", "Score": "0", "body": "Please explain what you're code is doing before posting it. The title alone is not necessarily sufficient information for any random person on this site to know what you're attempting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T23:19:32.330", "Id": "20982", "Score": "0", "body": "Basically the idea is that there is an image on each row that lists a thread or forum, defaulting to \"f_read.png\", which should be changed to \"f_unread.gif\" if there is an unread entry." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T23:55:59.397", "Id": "20984", "Score": "0", "body": "What happens when your users delete their client side storage? Everything shows up as unread again? There's a reason for the \"massive database on the server side\" approach." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T23:58:10.547", "Id": "20986", "Score": "0", "body": "@Corbin I think that this is an appropriate usage of localStorage. If everything shows up as unread the site still functions - the only effect is that one user has a slightly less convenient experience. And if that user wants to avoid it, they can stop deleting things they don't know the purpose of." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:01:09.423", "Id": "20988", "Score": "1", "body": "@st-boost That's definitely one way to see it, however, if I were a user, I would not expect that behavior. Also, what about a different browser or different computer? Deleting isn't the only way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:05:00.757", "Id": "20989", "Score": "1", "body": "@Corbin you're right, this can break in completely normal scenarios - between that and the delay in rendering, I'd say a server-side solution is definitely preferable. But I still think of this as an unimportant feature, and therefore an acceptable compromise if server resources are limited." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:09:24.327", "Id": "20991", "Score": "0", "body": "@st-boost Fair enough. However, I'd argue that if server resources are limited, a forum is the wrong thing to be hosting on that server :). I suppose this all comes down to opinion though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:21:57.723", "Id": "20993", "Score": "0", "body": "@Corbin or the current forum software, yes. But I'd say that's outside the scope of this question ... I'm just here to write javascript ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:22:48.537", "Id": "20994", "Score": "0", "body": "@st-boost I consider general approach to be inside the scope of questions. Once again, opinion I suppose :). (Also, there's a reason I posted it as a comment and not an answer.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:25:34.087", "Id": "20996", "Score": "0", "body": "The reason I chose this approach is not because of server resources, but more because the application is already designed to be used in a single browser on a single computer. While of course users are free to use it as they wish, the experience is overall better if they choose a single device/browser to use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:36:29.297", "Id": "20999", "Score": "0", "body": "@Corbin yeah yeah, I get it, you weren't wrong :) Let's just say the best approach depends on the environment, which we don't know much about." } ]
[ { "body": "<p>No big issues that I can see, but here are a few tips.</p>\n\n<hr>\n\n<p>When using for-in loops, add a <code>hasOwnProperty</code> check, like this:</p>\n\n<pre><code>for (var i in obj) {\n if (obj.hasOwnProperty(i) {\n // do stuff\n }\n }\n</code></pre>\n\n<p>Otherwise the loop will also iterate over properties of <code>Object.prototype</code>.</p>\n\n<hr>\n\n<p><code>data</code> can more simply and efficiently be declared like this:</p>\n\n<pre><code>data = localStorage[USERID + '.forumhistory'] ?\n JSON.parse(localStorage[USERID+'.forumhistory']) :\n {forum:{},thread:{}};\n</code></pre>\n\n<hr>\n\n<p>The switch statement might be more legibly written as a series of if else-if statements (with nesting), but that's mostly a stylistic choice.</p>\n\n<hr>\n\n<p><code>data</code> is, actually, the worst variable name there is. It is impossible to create a less specific name. I would suggest renaming it.</p>\n\n<hr>\n\n<p>In loops where you iterate over an array, like this:</p>\n\n<pre><code>var i, l = forums.length;\nfor (i = 0; i &lt; l; i++) {\n // use `forums[i]`\n}\n</code></pre>\n\n<p>If you know every element in <code>forums</code> is truthy (not 0, null, undefined, false, or \"\"), you can use this loop, which is shorter and more efficient, and in my opinion more legible.</p>\n\n<pre><code>var i, forum;\nfor (i = 0; forum = forums[i]; i++) {\n // use `forum`\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:20:30.443", "Id": "20992", "Score": "0", "body": "Okay, thank you for the tips. If I know for a fact that `Object.prototype` is never extended by any of my site's scripts, it is still worth adding that `hasOwnProperty` check?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:24:21.293", "Id": "20995", "Score": "0", "body": "If you're certain `Object.prototype` will never change, then no. But are you really certain? What if you include a third-party script, like an ad?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:26:43.073", "Id": "20997", "Score": "0", "body": "I'm not using any frameworks (I hate the things), and any ads will be served in an iframe from a different domain (I have a centralised ad setup for all my projects) so it can't affect the parent window's stuff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:31:42.687", "Id": "20998", "Score": "1", "body": "@Kolink What about browser add-ons? What if the project gets passed off to somebody else, who doesn't know your code assumes `Object.prototype` is unmodified? In the end it's probably not going to matter, but I always feel uncertain knowing my code assumes anything about its environment. Also, I'm so happy I found somebody else who won't touch frameworks :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:43:10.727", "Id": "21000", "Score": "0", "body": "Okay, understood. I'll make sure to add in the check. And yeah, it's always good to find a non-framework-user! Personally, I like to write my own code so that, when things go wrong, I know for a fact that it's my fault." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:59:42.217", "Id": "21001", "Score": "0", "body": "@Kolink and on top of that, everything runs faster. But I think the biggest downside to frameworks is that they tend to hide problems that require clever thinking or syntax, making it harder for coders to learn more about javascript as they research and write it." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:12:34.943", "Id": "12996", "ParentId": "12991", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T21:27:11.633", "Id": "12991", "Score": "1", "Tags": [ "javascript" ], "Title": "Forum \"read/unread\" in JavaScript" }
12991
<p>I wanted a timer, rather like the Visual Basic object, and I wanted it with no cumulative error. And I wanted it flexible, so I wouldn't have to write another one. I'm very lazy BTW, so lazy that I will go to great lengths to avoid having to write something a second time. Actually, this fits quite well with the "write once, refer often" coding style. I liked the flexibility of the .config() setup style used for Tk controls, so wanted to implement that.</p> <p>I spent a long time searching for timers, and there seemed to be about 3 basic types, I eventually settled on the <code>threading.Timer</code> repeat call model. I spent far too long battling with freezes in IDLE, before realizing that my timers appeared to run OK standalone, and that IDLE just didn't like threads (I've just installed IPython, and will see how that copes once I've learnt my way round it).</p> <p>Then I tried to get a flexible configuration, and that's where code bloat seemed to set in. I've tried to manage it back again by making lists of my attributes, and reusing those lists wherever I need them, I hope this class could serve as a pattern for any future classes with the minimum of editing. I understand the duck typing principle of try rather than test, but I prefer to have errors caught at the time I try to configure something, rather than later at the time I try to use it. I've tried to be as duck-like in my tests as possible, hoping to get the best of both worlds. I am not suggesting my tests are bomb-proof yet, I will test them more thoroughly in due course. My test for valid integers isn't quite as smart as I'd want it yet (accept 4, 0x11, '4', '0x11', reject 3.142) (int() covers enough of that ground for the moment), but that is a simpler issue to be tackled later.</p> <p>My concerns are:</p> <ol> <li><p>Before I use it as a pattern for other classes, have I done a reasonably pythonic job, or am I just kidding myself?</p></li> <li><p>There seem to be a lot of lines of support, and very little payload, could the same effect have been achieved more efficiently?</p></li> <li><p>In searching for timers, I've seen a lot of comments bemoaning the fact that Python libraries don't have a standard repeat timer. Is anybody going to run into trouble using this one?</p></li> </ol> <p></p> <pre><code>import time, threading class Pacer(): """ A Pacer object can be configured at instantiation, using config(kwargs), or at start(kwargs) Call Pacer_obj.config() with no args to get a list of valid kwargs It calls func_tick every period, with non-cummulative error (if possible) Set max_ticks or max_overruns to zero to disable them """ def __init__(self,**kwargs): self.zpint_keys=['max_overruns','max_ticks'] self.pfloat_keys=['period'] self.func_keys=['func_tick','func_done','func_over'] self.private_keys=['N_ticks','N_overruns','t_next_tick'] for key in self.zpint_keys: setattr(self,key,0) for key in self.pfloat_keys: setattr(self,key,1) for key in self.func_keys: setattr(self,key,None) for key in self.private_keys: setattr(self,key,0) self.config(**kwargs) def spill(self): print for key in self.zpint_keys+self.pfloat_keys+self.func_keys+self.private_keys: print key, '=',getattr(self,key) print def start(self,**kwargs): self.config(**kwargs) self.N_ticks=0 self.N_overruns=0 self.t_next_tick=time.time()+self.period self.t=threading.Timer(self.period,self.tick) self.t.start() def tick(self): if self.func_tick: self.func_tick() else: print "you do realise you haven't defined a tick callback, don't you" self.N_ticks += 1 self.t_next_tick += self.period # have we reached maximum number of ticks? if (self.N_ticks &gt;= self.max_ticks) and (self.max_ticks != 0): if self.func_done: self.func_done() else: print 'quit on max ticks, no callback defined' return # quit without scheduling another tick # OK, so still ticking # how long till next, with non-cummulative error time2wait=self.t_next_tick-time.time() if time2wait &lt;= 0: # damn, we've overrun time2wait=0 # set to least time possible self.N_overruns += 1 # how many has that been? if (self.N_overruns &gt;= self.max_overruns) and (self.max_overruns != 0): if self.func_over: self.func_over() else: print 'quit on too many missed schedules, no callback defined' return # quit without scheduling another tick # OK, so *still* ticking self.N_overruns=0 # reset the overrun counter self.t=threading.Timer(time2wait+0.001,self.tick) self.t.start() def stop(self): self.t.cancel() # and really nothing else needs to happen here # it stops the next tick from happening # which stops everything else def config(self,**kwargs): if not kwargs: usage={'non-neg integers':self.zpint_keys, 'positive floats':self.pfloat_keys, 'callback functions':self.func_keys} return usage for key in self.zpint_keys: if key in kwargs: keyval=kwargs.pop(key) try: val=int(keyval) if val&lt;0: print 'parameter ',key, ' must be zero or positive' break except: print 'parameter ',key,' must be an integer' break setattr(self,key,val) for key in self.pfloat_keys: if key in kwargs: keyval=kwargs.pop(key) try: val=float(keyval) if val &lt;= 0: print 'parameter ',key,' must be positive' break except TypeError: print 'parameter ',key,' must be a float' break setattr(self,key,val) for key in self.func_keys: if key in kwargs: keyval=kwargs.pop(key) if not callable(keyval): print 'parameter ',key,' must be callable function' break setattr(self,key,keyval) if kwargs: print 'unknown parameter(s) were supplied to Pacer.config()' print kwargs if __name__=='__main__': def hello(): print 'hello world' q=Pacer() q.spill() b=q.config() print b q.config(max_ticks=7.5) q.spill() q.config(interloper=3) q.config(func_tick=hello,max_ticks=3) q.spill() q.start() time.sleep(5) a=raw_input('press return to quit - ') </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T12:21:43.117", "Id": "21025", "Score": "0", "body": "Add docstrings!" } ]
[ { "body": "<p>My first impression is that it's overengineered by Python standards. (Or maybe just by my standards, which are a little on the cowboy side.)</p>\n\n<p>Some specific crits:</p>\n\n<ul>\n<li>Don't use prints for error cases in the config; raise exceptions instead. For\ndiagnostics that aren't necessarily show-stopping, use the <code>logging</code>\nmodule so that client code can decide how to handle them. </li>\n<li>My initial thought was not to track a callback function for the overrun case, but raise an exception instead, but that's problematic with the threading.</li>\n<li>For a\nprogrammer-facing object, I would never go to so much trouble in\naccepting different datatypes. A string is not a number and\npretending otherwise is dangerous. </li>\n<li>If you insist on retaining the\ntype checking and/or coercion, I would, rather than maintaining three\nseparate lists, maintain one list of (name,type) tuples, or possibly\na dict of lists keyed by type. But really, <code>self.period = float(period)</code>.</li>\n<li>Personally, I feel that <code>kwargs</code> games are for when you're tunneling through Python to an existing API.</li>\n</ul>\n\n<p>Returning usage from config is an interesting idea, useful in the interactive shell... but you still haven't quite explicitly documented the function's behavior in either the usage or the docstring, so a user still has to RTFS, and you've obfuscated the source with a lot of parameter management code that isn't doing useful work.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T09:55:32.010", "Id": "21023", "Score": "0", "body": "Thanks. Over engineered, that's what I was afraid of. A criticism I often level at my co-workers (in contrast to the \"necessary and sufficient\" of logical proof) is that something is unnecessary and insufficient, ie it's a lot of extra work and hasn't acheived the objective. Exceptions and logging - well, I am only \"aspiring level 2\", not got my head round those yet. Can you point to a good howto on logging? Accepting strings - point well taken. I think I should just accept all parameter setting things and then either do one consistency check in start(), or just use them with try/except." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T19:05:29.223", "Id": "21039", "Score": "0", "body": "Your desire to do parameter checking at config time instead of start time is reasonable, though, and we could talk all day about what the right thing to do is the user asks for `max_ticks = 7.5`. I come from the C culture where if you ask for something funny, you'll get defensible efficient behavior if possible or a crash if not, hence I would cast to int and never look back. There's a tutorial for `logging` in the standard library: http://docs.python.org/howto/logging.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T21:51:13.553", "Id": "21105", "Score": "0", "body": "Hmm, I was afraid you'd point me at the docs for logging. I've already read those, and it's left me still not quite certain how it's better than peppering my code with printfs. It must be, because it's there, and people use it. But it's still not clear to me how to use it to save time rather than to learn and type a whole new bunch of stuff." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T22:32:55.947", "Id": "21108", "Score": "2", "body": "`logging` is a lot more flexible in terms of filtering. You can add debugging messages all over the place, then turn them all on or off at once by setting the logging level, while leaving warnings and errors active. Other people using your code can arrange for your logging statements to route to the console, to log files, or to email a sysadmin, or whatever else they want, without changing the internals of your code, etc. Mostly it's somewhat impolite to spew directly to the console from a library that you intend other people to use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T00:25:44.560", "Id": "21372", "Score": "1", "body": "I'm going to concur with Russell Borogove. One python paradigm is \"there should be only one obvious way of doing things.\" In this case logging would be it. Note that the first section of the Logging HOWTO provides a handy table of when to use and when not to use logging." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T01:28:35.040", "Id": "12999", "ParentId": "12995", "Score": "2" } }, { "body": "<p>I think I've done enough thinking in the last week to answer my own question with an update. Thanks very much for all the comments here, and to a related OT post on stackoverflow.</p>\n\n<p>Some of my errors were not knowing about the batteries so I was reinventing wheels. I've kept the things from my first attempt that were specific objectives. However, the comments have helped me to acheive it in a much better way. To make my example clearer, I've stripped out all functionality, leaving only a pattern for the bare class.</p>\n\n<p>Just as python's strict use of indentation can be justified as \"you've got to get it right or it doesn't work\", the style of this class is \"you have to enter the property names, defaults and types, or it doesn't work\". But once you have, the class sets itself up, is self checking and self documenting, up to a point. Moving those to class attributes is an obvious improvement.</p>\n\n<p>Maybe the config() paradigm is frowned upon, but the first non-trivial programming I did in python was using tKinter, which uses that throughout consistently, and I've quite grown to like it. I like the flexibility to be able to instantiate, configure, trigger an object, with freedom for when key properties are set, especially when many are defaulted, or worse not defaulted but don't need to change from the last config. In additon, changing a property should often trigger some action in the objects I envisage, so doing it via a method is the right thing to do. </p>\n\n<p>Spill() was only really for rapid and lazy introspection. Now I've found out about pprint and <code>obj.__dict__</code>, that removes my need for it, and it doesn't really need aliasing. Calling my argument list .usage makes that apparent as well.</p>\n\n<p>Perhaps raising errors for things that could be warnings is a bit draconian, but hey, you've got to get it right or it won't work. I'm not sure I see the need to subclass those yet, maybe later. I'll find out how to use logging in due course. I've a list as long as my arm for things to master yet (pyaudio, {} formatting, matplotlib, etc etc) before that.</p>\n\n<p>I did start to put value checking into the config() function, before realising that there was little point in config bleating about max and min limits being exceeded, when application specific functions would also have to check more complicated value related stuff, like relationships between values. Basically, I felt that value checking in config would be unnecessary and insufficient. That, and reading the meaning of YAGNI on c2.com. Config will simply end with a call to self.consistency_check(), which is use-specific.</p>\n\n<p>Anyhow, this is what I've ended up with. Any more comments on the style, pythonicity etc for points I've not already covered above would be greatly appreciated.</p>\n\n<pre><code>class AnyClass():\n \"\"\" A pattern for a configurable class\n sort of EnthoughtTraitsLite\n \"\"\"\n\n # argument descriptor tuples (namestr,default,types_tuple)\n usage=[('period',1,('float','int','long')),\n ('func_tick','func_tick not defined',('function','str')),\n ('max_ticks',0,('int','long')),\n ('func_done','func_done not defined',('function','str')),\n ('max_overruns',0,('int','long')),\n ('func_over','func_over not defined',('function','str')),\n ('test_anytype',0,'')]\n\n # property descriptor tuples (namestr,default,types_tuple)\n private=[('_N_ticks',0,'int'),\n ('_N_overruns',0,'int'),\n ('_t_next_tick',0,'float')]\n\n def __init__(self,**kwargs): \n # set up properties\n for prop in self.usage+self.private:\n setattr(self,prop[0],prop[1])\n # eat whatever has been passed to it at setup\n self.config(**kwargs)\n\n def config(self,**kwargs):\n for prop_desc in self.usage:\n argname=prop_desc[0]\n OKtypes=prop_desc[2]\n if argname in kwargs:\n argval=kwargs.pop(argname)\n argtype=type(argval).__name__\n if OKtypes and (argtype not in OKtypes):\n raise TypeError('assignment to '+argname+' is type '+argtype+', should be in '+str(OKtypes))\n else:\n setattr(self,argname,argval)\n\n if kwargs:\n raise NameError('unknown parameter(s) '+repr(kwargs)+' supplied') \n\n\nif __name__=='__main__': \n import pprint\n dump=pprint.pprint\n\n def hello():\n print 'hello world'\n\n q=AnyClass()\n print 'usage'\n dump(q.usage)\n\n try:\n # q.config(max_ticks=3.5)\n q.config(max_ticks=-4)\n # q.config(interloper=3) \n q.config(func_tick=hello,max_ticks=3)\n q.config(test_anytype=3)\n except Exception as error:\n print\n dump(error)\n\n print\n print 'show all properties'\n dump(q.__dict__)\n\n a=raw_input('press return to quit - ')\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T09:31:31.737", "Id": "13213", "ParentId": "12995", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T00:02:29.667", "Id": "12995", "Score": "4", "Tags": [ "python", "object-oriented", "timer" ], "Title": "Timer class, to be taken as a model for other classes" }
12995
<p>I am very new to Java and programming theory and am desperately trying to improve my knowledge. This is the first program I've made without help and really would appreciate some feedback. I know there must be 1,000,000 better ways to do what I did.</p> <p>Notes:</p> <ul> <li>I want to move away from <code>main()</code> programming. How could I achieve this program using methods and OOP?</li> <li>I am aware that the <code>Ace</code> should not just be = 11 and should give the user the chance to dictate its value, but implementing that would not of taught me anything new.</li> <li>The way in which I calculated the dealers &amp; users card value is atrocious, especially because I had to re-iterate it constantly. This is the biggest problem I want to fix.</li> </ul> <p>Images of console to give you an idea of two runs:</p> <p><img src="https://i.stack.imgur.com/fUxhU.jpg" alt="enter image description here"></p> <p><img src="https://i.stack.imgur.com/poaPC.jpg" alt="enter image description here"></p> <p>Any and all comments are appreciated. I really want to get to grips with basic Java programming concepts before my bad habits are too engraved to break!</p> <pre><code>import java.util.*; public class BlackJack { public static void main(String[] args) { /* * Scanner &amp;&amp; User Variables */ Scanner kb = new Scanner(System.in); int usersDecision = 0; /* * Users &amp;&amp; Dealers Value Variables */ int usersValue = 0; int dealersValue = 0; /* * Suit &amp;&amp; Rank Arrays */ String[] card = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace"}; /* * Array Lists Users Cards &amp;&amp; Dealers Cards */ ArrayList&lt;String&gt; usersCards = new ArrayList&lt;String&gt;(); ArrayList&lt;String&gt; dealersCards = new ArrayList&lt;String&gt;(); /* * GENERATE DEALERS FIRST CARD */ for (int i = 0; i &lt;= 0; i++) { int randomGenNumber = (int) (Math.random()*13); dealersCards.add(card[randomGenNumber]); } /* * Print Dealers First Card */ System.out.println("The Dealer Was Dealt: " + dealersCards); /* * Deal Users Two Cards */ for (int i = 0; i &lt;= 1; i++) { int randomGenNumber = (int) (Math.random()*13); usersCards.add(card[randomGenNumber]); } /* * Print Users Two Cards */ System.out.println("The User Was Dealt: " + usersCards); /* * Check For BlackJack */ if(usersCards.contains("Ace")) { if(usersCards.contains("King") || usersCards.contains("Queen") || usersCards.contains("Jack") || usersCards.contains("10")){ System.out.println("You've Got BlackJack! Congratulations, You Win!"); System.exit(0); } else { System.out.println("You Did Not Get BlackJack!\n[1] Twist\n[2] Stick"); } } else { System.out.println("You Did Not Get BlackJack! :( \n[1] Twist\n[2] Stick"); } /* * Take Users Decision * Check Users Decision * While Loop * Switch Statement For Users Decision */ int x = 0; while(x==0) { usersDecision = kb.nextInt(); switch (usersDecision) { case 1: System.out.println("You've Twisted - Your Cards: " + usersCards); System.out.println("You've Twisted - Additional Card Dealt"); x = 0; /* * WHILE Twisting = True * Generate New Cards * Check Value of Cards * Bust/Twist/Stick For User */ for (int i = 0; i &lt;= 0; i++) { int randomGenNumber = (int) (Math.random()*13); usersCards.add(card[randomGenNumber]); } System.out.println(usersCards + "\n"); /* * Generate Users Card Value */ usersValue = 0; for(int i = 0; i &lt; usersCards.size(); i++) { if(usersCards.get(i).equals("2")) { usersValue += 2; } else if(usersCards.get(i).equals("3")) { usersValue += 3; } else if(usersCards.get(i).equals("4")) { usersValue += 4; } else if(usersCards.get(i).equals("5")) { usersValue += 5; } else if(usersCards.get(i).equals("6")) { usersValue += 6; } else if(usersCards.get(i).equals("7")) { usersValue += 7; } else if(usersCards.get(i).equals("8")) { usersValue += 8; } else if(usersCards.get(i).equals("9")) { usersValue += 9; } else if(usersCards.get(i).equals("10")) { usersValue += 10; } else if(usersCards.get(i).equals("Jack")) { usersValue += 10; } else if(usersCards.get(i).equals("Queen")) { usersValue += 10; } else if(usersCards.get(i).equals("King")) { usersValue += 10; } else if(usersCards.get(i).equals("Ace")) { usersValue += 11; } } /* * Print Users Value */ System.out.println("Users Cards Value: " + usersValue + ""); if(usersValue != 21 &amp;&amp; usersValue &lt;=21){ System.out.println("You Did Not Get BlackJack!\n[1] Twist\n[2] Stick"); } else if (usersValue == 21) { System.out.println("You Got BlackJack! Congratulations!"); } else if (usersValue &gt; 21) { System.out.println("You've Bust! You Lose!"); System.exit(0); } break; case 2: System.out.println("You've Stuck - Your Cards: " + usersCards +"\n"); x = 1; /* * For Loop * Generate Users Card Value */ usersValue = 0; for(int i = 0; i &lt;usersCards.size(); i++) { if(usersCards.get(i).equals("2")) { usersValue += 2; } else if(usersCards.get(i).equals("3")) { usersValue += 3; } else if(usersCards.get(i).equals("4")) { usersValue += 4; } else if(usersCards.get(i).equals("5")) { usersValue += 5; } else if(usersCards.get(i).equals("6")) { usersValue += 6; } else if(usersCards.get(i).equals("7")) { usersValue += 7; } else if(usersCards.get(i).equals("8")) { usersValue += 8; } else if(usersCards.get(i).equals("9")) { usersValue += 9; } else if(usersCards.get(i).equals("10")) { usersValue += 10; } else if(usersCards.get(i).equals("Jack")) { usersValue += 10; } else if(usersCards.get(i).equals("Queen")) { usersValue += 10; } else if(usersCards.get(i).equals("King")) { usersValue += 10; } else if(usersCards.get(i).equals("Ace")) { usersValue += 11; } } /* * Dealers Second Card * &amp;&amp; * Check Dealers Value &amp;&amp; Take Action */ System.out.println("Dealing Dealers Second Card!"); for (int i = 0; i &lt;= 0; i++) { int randomGenNumber = (int) (Math.random()*13); dealersCards.add(card[randomGenNumber]); } System.out.println(dealersCards + "\n"); /* * For Loop * Generate Dealers Card Value */ dealersValue = 0; for(int i = 0; i &lt; dealersCards.size(); i++) { if(dealersCards.get(i).equals("2")) { dealersValue += 2; } else if(dealersCards.get(i).equals("3")) { dealersValue += 3; } else if(dealersCards.get(i).equals("4")) { dealersValue += 4; } else if(dealersCards.get(i).equals("5")) { dealersValue += 5; } else if(dealersCards.get(i).equals("6")) { dealersValue += 6; } else if(dealersCards.get(i).equals("7")) { dealersValue += 7; } else if(dealersCards.get(i).equals("8")) { dealersValue += 8; } else if(dealersCards.get(i).equals("9")) { dealersValue += 9; } else if(dealersCards.get(i).equals("10")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Jack")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Queen")) { dealersValue += 10; } else if(dealersCards.get(i).equals("King")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Ace")) { dealersValue += 11; } } /* * Print Dealers Value */ System.out.println("Dealers Cards Value: " + dealersValue + ""); /* * Take Action On Dealers Value */ int y = 0; while(y==0) { dealersValue = 0; for(int i = 0; i &lt; dealersCards.size(); i++) { if(dealersCards.get(i).equals("2")) { dealersValue += 2; } else if(dealersCards.get(i).equals("3")) { dealersValue += 3; } else if(dealersCards.get(i).equals("4")) { dealersValue += 4; } else if(dealersCards.get(i).equals("5")) { dealersValue += 5; } else if(dealersCards.get(i).equals("6")) { dealersValue += 6; } else if(dealersCards.get(i).equals("7")) { dealersValue += 7; } else if(dealersCards.get(i).equals("8")) { dealersValue += 8; } else if(dealersCards.get(i).equals("9")) { dealersValue += 9; } else if(dealersCards.get(i).equals("10")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Jack")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Queen")) { dealersValue += 10; } else if(dealersCards.get(i).equals("King")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Ace")) { dealersValue += 11; } } /* * If Dealers Value: * &lt;=16 == 17 &lt; 17 == 21 &gt; 21 * */ if(dealersValue &lt;= 16) { int randomGenNumber = (int) (Math.random()*13); dealersCards.add(card[randomGenNumber]); System.out.println("Dealer Has Less Than 17 - Taking Another Card\n"); System.out.println("Dealers Cards: " + dealersCards); dealersValue = 0; for(int i = 0; i &lt; dealersCards.size(); i++) { if(dealersCards.get(i).equals("2")) { dealersValue += 2; } else if(dealersCards.get(i).equals("3")) { dealersValue += 3; } else if(dealersCards.get(i).equals("4")) { dealersValue += 4; } else if(dealersCards.get(i).equals("5")) { dealersValue += 5; } else if(dealersCards.get(i).equals("6")) { dealersValue += 6; } else if(dealersCards.get(i).equals("7")) { dealersValue += 7; } else if(dealersCards.get(i).equals("8")) { dealersValue += 8; } else if(dealersCards.get(i).equals("9")) { dealersValue += 9; } else if(dealersCards.get(i).equals("10")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Jack")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Queen")) { dealersValue += 10; } else if(dealersCards.get(i).equals("King")) { dealersValue += 10; } else if(dealersCards.get(i).equals("Ace")) { dealersValue += 11; } } System.out.println("Dealers Cards Value: " + dealersValue + "\n"); } /* * Checks dealersValue against usersValue * Prints Response */ if(dealersValue == 17 ) { System.out.println("Dealer Has 17 - Dealer Sticks\n"); y = 1; if(usersValue &lt; 17) { System.out.println("You Have: " + usersValue + " You Lost"); } else if(usersValue == dealersValue) { System.out.println("You Have: " + usersValue + " You Drew"); } else { System.out.println("You Have: " + usersValue + " You Won!"); } } if(dealersValue &gt; 17 &amp;&amp; dealersValue &lt; 21) { System.out.println("Dealer Has: " + dealersValue + " Dealer Sticks\n" ); y = 1; if(usersValue &lt; 18) { System.out.println("You Have: " + usersValue + " You Lost"); } else if(usersValue == dealersValue) { System.out.println("You Have: " + usersValue + " You Drew"); } else { System.out.println("You Have: " + usersValue + " You Won!"); } } if(dealersValue == 21) { System.out.println("Dealer Has BlackJack\n"); y = 1; if(usersValue == dealersValue) { System.out.println("You Have: " + usersValue + " You Drew"); } } if(dealersValue &gt; 21) { System.out.println("Dealer Has Busted - You Win!"); y = 1; } } break; default: System.out.println("Not A Valid Selection"); } }; } } </code></pre>
[]
[ { "body": "<p>You seem to be repeating sections like this.</p>\n\n<pre><code>for (int i = 0; i &lt;= 0; i++) {\n int randomGenNumber = (int) (Math.random()*13);\n\n dealersCards.add(card[randomGenNumber]);\n}\n</code></pre>\n\n<p>First, it does not make sense to use a <code>for</code> loop if the number of loops are just one. On the other hand, I also notice that you have </p>\n\n<pre><code>for (int i = 0; i &lt;= 1; i++) {\n int randomGenNumber = (int) (Math.random()*13);\n usersCards.add(card[randomGenNumber]);\n}\n</code></pre>\n\n<p>So why not refactor both into a separate method?</p>\n\n<pre><code>static final int MaxCard = 13;\nvoid dealCards(ArrayList&lt;String&gt; cards, int num) {\n for (int i = 0; i &lt; num; i++) {\n cards.add(card[(int) (Math.random()*MaxCard)]);\n }\n}\n</code></pre>\n\n<p>And you can use it thus</p>\n\n<pre><code>dealCards(dealersCards, 1); // for the first type\ndealCards(usersCards, 2); // for the second type\n</code></pre>\n\n<p>Also note that it is better to take out numbers such as <code>13</code> and declare them to be a constant with a good variable name that denotes their purpose. It helps you to understand your code at a later time.</p>\n\n<p>--</p>\n\n<pre><code>usersValue = 0;\nfor(int i = 0; i &lt; usersCards.size(); i++) {\n if(usersCards.get(i).equals(\"2\")) {\n usersValue += 2;\n } else if(usersCards.get(i).equals(\"3\")) {\n usersValue += 3;\n } else if(usersCards.get(i).equals(\"4\")) {\n usersValue += 4;\n } else if(usersCards.get(i).equals(\"5\")) {\n usersValue += 5;\n } else if(usersCards.get(i).equals(\"6\")) {\n usersValue += 6;\n } else if(usersCards.get(i).equals(\"7\")) {\n usersValue += 7;\n } else if(usersCards.get(i).equals(\"8\")) {\n usersValue += 8;\n } else if(usersCards.get(i).equals(\"9\")) {\n usersValue += 9;\n } else if(usersCards.get(i).equals(\"10\")) {\n usersValue += 10;\n } else if(usersCards.get(i).equals(\"Jack\")) {\n usersValue += 10;\n } else if(usersCards.get(i).equals(\"Queen\")) {\n usersValue += 10;\n } else if(usersCards.get(i).equals(\"King\")) {\n usersValue += 10;\n } else if(usersCards.get(i).equals(\"Ace\")) {\n usersValue += 11;\n }\n}\n</code></pre>\n\n<p>These sections seem to be repeating again and again. You could make them into a method like above, and call it instead of repeating them.</p>\n\n<pre><code>class NoParse extends Exception {}\n...\nString[] tenValcards = {\"Jack\", \"Queen\", \"King\"};\nint parseCard(String card) throws NoParse {\n char c = card.charAt(0);\n int i = Character.digit(c,10);\n switch(i) {\n case -1: {\n for (String c : tenValueCards)\n if c.equals(card) return 10;\n break;\n }\n case 1: {\n i = Character.digit(card.charAt(1),10);\n if (i == 0) return 10;\n break;\n }\n case 0: break;\n default: return i;\n }\n // handle the parse error.\n throw new NoParse(card);\n} \n</code></pre>\n\n<p>Using it,</p>\n\n<pre><code>usersValue += parseCard(usersCards.get(i));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T16:25:32.353", "Id": "13013", "ParentId": "13004", "Score": "6" } }, { "body": "<ol>\n<li><p>I'd use enums for the cards instead of Strings. It would make the code safer (since the compiler could check typos which is not possible with Strings). Related <em>Effective Java, 2nd Edition</em> chapters:</p>\n\n<ul>\n<li><em>Item 50: Avoid strings where other types are more appropriate</em></li>\n<li><em>Item 30: Use enums instead of int constants</em></li>\n</ul>\n\n<p>The enum values could contain the value of the card. It would improve <a href=\"http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29\">cohesion</a> and help you to get rid of the big if-else if structures, so it'd <a href=\"http://sourcemaking.com/refactoring/replace-conditional-with-polymorphism\">replace conditional with polymorphism</a>. Reference:</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</ul></li>\n<li><p>Furthermore, I'd create a <code>Hand</code> class to store the cards which a user or a dealer has, and it could have at least the following methods:</p>\n\n<ul>\n<li><code>void addCard(Card card)</code></li>\n<li><code>hasBlackJack()</code></li>\n<li><code>int getCardsValue()</code></li>\n</ul>\n\n<p><em>Code Complete 2nd Edition</em> has a good chapter about this (<em>Working Classes</em>).</p></li>\n<li><p>The type of the <code>usersCards</code> reference could be simply <code>List&lt;...&gt;</code>:</p>\n\n<pre><code>List&lt;...&gt; usersCards = new ArrayList&lt;...&gt;();\n</code></pre>\n\n<p>Reference: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p></li>\n<li><p><code>1</code> and <code>2</code> are magic numbers (in <code>[1] Twist\\n[2] Stick</code> and in the switch-case). It should be a named constant. It would improve readability.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T17:47:24.187", "Id": "13015", "ParentId": "13004", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T12:24:37.307", "Id": "13004", "Score": "5", "Tags": [ "java", "object-oriented", "beginner", "game", "playing-cards" ], "Title": "Using multiple methods with Blackjack" }
13004
<p>So this is my code and I would like to add subtraction, multiplication and division. If you have any suggestions on algorithms to use I would be very happy to see it. I do not wish to copy the code, I just want an outline of how to simply, and efficiently create a calculator. I want to make a calculator for KIDS with a friendly UI maybe showing dogs, cats, food etc. as the buttons. With 1 dog/cat for the 1 button and so on.....<br> I wish to put ads in this application, but I want the ads just to be under a donation/ad tab. </p> <p>Tell me what you think, questions, comments and concerns would be very much appreciated to help develop my app :)</p> <pre><code>package com.nickmarcoose.addingcalculatorfree; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class Addition extends Activity { EditText amount1; EditText amount2; TextView views; Button Addition1; double a; double b; double c; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); initControls(); } private void initControls() { amount1=(EditText)findViewById(R.id.amount1); amount2=(EditText)findViewById(R.id.amount2); views=(TextView)findViewById(R.id.view); Addition1=(Button)findViewById(R.id.start); Addition1.setOnClickListener(new Button.OnClickListener() { public void onClick (View view) { calculate();} }); } private void calculate() { a=Double.parseDouble(amount1.getText().toString()); b=Double.parseDouble(amount2.getText().toString()); c=b+a; views.setText(Double.toString(c)); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T14:53:58.410", "Id": "21030", "Score": "2", "body": "Your creating an app for kids so young they are still learning to count and you think it's appropriate to put ads in?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T15:12:48.910", "Id": "21031", "Score": "2", "body": "@James\nYou are right, great point. i should take them out until i get into more advanced UI and ages." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T12:37:49.277", "Id": "21058", "Score": "0", "body": "Your class seems to be incomplete - the `calculate()` method isn't even closed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T15:42:36.573", "Id": "21077", "Score": "0", "body": "@Donald.McLean it seems to be? can you elaborate or include what i should do?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T15:49:45.510", "Id": "21078", "Score": "0", "body": "it shows that it is closed at the end, but i am not 100% sure on how to check what you edited in the post. thanks in advance for helping." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:33:51.020", "Id": "21139", "Score": "0", "body": "My mistake. The formatting was so random that there was no way to tell which braces went with what." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T18:24:08.793", "Id": "21177", "Score": "0", "body": "@Donald.McLean how could i make it neater?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T12:21:57.027", "Id": "21208", "Score": "0", "body": "I already fixed the formatting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T19:17:58.010", "Id": "21257", "Score": "0", "body": "@Donald.McLean thank you so much for your help. and James . i know this isn't that good of an application but i am very appreciative." } ]
[ { "body": "<p>Not very familiar with Android development, so some of this may be totally off the rails.</p>\n\n<p>Depending on how educational you want this to be, you could visually demonstrate simple algorithms to teach how various operations work (e.g. animations). Also, since you're targeting little kids, I'm not sure double is necessary.</p>\n\n<p>Kid-friendly algorithms you could demonstrate below. You could step through each stage of an operation, e.g. by moving animals from pile to pile. You could skip demonstrations if the numbers are large, or make them run in the background/interruptable.</p>\n\n<pre><code>public int add(int left, int right)\n{\n if (right == 0)\n {\n return left;\n }\n return add(left + 1, right - 1);\n}\n\npublic int subtract(int left, int right)\n{\n if (right == 0)\n {\n return left;\n }\n return subtract(left - 1, right - 1);\n}\n\npublic int multiply(int left, int right)\n{\n if (left == 0 || right == 0)\n {\n return 0;\n }\n\n if (left == 1)\n {\n return right;\n }\n else if (right == 1)\n {\n return left;\n }\n\n if (left &lt; right)\n {\n return multiplyByAdding(right, left, 0);\n }\n\n return multiplyByAdding(left, right, 0);\n}\n\nprivate int multiplyByAdding(int baseNumber, int timesLeft, int productSoFar)\n{\n if (timesLeft == 0)\n {\n return productSoFar;\n }\n\n return multiplyByAdding(baseNumber, timesLeft - 1, productSoFar + baseNumber);\n}\n\n//division by zero needs to be handled at UI level to explain why it doesn't work\n//you might want to do something other than throwing an exception here\npublic int divide(int dividend, int divisor) throws ArithmeticException\n{\n if (divisor == 0)\n {\n throw new ArithmeticException();\n }\n return divideBySubtracting(dividend, divisor, 0);\n}\n\nprivate int divideBySubtracting(int dividend, int divisor, int quotientSoFar)\n{\n divident -= divisor;\n if (dividend &lt;= 0)\n {\n return quotientSoFar;\n }\n return divideBySubtracting(divident, divisor, quotientSoFar + 1);\n}\n\n//division explains this, so we can cheat here\npublic int modulo(int dividend, int divisor)\n{\n return dividend % divisor;\n}\n</code></pre>\n\n<p>In the code you posted, you have UI and logic mixed together. You probably want to separate them into different modules to keep them clean.</p>\n\n<p>The following is rough pseudocode for how I might organize things. I've left out a lot of stuff that would need to be filled in to make this work, of course.</p>\n\n<pre><code>public enum Operation\n{\n Addition,\n Subtraction,\n Multiplication,\n Division\n}\n\npublic class Calculator\n{\n public int calculate(int left, int right, Operation op)\n {\n switch(op)\n {\n case Operation.Addition:\n return add(left, right);\n case Operation.Subtraction:\n return subtract(left, right);\n case Operation.Multiplication:\n return multiply(left, right);\n case Operation.Division:\n return divide(left, right);\n default:\n throw new UnsupportedOperationException(operation.toString() + \" not implemented.\");\n }\n }\n}\n\npublic class MyActivity extends Activity\n{\n Operation operation;\n\n //...\n\n void calculate()\n {\n a = calculator.parse(leftAmount);\n b = calculator.parse(rightAmount);\n answer = calculator.calculate(operation, a, b);\n if (operation == Operation.Division)\n {\n remainder = calculator.modulo(a, b);\n }\n update();\n }\n\n //called when leftOp, rightOp, and/or answer change\n //numbers greater than 10 could just be printed numbers\n void update(int leftOp, int rightOp, int answer)\n {\n remainderView.clear();\n\n if (leftOp != previousLeftOp)\n {\n leftView.setContent( ImageFactory.getImageByNumber(leftOp), leftOp );\n }\n\n if (rightOp != previousRightOp)\n {\n rightView.setContent( ImageFactory.getImageByNumber(rightOp), rightOp );\n }\n\n if (answer != previousAnswer)\n {\n answerView.setContent( ImageFactory.getImageByNumber(answer), answer );\n if (operation == Operation.Division &amp;&amp; remainder != 0)\n {\n remainderView.setContent( ImageFactory.getImageByNumber(remainder), remainder );\n }\n }\n previousLeftOp = leftOp;\n previousRightOp = rightOp;\n previousAnswer = answer;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T12:43:51.583", "Id": "21506", "Score": "1", "body": "I just woke up and read this, and i'm amazed how easy you made it look. now i can convert that into my own+android version of it. but i plan on making it more than one variable that can be combined with */-+ operations.\nso like maybe x+6=1. i want to be able to make like this. but i want to figure this out on my own. so thank you for helping me get started. I plan on making a few modifications to the whole thing though, and maybe changing some colors. like if the number is negative make it red. and positive is blue. unreal numbers are purple. (kids=4<->14)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T07:37:50.793", "Id": "13307", "ParentId": "13005", "Score": "2" } } ]
{ "AcceptedAnswerId": "13307", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T12:34:31.107", "Id": "13005", "Score": "3", "Tags": [ "java", "android", "calculator" ], "Title": "Basic android calculator" }
13005
<p>I've created a simple Javascript library to be able to create "classes" and extend them defining instance and static methods and variables.</p> <p>It consists in a simple function Class with two methods: create and extend.</p> <pre><code>var Class = function(){}; Class.extend = function(obj){ var Extended = function(){}; for(var key in this.prototype){ Extended.prototype[key] = this.prototype[key]; } for(var key in obj){ Extended.prototype[key] = obj[key]; }; Extended.prototype.constructor = Extended; for (var key in this) { Extended[key] = this[key]; }; return Extended; }; Class.create = function(constructor){ var created = new this(); for(var key in constructor){ created[key] = constructor[key]; } return created; }; </code></pre> <p>Here there's an example of what the library is able to do:</p> <pre><code>var Model = Class.extend({ fields: {}, save: function(){ return "saving a model at " + Model.url; }, destroy: function(){ return "destroying..."; } }); Model.url = "http://localhost"; Model.all = function(){ return "all from " + Model.url; }; Model.find = function(id){ return "finding by " + id; }; var User = Model.extend({ fields: { username: "default username", password: "default password", }, logout: function(){ return "logged out " + this.fields.username; }, destroy: function(){ return this.logout() + " and account destroyed!"; } }); User.url = Model.url + "/users"; User.all = function(){ return "overriding parent! all from " + User.url; } User.findByUsername = function(username){ return "finding by username: " + username; }; </code></pre> <p>And I've created a js fiddle to test the example <a href="http://jsfiddle.net/R6jGe/" rel="nofollow">http://jsfiddle.net/R6jGe/</a></p> <p>There's no way to call a parent instance method or variable.</p> <p>how do you think the library could be improved?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T14:12:18.997", "Id": "21029", "Score": "0", "body": "[Fixed your code](http://jsfiddle.net/R6jGe/3/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T20:41:30.007", "Id": "21101", "Score": "0", "body": "@Raynos: you have lost distinction between static methods vs instance methods. Matteo: you are unable to have private variables share between privileged class methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T21:01:18.420", "Id": "21102", "Score": "0", "body": "@BillBarry there is no distinction between static & instance. private variables have no value. privileged methods are silly" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:53:31.337", "Id": "21126", "Score": "0", "body": "@Raynos i need distinction between static and instance methods." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:53:42.540", "Id": "21127", "Score": "0", "body": "@BillBarry mmm... for private variables I may use the module pattern but i don't think i need them for now... but how to share them between privileged methods?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T14:31:57.000", "Id": "21147", "Score": "0", "body": "@MatteoPagliazzi [distinction between static and instance](http://jsfiddle.net/R6jGe/6/). The notion of private variables are still silly. Simply do not use them." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T15:39:27.807", "Id": "21151", "Score": "0", "body": "@Raynos: I've been playing with this some now (I don't generally do inheritance OOP in JS because there is a lot of space for subtle errors) but I have managed to [come up with this.](http://stackoverflow.com/questions/8032566/emulate-super-in-javascript/11199220#11199220)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T15:46:17.937", "Id": "21152", "Score": "0", "body": "That last [JsFiddle](http://jsfiddle.net/R6jGe/8/) is pretty good, but I think it loses a little of the link between the `Model` class and an instance of the `ModelProto` class (and same for `User`; though I am not sure that is a bad thing, perhaps the need for class level variables is a sign of something smelly elsewhere). I updated it to get rid of the global errors (you get them because of it trying to grab files that don't exist)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:20:40.053", "Id": "21156", "Score": "0", "body": "@BillBarry I have completely given up on class models. That particular question is only interesting if you can answer the \"how to have correct super mechanics\" part of the question. Keep pestering me on [chat.SO](http://chat.stackoverflow.com/rooms/17/javascript) to look into your solution and at some point I'll give good critique." } ]
[ { "body": "<p>I read your code several times, and I could only find few observations:</p>\n\n<ul>\n<li>jQuery has <code>extend</code> as well, the idea of it is sound, you could consider working with <code>arguments</code> and allow for n objects like jQuery does</li>\n<li>I am not sure that always overriding the constructor is a good idea in <code>extend</code></li>\n<li>In the same vein, your approach does not allow for custom constructors that take parameters, whereas most OO classes have those ( <code>new Customer( \"Bob\" )</code> to give a silly example)</li>\n<li>From a lint perspective:\n<ul>\n<li>You declare <code>var key</code> thrice in <code>extend</code>, you only need to declare it once, preferably on top</li>\n<li><code>for</code> loop blocks do not need semicolons</li>\n<li>You should really look into <code>.hasOwnProperty()</code>, I am pretty sure your code can cause subtle bugs by smushing everything together</li>\n</ul></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T14:01:27.567", "Id": "40739", "ParentId": "13006", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T13:17:56.037", "Id": "13006", "Score": "3", "Tags": [ "javascript", "object-oriented", "classes", "prototypal-class-design" ], "Title": "Implementation of Javascript Classes and Inheritance" }
13006
<p>For the following C linked list implementation, please give me some suggestions for improved efficiency, style and design. This implementation is not 100% complete, please give some suggestions for additional features. Notice the data type for the list is void*, I want it to be as generic as possible.</p> <p>accList.h:</p> <pre><code>#ifndef ACCLIST_H #define ACCLIST_H #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; struct accListNode //the nodes of a linked-list for any data type { void *data; //generic pointer to any data type struct accListNode *next; //the next node in the list }; struct accList //a linked-list consisting of accListNodes { struct accListNode *head; struct accListNode *tail; int size; }; void accList_allocate(struct accList *theList); //allocate the accList and set to NULL void appendToEnd(void *data, struct accList *theList); //append data to the end of the accList void removeData(void *data, struct accList *theList); //removes data from accList #endif </code></pre> <p>accList.c:</p> <pre><code>#include "accList.h" #include "cmpsc311.h" void accList_allocate(struct accList *theList) //allocate and initialize to NULL values { theList = Malloc(sizeof(struct accList)); theList-&gt;head = NULL; theList-&gt;tail = NULL; theList-&gt;size = 0; } void appendToEnd(void *data, struct accList *theList) { struct accListNode *newNode = Malloc(sizeof(struct accListNode)); newNode-&gt;data = data; newNode-&gt;next = NULL; if(theList-&gt;head == NULL) //the list is empty { theList-&gt;head = theList-&gt;tail = newNode; } else //the list is not empty { theList-&gt;tail-&gt;next = newNode; theList-&gt;tail = newNode; } } void removeData(void *data, struct accList *theList) { if(theList-&gt;head == NULL) //the list is empty return; else if(theList-&gt;head == theList-&gt;tail) //there is one element in the list { free(theList-&gt;head); theList-&gt;head = NULL; } else if(data == theList-&gt;head-&gt;data) //the element to be removed is the head { struct accListNode *temp = theList-&gt;head-&gt;next; free(theList-&gt;head); theList-&gt;head = temp; } else if(data == theList-&gt;tail-&gt;data) //the element to be removed is the tail { struct accListNode *cur; struct accListNode *prev = NULL; for(cur = theList-&gt;head; cur-&gt;next != NULL; prev = cur, cur = cur-&gt;next); free(theList-&gt;tail); prev-&gt;next = NULL; theList-&gt;tail = prev; } else //any other node { struct accListNode *prev = NULL; struct accListNode *cur; for(cur = theList-&gt;head; cur != NULL; prev = cur, cur = cur-&gt;next) { if(cur-&gt;data == data) //this is the node we must free { prev-&gt;next = cur-&gt;next; free(cur); } } } } </code></pre> <p>I think the remove function needs the most work. I did post that function on this site, however I think I needed to include the whole implementation to get the best feedback. Will this work on an embedded system?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-22T01:15:49.680", "Id": "45330", "Score": "0", "body": "What happens to the size variable of the accList ? Should be updated whenever you add a new node in the list right ?" } ]
[ { "body": "<p>I see two issues with the removeData function. The first is in the \"single item list\" section:</p>\n\n<pre><code>else if(theList-&gt;head == theList-&gt;tail) //there is one element in the list\n{\n free(theList-&gt;head);\n theList-&gt;head = NULL;\n}\n</code></pre>\n\n<p>What happens if I have a list with a single item in it, and I ask the removeData() function to remove a piece of data that <em>isn't</em> in the list? It'll remove the wrong item instead of ignoring the function call. It should really look like this:</p>\n\n<pre><code>else if(theList-&gt;head == theList-&gt;tail) //there is one element in the list\n{\n if (theList-&gt;head-&gt;data == data) {\n free(theList-&gt;head);\n theList-&gt;head = NULL;\n theList-&gt;tail = NULL;\n }\n}\n</code></pre>\n\n<p>Note that I also set the tail pointer to NULL, which you've missed.</p>\n\n<p>Secondly, the section of the function that deals with searching for the data within the list should really exit once it finds a match, unless you are specifically intending to remove <em>all</em> instances of <code>data</code> from the list.</p>\n\n<p>Here's the code:</p>\n\n<pre><code>if(cur-&gt;data == data) //this is the node we must free\n{\n prev-&gt;next = cur-&gt;next;\n free(cur);\n}\n</code></pre>\n\n<p>Here's what I'd do:</p>\n\n<pre><code>if(cur-&gt;data == data) //this is the node we must free\n{\n prev-&gt;next = cur-&gt;next;\n free(cur);\n return;\n}\n</code></pre>\n\n<p>To make it more obvious what's going on, I'd probably rename the function to <code>removeFirstInstance()</code>, and maybe have another function called <code>removeAllInstances()</code> that followed your current design, but that's somewhat anathema to the terseness of idiomatic C (I like descriptive names rather than obtuse names that encourage me constantly to have the API docs open).</p>\n\n<p>I can also see an opportunity for a tiny optimisation:</p>\n\n<pre><code>for(cur = theList-&gt;head; cur != NULL; prev = cur, cur = cur-&gt;next)\n</code></pre>\n\n<p>You already know that the data isn't stored in the head node from earlier if statements, so you can skip the first item in the search loop:</p>\n\n<pre><code>for(cur = theList-&gt;head-&gt;next; cur != NULL; prev = cur, cur = cur-&gt;next)\n</code></pre>\n\n<p>If I were to rewrite this method it'd probably look like this:</p>\n\n<pre><code>void removeData(void *data, struct accList *list) {\n\n struct accListNode *previous = NULL;\n struct accListNode *current = list-&gt;head;\n\n while (current != NULL) {\n\n if (current-&gt;data == data) {\n\n if (list-&gt;head == current) list-&gt;head = current-&gt;next;\n if (list-&gt;tail == current) list-&gt;tail = previous;\n\n if (previous != NULL) previous-&gt;next = current-&gt;next;\n\n free(current);\n --size;\n return;\n }\n\n previous = current;\n current = current-&gt;next;\n }\n}\n</code></pre>\n\n<p>I'd forgo the micro-optimsation of all of the guard clauses in favour of a shorter method.</p>\n\n<p>One more problem that applies generally: you have a <code>size</code> value in the list struct but you never change its value. Either increase it in the append function and decrease it in the remove function or remove it from the struct. As it stands it is misleading.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T14:39:53.260", "Id": "13009", "ParentId": "13007", "Score": "3" } }, { "body": "<p>Several problems I see:</p>\n\n<h2>accList_allocate</h2>\n\n<p><code>accList_allocate</code> doesn't do what you probably think. It creates a new <code>accList</code>, yes, but this new one will not be visible to the caller (and thus, will be lost as memory leakage). If you want to initialize the pointer passed to it, use a pointer-to-pointer:</p>\n\n<pre><code>void accList_allocate(struct accList **outList) //allocate and initialize to NULL values\n{\n struct accList* theList = Malloc(sizeof(struct accList));\n theList-&gt;head = NULL;\n theList-&gt;tail = NULL;\n theList-&gt;size = 0;\n *outList = theList;\n}\n</code></pre>\n\n<p>Also, you should really check the return value of <code>Malloc</code>. Especially on embedded systems, there's a real possibility of running out of memory. Let the caller handle the error, but tell him that something's wrong.</p>\n\n<h2>appendToEnd</h2>\n\n<p>Same as with <code>accList_allocate</code>, check <code>Malloc</code>'s return value and return some kind of error code if it's NULL. What you're writing there is library code that should always handle errors gracefully and let the caller decide whether to crash and burn or recover and try again.</p>\n\n<h2>removeData</h2>\n\n<p>Please refer to <a href=\"https://codereview.stackexchange.com/a/12992/14047\">my answer in your other thread</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T14:53:47.913", "Id": "13011", "ParentId": "13007", "Score": "8" } }, { "body": "<p>Isn't this an issue?</p>\n\n<pre><code>void appendToEnd(void *data, struct accList *theList)\n{\n struct accListNode *newNode = Malloc(sizeof(struct accListNode));\n newNode-&gt;data = data; &lt;===\n</code></pre>\n\n<p>What happens if the input is freed. The linked list will also lose the value.\nI think the value should be copied here.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T04:33:01.973", "Id": "13034", "ParentId": "13007", "Score": "3" } } ]
{ "AcceptedAnswerId": "13011", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T14:13:41.143", "Id": "13007", "Score": "8", "Tags": [ "c", "linked-list" ], "Title": "C linked list implementation" }
13007
<p>Everything in this code is completely working, but I still feel that this code needs to be refactored. any suggestions? </p> <pre><code>&lt;?php class Db_CheckUsername{ protected $_conn; protected $_username; protected $_minimumChars = 8; protected $_errors = array(); public function __construct($username, $conn){ $this-&gt;_username = $username; $this-&gt;_conn= $conn; } public function check(){ $sql = "SELECT * FROM accounts WHERE username = '{$this-&gt;_username}'"; $result = $this-&gt;_conn-&gt;query($sql); $numRows = $result-&gt;num_rows; if(preg_match('/\s/',$this-&gt;_username)){ $this-&gt;_errors[] = "Spaces are not allowed"; } if($numRows &gt; 0){ $this-&gt;_errors[] = "Username Taken"; } if(strlen($this-&gt;_username) &lt; $this-&gt;_minimumChars){ $this-&gt;_errors[] = "Username Should Contain, atleast {$this-&gt;_minimumChars} chars"; } return $this-&gt;_errors ? false : true; } public static function isUsernameCorrect($username,$conn){ } public function getErrors(){ return $this-&gt;_errors; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T20:01:38.687", "Id": "21040", "Score": "0", "body": "consider writing ORM model" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T20:08:03.060", "Id": "21041", "Score": "0", "body": "one function does perform too many tasks. Drop this one into small ones" } ]
[ { "body": "<p>I meant to write one or two brief points when I started writing this, but erm, ended up a bit more :). Anyway, some of the stuff is quite briefly explained, so if anything needs more elaboration/defense, let me know and I'll edit in more information.</p>\n\n<p><strong>SQL Injection</strong></p>\n\n<p>Your query that checks for the username is open to SQL injection. You should use <a href=\"http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php\" rel=\"nofollow\">prepared statements</a>.</p>\n\n<p><strong>Don't pass in the username</strong></p>\n\n<p>If you pass the username to <code>check()</code> instead of to the constructor, the object can be reusable.</p>\n\n<pre><code>public function check($username) { ... }\n</code></pre>\n\n<p><strong>Allow configuration</strong></p>\n\n<p>You might as well allow <code>$_minimumChars</code> to be configured. There's a lot of ways to go about this, but as long as it's only one configuration item, the easiest way would be an argument in the constructor:</p>\n\n<pre><code>public function __construct(mysqli $conn, $minimumChars = 8)\n{\n $this-&gt;_conn = $conn;\n $this-&gt;_minimumChars = $minimumChars;\n}\n</code></pre>\n\n<p><strong>Be strict about types when possible (and reasonable)</strong></p>\n\n<p>If the signature is:</p>\n\n<pre><code>public function __construct(mysqli $conn, $minimumChars = 8)\n</code></pre>\n\n<p>And the object is created accidentally with something that is not an instance of <code>mysqli</code>, the error will be caught much sooner than if the strict check is not there. Not particularly required, just there's not a very strong reason against it.</p>\n\n<p><strong>Break it up into more classes -- Part 1 - Validators</strong></p>\n\n<p>The benefit of this is very arguable with a small code base, however, later down the road, it will likely be nice. Consider breaking each validation into its own class:</p>\n\n<pre><code>interface Validator {\n public function isValid($input);\n public function getErrors();\n}\n\n//Because I'm lazy :p\nclass Validator_AbstractValidator {\n\n private $_errors = array();\n\n abstract public function isValid($input);\n\n public function getErrors()\n {\n return $this-&gt;_errors;\n }\n\n protected function _addError($message) {\n $this-&gt;_errors[] = $message;\n }\n\n}\n\nclass Validator_NoSpaces extends Validator_AbstractValidator {\n public function isValid($input) {\n //You would probably want to add a check that $input can be cast to a string\n if (preg_match('/\\s/', $input)){\n $this-&gt;_addError(\"Spaces are not allowed\");\n return false;\n }\n return true;\n }\n}\n\nclass Validator_MinimumLength extends Validator_AbstractValidator {\n\n protected $_minLength;\n\n public function __construct($minLength)\n {\n if (!is_int($minLength) &amp;&amp; !ctype_digit($minLength)) {\n throw new Validator_Exception(\"minLength must be an integer\");\n }\n $this-&gt;_minLength = (int) $minLength;\n }\n\n public function isValid($input)\n {\n //Once again, should probably have some kind of validation that $input\n //can be cast to a string\n if (strlen($input) &gt; $this-&gt;_minLength) {\n return true;\n } else {\n $this-&gt;_addError(\"Input must be at least {$this_minLength}\");\n return false;\n }\n }\n\n}\n</code></pre>\n\n<p>The advantage of this is that it allows you to abstract away the idea of validations, and it allows you to centralize the management of validation rules. For example, suppose that your username and email address fields both had the requirement that they not contain spaces.</p>\n\n<p>Now, what if you want to change the logic from the regular expression, to a more strict, <code>strpos($input, ' ') === false</code>? If the validations are all abstracted away, you only have to change this code in one place. If you've repeated the low level validations inside of your <code>Db_CheckUsername</code>, you have to change it in two places. (This is one of the major aspects of DRY by the way.)</p>\n\n<hr>\n\n<p>You may have noticed that the error messages are hard coded. This would likely not be the desired behavior. What you could do there is store the errors in some kind of array indexed by error type, and then instead of <code>_addError</code> adding a raw message, it would add an error type (which would map to an error). <em>(Note: this approach is 100% stolen from the Zend Framework validators :))</em></p>\n\n<p><strong>Break it up into more classes -- Part 2 - Element</strong></p>\n\n<p>This obviously leaves your code in a rather awkward spot, though the obvious solution of replacing the validations in the <code>check</code> method with the validators is essentially the solution.</p>\n\n<p>What I would do is abstract away the idea of form element. You could take the idea as far as a you want (rendering, data manipulation, so on), but I'll just focus on validation:</p>\n\n<pre><code>//We want the element to have an isValid method and a getErrors method()\n//(you could make a separate interface for this, but really an element is\n//just a collection of Validator instances)\ninterface Form_ElementInterface extends Validator { }\n\nclass Form_Element_AbstractElement extends Validator_AbstractValidator implements Form_ElementInterface\n{\n\n protected $_validators = array();\n\n public function addValidator(Validator $validator)\n {\n $this-&gt;_validators[] = $validator;\n }\n\n public function getValidators()\n {\n return $this-&gt;_validators;\n }\n\n protected function _addErrors(array $errors)\n {\n foreach ($errors as $error) {\n $this-&gt;_addError($error);\n }\n }\n\n public function hasErrors()\n {\n return (count($this-&gt;getErrors()) !== 0);\n }\n\n public function isValid($input)\n {\n foreach ($this-&gt;_validators as $validator) {\n if (!$validator-&gt;isValid($input)) {\n $this-&gt;_addErrors($validator-&gt;getErrors());\n }\n }\n return !$this-&gt;hasErrors();\n }\n\n}\n\nclass Form_Element_Username extends Form_Element_AbstractElement\n{\n public function __construct($minLength = 8)\n {\n $this-&gt;addValidator(new Validator_NoSpaces());\n $this-&gt;addValidator(new Validator_MinimumLength($minLength));\n //...\n }\n}\n</code></pre>\n\n<p>Some of the names have gotten a little bleh, but hopefully the concept is still there. (I can never decide what to name interfaces/abstract classes...)</p>\n\n<p>I don't particularly like the design of <code>Form_Element_Username</code> there. I would probably just use the elements from the outside instead of creating a complicated graph of objects and dependencies (a <code>mysqli</code> would have to be passed through there for example).</p>\n\n<pre><code>$username = new Form_Element();\n$username-&gt;addValidator(new Validator_NoSpaces());\n$username-&gt;addValidator(Validator_UserNotExists($db));\n</code></pre>\n\n<p>Or if you decided to take the flexible error message route, it may look like:</p>\n\n<pre><code>$username = new Form_Element();\n$username-&gt;addValidator(new Validator_NoSpaces(array(\n 'messages' =&gt; array(\n Validator_NoSpaces::CONTAINS_SPACE =&gt; \"Usernames cannot contain spaces\"\n ),\n)));\n$username-&gt;addValidator(Validator_UserNotExists(array(\n 'db' =&gt; $db,\n 'messages' =&gt; array(\n Validator_UserNotExists::USERNAME_EXISTS =&gt; \"The username provided already exists\",\n ),\n)));\n</code></pre>\n\n<p>Note that passing in an array of arguments instead of proper separate parameters is often bad practice. (In fact, it's definitely bad practice here.) It has the advantage though of allowing you to easily store data in config files and then construct validators based on that.</p>\n\n<p><strong>Break it up into more classes -- Part 3 - Form</strong></p>\n\n<p>(Not going to write code on this as the concept should be clear by now.)</p>\n\n<p>Just as an Element is a collection of validations, a form is, in a lot of ways, just a collection of elements. You could extend the idea of elements and validators to entire forms which would provide centralized management of form logic, and much cleaner use than the 10-20 lines it would take to make each element in the way presented above.</p>\n\n<pre><code>class Form_UserRegistration extends Form_AbstractForm\n{\n //In the constructor or some kind of setup method (called by the abstract constructor),\n //you would want to a username element, a password element, and so on\n}\n</code></pre>\n\n<p>Then the usage:</p>\n\n<pre><code>$errors = null;\n$regForm = new Form_UserRegistration();\n\nif ($_SERVER['REQUEST_METHOD'] === \"POST\") {\n if ($regForm-&gt;isValid($_POST)) {\n //Create the user\n } else {\n //Render these under the form or something\n $errors = $regForm-&gt;getErrors();\n }\n}\n</code></pre>\n\n<p><strong>Design note</strong></p>\n\n<p>It's a bit of an odd design to mutate the errors array behind the scenes while only returning a bool from <code>isValid</code>. In particular, it may be a bit cleaner design to directly return the array of errors. I didn't go with this approach because it complicates use of the objects, and the framework I'm most familiar with does it with two separate methods, so it's just what I'm used to.</p>\n\n<p>Basically, the isValid method could look like:</p>\n\n<p>For completeness:</p>\n\n<pre><code>public function validate($input) {\n $errors = array();\n\n if (...) {\n $errors[] = \"...\";\n }\n\n return $errors;\n\n}\n\n//Usage:\n$errors = $obj-&gt;validate($input);\nif (count($errors)) {\n //errors\n} else {\n //success\n}\n</code></pre>\n\n<p>(Or you could return <code>true</code> in place of the empty array)</p>\n\n<p><strong>ZF Credit</strong></p>\n\n<p>I should mention that Validator and Element concepts are highly based on the Zend Framework <code>Zend_Validate_Interface</code> and <code>Zend_Element_Abstract</code> classes.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T21:46:48.053", "Id": "21042", "Score": "0", "body": "\"If you pass the username to check() instead of to the constructor, the object can be reusable.\" - Then, the `$_error` should not be a class instance. Anyway, +1 :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T22:16:18.033", "Id": "21044", "Score": "0", "body": "@palacsint I considered that quite a bit when making the Validator interface and couldn't decide how I feel about it. I suppose it is bad design to silently mutate an object as a side effect. Will edit the post in a bit when I get the chance. (Happen to know if there's a name for that by the way?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T02:01:36.027", "Id": "21048", "Score": "0", "body": "Can you show me how am I going to used Part 1 and Part 2, with implementations, I do get the concept, but the implementation is completely vague" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T02:51:21.107", "Id": "21049", "Score": "0", "body": "@user962206 Have provided complete implementations of parts of it, so am not sure what you mean. Do you mean like an entire form from submission to creation? Or what?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T03:18:59.267", "Id": "21050", "Score": "0", "body": "btw in Form_Element_AbstractElement, did you declare hadErrors variable? I can't seem to find it" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T04:29:00.487", "Id": "21051", "Score": "0", "body": "@user962206 It's a method, not a variable, but no, it was a typo. Was supposed to be `hasErrors`." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T21:21:32.070", "Id": "13021", "ParentId": "13008", "Score": "2" } }, { "body": "<p>The <code>Spaces are not allowed</code> and the <code>Username should contain, at least...</code> checks could be in the constructor (or at least before the SQL query). Furthermore, there is no point to run the SQL query if the username cannot be valid (it won't be in the database anyway).</p>\n\n<p>The <code>isUsernameCorrect($username,$conn)</code> function is empty. Is it really required?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T21:51:55.397", "Id": "13024", "ParentId": "13008", "Score": "1" } } ]
{ "AcceptedAnswerId": "13021", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T14:35:46.477", "Id": "13008", "Score": "2", "Tags": [ "php", "mysqli" ], "Title": "Username verification class" }
13008
<p>My code here is completely working, but I feel like I destroyed or didn't follow the DRY rule, what suggestions can you give to me for this code??</p> <pre><code>&lt;?php require_once("./includes/Utilities.php") ;?&gt; &lt;?php require_once("./includes/Db_Resources/db_connection.php");?&gt; &lt;?php require_once("./includes/Db/DatabaseUtilities.php"); ?&gt; &lt;?php if(isset($_POST['submit'])){ require_once("./includes/process_form.inc.php"); require_once('./includes/Db/CheckPassword.php'); require_once('./includes/Db/CheckUsername.php'); $check_pwd = new Db_CheckPassword($password); $check_user = new Db_CheckUsername($username,$conn); $passwordOK = $check_pwd-&gt;check();//Checks if Password is valid $userOK = $check_user-&gt;check();//Checks if Username is valid //Checks if Password is the same with the retyped password $password_match = Db_CheckPassword::confirmPassword($password,$conf_pass); //if everything is okay! we'll finally add the muthafucking users account if($userOK &amp;&amp; $passwordOK &amp;&amp; $password_match){ if(Db_DatabaseUtilities::registerAccount($conn,$username,$password,$email)){ header("Location: login.php"); exit; } }else{ $pass_error = $check_pwd -&gt; getErrors(); $user_error = $check_user-&gt;getErrors(); } } ?&gt; </code></pre>
[]
[ { "body": "<p>Here are some things that I would recommend:</p>\n\n<ul>\n<li><strong>PHP tags</strong>. There's no point in closing and reopening PHP tags if there is no non-PHP code in between. For this file, a single opening PHP tag is all you need for the entire thing. Closing PHP tags (anywhere in the file) can bring potential issues such as unnoticed white space, which will throw errors if you try to use <code>header()</code> or similar later on.</li>\n<li><strong><code>header()</code></strong> - When using <code>header('Location: xxxxx');</code>, you should use a full URL, not a relative URL, since it is making an HTTP request. Sure, it probably works most of the time, but let's follow the spec and not take chances.</li>\n<li><strong><code>isset($_POST['submit'])</code></strong> - Some versions of Internet Explorer (not sure when this was fixed) will ignore the name/value of the submit button if it is being used as an image (example: <code>&lt;input type=\"image\" src=\"login.png\" name=\"submit\" value=\"Login\" /&gt;</code>). I would check for a different form element (or even the <code>$_POST</code> array itself) to eliminate that potential bug.</li>\n<li><strong>Required files</strong> - Since I don't know how the rest of your application is structured, this one is more speculation. But if you find yourself repeating these required lines often in different files, you should consider consolidating the <code>require_once()</code> lines to a single appropriate file. For instance, all of your database connections can be done in once place. All of the form validation files can be consolidated, also. This leaves you with only needing to do a single <code>require_once()</code> in your app's files, and only needing to maintain and update a single file elsewhere if you want to change or add functionality.</li>\n<li><strong><code>registerAccount()</code> failure?</strong> - You perform a redirect if the <code>registerAccount()</code> method is successful, but don't do anything if it fails. Always have an action for when things fail, because they probably will at some point. Logging error messages, even sending yourself an email when it happens is a good way to notice a major error quickly in the event that it happens.</li>\n</ul>\n\n<p>This one is more personal preference, but might be worth it to you:</p>\n\n<ul>\n<li>I would rename the <code>check()</code> method in your user and password classes to <code>isValid()</code>, since that's what you're specifically looking for (even says so in the comments). I always try to name methods based on context. You could even use the methods directly in your <code>if</code> statement - no real point in assigning those variables, since you only use them once and they don't really save much typing later on.</li>\n</ul>\n\n<p>I hope that helps. :)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T21:43:52.083", "Id": "13022", "ParentId": "13010", "Score": "2" } }, { "body": "<p>One minor thing to add to Cryode's answer:</p>\n\n<pre><code>Db_DatabaseUtilities::registerAccount($conn,$username,$password,$email)\n</code></pre>\n\n<p>This is either named badly, or likely violates the <a href=\"http://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">single responsibility principle</a>.</p>\n\n<p>You should consider moving it into some kind of Account model (or pseudo-model), or at least trying to separate it from general DB utilities items. </p>\n\n<p><code>Db_DatabaseUtilities</code> is going to create all kinds of dependencies throughout your code, and worse, since it's being called statically, there's no potential to inject the dependency. (Well, technically you could, but it would get very, very ugly.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T22:24:23.280", "Id": "13026", "ParentId": "13010", "Score": "1" } } ]
{ "AcceptedAnswerId": "13022", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T14:43:26.220", "Id": "13010", "Score": "2", "Tags": [ "php", "form", "mysqli" ], "Title": "Inserting data in the database through POST" }
13010
<p>I created an XML wrapper to easily access XML data. Please tell me what do you think about it.</p> <ul> <li>Performance</li> <li>Scalability </li> <li>Anything else...</li> </ul> <p>This is how you use it:</p> <pre><code>var xml = new Xml(dataString); xml.load("UserEmail"); alert(xml.length + ", " + xml.getValueAt(0)); // Out: 2, jchen@contoso.com </code></pre> <p>XML source file:</p> <pre><code>&lt;Users&gt; &lt;Users&gt; &lt;UserEmail&gt;jchen@contoso.com&lt;/UserEmail&gt; &lt;UserPassword&gt; BA56E5E0366D003E98EA1C7F04ABF8FCB3753889 &lt;/UserPassword&gt; &lt;/Users&gt; &lt;Users&gt; &lt;UserEmail&gt;Kim@contoso.com&lt;/UserEmail&gt; &lt;UserPassword&gt; 07B7F3EE06F278DB966BE960E7CBBD103DF30CA6 &lt;/UserPassword&gt; &lt;/Users&gt; &lt;/Users&gt; </code></pre> <p>Source:</p> <pre><code>function Xml(xmlString) { var parser = function() { if (typeof window.DOMParser != "undefined") { return (new window.DOMParser()).parseFromString(xmlString, "text/xml"); } else if (typeof window.ActiveXObject != "undefined" &amp;&amp; new window.ActiveXObject("Microsoft.XMLDOM")) { var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(xmlString); return xmlDoc; } else { throw new Error("XML parser not found"); } }; var data = parser(xmlString); var elements = null; this.length = 0; this.load = function(nodeName){ elements = data.documentElement.getElementsByTagName(nodeName); this.length = elements.length; }; this.getValueAt = function(index) { if(!elements || index &gt;= this.length){ return null; } var element = elements.item(index); return element.childNodes[0].data; }; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T12:59:06.310", "Id": "21034", "Score": "0", "body": "It can usefully handle very simple XMLs. It doesn't retrieve the value of attributes. It gives worthless values for element nodes. It doesn't support a decent selector engine. If it's good for your purposes, use it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T13:33:30.453", "Id": "21035", "Score": "0", "body": "\"Would you write your own XML Parser? Only if you're f***ing crazy.\" http://secretgeek.net/csv_trouble.asp" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T13:40:55.267", "Id": "21036", "Score": "0", "body": "@David pmpl nice one ;)" } ]
[ { "body": "<p>From a quick read : </p>\n\n<ul>\n<li><p><code>Xml</code> seems like a bad name for your wrapper, you should consider something like <code>xmlParser</code> ?</p></li>\n<li><p>I would allow access to <code>data</code> and <code>elements</code> by using <code>this</code> instead of <code>var</code> because you wrap so little of the XML parser API</p></li>\n<li><p><code>this.length</code> seems wrong ( the parser has no length), maybe <code>loadedElementCount</code>, but even that is pretty bad, I would just let the caller use <code>elements.length</code>.</p></li>\n<li><p>I would <code>return elements</code> in <code>this.load</code>, since that is pretty much what the caller would need next.</p></li>\n<li><p>You are not checking for falsey values of <code>nodeName</code> in <code>this.load</code></p></li>\n<li><p>I would not create a <code>var element</code> in getValueAt, I would just return <code>elements.item(index).childNodes[0].data</code></p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-13T19:43:44.813", "Id": "39174", "ParentId": "13014", "Score": "2" } } ]
{ "AcceptedAnswerId": "39174", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-23T12:48:47.103", "Id": "13014", "Score": "3", "Tags": [ "javascript", "xml", "parsing" ], "Title": "Javascript XML Parser wrapper" }
13014
<h2>Further Information</h2> <ul> <li>See <a href="http://en.wikipedia.org/wiki/Blackjack" rel="nofollow" title="Wikipedia Blackjack">Blackjack on Wikipedia</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T18:38:14.857", "Id": "13016", "Score": "0", "Tags": null, "Title": null }
13016
Card Game – Where the aim is to get your cards as closer to 21 then the dealer, while not going over. J, Q, K are worth 10. A are either 11 or 1.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T18:38:14.857", "Id": "13017", "Score": "0", "Tags": null, "Title": null }
13017
<p>I wanted to learn how to work with file I/O properly and found an assignment in my college papers and decided to write it:</p> <pre><code>//Write a C program which reads data about books and inputs them into a file named books.txt, like this: // //book_name#author_name#page_num#code#is_lent# // //book_name is an array of a maximum of 50 characters, author_name is an array of a maximum of 50 characters, //page_num is an integer, code is an integer, is_lent is an integer of interval [0, 1] where 1 //means that the book is lent, and 0 that it isn't. //Program creates a new file if it exists or opens an existing one and appends new //data on the end. Input ends when the book name is 'x'. //Print the contents of the file. #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string.h&gt; /* Function prototypes */ void buff_clr( void ); void write_to_file( FILE *fp ); void read_from_file( FILE *fp ); void remove_newline( char *string ); int main() { FILE *fp; fp = fopen( "Books.txt" , "a+" ); if( fp == NULL ) { fprintf( stderr , "Error opening file" ); exit( 1 ); } write_to_file( fp ); read_from_file( fp ); fclose( fp ); return 0; } /* Removes newline from strings caused by fgets() */ void remove_newline(char *string) { char *ptr; if ( ( ptr = strchr( string , '\n' ) ) != NULL ) *ptr = '\0'; } /* Picks up left over characters from the buffer in case there are any */ void buff_clr(void) { char garbage; do { garbage = getchar(); }while( garbage != '\n' ); } /* Requests input and writes it to file */ void write_to_file( FILE *fp ) { struct book_s { char book_title[50]; char author_name[50]; unsigned int page_num; unsigned int code; unsigned int is_lent; }book; while(1) { /* Data input into struct */ printf( "Book title: " ); fgets( book.book_title , 50 , stdin ); remove_newline(book.book_title); if( strcmp( book.book_title , "x") == 0 ) { break; } printf( "Name of the author: "); fgets( book.author_name , 50 , stdin ); remove_newline(book.author_name); printf( "Number of pages: " ); scanf( "%d" , &amp;book.page_num ); printf( "Book code: " ); scanf( "%d" , &amp;book.code ); do { printf( "Is book lent(1 = yes , 0 = no):" ); scanf( "%d" , &amp;book.is_lent ); }while(book.is_lent &gt; 1); /* Data input into file */ fprintf( fp , "%s#%s#%d#%d#%d#\n", book.book_title , book.author_name , book.page_num , book.code , book.is_lent ); printf( "\n\n" ); buff_clr(); //Using this here because without it a '\n' sneaks into book title on next iteration for some reason } } /* Reads the file we've just written to */ void read_from_file( FILE *fp ) { struct book_s { char book_title[50]; char author_name[50]; char page_num[5]; char code[20]; char is_lent[1]; }book; char line[BUFSIZ]; //Rewind to start of file fseek(fp, 0, SEEK_SET); while( fgets( line , sizeof(line) , fp ) != NULL ) { strcpy( book.book_title , strtok( line , "#" ) ); strcpy( book.author_name , strtok( NULL , "#" ) ); strcpy( book.page_num , strtok( NULL , "#" ) ); strcpy( book.code , strtok( NULL , "#" ) ); strcpy( book.is_lent , strtok( NULL , "#" ) ); printf( "\nBook title: %s", book.book_title ); printf( "\nName of the author: %s", book.author_name ); printf( "\nPage num: %s", book.page_num ); printf( "\nBook code: %s", book.code ); printf( "\nIs book lent: %s", book.is_lent ); printf( "\n\n" ); } } </code></pre> <p>Now this all works within the confines of the assignment.</p> <ol> <li>Is my code too long?</li> <li>Could this have been written any shorter?</li> <li>Could this have been written any better?</li> <li>Did I miss anything?</li> <li>Are there any mistakes?</li> </ol> <p>A few things to note:</p> <p>I know I don't really need <code>struct</code>s but I had an idea of using them to create arrays of data and then print them one by one. I decided to scrap that idea since the only thing I'd accomplish is more lines of code and more memory wasted, but I liked the look of the struct so I kept it.</p> <p>Is there a way I could read all the data in their rightful forms without having to read them all as a string and then parse them and then convert them (I didn't convert integers here since I didn't really need to)? I know I can't use <code>fscanf()</code> which would read strings until the whitespace character so it would try to gobble the whole line up since there aren't any.</p> <p>Also, what if I had to read multiple lines of varying lengths and file types? For example, if instead of <code>book_name#author_name#page_num#code#is_lent#</code> being all one line, what if it was this?</p> <blockquote> <pre><code>book_name#page_num# author_name#code#is_lent# </code></pre> </blockquote> <p>What would be the ways of reading such input?</p>
[]
[ { "body": "<p>I'm not a C guru, so just two small notes:</p>\n\n<ol>\n<li><p>It does something strange (seems an endless loop) for the following input:</p>\n\n<pre><code>Book title: a\nName of the author: a\nNumber of pages: a\n</code></pre></li>\n<li><p>The <code>50</code> magic number should be a named constant:</p>\n\n<pre><code>char book_title[50];\nchar author_name[50];\n</code></pre>\n\n<p>The code uses them multiple times.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T22:02:24.827", "Id": "21043", "Score": "1", "body": "1. I forgot to put any guards to check if the input for page number is not an integer\n\n\n\n\n2. I probably should have made it a constant" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T21:21:20.710", "Id": "13020", "ParentId": "13018", "Score": "2" } }, { "body": "<p>Regarding correctness, read_from_file has some issues:</p>\n\n<p>If the file content is malformed, and there is no item for e.g. the last strcpy line to read, then strtok will return null, and strcpy will try to copy a null pointer. Crash. </p>\n\n<p>If the item in the file is larger than the strcpy destination buffers (the ones in your structure), then strcpy will keep going till it gets to the end of the destination string, overwriting other variables in your memory - a buffer overrun. This is a serius security flaw. </p>\n\n<p>I suggest you use fscanf instead of memcpy and strtk. </p>\n\n<p>Write to file:</p>\n\n<p>I suggest rather than using a while(1), you go:</p>\n\n<pre><code> printf(\"Press x to exit\");\n char chrExitCommandIfX = getchr();\n\n while(chrExitCommandIfX != 'x') {\n\n ...\n\n printf(\"Press x to exit\");\n char chrExitCommandIfX = getchr();\n }\n</code></pre>\n\n<p>Also, I suggest taking all the input first, as a dense block of fgetgs(), and then outputting the captured text for the user to confirm as a single printf statement. You can format the text like this for readability: <a href=\"http://dalelane.co.uk/blog/?p=88\" rel=\"nofollow\">http://dalelane.co.uk/blog/?p=88</a></p>\n\n<p>But the comments for this function are my taste I guess. </p>\n\n<p>More generally:\nWhy not use a YAML libary? I mean, it a way that's a dumb question - you are figuring out file IO right? But I think 'is there a libary I could use for this' is a good question to be in the habit of asking...</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T12:39:21.333", "Id": "21059", "Score": "0", "body": "about the custom library.I forgot to mention that i'm learning this so i could help my friend pass his programming class. I would use a custom library if i could but since he can't i have to depend on default libraries.\n\nI'll include guards to check if strtok returns null.\n\nUsing fscanf to read input? I tried that, however fscanf doesn't really work well for strings if the strings are first to be read. fscanf will read the string until the first whitespace character and thus it will try to read my whole line." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T14:50:01.467", "Id": "21068", "Score": "0", "body": "Actually fscanf's format strings are more flexible and complicated than that. You can use them as a kind of mini regex. For instance, you can read multiple lines, and use whatever charecter (e.g. #) to mark the end of a string.\nMost importantly, you can specify the max expected length of the strings %s to avoid running off the end of your buffers. \nI believe it stops reading at the apparant end of it's search string, rather than consuming to the next newline. \nIt isn't wonderfully documented, but it's good to know." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T15:31:09.980", "Id": "21076", "Score": "0", "body": "I tried writing something like `fscanf(fp , \"%50[^#]%*c%50[^#]%*c%d#%d#%d#\" , .... );` To read the strings until the # character with `[^#]` and then discard the # character with `%*c` , however this did not work. The first variable contained garbage while others were empty.\n\nIf i just used `fscanf(fp, \"%s#%s#%d#%d#%d#\", ....)` Then what i said earlier ,about reading the whole line as a string since there are no whitespace characters, would happen" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:39:15.380", "Id": "21082", "Score": "0", "body": "Try this: http://pastie.org/4149470\nI think the string you put there should work... but I got confused and tried to scanf %d into the page.booknum item in your structure, which was a char array. Trying to put a single number into an array as a whole = mess. Maybe you made the same mistake, or didn't read into a valuetype with &" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T18:58:28.160", "Id": "21095", "Score": "0", "body": "So i guess i messed up by using `%*c` to try and discard the `#`? I think when i tried scanf that i did change the appropriate struct members to int and that i used `&` but i can't be sure. Thanks for the correct code. Along with the correct way of using scanf you also gave me a few control ideas (i would never think of intSize and intScanResult variables to check if the file has any data and if scanf is reading it, i'd probably just use if scanf() == 5 so thanks for the ideas)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T01:04:52.863", "Id": "21110", "Score": "0", "body": "I think %*c should have been fine, it just says 'eat the next charecter, discard it'. I subsituted it in instead of the # and found my code worked. To me using # is more obvius = better, dunno if you agree? Anyway, imho you're picking up c pretty damn fast, your friend is lucky to have such a coursework machine." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T01:29:35.483", "Id": "13033", "ParentId": "13018", "Score": "4" } }, { "body": "<p>Here:</p>\n\n<pre><code>void buff_clr(void)\n{\n char garbage;\n do\n {\n garbage = getchar();\n }while( garbage != '\\n' );\n}\n</code></pre>\n\n<p>You want to detect <code>EOF</code> otherwise the function might hang if there are no <code>'\\n'</code> left. For this reason always use <code>int</code> to get the result of <code>getchar()</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-08-07T07:50:36.587", "Id": "59361", "ParentId": "13018", "Score": "1" } } ]
{ "AcceptedAnswerId": "13033", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T19:43:52.113", "Id": "13018", "Score": "4", "Tags": [ "c", "strings", "io" ], "Title": "Simple text file I/O for book data" }
13018
<p>I'm a little frustrated with the state of url parsing in python, although I sympathize with the challenges. Today I just needed a tool to join path parts and normalize slashes without accidentally losing other parts of the URL, so I wrote this:</p> <pre><code>from urlparse import urlsplit, urlunsplit def url_path_join(*parts): """Join and normalize url path parts with a slash.""" schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts)) # Use the first value for everything but path. Join the path on '/' scheme = next((x for x in schemes if x), '') netloc = next((x for x in netlocs if x), '') path = '/'.join(x.strip('/') for x in paths if x) query = next((x for x in queries if x), '') fragment = next((x for x in fragments if x), '') return urlunsplit((scheme, netloc, path, query, fragment)) </code></pre> <p>As you can see, it's not very DRY, but it does do what I need, which is this:</p> <pre><code>&gt;&gt;&gt; url_path_join('https://example.org/fizz', 'buzz') 'https://example.org/fizz/buzz' </code></pre> <p>Another example:</p> <pre><code>&gt;&gt;&gt; parts=['https://', 'http://www.example.org', '?fuzz=buzz'] &gt;&gt;&gt; '/'.join([x.strip('/') for x in parts]) # Not sufficient 'https:/http://www.example.org/?fuzz=buzz' &gt;&gt;&gt; url_path_join(*parts) 'https://www.example.org?fuzz=buzz' </code></pre> <p>Can you recommend an approach that is readable without being even more repetitive and verbose?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T05:43:32.700", "Id": "21054", "Score": "1", "body": "Why can't you just use `os.path.join` for taking care of the joining and such?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T11:31:36.060", "Id": "21057", "Score": "2", "body": "@Blender what if someone runs this code on Windows?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T19:32:44.900", "Id": "21258", "Score": "0", "body": "Could you please give more examples of the kind of input that would require your above code to accomplish? (i.e provide some test cases that should pass for the solution to be acceptable?). What about some thing simple such as `return '/'.join([x.strip('/') for x in parts])`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T12:03:14.563", "Id": "21333", "Score": "0", "body": "Sure, how about `parts=['https://', 'http://www.example.org', '?fuzz=buzz']`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-14T15:50:46.490", "Id": "234580", "Score": "1", "body": "Just got burned by `urlparse.urljoin` today because it culls any existing paths on the first parameter. _Who in the hell thought that was a great idea?_" } ]
[ { "body": "<p>I fully agree with Blender. Just use the os.path module. It provides a method to join paths and it also has methods to normalize pathnames (eg. os.path.normpath(pathname)) to use it on every OS with different separators.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T14:49:48.633", "Id": "22262", "Score": "1", "body": "`os.path.normpath` does not use forward slashes on Windows by default, and it's not intelligent about keeping the double slashes after `http://`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-10-16T14:15:58.280", "Id": "28010", "Score": "0", "body": "@kojiro Yes, but you can `import posixpath` instead of `import os.path` to get the correct slashes. I do believe you are correct about the `http://` though" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-18T13:07:50.357", "Id": "13785", "ParentId": "13027", "Score": "0" } }, { "body": "<p>I'd suggest the following improvements (in descending order of importance):</p>\n\n<ol>\n<li>Extract your redundant generator expression to a function so it only occurs <em>once</em>. To preserve flexibility, introduce <code>default</code> as an optional parameter</li>\n<li>This makes the comment redundant because <code>first</code> is a self-documenting name (you could call it <code>first_or_default</code> if you want to be more explicit), so you can remove that</li>\n<li>Rephrase your docstring to make it more readable: <em>normalize</em> and <em>with a slash</em> don't make sense together</li>\n<li><a href=\"http://www.python.org/dev/peps/pep-0008/#pet-peeves\" rel=\"nofollow\">PEP 8 suggests not to align variable assignments</a>, so does <em>Clean Code</em> by Robert C. Martin. However, it's more important to be consistent within your project. </li>\n</ol>\n\n<hr>\n\n<pre><code>def url_path_join(*parts):\n \"\"\"Normalize url parts and join them with a slash.\"\"\"\n schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))\n scheme = first(schemes)\n netloc = first(netlocs)\n path = '/'.join(x.strip('/') for x in paths if x)\n query = first(queries)\n fragment = first(fragments)\n return urlunsplit((scheme, netloc, path, query, fragment))\n\ndef first(sequence, default=''):\n return next((x for x in sequence if x), default)\n</code></pre>\n\n<hr>\n\n<p>If you're looking for something a bit more radical in nature, why not let <code>first</code> handle several sequences at once? (Note that unfortunately, you cannot combine default parameters with sequence-unpacking in Python 2.7, which has been fixed in Python 3.)</p>\n\n<pre><code>def url_path_join(*parts):\n \"\"\"Normalize url parts and join them with a slash.\"\"\"\n schemes, netlocs, paths, queries, fragments = zip(*(urlsplit(part) for part in parts))\n scheme, netloc, query, fragment = first_of_each(schemes, netlocs, queries, fragments)\n path = '/'.join(x.strip('/') for x in paths if x)\n return urlunsplit((scheme, netloc, path, query, fragment))\n\ndef first_of_each(*sequences):\n return (next((x for x in sequence if x), '') for sequence in sequences)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-03-27T12:16:14.453", "Id": "24416", "ParentId": "13027", "Score": "5" } } ]
{ "AcceptedAnswerId": "24416", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T22:34:16.367", "Id": "13027", "Score": "15", "Tags": [ "python", "parsing", "url" ], "Title": "Joining url path components intelligently" }
13027
<p>In the world of casinos, there are different types of games and jackpots. In this example, there are normal jackpots, multi-casino jackpots. I have a separate model for each of these. I need to display these in-line with each other. For instance, I'm grabbing the top 10 Caribbean Stud jackpots (Model: Jackpot), then displaying the top 10 multi-casino Caribbean stud jackpots (Model: MultiJackpot), and then displaying the top 10 Blackjack jackpots (Model: Jackpot) followed by the top 10 multi-casino Blackjack jackpots (Model: MultiJackpot).</p> <p>I have two main problems with a chunk of code: I need to interpolate 2 different models in a specific order in a list.</p> <p>This is a simplified example, but I have a similar scenario with slot jackpots where the models differ even more, which is preventing me from merging the models themselves.</p> <p>Currently (and very inefficiently) I am doing 1 database call for each game and assigning it to its own instance variable for the view.</p> <pre><code>@caribbean_stud = Jackpot.where(:jackpot_game_id =&gt; JackpotGame.find_by_name("Caribbean Stud")).order("prize DESC").limit(10) @multi_caribbean_stud = MultiJackpot.where(:multi_jackpot_game_id =&gt; MultiJackpotGame.find_by_name("Caribbean Stud")).order("prize DESC").limit(10) @progressive_blackjack = Jackpot.where(:jackpot_game_id =&gt; JackpotGame.find_by_name("Progressive Blackjack")).order("prize DESC").limit(10) @multi_progressive_blackjack = MultiJackpot.where(:multi_jackpot_game_id =&gt; MultiJackpotGame.find_by_name("Progressive Blackjack")).order("prize DESC").limit(10) </code></pre> <p>In the view, I'm taking each instance variable and hard coding the order/interpolation.</p> <p>The obvious 2 problem I'm running into:</p> <ol> <li>Many more database calls than necessary (I have over 30 games I'm doing this for)</li> <li>The view is not DRY (I could move the output for each model here into a partial, but I'm still hard coding the actual order &amp; interpolation.)</li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-30T22:54:04.663", "Id": "143334", "Score": "0", "body": "Which version of Rails are you using?" } ]
[ { "body": "<p>First of all, the fact that you are mixing the use of <code>Jackpot</code> and <code>MultiJackpot</code> in this way suggests that they are really 2 different instances of a common, underlying concept. That calls into question whether they really need to be implemented as two different models. But that's up to you; you know the specifics of your own application.</p>\n\n<p>As for removing the duplication, how about something along the lines of:</p>\n\n<pre><code>games = ['Caribbean Stud', 'Progressive Blackjack']\n@jackpots = games.map do |game|\n [Jackpot.where(...),\n MultiJackpot.where(...)]\nend\n</code></pre>\n\n<p>You end up with an extra level of array nesting in the results, which could be eliminated with <code>flatten(1)</code>. Or if don't mind adding your own methods to Array, I like to add one called <code>mappend</code>... I find it useful in almost every project. It it like <code>map</code>, but it appends all the returned arrays together to form a single array.</p>\n\n<p>If you need the names of the games together with the results, you can <code>games.zip(@jackpots)</code> (you need the extra level of nesting for that one).</p>\n\n<p>As for the DB calls, you'll find it hard to work around that while still using your nice Active Record query helpers. When DB performance is critical, I usually end up rolling my own SQL, perhaps using custom helpers added to model classes.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T00:31:24.547", "Id": "13031", "ParentId": "13030", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-24T20:37:48.260", "Id": "13030", "Score": "2", "Tags": [ "ruby-on-rails", "ruby" ], "Title": "Casino jackpot models" }
13030
<p>Here's something I tried putting together as I'm learning. Critiques on anything are welcome. There's also a logic bug in the Plane module I can't identify.</p> <p>The long and the short are that it takes the URI "some float/some float/some float/some float", and makes the first 2 (x,y) coord where something is, and the second 2 (x,y) coord where it wants to go. If there are no things overlapping the desired space, it will return the coords of the new location. If there is an overlap, it will return the original coords.</p> <p>Extra points if you can find the logic bug I've been trying to find where it's thinking all coords are a collision with something.</p> <p><strong>plane.hs:</strong></p> <pre><code>module Plane where type X = Float type Y = Float type Direction = Float type Location = (X, Y) type Size = (Float, Float) type TopLeftCorner = Location type TopRightCorner = Location type BottomLeftCorner = Location type BottomRightCorner = Location data Shape = Rectangle deriving (Eq, Show) data Corner = RectangleCorners { topLeftCorner :: TopLeftCorner, topRightCorner :: TopRightCorner, bottomRightCorner :: BottomRightCorner, bottomLeftCorner :: BottomLeftCorner} data Artifact = Artifact { shape :: Shape, location :: Location, size :: Size } deriving (Eq, Show) type Plane = [Artifact] moveArtifact :: Plane -&gt; Artifact -&gt; Location -&gt; Artifact moveArtifact plane originalArtifact (moveToX, moveToY) | artifactCanGoToLoc = Artifact Rectangle (moveToX, moveToY) $ size originalArtifact | otherwise = originalArtifact where artifactCorners = corners originalArtifact artifactCanGoToLoc = not $ topLeftCorner artifactCorners `inside` plane || topRightCorner artifactCorners `inside` plane || bottomRightCorner artifactCorners `inside` plane || bottomLeftCorner artifactCorners `inside` plane corners :: Artifact -&gt; Corner corners (Artifact Rectangle (artifactX, artifactY) (artifactW,artifactH)) = RectangleCorners ((-) artifactX $ artifactW / 2, (+) artifactY $ artifactH / 2) ((+) artifactX $ artifactW / 2, (+) artifactY $ artifactH / 2) ((+) artifactX $ artifactW / 2, (-) artifactY $ artifactH / 2) ((-) artifactX $ artifactW / 2, (-) artifactY $ artifactH / 2) inside :: Location -&gt; Plane -&gt; Bool inside x y = insideAcc False x y insideAcc :: Bool -&gt; Location -&gt; Plane -&gt; Bool insideAcc False (locToCheckX, locToCheckY) (Artifact Rectangle (artifactX, artifactY) (artifactW,artifactH):artifacts) = insideAcc (upperRightX &gt; locToCheckX &amp;&amp; lowerLeftX &lt; locToCheckX &amp;&amp; upperRightY &gt; locToCheckY &amp;&amp; lowerLeftY &lt; locToCheckY) (locToCheckX, locToCheckY) artifacts where upperRightX = (+) artifactX $ artifactW / 2 upperRightY = (+) artifactY $ artifactH / 2 lowerLeftX = (-) artifactY $ artifactH / 2 lowerLeftY = (-) artifactX $ artifactW / 2 insideAcc _ _ _ = True </code></pre> <p><strong>main.hs:</strong></p> <pre><code>{-# LANGUAGE OverloadedStrings #-} module Main ( main ) where import Plane import Network.Wai import Network.Wai.Handler.Warp import Network.HTTP.Types (status200, status404) import Blaze.ByteString.Builder (copyByteString) import qualified Data.ByteString.UTF8 as BU import Data.Monoid import Data.Text (Text, unpack) import Control.Applicative ((&lt;*&gt;), (*&gt;), (&lt;$&gt;), (&lt;|&gt;), pure) import qualified Data.Attoparsec.Text as A import qualified Data.Attoparsec.Combinator as AC import Data.Attoparsec.Text (Parser) import Control.Monad.Trans.Resource import Network.HTTP.Types main :: IO () main = do let port = 3000 putStrLn $ "Listening on port " ++ show port run port app app :: Request -&gt; ResourceT IO Response app req = do return $ moveArtifactResponse path where path = pathInfo req moveArtifactResponse :: [Text] -&gt; Response moveArtifactResponse splitPath@(oldX:oldY:newX:newY:_) = case (maybeArtifact, maybeX, maybeY) of (Just artifact, Just x, Just y) -&gt; createJsonResponse $ show $ location $ moveArtifact examplePlane (artifact) (x, y) (_, _, _) -&gt; notFoundResponse splitPath where maybeArtifact = textToArtifact oldX oldY maybeX = textToFloat newX maybeY = textToFloat newY moveArtifactResponse splitPath = notFoundResponse splitPath notFoundResponse :: [Text] -&gt; Response notFoundResponse path = createErrorResponse status200 $ "404 NOT FOUND LOCATION READ AS: " ++ (show $ fmap textToFloatString path) ++ "&lt;br/&gt;" ++ (concat $ fmap show examplePlane) createResponse :: BU.ByteString -&gt; Status -&gt; (String -&gt; Response) createResponse contentType status response = do ResponseBuilder status [("Content-Type", contentType)] . mconcat . fmap copyByteString $ [BU.fromString response] createErrorResponse = createResponse "text/html" createJsonResponse = createResponse "text/javascript" status200 createHtmlResponse = createResponse "text/html" status200 textToFloat :: Text -&gt; Maybe Float textToFloat x | (length $ textReads x) /= 1 = Nothing | (snd $ head $ textReads x) /= [] = Nothing | otherwise = Just $ fst $ head $ textReads x where textReads = reads . unpack :: Text -&gt; [(Float, String)] textToArtifact :: Text -&gt; Text -&gt; Maybe Artifact textToArtifact textX textY = case (maybeX, maybeY) of (Just x, Just y) -&gt; Just $ Artifact Rectangle (x, y) (1,1) (_, _) -&gt; Nothing where maybeX = textToFloat textX maybeY = textToFloat textY textToFloatString :: Text -&gt; Maybe String textToFloatString x | textReads x == [] = Nothing | (snd $ head $ textReads x) /= [] = Nothing | otherwise = Just $ unpack x where textReads = reads . unpack :: Text -&gt; [(Float, String)] examplePlane :: Plane examplePlane = [ Artifact Rectangle (3, 3) (2,2), Artifact Rectangle (3, 8) (2,2), Artifact Rectangle (8, 3) (2,2), Artifact Rectangle (8, 8) (2,2)] </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T04:45:37.343", "Id": "21052", "Score": "0", "body": "On a side note, this is on github https://github.com/JimmyHoffa/HaskJunk" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T19:10:54.857", "Id": "21098", "Score": "0", "body": "Sorry for missing the pragma- I didn't know what that was, leksah just puts it there, didn't know it did anything so I didn't copy it for this heh" } ]
[ { "body": "<p>Here are some suggestions. Get rid of data types that do not carry their weight. For example, Shape should really be one of the constructors.</p>\n\n<p>plane.hs</p>\n\n<pre><code>module Plane where\n\ntype X = Float\ntype Y = Float\ntype Location = (X, Y)\ntype Size = (Float, Float)\n\ndata Artifact = Rectangle {location :: Location,size :: Size }\n deriving (Eq, Show)\n\ntype Plane = [Artifact]\n\nmoveArtifact :: Plane -&gt; Artifact -&gt; Location -&gt; Artifact\nmoveArtifact plane original moveToXY\n | canGoTo = Rectangle moveToXY $ size original\n | otherwise = original\n where canGoTo = not $ any (flip inside plane) $ corners original\n</code></pre>\n\n<p>It seems the corner Datatype does not add much value.</p>\n\n<pre><code>corners :: Artifact -&gt; [Location]\ncorners r = map (flip opapply r) [((-),(+)),((+),(+)),((+),(-)),((-),(-))]\n\nopapply :: (X -&gt; Float -&gt; X, Y -&gt; Float -&gt; Y) -&gt; Artifact -&gt; Location\nopapply (opx, opy) (Rectangle (x,y) (w,h)) = (x `opx` w / 2, y `opy` h / 2)\n\ninside :: Location -&gt; Plane -&gt; Bool\ninside l p = any (insideAcc l) p\n\n{-\n - ul ur\n - ll lr\n -}\n\ninsideAcc :: Location -&gt; Artifact -&gt; Bool\ninsideAcc (x, y) r = (urX &gt; x &amp;&amp; llX &lt; x &amp;&amp; urY &gt; y &amp;&amp; llY &lt; y)\n where (urX,urY) = opapply ((+),(+)) r\n (llX,llY) = opapply ((-),(-)) r\n</code></pre>\n\n<p>--\nMain.hs </p>\n\n<pre><code>{-# LANGUAGE OverloadedStrings, UnboxedTuples #-}\nmodule Main (main) where\n\nimport Plane\nimport Network.Wai\nimport Network.Wai.Handler.Warp\nimport Blaze.ByteString.Builder (copyByteString)\nimport qualified Data.ByteString.UTF8 as BU\nimport Data.Monoid\nimport Data.Maybe\nimport Data.Text (Text, unpack)\n\nimport Control.Applicative ((&lt;*&gt;), (&lt;$&gt;))\nimport Control.Monad.Trans.Resource\nimport Network.HTTP.Types\n\nmain :: IO ()\nmain = do\n let port = 3000\n putStrLn $ \"Listening on port \" ++ show port\n run port app\n\napp :: Request -&gt; ResourceT IO Response\napp = return . moveArtifactResponse . pathInfo\n</code></pre>\n\n<p>As before, be on the look out for generic functions</p>\n\n<pre><code>pairApply :: (a -&gt; Maybe b) -&gt; (a,a) -&gt; Maybe (b,b)\npairApply fn (x,y) = (,) &lt;$&gt; fn x &lt;*&gt; fn y\n</code></pre>\n\n<p>Sometimes applicatives can make your code simpler.</p>\n\n<pre><code>moveArtifactResponse :: [Text] -&gt; Response\nmoveArtifactResponse splitPath = fromMaybe (notFoundResponse splitPath) $ case splitPath of\n (x:y:x':y':_) -&gt; fn &lt;$&gt; textToArtifact (x, y) &lt;*&gt; pairApply textToFloat (x', y') \n _ -&gt; Nothing\n where fn = ((createJsonResponse . show . location) .) . moveArtifact examplePlane\n\nnotFoundResponse :: [Text] -&gt; Response\nnotFoundResponse path = createErrorResponse status200\n $ \"404 NOT FOUND LOCATION READ AS: \" ++\n (show $ map textToFloatString path) ++ \"&lt;br/&gt;\" ++ concatMap show examplePlane\n\ncreateResponse :: BU.ByteString -&gt; Status -&gt; (String -&gt; Response)\ncreateResponse contentType status response = fn $ [BU.fromString response]\n where fn = ResponseBuilder status [(\"Content-Type\", contentType)] \n . mconcat . fmap copyByteString\n\ncreateErrorResponse = createResponse \"text/html\"\ncreateJsonResponse = createResponse \"text/javascript\" status200\ncreateHtmlResponse = createResponse \"text/html\" status200\n</code></pre>\n\n<p>profit from our generic pairApply here.</p>\n\n<pre><code>textToArtifact :: (Text, Text) -&gt; Maybe Artifact\ntextToArtifact textXY = pairApply textToFloat textXY &gt;&gt;= return . flip Rectangle (1,1)\n</code></pre>\n\n<p>It should be possible to refactor the following two definitions.</p>\n\n<pre><code>textToFloat :: Text -&gt; Maybe Float\ntextToFloat x\n | (length $ textReads x) /= 1 = Nothing\n | (snd $ head $ textReads x) /= [] = Nothing\n | otherwise = Just $ fst $ head $ textReads x\n\ntextToFloatString :: Text -&gt; Maybe String\ntextToFloatString x\n | textReads x == [] = Nothing\n | (snd $ head $ textReads x) /= [] = Nothing\n | otherwise = Just $ unpack x\n\ntextReads = reads . unpack :: Text -&gt; [(Float, String)]\n\nexamplePlane :: Plane\nexamplePlane = [Rectangle (3, 3) (2,2),Rectangle (3, 8) (2,2), \n Rectangle (8, 3) (2,2), Rectangle (8, 8) (2,2)]\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T19:08:52.893", "Id": "21097", "Score": "0", "body": "Getting rid of shape makes sense, I like that. Also your simplification of insideAcc by using any in inside is nice. Thanks! I'm not certain of getting rid of position, or what exactly you're referring to I guess." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T19:21:24.240", "Id": "21099", "Score": "0", "body": "Oh I see- you got rid of the explicit corners. Yes, recognizing it as a list does make it much easier to work with I see, great insight!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T21:26:49.607", "Id": "21103", "Score": "0", "body": "@JimmyHoffa yes, I mentally parsed the four corners as position :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:50:23.433", "Id": "21143", "Score": "0", "body": "You're definition of 'generic functions' is very different from mine, but you're absolutely right, this makes sense. Thanks a lot! I'll really need to dig into applicatives more.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T18:32:17.170", "Id": "21180", "Score": "0", "body": "I am looking for type generic functions, specifically combinators :) (should have used the later term instead?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T19:03:31.803", "Id": "21181", "Score": "0", "body": "Referring to it as generic made more sense to me actually, but now I know what 'combinator' means, thanks :)" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:42:52.153", "Id": "13047", "ParentId": "13035", "Score": "4" } }, { "body": "<p>Here's the simplest rewrite I could come up with for your artifact collision detection algorithm:</p>\n\n<pre><code>module Plane where\n\ntype Location = (Float, Float)\ntype Size = (Float, Float)\ndata Artifact = Artifact { location :: Location, size :: Size }\n\nxMin (Artifact (x, y) (w, h)) = x - w / 2\nxMax (Artifact (x, y) (w, h)) = x + w / 2\nyMin (Artifact (x, y) (w, h)) = y - h / 2\nyMax (Artifact (x, y) (w, h)) = y + h / 2\n\ntype Plane = [Artifact]\n\nmoveArtifact :: Plane -&gt; Location -&gt; Artifact -&gt; Maybe Artifact\nmoveArtifact plane newLoc oldArtifact =\n if newArtifact `collidesWith` plane then Nothing else Just newArtifact\n where newArtifact = oldArtifact { location = newLoc }\n\n(locX, locY) `isInsideOf` a = xMin a &lt; locX &amp;&amp; locX &lt; xMax a\n &amp;&amp; yMin a &lt; locY &amp;&amp; locY &lt; yMax a\n\nmobileArtifact `collidesWith` plane = not . or $ do\n x &lt;- [xMin, xMax]\n y &lt;- [yMin, yMax]\n let location = (x mobileArtifact, y mobileArtifact)\n existingArtifact &lt;- plane\n return $ location `isInsideOf` existingArtifact\n</code></pre>\n\n<p>Some comments:</p>\n\n<p>Your collision detection had two bugs. One was that you were mixing up X and Y coordinates:</p>\n\n<pre><code>lowerLeftX = (-) artifactY $ artifactH / 2\nlowerLeftY = (-) artifactX $ artifactW / 2\n</code></pre>\n\n<p>I think you meant to switch those.</p>\n\n<p>The second bug was that your <code>insideAcc</code> function always returned <code>True</code> when it hit the empty list, regardless of what <code>Bool</code> value it currently had stored. This is why your collision detection always registered a collision.</p>\n\n<p>Your artifact movement also had a bug, in that you were checking the original position of the artifact for collisions and not the new position.</p>\n\n<p>Your <code>insideAcc</code> function was more complicated than it needed to be. A much simpler version is to use the <code>any</code> or <code>or</code> versions from the Prelude:</p>\n\n<pre><code>any :: (a -&gt; Bool) -&gt; [a] -&gt; Bool\n</code></pre>\n\n<p><code>any p</code> returns true if the predicate <code>p</code> evaluate to <code>True</code> for any value in the list.</p>\n\n<pre><code>or :: [Bool] -&gt; Bool\nor = any id\n</code></pre>\n\n<p><code>or</code> just evaluates a list of boolean values and returns <code>True</code> if at least one is true.</p>\n\n<p>In my rewrite, I used the <code>or</code> function to see of the list of returned <code>Bool</code>s had any <code>True</code>s.</p>\n\n<p>I rewrote <code>moveArtifact</code> to return a <code>Maybe Artifact</code>, otherwise you'd have to use floating point equality to tell if your <code>Artifact</code> moved, which would work but would be kind of weird. You can always recover your original behavior by using the <code>fromMaybe</code> function which extracts a value from a <code>Maybe</code>, providing a default value (i.e. your original artifact) if it is a <code>Nothing</code>.</p>\n\n<p>The most important trick I used when rewriting your code was the list monad (i.e. list comprehensions). This is a very useful trick when you need to do something on various permutations of certain values. The collision checking function checks every permutation of the three lists (i.e. <code>[xMin, xMax]</code>, <code>[yMin, yMax]</code>, and <code>plane</code>) for collisions.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T18:12:44.233", "Id": "21255", "Score": "0", "body": "Would it be bad practice to use a guard in moveArtifact rather than the if then else? I really like your greatly reduced version of this whole thing! Much simpler than mine, I'll have to wrap my head around how you're using <-, thanks for the critiques and I'll have to remember to look for higher order functions like any/or in the future! Also, great thought to make it return a maybe so the consumer can decide if the reaction to Nothing is the old location or something else altogether." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T19:48:30.943", "Id": "21259", "Score": "0", "body": "@JimmyHoffa Using guards is just fine. To understand `<-`, I recommend first learning about [list comprehensions](http://www.haskell.org/haskellwiki/List_comprehension), then learn about [monads](http://blog.sigfpe.com/2006/08/you-could-have-invented-monads-and.html). Also, when searching for higher order functions, you can use [Hoogle](http://www.haskell.org/hoogle/) or [Hayoo](http://holumbus.fh-wedel.de/hayoo/hayoo.html), which let you search for functions by type." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:11:53.857", "Id": "13129", "ParentId": "13035", "Score": "5" } } ]
{ "AcceptedAnswerId": "13129", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T04:40:44.590", "Id": "13035", "Score": "10", "Tags": [ "beginner", "haskell", "computational-geometry", "collision" ], "Title": "Artifact collision in plane module" }
13035
<p>My CSS feels dirty and I have no idea how to improve it. </p> <p>Suggestions are greatly appreciated!</p> <pre><code>html, body { border:0; margin:0; padding:0; } body { font: normal 12px helvetica,sans-serif; } .header { background-color:#242424; height:40px; } .header h1, h2 { text-transform:uppercase; } .header h1 { color:#FFF; display:inline; font-size:12px; } .header h2 { color:#B4B4B4; display:inline; font-size:12px; } .header #title, .sub #nav, #content { margin:0 auto; width:797px; } .header #title { padding-top:12px; } .header #version { color:#FFF; float:right; font-size:10px; margin:-13px 10px 0 0; } .sub { background-color:#E4F2FD; border-bottom:#D1E5EE solid 1px; height:30px; } .sub ul, li { margin:0; padding:0; list-style:none; } .sub li { float:left; padding-left:10px; margin:8px 20px 0 -18px; } .sub li a { color:#21759B; padding:8px; text-decoration:none; } .sub li a:hover { background-color:#FFF; } #content { margin-top:15px; } h1 { font-size:13px; } hr { border:0; height:1px; background-color:#E9E9E9; } .quick-add { background-color:#E9E9E9; color:#575757; font-size:12px; margin-top:10px; padding:2px; } .quick-add td { padding-left:8px; } #data { margin-top:15px; } #member { width:100.5%; margin-left:-1px;} #even { background-color:#EFF8FF; color:#21759B; } #odd { background-color:#FFF; } #data td { padding:3px; } #a { width:5%; text-align:center;} #b { width:40%; } #c { width:10%; } #d { width:20%; } #e { width:15%; } </code></pre> <p>Also, I have two different tables on two different pages (one for members and another for information) what's the best way to independently style them?</p> <p>Thanks!</p>
[]
[ { "body": "<p>You can try tools like <a href=\"http://csstidy.sourceforge.net/\" rel=\"nofollow\">CSSTidy</a> to clean your CSS. Here is an online tool who use CSSTidy with the result of the cleaning with default setup: <a href=\"http://www.cleancss.com/\" rel=\"nofollow\">http://www.cleancss.com/</a></p>\n\n<pre><code>html,body {\n border:0;\n margin:0;\n padding:0;\n}\n\nbody {\n font:normal 12px helvetica,sans-serif;\n}\n\n.header {\n background-color:#242424;\n height:40px;\n}\n\n.header h1,h2 {\n text-transform:uppercase;\n}\n\n.header h1 {\n color:#FFF;\n display:inline;\n font-size:12px;\n}\n\n.header h2 {\n color:#B4B4B4;\n display:inline;\n font-size:12px;\n}\n\n.header #title,.sub #nav,#content {\n margin:0 auto;\n width:797px;\n}\n\n.header #title {\n padding-top:12px;\n}\n\n.header #version {\n color:#FFF;\n float:right;\n font-size:10px;\n margin:-13px 10px 0 0;\n}\n\n.sub {\n background-color:#E4F2FD;\n border-bottom:#D1E5EE solid 1px;\n height:30px;\n}\n\n.sub ul,li {\n list-style:none;\n margin:0;\n padding:0;\n}\n\n.sub li {\n float:left;\n margin:8px 20px 0 -18px;\n padding-left:10px;\n}\n\n.sub li a {\n color:#21759B;\n padding:8px;\n text-decoration:none;\n}\n\nh1 {\n font-size:13px;\n}\n\nhr {\n background-color:#E9E9E9;\n border:0;\n height:1px;\n}\n\n.quick-add {\n background-color:#E9E9E9;\n color:#575757;\n font-size:12px;\n margin-top:10px;\n padding:2px;\n}\n\n.quick-add td {\n padding-left:8px;\n}\n\n#member {\n margin-left:-1px;\n width:100.5%;\n}\n\n#even {\n background-color:#EFF8FF;\n color:#21759B;\n}\n\n#data td {\n padding:3px;\n}\n\n#a {\n text-align:center;\n width:5%;\n}\n\n#b {\n width:40%;\n}\n\n#c {\n width:10%;\n}\n\n#d {\n width:20%;\n}\n\n#e {\n width:15%;\n}\n\n.sub li a:hover,#odd {\n background-color:#FFF;\n}\n\n#content,#data {\n margin-top:15px;\n}\n</code></pre>\n\n<p>You can tweak a lot of option to optimize your CSS to your liking</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T07:54:23.333", "Id": "13037", "ParentId": "13036", "Score": "4" } }, { "body": "<h2>Use classes instead of ids</h2>\n\n<ul>\n<li>#even</li>\n<li>#odd</li>\n<li>#a, #b, #c, #d, #e</li>\n</ul>\n\n<p>These are clearly repeating patterns that might happen several times in the same page.<br>\nAn id is supposed to be unique on the page.</p>\n\n<h2>Use better names</h2>\n\n<p>The id or class of an HTML element, like a class or function name when programming, is supposed to describe it.<br>\n<code>#a</code>, <code>#b</code>, etc, are bad names. If your HTML and CSS are small, it's not complicated to figure out what they do. But if they grow, or if someone else picks up your code, it might start to get tricky to figure out what each class/id is about.</p>\n\n<p>Clear nomenclature is better.</p>\n\n<h2>Use relative sizes</h2>\n\n<p>Your <code>body</code> defines font-size as 12px. Your <code>h3</code>, 13px.<br>\nIf you change the body's font-size, you will have to hunt down all other definitions and update them - e.g. the h3.</p>\n\n<p>If you define the first font-size absolutely (body: 12px) and then define all others relatively (h3: 110%), when you update the body's font-size the others adjust automatically.<br>\nThis has the added advantage of being friendlier to people using user styles, e.g. people that use larger font-sizes to be able to read better.</p>\n\n<h2>Misc</h2>\n\n<ul>\n<li><p>On the <code>hr</code>, why not style the border instead of clearing the border and using background-colour?</p></li>\n<li><p>I see too many negative margins. It feels somehow wrong.</p></li>\n</ul>\n\n<h2>\"Two different tables\"</h2>\n\n<p>I would first style them exactly the same, and then if necessary just add extra styles to differentiate them - perhaps change the colour of the borders or the background of the headers.<br>\nI'm not sure what you are asking there.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T15:09:02.207", "Id": "21074", "Score": "0", "body": "IDs**\nSo, instead of #a, #b, etc. use .a, .b\n\nMisc**\nHr - for some reason, that didn't work for me. I guess I did it wrong and ended up messing with the background.\n\nNegative margins - the only way I could get things to align properly. It is bad, I know. But like I said, I couldn't do any better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T16:16:03.203", "Id": "21080", "Score": "0", "body": "Yes, classes instead of ids means to use e.g. `.odd { background-color:#FFF; }`. (In this case I would probably use `td.odd { background-color:#FFF; }`)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T21:59:31.010", "Id": "21106", "Score": "0", "body": "Thanks for the advice! As per the negative margins, I'm not really sure how to fix them considering how my elements just jump around." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:27:31.657", "Id": "21122", "Score": "0", "body": "If you want help with that, you would have to share the HTML as well. A working [JSFiddle](http://jsfiddle.net/) would be ideal. But I would open a new question, rather than editing this one." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:38:58.967", "Id": "21337", "Score": "0", "body": "`even` and `odd` should absolutely be classes. I also agree that they should be attached to just the `td`. I also really like the statement about relative sizes, that is a great idea. Thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:53:33.553", "Id": "21339", "Score": "0", "body": "Actually, it is the tr that is odd, not the td. I should have wrote `tr.odd { background-color:#FFF; }`. Woops!" } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T09:06:53.823", "Id": "13038", "ParentId": "13036", "Score": "11" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T06:12:04.007", "Id": "13036", "Score": "7", "Tags": [ "optimization", "css" ], "Title": "CSS Optimization? How can I clean my code" }
13036
<p>The code works, but I guess it could be much better.</p> <pre><code>/* DESCRIPTION The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated. NOTE If the length of src is less than n, strncpy() pads the remainder of dest with null bytes. */ char *strncpy(char *dest, const char *src, size_t n) { size_t i = 0; char *d = dest; while ((i++ &lt; n) &amp;&amp; (*d++ = *src++)); while (i++ &lt; n) { *d++ = 0; } return dest; } /* DESCRIPTION The stlcpy() function copies the string pointed to by src. to the buffer pointed to by dest. The strings may not overlap. NOTE The destination string dest may *NOT* be large enough to receive the copy, then the truncation happpens. size_d is the size of destination buffer. */ char *strlcpy(char *dest, const char *src, size_t size_d) { size_t i = 0; char * d = dest; while ((i &lt; size_d) &amp;&amp; (*d++ = *src++)) i++; if (i &lt; size_d)//everything copied. { if (i &lt; size_d -1) { *d = 0; } else { //truncating the last char. dest[i-1] = 0; } } else if (i == size_d) { //truncating the src, size_d - 1 bytes copied. dest[i-1] = 0; } else { //i &gt; size_d, impossible. } return dest; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T13:08:25.973", "Id": "21063", "Score": "1", "body": "Why are you writing C-like code when working with C++? What functionality do you want to achieve what you wouldn't get from using `std::string` and it's functionalities?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T15:25:20.130", "Id": "21075", "Score": "0", "body": "@zxcdw just for practicing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T20:57:35.377", "Id": "21184", "Score": "1", "body": "@upton, perhaps you should consider removing c++ tag? c++ is a very different language with emphasis on different idioms, and your code may not get enough traction from c programmers if you indicate that c++ is involved. Conversely, you might get flamed for writing c like code in c++ if you claim it to be good c++ code." } ]
[ { "body": "<p>This would be my solution:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n\nint main() {\n // C++, so use what it provides you. A relatively flexible string library.\n std::string a = \"Hello \";\n std::string b = \"World!\";\n std::string c;\n\n // easy, simple, reliable, safe and FAST string copying and concatenation!\n c = a + b;\n\n std::cout &lt;&lt; c &lt;&lt; std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>After all, since you are working with C++, take advantage of what it offers you. Writing C is outright dumb unless you have a reason to do so, as it gives you no benefits at all. It's not secure, it's slow, it's complex and bug prone.</p>\n\n<p>If your code works, what makes you think \"it could be much better\"? What is <strong>better</strong> than working code? The thing is, that if it works don't fix it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T15:54:59.800", "Id": "21079", "Score": "0", "body": "\"What is better than working code?\" How about working, maintainable code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T16:55:51.860", "Id": "21081", "Score": "0", "body": "@BenjaminKloster yes and robust code and fast code and elegant code and whatnot. However, the bottom line is that if it works, don't try to fix it \"just because\". The fact that something *works* is far, far more important than the rest. If something is broken, it is useless. You get what I mean. ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:53:00.620", "Id": "21246", "Score": "0", "body": "@zxcdw This is codereview, not if-it-works-dont-fix-it.stackeexchange." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T13:20:28.380", "Id": "13045", "ParentId": "13040", "Score": "0" } }, { "body": "<p>Since you have written it for practice (as indicated in your comment), and <code>strncpy</code> has been implemented in various <a href=\"http://freebsd.active-venture.com/FreeBSD-srctree/newsrc/libkern/strncpy.c.html\" rel=\"nofollow\">platforms</a> in rather similar manner, I assume that you want comment on the function behavior itself and not specifically whether it conforms to the <code>strncpy</code> POSIX function.</p>\n\n<p>I am aware that the second function strlcpy handles many of the criticisms below, but there is no indication in your question that you have considered these.</p>\n\n<p>My first problem with the <code>strncpy</code> is that it allows no indication of failure or indication of any behavior even though there is a possibility of a few different behaviors that the user may be interested in.</p>\n\n<ul>\n<li>The first n characters may not contain a <code>\\0</code></li>\n<li>Did we truncate at <code>n</code>? or was the <code>src</code> small enough?</li>\n<li>How many characters were copied?</li>\n</ul>\n\n<p>We are using the return value by returning the <code>dest</code> even though this information is no different from the parameter that was passed in.</p>\n\n<p>Secondly, if the buffer was small enough, the function is zeroing out the remainder of the memory. This seems to be a wasteful effort. Perhaps it is enough to just null terminate the string?</p>\n\n<pre><code>int strncpy(char *dest, const char *src, size_t n) {\n size_t i = 0;\n while ((i++ &lt; n) &amp;&amp; (*dest++ = *src++));\n if (i &lt; n) {\n *dest = 0;\n return i;\n }\n return -1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:00:45.827", "Id": "13126", "ParentId": "13040", "Score": "2" } } ]
{ "AcceptedAnswerId": "13126", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T11:39:55.107", "Id": "13040", "Score": "2", "Tags": [ "c++", "c" ], "Title": "C like Cpp code to do strncpy and copy a string to a buffer which is not long enough" }
13040
<p>I've been given the following PHP code:</p> <pre><code>if(empty($search)){ $_SESSION['keyword_exists'] = "no"; }else{ if(isset($_SESSION['old_keyword']) &amp;&amp; $_SESSION['old_keyword'] != $search){ $_SESSION['keyword_exists'] = "no"; } } if(isset($_REQUEST['limitstart']) &amp;&amp; $_REQUEST['limitstart'] &gt; 0){ if (!empty($search)) { if(isset($_SESSION['keyword_exists']) &amp;&amp; $_SESSION['keyword_exists'] === "yes"){ //intentionally left blank? }else{ $limitstart = "0"; $_SESSION['keyword_exists'] = "yes"; $_SESSION['old_keyword'] = $search; } } }else{ $limitstart = "0"; } </code></pre> <p>I'm not entirely sure what this code does, as I'm fairly new to PHP and webdev. The one comment is mine. Is there any way to clean this up so that the next guy to see this is less confused than I am?</p>
[]
[ { "body": "<p>Let's start with the basics:</p>\n\n<ul>\n<li>$_SESSION: This is a global array that holds all your <a href=\"http://php.net/manual/en/features.sessions.php\" rel=\"nofollow\">session information</a>.</li>\n<li>$_REQUEST: This is a global array that contains the contents of $_GET, $_POST and $_COOKIE. Read more on PHP's <a href=\"http://www.php.net/manual/en/language.variables.superglobals.php\" rel=\"nofollow\">superglobals</a>.</li>\n</ul>\n\n\n\n<pre><code>if( empty($search) ) {\n\n $_SESSION['keyword_exists'] = \"no\";\n\n} else {\n\n if( isset($_SESSION['old_keyword']) &amp;&amp; $_SESSION['old_keyword'] != $search ) {\n $_SESSION['keyword_exists'] = \"no\";\n }\n\n}\n</code></pre>\n\n<p>The outer if depends on whether the <code>$search</code> variable is empty or not. Empty in context <a href=\"http://th.php.net/manual/en/function.empty.php\" rel=\"nofollow\">could mean</a>:</p>\n\n<blockquote>\n <ul>\n <li>\"\" (an empty string)</li>\n <li>0 (0 as an integer)</li>\n <li>0.0 (0 as a float)</li>\n <li>\"0\" (0 as a string)</li>\n <li>NULL</li>\n <li>FALSE</li>\n <li>array() (an empty array)</li>\n <li>var $var; (a variable declared, but without a value in a class)</li>\n </ul>\n</blockquote>\n\n<p>If <code>$search</code> is empty, <code>$_SESSION['keyword_exists']</code> is set to \"no\" (can't read the author's mind, but my choice would be <code>false</code>, not a string). From the naming we can assume that <code>$search</code> holds (or not) the keyword(s) of a search. Now if that is <em>not</em> empty:</p>\n\n<pre><code> if( isset($_SESSION['old_keyword']) &amp;&amp; $_SESSION['old_keyword'] != $search ) {\n $_SESSION['keyword_exists'] = \"no\";\n }\n</code></pre>\n\n<p>The first clause, <code>isset($_SESSION['old_keyword'])</code> essentially checks if there's an \"old_keyword\" index in the <code>$_SESSION</code> array (and whether it's <code>null</code> or not), that's a pretty typical check for arrays. The second check, that executes if and only if the first one passes, checks whether what's in <code>$_SESSION['old_keyword']</code> is <em>not</em> the same as what's in <code>$search</code>. I'm assuming that the author had <em>some</em> reason for that, but can't imagine what that reason is. </p>\n\n<p>Summarizing what happens here, if: </p>\n\n<ul>\n<li><code>$search</code> is empty, or </li>\n<li><code>$search</code> is <em>not</em> the same as <code>$_SESSION['old_keyword']</code></li>\n</ul>\n\n<p>...then <code>$_SESSION['keyword_exists'] = \"no\"</code>. A perhaps simpler way to write that would be:</p>\n\n<pre><code>if(\n empty($search)\n || ( isset($_SESSION['old_keyword']) &amp;&amp; $_SESSION['old_keyword'] != $search )\n) {\n $_SESSION['keyword_exists'] = \"no\";\n}\n</code></pre>\n\n<p>Moving on to the next part: </p>\n\n<pre><code>if( isset($_REQUEST['limitstart']) &amp;&amp; $_REQUEST['limitstart'] &gt; 0 ) {\n\n ...\n\n} else {\n $limitstart = \"0\";\n}\n</code></pre>\n\n<p>The clause is very similar to the one discussed previously, only this time other than checking if <code>$_REQUEST</code> has a <code>\"limitstart\"</code> index, the author also checks that the value is larger than zero. That's an unsafe check, because at this point we don't now what the type of the value in <code>$_REQUEST['limitstart']</code> is, and if it's anything other than a number, there will be automatic type juggling involved, and the check is <em>completely</em> unreliable. </p>\n\n<p>From the name and context, I'm assuming the variable should hold an integer (if anything) that limits the search. If the variable doesn't hold anything, the limit is set to zero (<code>$limitstart = \"0\"</code>), curiously using a string form of zero. I'd rewrite that check as:</p>\n\n<pre><code>$limitstart = 0;\n\nif(\n isset($_REQUEST['limitstart']) \n &amp;&amp; ( is_int($_REQUEST['limitstart']) || ctype_digit($_REQUEST['limitstart']) )\n &amp;&amp; $_REQUEST['limitstart'] &gt; 0\n) {\n\n ...\n\n} \n</code></pre>\n\n<p><code>is_int()</code> checks whether the value is an integer and <code>ctype_digit()</code> whether it's a string that only contains digits (thus a integer in string form), any of the two is acceptable for the following check, <code>$_REQUEST['limitstart'] &gt; 0</code>. I've also moved <code>$limitstart = 0;</code> out of the check, I'm initializing it to zero and will override if and only if there's a need. But let's see what happens if the check is true:</p>\n\n<pre><code> if ( !empty($search) ) {\n if( isset($_SESSION['keyword_exists']) &amp;&amp; $_SESSION['keyword_exists'] === \"yes\" ) {\n //intentionally left blank?\n } else {\n $limitstart = \"0\";\n $_SESSION['keyword_exists'] = \"yes\";\n $_SESSION['old_keyword'] = $search;\n }\n }\n</code></pre>\n\n<p>This is obviously incomplete. The outer check is simple enough, it's whether <code>$search</code> is empty or not. If it's empty, nothing happens, if it's <em>not</em>, the inner check is on whether <code>_SESSION</code> has a <code>\"keyword_exists\"</code> index, and if it's value is <code>\"yes\"</code>. If that's true, <em>something</em> happens, but who knows what? I'm assuming one of the things that would happen would be to set a proper value to <code>$limitstart</code>. Anyways, if the check is false:</p>\n\n<ul>\n<li><code>$limitstart</code> remains zero,</li>\n<li><code>$_SESSION['keyword_exists']</code> for some reason becomes <code>\"yes\"</code>, and</li>\n<li><code>$_SESSION['old_keyword']</code> becomes <code>$search</code>.</li>\n</ul>\n\n<p>Unfortunately, I have no idea why. Anyways, my full rewrite would be:</p>\n\n<pre><code>if(\n empty($search)\n || ( isset($_SESSION['old_keyword']) &amp;&amp; $_SESSION['old_keyword'] != $search )\n) {\n $_SESSION['keyword_exists'] = \"no\";\n}\n\n$limitstart = 0;\n\nif(\n isset($_REQUEST['limitstart']) \n &amp;&amp; ( is_int($_REQUEST['limitstart']) || ctype_digit($_REQUEST['limitstart']) )\n &amp;&amp; $_REQUEST['limitstart'] &gt; 0\n) {\n\n if ( !empty($search) ) {\n if( isset($_SESSION['keyword_exists']) &amp;&amp; $_SESSION['keyword_exists'] === \"yes\" ) {\n //intentionally left blank?\n } else {\n $_SESSION['keyword_exists'] = \"yes\";\n $_SESSION['old_keyword'] = $search;\n }\n }\n\n} \n</code></pre>\n\n<p>The code is equivalent, and will work (?) if you replace it in your script. Hope it clarifies things a bit. The overall quality of the code is bad, there are some hints of an amateur developer there, and you shouldn't really worry that you didn't grasp what the code does, since you are unfamiliar with the language. It's an incomplete and mostly poorly written piece of code, good luck with it ;)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:34:57.050", "Id": "21217", "Score": "0", "body": "Thanks a lot, I learned quite a bit from this. I wish I could give you more than +25 rep, you deserve it. Thanks for the rewrite. It feels good knowing I'm not the only one confused by this (outsourced) code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T16:42:12.260", "Id": "21418", "Score": "0", "body": "@SomeKittens: I'd only like to add that using [`filter_input()`](http://us3.php.net/manual/en/function.filter-input.php) would look cleaner compared to `is_int()` and `ctype_digit()`. And also that `$_REQUEST` is not a very secure array to use. Using the proper array (`$_POST`, `$_GET`, etc...) if you know the source would be much better. Otherwise, this is a very good review +1" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T08:38:03.353", "Id": "13115", "ParentId": "13044", "Score": "4" } } ]
{ "AcceptedAnswerId": "13115", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T13:17:26.120", "Id": "13044", "Score": "4", "Tags": [ "php", "search" ], "Title": "Improve search keyword" }
13044
<p>I've written a general purpose repeat function which allows you to repeat a callback function X times separated by I intervals with the option to start immediately or after the interval. It can also default to just looping infinitely, which is what <code>setInterval</code> does. Is there a better approach, or any improvements people can provide? Make sure to comment out all but one of the examples :)</p> <pre><code>function repeatXI(callback, interval, repeat, immediate) { repeat = typeof repeat == 'undefined' ? -1 : repeat; interval = interval &lt;= 0 ? 1000 : interval; immediate = typeof immediate == 'undefined' ? false : immediate; var offset = immediate ? 0 : 1; var id = null; if (repeat &gt; 0) { for (var i = 0; i &lt; repeat; i++) { id = setTimeout(callback, interval * (i + offset)); } } else { id = setInterval(callback, interval); } return id; } // Example var someFunc = function () {console.log(1);} // Repeats forever, 1 second apart repeatXI(someFunc, 1000); // Repeats 10 times, 1 second apart, beginning after 1 second repeatXI(someFunc, 1000, 10); // Same as above, but beginning now repeatXI(someFunc, 1000, 10, true); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-04-08T22:46:37.460", "Id": "155591", "Score": "0", "body": "Also good to note the difference in setTimeout and setInterval - http://stackoverflow.com/questions/729921/settimeout-or-setinterval" } ]
[ { "body": "<p>It's pretty much commented in the code. The usage is still the same as the one you used. <a href=\"http://jsfiddle.net/J8Umt/\" rel=\"nofollow\">Here's a demo</a>.</p>\n\n<pre><code>function repeatXI(callback, interval, repetitions, immediate) {\n\n //general purpose repeater function\n function repeater(repetitions) {\n if (repetitions &gt;= 0) {\n\n //use call or apply so we can specify \"this\"\n callback.call(this);\n\n //repeat\n setTimeout(function() {\n\n //the idea of passing the repetition count replaces the loop\n //the -- means that the initial iteration turns the repeat to -1\n //since the condition runs when &gt;=0 repetitions\n repeater(--repetitions);\n }, interval);\n }\n }\n\n //set defaults using ||\n //|| means \"use this value OR the default\"\n //if you want to be strict, you can do type checks instead\n repetitions = repetitions || 0;\n interval = interval || 1000;\n\n //if immediate, call instantly, else, delay\n if (immediate) {\n console.log('immediate');\n repeater(--repetitions);\n } else {\n console.log('delayed');\n setTimeout(function() {\n repeater(--repetitions);\n }, interval);\n }\n}\n</code></pre>\n\n<p>Witout comments and packed:</p>\n\n<pre><code>function repeatXI(callback, interval, repetitions, immediate) {\n function repeater(repetitions) {\n if (repetitions &gt;= 0) {\n callback.call(this);\n setTimeout(function () {\n repeater(--repetitions)\n }, interval)\n }\n }\n repetitions = repetitions || 0;\n interval = interval || 1000;\n if (immediate) {\n repeater(--repetitions)\n } else {\n setTimeout(function () {\n repeater(--repetitions)\n }, interval)\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T18:55:03.150", "Id": "13050", "ParentId": "13046", "Score": "3" } }, { "body": "<p>I don't see anything problematic with your code, but just for fun, here are some alternative approaches to various parts of the code. It's 100% DRY, and functionally identical to the original.</p>\n\n<pre><code>function repeatXI(callback, interval, repeats, immediate) {\n var timer, trigger;\n trigger = function () {\n callback();\n --repeats || clearInterval(timer);\n };\n\n interval = interval &lt;= 0 ? 1000 : interval; // default: 1000ms\n repeats = parseInt(repeats, 10) || 0; // default: repeat forever\n timer = setInterval(trigger, interval);\n\n if( !!immediate ) { // Coerce boolean\n trigger();\n }\n}\n</code></pre>\n\n<p><strong><a href=\"http://jsfiddle.net/NdhCR/\" rel=\"nofollow\">And here's a jsfiddle demo</a></strong></p>\n\n<p>If you want, you can return <code>timer</code> from the function (as I do in the demo), so you can clear it (i.e. cancel the repeater) elsewhere in your code.</p>\n\n<p>Regardless of the implementation-specifics it's worth noting that timers are unreliable at the best of times (since JS is single-threaded). Depending on your needs it may not be a good idea to set <em>n</em> timeouts at <code>n * interval</code> as you do for finite repeats. If a few of the timeouts get blocked long enough, they'll all queue up, and fire at once, once the thread clears. With <code>setInterval</code> though, you're guaranteed that there'll be <em>at least</em> <code>interval</code> time between the callbacks.</p>\n\n<p>So it depends on your needs how you want to implement it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T01:52:15.257", "Id": "21112", "Score": "0", "body": "good point regarding the intervals!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T02:03:45.737", "Id": "21186", "Score": "0", "body": "@AramKocharyan No prob. Don't forget to click the checkmark on mine or Joseph's answer - whichever one you think helped the most" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T19:09:05.653", "Id": "13051", "ParentId": "13046", "Score": "6" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T14:45:00.833", "Id": "13046", "Score": "3", "Tags": [ "javascript" ], "Title": "JavaScript: Repeat a function X times at I intervals" }
13046
<p>If you look at the condition of <code>If calculated Then</code> in the code below, this is what slowing down the code. While the code provided seem fast with <code>Const initBit = 4</code> try it with something over 12. I want to be able to use this code (with calculated param as <code>true</code>) with <code>initBit</code> of 20 or more. </p> <p><strong>Beware</strong> that 20 or more might require a gig or more of RAM and/or compiled as x64.</p> <p>C# code (converted with an online tool from VB.NET):</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; static class Module1 { public static void Main() { Console.WindowHeight = 59; int initBit = 4; var sw = Stopwatch.StartNew(); initBits(initBit, false); sw.Stop(); printResult(sw, false); sw = Stopwatch.StartNew(); initBits(initBit, true); sw.Stop(); printResult(sw, true); Console.Read(); } private static int maxBits; private static int[] CountBit; private static int[] CalculatedBit; private static int[] MapBit; private static void initBits(int maxBit, bool calculated) { int[] calc = null; bool calcOk = false; int calcOkPos = 0; List&lt;int&gt; calcResult = new List&lt;int&gt;(); int findPos = 0; maxBits = ((1 &lt;&lt; maxBit)) - 1; calc = new int[maxBits + 1]; CountBit = new int[maxBits + 1]; MapBit = new int[maxBits + 1]; for (var i = 0; i &lt;= maxBits; i++) { CountBit[i] = getBitCount(i); } calcResult.Add(0); for (var i = maxBits; i &gt;= 1; i += -1) { for (var j = 0; j &lt;= CountBit[i] - 1; j++) { calc[j] = getBitValue(i, j); } calcOk = false; if (calculated) { findPos = calcResult.IndexOf(calc[0], 0); while (findPos != -1) { calcOk = true; for (var k = 0; k &lt;= CountBit[i] - 1; k++) { calcOk = calcOk &amp;&amp; calcResult[findPos + k] == calc[k]; if (!calcOk) break; // TODO: might not be correct. Was : Exit For } if (calcOk) { calcOkPos = findPos; break; // TODO: might not be correct. Was : Exit While } findPos = calcResult.IndexOf(calc[0], findPos + 1); } } if (!calcOk) { MapBit[i] = calcResult.Count; for (var j = 0; j &lt;= CountBit[i] - 1; j++) { calcResult.Add(calc[j]); } } else { MapBit[i] = calcOkPos; } } CalculatedBit = calcResult.ToArray(); calcResult.Clear(); } private static int getBitCount(int bits) { bits = bits - ((bits &gt;&gt; 1) &amp; 0x55555555); bits = (bits &amp; 0x33333333) + ((bits &gt;&gt; 2) &amp; 0x33333333); return ((bits + (bits &gt;&gt; 4) &amp; 0xf0f0f0f) * 0x1010101) &gt;&gt; 24; } private static int getBitValue(int bits, int pos) { for (var k = 0; k &lt;= pos - 1; k++) { bits = bits &amp; bits - 1; } return bits ^ bits &amp; (bits - 1); } private static void printResult(Stopwatch sw, bool calculated) { StringBuilder sb = new StringBuilder(); sb.AppendLine(" Calculated : " + calculated.ToString() + Environment.NewLine + " maxBits : " + maxBits.ToString() + " (" + getBitCount(maxBits) + ")" + Environment.NewLine + " CalculatedBit.Length : " + CalculatedBit.Length.ToString()); //if initBit is 6 or less if (CalculatedBit.Length &lt;= 65) { sb.AppendLine(Environment.NewLine + " Started with" + Environment.NewLine + " Number : Value"); for (var i = 0; i &lt;= maxBits; i++) { sb.Append(i.ToString().PadLeft(10) + " : "); for (var j = 0; j &lt;= (CountBit[i] == 0 ? 1 : CountBit[i] - 1); j++) { sb.Append(getBitValue(i, j).ToString() + " "); } sb.AppendLine(""); } sb.AppendLine(Environment.NewLine + " Index : Value"); for (var i = 0; i &lt;= CalculatedBit.GetUpperBound(0); i++) { sb.AppendLine(i.ToString().PadLeft(9) + " : " + CalculatedBit[i].ToString()); } sb.AppendLine(Environment.NewLine + " Number : MapBit : CountBit : Value"); for (var i = 0; i &lt;= maxBits; i++) { sb.Append(i.ToString().PadLeft(10) + " : " + MapBit[i].ToString().PadLeft(6) + " : " + CountBit[i].ToString().PadLeft(8) + " : "); for (var k = 0; k &lt;= (CountBit[i] == 0 ? 1 : CountBit[i] - 1); k++) { sb.Append(CalculatedBit[MapBit[i] + k].ToString() + " "); } sb.AppendLine(""); } } sb.AppendLine(Environment.NewLine + " Took: " + sw.ElapsedMilliseconds + "ms" + Environment.NewLine); Console.Write(sb.ToString()); Debug.Write(sb.ToString()); } } </code></pre> <p>Make sure, <strong>if you do create a VB.NET project</strong>, to "check" the setting "Remove integer overflow checks" in "Advanced Compiler Settings" in the "Compile" tab in the project "Properties" to let the magic of <code>getBitCount</code> function work.</p> <p>VB.NET code:</p> <pre class="lang-vb prettyprint-override"><code>Imports System.Text Module Module1 Sub Main() Console.WindowHeight = 59 Const initBit = 4 Dim sw = Stopwatch.StartNew initBits(initBit, False) sw.Stop() printResult(sw, False) sw = Stopwatch.StartNew initBits(initBit, True) sw.Stop() printResult(sw, True) Console.Read() End Sub Private maxBits As Integer Private CountBit() As Integer Private CalculatedBit() As Integer Private MapBit() As Integer Private Sub initBits(ByVal maxBit As Integer, ByVal calculated As Boolean) Dim calc() As Integer Dim calcOk As Boolean Dim calcOkPos As Integer Dim calcResult As New List(Of Integer) Dim findPos As Integer maxBits = ((1 &lt;&lt; maxBit)) - 1 ReDim calc(maxBits) ReDim CountBit(maxBits) ReDim MapBit(maxBits) For i = 0 To maxBits CountBit(i) = getBitCount(i) Next calcResult.Add(0) For i = maxBits To 1 Step -1 For j = 0 To CountBit(i) - 1 calc(j) = getBitValue(i, j) Next calcOk = False If calculated Then findPos = calcResult.IndexOf(calc(0), 0) While findPos &lt;&gt; -1 calcOk = True For k = 0 To CountBit(i) - 1 calcOk = calcOk AndAlso calcResult(findPos + k) = calc(k) If Not calcOk Then Exit For Next If calcOk Then calcOkPos = findPos Exit While End If findPos = calcResult.IndexOf(calc(0), findPos + 1) End While End If If Not calcOk Then MapBit(i) = calcResult.Count For j = 0 To CountBit(i) - 1 calcResult.Add(calc(j)) Next Else MapBit(i) = calcOkPos End If Next CalculatedBit = calcResult.ToArray calcResult.Clear() End Sub Private Function getBitCount(bits As Integer) As Integer bits = bits - ((bits &gt;&gt; 1) And &amp;H55555555) bits = (bits And &amp;H33333333) + ((bits &gt;&gt; 2) And &amp;H33333333) Return ((bits + (bits &gt;&gt; 4) And &amp;HF0F0F0F) * &amp;H1010101) &gt;&gt; 24 End Function Private Function getBitValue(bits As Integer, pos As Integer) As Integer For k = 0 To pos - 1 bits = bits And bits - 1 Next Return bits Xor bits And (bits - 1) End Function Private Sub printResult(ByVal sw As Stopwatch, ByVal calculated As Boolean) Dim sb As New StringBuilder sb.AppendLine(" Calculated : " &amp; calculated.ToString &amp; Environment.NewLine &amp; " maxBits : " &amp; maxBits.ToString &amp; " (" &amp; getBitCount(maxBits) &amp; ")" &amp; Environment.NewLine &amp; " CalculatedBit.Length : " &amp; CalculatedBit.Length.ToString) If CalculatedBit.Length &lt;= 65 Then 'if initBit is 6 or less sb.AppendLine(Environment.NewLine &amp; " Started with" &amp; Environment.NewLine &amp; " Number : Value") For i = 0 To maxBits sb.Append(i.ToString.PadLeft(10) &amp; " : ") For j = 0 To If(CountBit(i) = 0, 1, CountBit(i)) - 1 sb.Append(getBitValue(i, j).ToString &amp; " ") Next sb.AppendLine("") Next sb.AppendLine(Environment.NewLine &amp; " Index : Value") For i = 0 To CalculatedBit.GetUpperBound(0) sb.AppendLine(i.ToString.PadLeft(9) &amp; " : " &amp; CalculatedBit(i).ToString) Next sb.AppendLine(Environment.NewLine &amp; " Number : MapBit : CountBit : Value") For i = 0 To maxBits sb.Append(i.ToString.PadLeft(10) &amp; " : " &amp; MapBit(i).ToString.PadLeft(6) &amp; " : " &amp; CountBit(i).ToString.PadLeft(8) &amp; " : ") For k = 0 To If(CountBit(i) = 0, 1, CountBit(i)) - 1 sb.Append(CalculatedBit(MapBit(i) + k).ToString &amp; " ") Next sb.AppendLine("") Next End If sb.AppendLine(Environment.NewLine &amp; " Took: " &amp; sw.ElapsedMilliseconds &amp; "ms" &amp; Environment.NewLine) Console.Write(sb.ToString) Debug.Write(sb.ToString) End Sub End Module </code></pre> <p>Result:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Calculated : False maxBits : 15 (4) CalculatedBit.Length : 33 Started with Number : Value 0 : 0 1 : 1 2 : 2 3 : 1 2 4 : 4 5 : 1 4 6 : 2 4 7 : 1 2 4 8 : 8 9 : 1 8 10 : 2 8 11 : 1 2 8 12 : 4 8 13 : 1 4 8 14 : 2 4 8 15 : 1 2 4 8 Index : Value 0 : 0 1 : 1 2 : 2 3 : 4 4 : 8 5 : 2 6 : 4 7 : 8 8 : 1 9 : 4 10 : 8 11 : 4 12 : 8 13 : 1 14 : 2 15 : 8 16 : 2 17 : 8 18 : 1 19 : 8 20 : 8 21 : 1 22 : 2 23 : 4 24 : 2 25 : 4 26 : 1 27 : 4 28 : 4 29 : 1 30 : 2 31 : 2 32 : 1 Number : MapBit : CountBit : Value 0 : 0 : 0 : 0 1 : 32 : 1 : 1 2 : 31 : 1 : 2 3 : 29 : 2 : 1 2 4 : 28 : 1 : 4 5 : 26 : 2 : 1 4 6 : 24 : 2 : 2 4 7 : 21 : 3 : 1 2 4 8 : 20 : 1 : 8 9 : 18 : 2 : 1 8 10 : 16 : 2 : 2 8 11 : 13 : 3 : 1 2 8 12 : 11 : 2 : 4 8 13 : 8 : 3 : 1 4 8 14 : 5 : 3 : 2 4 8 15 : 1 : 4 : 1 2 4 8 Took: 1ms Calculated : True maxBits : 15 (4) CalculatedBit.Length : 13 Started with Number : Value 0 : 0 1 : 1 2 : 2 3 : 1 2 4 : 4 5 : 1 4 6 : 2 4 7 : 1 2 4 8 : 8 9 : 1 8 10 : 2 8 11 : 1 2 8 12 : 4 8 13 : 1 4 8 14 : 2 4 8 15 : 1 2 4 8 Index : Value 0 : 0 1 : 1 2 : 2 3 : 4 4 : 8 5 : 1 6 : 4 7 : 8 8 : 1 9 : 2 10 : 8 11 : 1 12 : 8 Number : MapBit : CountBit : Value 0 : 0 : 0 : 0 1 : 1 : 1 : 1 2 : 2 : 1 : 2 3 : 1 : 2 : 1 2 4 : 3 : 1 : 4 5 : 5 : 2 : 1 4 6 : 2 : 2 : 2 4 7 : 1 : 3 : 1 2 4 8 : 4 : 1 : 8 9 : 11 : 2 : 1 8 10 : 9 : 2 : 2 8 11 : 8 : 3 : 1 2 8 12 : 3 : 2 : 4 8 13 : 5 : 3 : 1 4 8 14 : 2 : 3 : 2 4 8 15 : 1 : 4 : 1 2 4 8 Took: 0ms </code></pre> </blockquote> <hr> <p>That code is a kind of a compressed cached dictionary (<code>calculatedBit</code>) that can rebuild a number from 2 information, the position (<code>mapBit</code>) and the number of bits (<code>countBit</code>).</p> <p><strong>I will use the result (with Calculated : True) provided to explain it.</strong></p> <p>I passed the value 4 to the method so I'm asking "create the dictionary for number 0 to 15" because 15 = 1111. I start at 15 and loop until 1 (0 is hard-coded to be at position 0 of the <code>calculatedBit</code>). For each number, I'm getting the number of bits that are 1 (and not 0) and I'm getting the value of each bits.</p> <p>Let say I'm at number 6, (0110), I set countbit(6) = 2 and this array of int 2, 4. I'm looping through the dictionary to find that specific pattern: 2, 4. Since 15 is already cached (1111, countbit 4, and this list 1, 2, 4, 8) and the lookup is telling me that 2, 4 is found at position 2, I set mapbit(6) = 2.</p> <p>With all that cached information, I can simply rebuild the number without having to call the function getBitValue and getBitCount which are more expensive than a reference in an array.</p> <p>If I want to rebuild the number 6, I can simply say; get me the position, mapbit(6), and the number of bit to sum, countbit(6) and I can simply do a LINQ call or a loop from 2 to 3 in the arrat <code>calculatedBit</code> and I have my number 6.</p> <p>In my program, I have a huge loop that want a random bit, that is 1, from a number. I only have to do <code>calculatedbit(mapbit(num) + random.next(0,countbit(num)))</code> to get that random bit. By precalculating everything, I'm gaining 50 to 75% in speed since I don't have to call the <code>getBitValue</code> and <code>getBitCount</code> function millions of time. Which means I don't have to do <code>getBitValue(num, random.next(0,getBitCount(num)))</code>.</p> <p>My problem is that caching above 14 bits (1111111111111) is VERY slow and without the lookup, it can get pretty big. 25 bits can take 2.5 gigs of RAM.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:38:13.800", "Id": "21083", "Score": "3", "body": "I think the relevant code here is only a few lines. But because of all the WriteLining I'm not sure." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:42:02.600", "Id": "21084", "Score": "0", "body": "@HenkHolterman, don't look at the printResult. it's just to see the end result" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:42:10.373", "Id": "21085", "Score": "0", "body": "Instead of generating data and then matching it against the pattern, why not generate data that matches by construction?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:43:51.630", "Id": "21087", "Score": "0", "body": "I moved the printresult code at the end" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:47:06.530", "Id": "21088", "Score": "0", "body": "@BenVoigt, generating the data with initbit set at 25 and calculated to false take over 2 gig of ram, you can see why it is not a good idea" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:58:53.320", "Id": "21089", "Score": "0", "body": "Why did you post VB *and* C# code? Wouldn’t one be enough?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:59:57.853", "Id": "21090", "Score": "0", "body": "@KonradRudolph, yes but this way I can reach more people" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T18:15:10.117", "Id": "21092", "Score": "5", "body": "Can you talk through a bit what this code is tryign to do, especially the bit you want optimised. The code is quite complex and the only thing that makes sense of what you are doing is counting the bits... Unfortunately your code has some confusingly named variables (eg maxBits isn't the maximum number of bits as I would have expected but seems to be the maximum value without any bits set higher than maxbits). Cleaning up some of that might make everybody's life easier." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T18:24:34.317", "Id": "21093", "Score": "0", "body": "@Fredou You can reasonably expect that competent C# programmers can understand and critique the code in question, and vice versa. But well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T03:04:24.680", "Id": "22559", "Score": "1", "body": "@Fredou: what is the purpose of your app? Are you facing a problem that requires counting items, searching/retrieving from a collection or is it mostly compression/encoding? Have you considered standard algorithms and data structures suitable for that kind of work? For example, hash|dictionaries|associative arrays, or tree-like data structures? For dictionary-based encoding, study classic algorithms (e.g. Lempel-Ziv, etc). Cheers!" } ]
[ { "body": "<p>I found the perfect way! It was right in front of me; I just had to look at the data itself.</p>\n\n<pre><code>Private Sub initBits(ByVal maxBit As Integer)\n\n maxBits = ((1 &lt;&lt; maxBit)) - 1\n ReDim CountBit(maxBits)\n ReDim MapBit(maxBits)\n\n For i = 1 To maxBits\n CountBit(i) = getBitCount(i)\n Next\n\n Dim StopBit = (maxBits &gt;&gt; 1)\n Dim StartBit = maxBits\n Dim count As Integer = 0\n\n For i = StartBit To StopBit + 1 Step -2\n count += CountBit(i)\n Next\n\n ReDim CalculatedBit(count)\n count = 1\n For i = StartBit To StopBit + 1 Step -2\n MapBit(i) = count\n For j = 0 To CountBit(i) - 1\n CalculatedBit(count) = getBitValue(i, j)\n count += 1\n Next\n Next\n\n Do\n count = StartBit\n StartBit = StopBit\n StopBit = StopBit &gt;&gt; 1\n For i = StartBit To StopBit + 1 Step -2\n MapBit(i) = MapBit(count)\n count -= 2\n Next\n Loop Until StopBit = 0\n\n For i = 3 To maxBits Step 2\n MapBit(i - 1) = MapBit(i) + 1\n Next\nEnd Sub\n</code></pre>\n\n<p>Data:</p>\n\n\n\n<blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>Number : MapBit : CountBit : Value\n 0 : 0 : 0 : 0 \n 1 : 1 : 1 : 1 \n 2 : 2 : 1 : 2 \n 3 : 1 : 2 : 1 2 \n 4 : 6 : 1 : 4 \n 5 : 5 : 2 : 1 4 \n 6 : 2 : 2 : 2 4 \n 7 : 1 : 3 : 1 2 4 \n 8 : 12 : 1 : 8 \n 9 : 11 : 2 : 1 8 \n 10 : 9 : 2 : 2 8 \n 11 : 8 : 3 : 1 2 8 \n 12 : 6 : 2 : 4 8 \n 13 : 5 : 3 : 1 4 8 \n 14 : 2 : 3 : 2 4 8 \n 15 : 1 : 4 : 1 2 4 8\n</code></pre>\n</blockquote>\n\n<p>The dictionary I made of the odd numbers of the second half in this example: 15, 13, 11 and 9.</p>\n\n<p>The rest is just the same pattern; look at 7, 5, 3 and 1. This <code>mapbit(num)</code> reference are the same as 15, 13, 15 and 15. I do not need to loop through the dictionary like i was doing before; it's a simple logic.</p>\n\n<p>Then the even numbers, which is always <code>mapbit(evennumber) = mapbit(evennumber+1) +1</code>. No need to find the pattern again.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-16T20:12:40.217", "Id": "23991", "Score": "1", "body": "The question looks intriguing; I wish I understood what it is about though. I suspect that you need a lot less code than you have. Also, storing things in a dictionary rather than an array cannot possibly be faster." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T02:07:39.693", "Id": "13139", "ParentId": "13048", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T17:29:23.900", "Id": "13048", "Score": "3", "Tags": [ "c#", ".net", "vb.net", "bitwise" ], "Title": "Finding patterns in a growing collection" }
13048
<p>I thought to spent my free time by solving a puzzle: <a href="http://www.spotify.com/int/jobs/tech/best-before/" rel="nofollow">Best Before Spotify Puzzle</a>.</p> <p>I coded in Java, and yeah I did not clean up my code (just a rough work) and I have yet to optimize... so I did check for possible test cases (including leap year) and could not find any of these cases failing, but I got a reply from the bot as "wrong answer". Here is my code, could anyone please find where my test case fails?</p> <p>Algorithm: </p> <ol> <li>Generate 6 different inputs (for 3 inputs, permutation goes as 3*2). </li> <li>Choose the best earliest date of all 6 inputs.</li> </ol> <pre><code>import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Collections; public class bestbefore { int array[]=new int[3]; ArrayList&lt;Integer&gt; temp=new ArrayList&lt;Integer&gt;(); int prevy=10000; int prevd=1000; int prevm=1000; int flag=0; String tem; public static void main(String[] args) { bestbefore b4=new bestbefore(); b4.input(); } void input() throws IllegalArgumentException { InputStreamReader input=new InputStreamReader(System.in); BufferedReader inputs=new BufferedReader(input); try { tem=inputs.readLine(); String [] temps=tem.split("/"); try { array[0]=Integer.valueOf(temps[0]).intValue(); temp.add(array[0]); array[1]=Integer.valueOf(temps[1]).intValue(); temp.add(array[1]); array[2]=Integer.valueOf(temps[2]).intValue(); temp.add(array[2]); } catch (ArrayIndexOutOfBoundsException e) { // TODO: handle exception error(); } catch (NumberFormatException e) { // TODO: handle exception error(); } for(int i=0;i&lt;3;i++) { for(int j=1;j&lt;=2;j++) { if(j==1) { int year=temp.get(0); int month=temp.get(1); int date=temp.get(2); //System.out.println("Passing"+year+"/"+month+"/"+date); calculate(year,month,date); } else { int year=temp.get(0); int month=temp.get(2); int date=temp.get(1); //System.out.println("Passing"+year+"/"+month+"/"+date); calculate(year,month,date); } } Collections.rotate(temp, -1); } if((array[0] &lt;=0)|| (array [1]&lt;=0)|| (array[2] &lt;=0) ||(String.valueOf(array[0]).length()==3)) { flag=0; } if(flag==0) { System.out.println(array[0]+"/"+array[1]+"/"+array[2]+" is illegal"); } else { if(flag!=0) { String prem=String.valueOf(prevm); String pred=String.valueOf(prevd); if(String.valueOf(prevm).length()&lt;=1) { prem=0+prem; } if(String.valueOf(prevd).length()&lt;=1) { pred=0+pred; } System.out.println(prevy+"-"+prem+"-"+pred); } } } catch (IOException e) { // TODO Auto-generated catch block System.out.println("Invalid input"); } } private void error() { // TODO Auto-generated method stub System.out.println(tem+" is illegal"); System.exit(0); } void calculate(int year,int month,int date) { if(String.valueOf(year).length()&lt;3) { year=(year+2000); } boolean leap=false; if((year%4==0)&amp;&amp;((year%100==0))) { if(year%400==0) { leap=true; //System.out.println("Leap year"+year); } } switch (month) { case 1: case 3: case 5: case 7: case 8: case 10: case 12: if(date&gt;=1 &amp;&amp; date&lt;=31) { if(year&lt;prevy) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } else if((year==prevy)&amp;&amp; (month&lt;prevm)) { //System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } else if ((year==prevy) &amp;&amp;(month==prevm)) { if(date&lt;prevd) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } } else { } } break; case 4: case 6: case 9: case 11: if(date&gt;=1 &amp;&amp;date&lt;=30) { if(year&lt;prevy) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } else if((year==prevy)&amp;&amp; (month&lt;prevm)) { //System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } else if ((year==prevy) &amp;&amp;(month==prevm)) { if(date&lt;prevd) { //System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } } else { } } break; case 2: if(leap==true) { if(date&gt;=1 &amp;&amp;date&lt;=29) { if(year&lt;prevy) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } else if((year==prevy)&amp;&amp; (month&lt;prevm)) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } else if ((year==prevy) &amp;&amp;(month==prevm)) { if(date&lt;prevd) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } } else { } } } if(leap==false) { if(date&gt;=1 &amp;&amp; date&lt;=28) { if(year&lt;prevy) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } else if((year==prevy)&amp;&amp; (month&lt;prevm)) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } else if ((year==prevy) &amp;&amp;(month==prevm)) { if(date&lt;prevd) { // System.out.println("generated"+year+"-"+month+"-"+date); flag=1; prevy=year; prevm=month; prevd=date; } } else { } } } break; } } } </code></pre>
[]
[ { "body": "<p>Oh dear, your code looks horrible. Note, that there are not so many people willing to review such a code. It is a must to follow the <a href=\"http://www.oracle.com/technetwork/java/codeconv-138413.html\">code conventions</a> and format your code correctly. The latter can easily be done with an IDE.</p>\n\n<p>CodeReview is a site to review your code and not to find errors in it. Print the values you expect to the console or use the debugger to recognize what your code is doing.</p>\n\n<p>Therefore only some hints to make your code more clean:</p>\n\n<p>Class names should be written in <code>UpperCamelCase</code></p>\n\n<hr>\n\n<p>Extract complicated code or code duplicates to methods. In method <code>calculate</code> you should extract the code of each case-statement to a method to clear to switch-case up:</p>\n\n<pre><code>switch (month) {\n case 1:\n case ...\n case 12: methodCall1(); break; // rename this method\n case ...\n case 11: methodCall2(); break; // rename this method\n case 2: methodCall3(); break; // rename this method\n}\n</code></pre>\n\n<hr>\n\n<p>In method <code>calculate</code> in <code>case 2</code> the code in the if statements are identical. Don't do such a code duplicate. Extract the code lines which are identical to methods (nearly all in this case) or extract the things which differs. In this case the if-header:</p>\n\n<pre><code>int value = 0;\nif (leap) {\n value = 29;\n}\nelse {\n value = 28;\n}\n...\nif (date &gt;= 1 &amp;&amp; date &lt;= value)\n...\n</code></pre>\n\n<p>The same can be done in the remaining cases.</p>\n\n<hr>\n\n<p>The logic in <code>input</code> in too complex. For example, what does this if mean:</p>\n\n<pre><code>if (array[0] &lt;= 0 || array[1] &lt;= 0 || array[2] &lt;= 0\n || String.valueOf(array[0]).length() == 3)\n</code></pre>\n\n<p>Extract it to a method and give it a useful name. Some for other code blocks. You can split up <code>input</code> at least to 4 further methods.</p>\n\n<hr>\n\n<p>If you clean up your code a lot, probably you will find the errors by yourself. And if not you will get more notice from other people if you post better code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T21:13:39.387", "Id": "13053", "ParentId": "13049", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T18:46:22.263", "Id": "13049", "Score": "2", "Tags": [ "java", "unit-testing", "contest-problem" ], "Title": "Spotify Best Before puzzle" }
13049
<p>This works, but nvl AND case seem redundant. Basically, if null then 'N' else 'Y.</p> <p>CHICKEN_HATCH_DATE is a DATE data type.</p> <pre><code> select stricken_chicken_id, case nvl(to_char(chicken_hatch_date),'N') when 'N' then 'N' else 'Y' end chicken_hatch_date from stricken_chicken; </code></pre>
[]
[ { "body": "<p>I'm not sure what's wrong with your code, but if you don't like all of those <code>'N'</code>'s would </p>\n\n<pre><code> select stricken_chicken_id,\n case when to_char(chicken_hatch_date) is null then\n 'N'\n else\n 'Y'\n end chicken_hatch_date \n from stricken_chicken;\n</code></pre>\n\n<p>work for you?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T01:34:06.740", "Id": "21111", "Score": "0", "body": "I tweaked this slightly.. yielding select id, case when hatch_date is null then 'N' else 'Y' end .... There is no need to perform any operation on hatch_date." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T21:45:44.400", "Id": "13054", "ParentId": "13052", "Score": "4" } }, { "body": "<p>If your aim is to print N for a null date why not check that directly?</p>\n\n<pre><code>SELECT\n stricken_chicken_id,\n CASE \n WHEN chicken_hatch_date IS NULL THEN\n 'N'\n ELSE\n 'Y'\n END AS \"chicken_hatch_date\" \nFROM\n stricken_chicken;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T11:41:07.220", "Id": "78915", "Score": "1", "body": "Won't this always choose 'Y'?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T13:23:31.087", "Id": "78926", "Score": "0", "body": "Well spotted - moved the variable so that the statement becomes IS NULL" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T21:21:35.037", "Id": "13652", "ParentId": "13052", "Score": "4" } }, { "body": "<p>I think that better approach is to use \"decode\" instead of \"case\" in this example:</p>\n\n<pre><code>select stricken_chicken_id\n ,decode(chicken_hatch_date, null, 'N', 'Y') chicken_hatch_date\n from stricken_chicken;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-12-11T12:34:32.140", "Id": "19488", "ParentId": "13052", "Score": "1" } }, { "body": "<p>IMHO, <code>nvl2</code> is easier to read:</p>\n\n<pre><code>select stricken_chicken_id,\n nvl2(chicken_hatch_date, 'Y', 'N') chicken_hatch_date\n from stricken_chicken;\n</code></pre>\n\n<p><em>Updated:</em> </p>\n\n<ul>\n<li>Corrected <kbd>.</kbd> to <kbd>,</kbd></li>\n<li>Corrected order of parameters to <code>nvl2()</code></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T11:38:05.670", "Id": "78914", "Score": "0", "body": "This will not work properly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T16:50:17.327", "Id": "78981", "Score": "0", "body": "@kyooryu I fixed a typo, the period after `stricken_chicken_id` should have been a comma. With that correction, this does work." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T18:35:16.837", "Id": "79007", "Score": "1", "body": "It will, however 'Y' and 'N' are mixed up - N should come when chicken_hatch_date is null, in your query it will be the other way round." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-25T20:38:47.827", "Id": "79050", "Score": "0", "body": "I've swapped the order of the parameters in Rev 3." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-26T21:03:04.970", "Id": "42899", "ParentId": "13052", "Score": "3" } } ]
{ "AcceptedAnswerId": "13054", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-25T19:15:46.223", "Id": "13052", "Score": "4", "Tags": [ "sql", "oracle", "null" ], "Title": "Simplify Oracle SQL: Treat null date as 'N' and non-null date as 'Y'" }
13052
<p>I am creating a database class in PHP but I feel that there's something wrong with my code. Is there any suggestion to refactor this? I feel like there's something wrong and missing in this code.</p> <pre><code>&lt;?php require_once("db_constants.inc.php"); Class MySqli_Database { public $db; public function __construct($db_host,$db_username,$db_password,$db_name) { $this-&gt;db = new mysqli($db_host,$db_username,$db_password,$db_name); } public function __performSql($sql) { } public static function closeConnection($conn) { $this-&gt;db_close(); } } $conn = new MySqli_Database (DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME) or die("Could Not Connect To Database: " . mysqli_errno()); </code></pre> <p>Perform SQL will just basically execute the query, though I haven't included the code yet, but I will soon. Also if you have tutorials or guide when creating a database class for MySQLi please post it. It would be a great help.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:30:20.203", "Id": "21123", "Score": "2", "body": "What does this class offer that wasn’t available before? At the moment, nothing." } ]
[ { "body": "<p><strong>What is the purpose of this class?</strong></p>\n\n<blockquote>\n <p>Creating a database class in PHP with mySQLI</p>\n</blockquote>\n\n<p>MySQLi is a \"database class.\" (Whatever meaning of \"database class\" you choose)</p>\n\n<ul>\n<li>Are you trying to make a class that adds on to MySQLi?</li>\n<li>Are you trying to make a class that abstracts away certain operations (a <a href=\"http://en.wikipedia.org/wiki/Database_abstraction_layer\" rel=\"nofollow\">DBAL</a>)?</li>\n<li>Are you trying to make a class that maps objects to a database (<a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"nofollow\">ORM</a>)?</li>\n</ul>\n\n<p><strong><code>require_once(\"db_constants.inc.php\");</code></strong></p>\n\n<p>The file that your class is defined in does not need to be aware of your connnection details. Only the file that uses the class needs to know that, not the file that defines the class (unless of course, it's the same file, but it rarely should be).</p>\n\n<p><strong>or die</strong></p>\n\n<p>Constructors cannot return values, so this will never work.</p>\n\n<p>The proper way to handle errors with objects is <a href=\"http://en.wikipedia.org/wiki/Exception_handling\" rel=\"nofollow\">exceptions</a>. Please note though that exceptions should only be used when something that's actually <em>exceptional</em> happens. It's far to easy to fall into the anti-pattern of using exceptions as return values.</p>\n\n<p>In the case of mysqli's constructor failign to create a connection, that is definitely a cause for an exception. (I tend to avoid the possibility of an object being in an unstable state.)</p>\n\n<p><strong>closeConnection</strong></p>\n\n<p>Why does this take a parameter when the connection is encapsulated in the class?</p>\n\n<p>Also, unless you're going to have an <code>openConnection</code> method, avoid this. Just let the destructor handle this. Why would a user ever want to close the connection but keep the instance alive?</p>\n\n<p><strong>PDO vs MySQLi</strong></p>\n\n<p>I'm heavily biased in this one since I've always used PDO and never written a single line of code with MySQLi, but I've never seen the advantage of MySQLi over PDO. I suppose there's a few MySQL functionalities that MySQLi supports and PDO doesn't, but they must be quite edge cases as I've never run into anything.</p>\n\n<p><strong>Concluding Remarks</strong></p>\n\n<p>I feel like there's barely anything here to review. The goal of your code is not quite clear. Can you explain a little more what your end goal is? What is the purpose of this class? What is an example use case?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T14:20:04.153", "Id": "21145", "Score": "0", "body": "Sorry, I am really not familiar with the terms, but I aim to to make a class that abstracts away certain operations and also Are you trying to make a class that maps objects to a database. That's it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T09:09:27.760", "Id": "21201", "Score": "0", "body": "@user962206 What you're describing are called a DBAL and an ORM, respectively. They are distinct ideas and (typically) libraries. They're also extremely difficult to get right (though also extremely interesting to design). You may want to look into a few projects like Doctrine DBAL, Doctrine ORM and Propel for ideas." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:00:53.190", "Id": "13066", "ParentId": "13056", "Score": "3" } } ]
{ "AcceptedAnswerId": "13066", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T01:32:19.283", "Id": "13056", "Score": "3", "Tags": [ "php", "mysqli" ], "Title": "Creating a database class in PHP with MySQLi" }
13056
<p>I'm looking to see if my current evolution of ETL logic is getting in the ball park of "how it's done in the real world". </p> <ol> <li>Specifically, do I use the metaphors correctly (<code>Extract</code>, <code>Transform</code>, <code>Load</code>)?</li> <li>Is this code reasonably clear for another developer's consumption?</li> <li>Is the OO nature clean or should it be decomposed more?</li> </ol> <p>The steps are as follows:</p> <ul> <li>Clear out the staging table</li> <li>Get records from external system via service</li> <li>Load records into staging table</li> <li>Let a SQL view do the work of aggregating and transforming</li> <li>Load rows into local database</li> </ul> <pre class="lang-cs prettyprint-override"><code>class CakeSyncher { public struct Parameters { public int OfferId; public int Year; public int Month; public int FromDay; public int ToDay; public DateTime FromDate { get { return new DateTime(this.Year, this.Month, this.FromDay); } } public DateTime ToDate { get { return new DateTime(this.Year, this.Month, this.ToDay); } } } private readonly Parameters parameters; private readonly ILogger logger; private readonly CakeWebService cakeService; private List&lt;conversion&gt; extractedConversions; private CakeEntities cakeEntities; private EomDatabaseEntities eomEntities; private List&lt;CakeConversionSummary&gt; conversionSummaries; private Dictionary&lt;CakeConversionSummary, Item&gt; itemsFromConversionSummaries; public CakeSyncher(ILogger logger, Parameters parameters) { this.parameters = parameters; this.logger = logger; this.cakeService = new CakeWebService(this.logger); } public void SynchStatsForOfferId() { try { using (this.cakeEntities = new CakeEntities()) { this.DeleteExistingConversions(); this.cakeEntities.SaveChanges(); } using (this.cakeEntities = new CakeEntities()) { this.ExtractConversions(); this.StageExtractedConversions(); this.cakeEntities.SaveChanges(); using (this.eomEntities = EomDatabaseEntities.Create()) { this.ReadConversionSummaries(); this.TransformConversionSummariesToItems(); this.LoadItems(); this.eomEntities.SaveChanges(); } } } catch (Exception ex) { throw ex; } } #region Prepare private void DeleteExistingConversions() { this.logger.Log("Deleting existing conversions..."); var existingConversions = this.cakeEntities.CakeConversions.ByOfferIdAndDateRange(this.parameters.OfferId, this.parameters.FromDate, this.parameters.ToDate); foreach (var conversion in existingConversions) { this.cakeEntities.CakeConversions.DeleteObject(conversion); } this.logger.Log("Deleted " + existingConversions.Count() + " conversions."); } #endregion #region Extract private void ExtractConversions() { logger.Log("Extracting conversions..."); this.extractedConversions = this.cakeService.Conversions(this.parameters.OfferId, this.parameters.FromDate, this.parameters.ToDate); logger.Log("Extracted " + this.extractedConversions.Count + " conversions."); } private void StageExtractedConversions() { this.logger.Log("Staging extracted conversions..."); this.extractedConversions.ForEach(extractedConversion =&gt; { var cakeConversion = this.cakeEntities.CakeConversions.Create(extractedConversion.IdAsInt); cakeConversion.Update(extractedConversion); }); this.logger.Log("Staged " + this.extractedConversions.Count + "."); } #endregion #region Transform private void ReadConversionSummaries() { this.conversionSummaries = cakeEntities.CakeConversionSummaries.ByOfferIdAndDateRange(this.parameters.OfferId, this.parameters.FromDate, this.parameters.ToDate).ToList(); } private void TransformConversionSummariesToItems() { this.itemsFromConversionSummaries = this.conversionSummaries.ToDictionary(c =&gt; c, c =&gt; c.Item(this.eomEntities)); } #endregion #region Load private void LoadItems() { logger.Log("Loading items from conversion summaries..."); foreach (var conversionSummary in this.itemsFromConversionSummaries.Keys.ToList()) { var item = this.itemsFromConversionSummaries[conversionSummary]; if (item == null) { item = CreateItem(conversionSummary, item); } else { logger.Log(string.Format("Updating item {0} from conversion {1}", item.name, conversionSummary.Name)); } item.Update(this.eomEntities, conversionSummary, this.cakeService, this.logger); } logger.Log("Items loaded."); } private Item CreateItem(CakeConversionSummary conversionSummary, Item item) { logger.Log("Creating item: " + conversionSummary.Name); item = new Item(); eomEntities.Items.AddObject(item); return item; } #endregion } </code></pre>
[]
[ { "body": "<p>A few things that caught my eye:</p>\n<h3>Naming</h3>\n<pre><code>public Date FromDate {[...]}\npublic Date ToDate {[...]}\n</code></pre>\n<p>if that weren't readonly Properties, i'd assume they are conversion methods. Try to find a better name like: <code>StartDate</code> / <code>EndDate</code>.</p>\n<h3>Regions</h3>\n<p>Regions are cool. You can hide boilerplate code easily and structure large classes into nice small subsets. What you do here is something completely different. You Pack important Methods into very small logical structures. Why? Instead use the IDE to collapse the function to headers. This is just as efficient and definitely better than:</p>\n<pre><code>#region Load\nprivate void LoadItems(){[...]}\n\nprivate Item CreateItem(CakeConversionSummary conversionSummary, Item item){[...]}\n#endregion\n</code></pre>\n<p>You hide <code>CreateItem</code> in a section called &quot;Load&quot;. This makes no sense as creating is quite different from loading.</p>\n<h3>Var keyword</h3>\n<p>I really like the <code>var</code>-Keyword. IT seems you do too. But this creates a problem. There is no real gain in doing stuff like the following:</p>\n<pre><code>foreach(var conversionSummary in this.itemsFromConversionSummaries.Keys.ToList())\n{\n var item = this.itemsFromConversionSummaries[conversionSummary];\n if (item == null)\n //...\n}\n</code></pre>\n<p>When reading this code, I cannot help but ask myself: Why are you not using the Types?</p>\n<pre><code>foreach(ConversionSummary conversionSummary in this.itemsFromConversionSummaries.Keys.ToList())\n{\n Item item = this.itemsFromConversionSummaries[conversionSummary];\n if (item == null)\n // ...\n}\n</code></pre>\n<p>Type renaming is not a problem with the new IDE's.</p>\n<h3>Object Hierarchy</h3>\n<p>Code like this is smelly:</p>\n<pre><code>this.cakeEntities.CakeConversions.ByOfferIdAndDateRange([...]);\n</code></pre>\n<p>You are walking through the object hierarchy waay too long. This violates the <a href=\"http://en.wikipedia.org/wiki/Law_of_Demeter\" rel=\"nofollow noreferrer\">Law of Demeter.</a></p>\n<blockquote>\n<p>More formally, the Law of Demeter for functions requires that a method m of an object O may only invoke the methods of the following kinds of objects:</p>\n<ul>\n<li>O itself</li>\n<li>m's parameters</li>\n<li>Any objects created/instantiated within m</li>\n<li>O's direct component objects</li>\n<li>A global variable, accessible by O, in the scope of m</li>\n</ul>\n</blockquote>\n<p><strong>Suggestion:</strong> move the <code>ByOfferIdAndDateRange</code> from the <code>CakeConversions</code> to the <code>CakeEntities</code></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-08T11:06:21.240", "Id": "46631", "ParentId": "13057", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T02:32:21.523", "Id": "13057", "Score": "3", "Tags": [ "c#", "etl" ], "Title": "ETL code to synchronize external system to internal database" }
13057
<p>What I am trying to accomplish is to create an efficient thread-safe singleton base class (as stated in the title).</p> <p>So this is my singleton class, which is used via inheritance (see below).</p> <pre><code>#pragma once #ifndef SINGLETON_HEADER_INCLUDED #define SINGLETON_HEADER_INCLUDED #include &lt;memory&gt; template &lt;class T&gt; class singleton { public: static T *get_instance(void) { if(instance.get() == 0 || instance == (NULL &amp;&amp; 0) || !instance) { instance = std::shared_ptr&lt;T&gt;(new T()); } return instance; } static delete_instance(void) { delete instance; instance = (NULL &amp;&amp; 0); return; } protected: singleton(void); virtual ~singleton(void); private: singleton(const singleton&amp;); singleton&amp; operator = (const singleton&amp;); static volatile std::shared_ptr&lt;T&gt; instance; }; template &lt;class T&gt; template *singleton&lt;T&gt;::instance = 0; #endif </code></pre> <p>Here is the class in use:</p> <pre><code>#include "singleton.hpp" class opengl_renderer : public singleton&lt;opengl_renderer&gt; { friend class singleton&lt;opengl_renderer&gt;; etc... }; </code></pre> <p>So basically, I am looking for some tips and reviews on my class -> I feel as if it isn't working the way I imagine it should. But it is functional at its current state.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T12:47:54.027", "Id": "21131", "Score": "1", "body": "By the way, this is a prime example of [cargo cult programming](http://en.wikipedia.org/wiki/Cargo_cult_programming). The code merely has the *semblance* of actual, meaningful code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T14:26:43.213", "Id": "21146", "Score": "1", "body": "This is off-topic. codereview.SE is for working code. This doesn't even compile." } ]
[ { "body": "<p>Your code doesn’t compile, and if it would compile, it would crash.</p>\n\n<p>You are trying to assign a <code>shared_ptr</code> to a raw pointer. You are also trying to <code>delete</code> a <code>shared_ptr</code> and this leads me to believe that you don’t understand <a href=\"http://en.wikipedia.org/wiki/Smart_pointer\">what a smart pointer actually does</a>.</p>\n\n<p>In fact, your code contains a multitude of errors. More on that below.</p>\n\n<p>First, about the use of <code>shared_ptr</code>. In fact, a shared pointer denotes <em>shared</em> ownership, and this is patently not the case here: the singleton is the owner, nobody else.</p>\n\n<p>A shared pointer is inappropriate here, what you want is a <code>unique_ptr</code>.</p>\n\n<p>Then, don’t expose a pointer to the user, expose a <em>reference</em> via <code>get_instance</code> (i.e. habe <code>get_instance()</code> return <code>T&amp;</code>. And I would rename <code>get_instance</code> to plain <code>instance</code> (which is more C++-y), and rename the private field to something else.</p>\n\n<p>Finally, reconsider your usage of a singleton in the first place. The singleton is generally considered an anti-pattern and real, legitimate uses are so rare that it doesn’t pay to have a singleton base class.</p>\n\n<h1>Detailed code critique</h1>\n\n<pre><code>if(instance.get() == 0 || instance == (NULL &amp;&amp; 0) || !instance) {\n</code></pre>\n\n<p>This is doing the same check three times. Why? Once is enough – the latter is the correct usage.</p>\n\n<p>But this code isn‘t thread-safe anyway, in fact, it’s not making any effort to be thread-safe at all.</p>\n\n<pre><code>return instance;\n</code></pre>\n\n<p>As already said, you cannot cast a <code>shared_ptr</code> to a plain pointer.</p>\n\n<pre><code>static delete_instance(void)\n</code></pre>\n\n<p>That doesn’t compile, it’s missing a return value. Also, who is going to call this method? It should never be called probably, so just delete it.</p>\n\n<pre><code>delete instance;\n</code></pre>\n\n<p>As mentioned above, this doesn’t work, and is meaningless. The whole point of a smart pointer is that you don’t need manual deletion.</p>\n\n<pre><code>instance = (NULL &amp;&amp; 0);\n</code></pre>\n\n<p>This code makes <em>no</em> sense. What is it supposed to do?</p>\n\n<pre><code>virtual ~singleton(void);\n</code></pre>\n\n<p>You have declared the destructor but you haven’t <em>defined</em> it. The implementation will be empty but you still need to define it.</p>\n\n<pre><code>static volatile std::shared_ptr&lt;T&gt; instance;\n</code></pre>\n\n<p><code>volatile</code> probably isn’t meaningful here. In particular, its meaning is unrelated to cross-thread access (unfortunately). But even if it was related to cross-thread access, this wouldn’t make your code thread-safe, it would simply mean that threads would read the most up-to-date version of the variable.</p>\n\n<pre><code>friend class singleton&lt;opengl_renderer&gt;;\n</code></pre>\n\n<p>What do you need this line for?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T12:31:01.017", "Id": "13072", "ParentId": "13059", "Score": "10" } }, { "body": "<p>Everything Konrad said.</p>\n\n<p>But I would not even use a member to hold the instance.<br>\nI would make it a static member of the instance() method:</p>\n\n<pre><code>static T&amp; instance()\n {\n#if !defined(__GNUC__) || (__GNUC__ &lt;= 3)\n static lock lockingObject; // gets lock in constructor\n // releases lock in destructor\n#endif\n static T instance; // notice the static\n return instance;\n }\n</code></pre>\n\n<p>On g++ it is already thread safe (they have an extension the makes it thread safe). On other compilers you need to add a lock around the method (but only the first time it is called).</p>\n\n<p>It is instantiated on first use and automatically destroyed.</p>\n\n<p>See: <a href=\"https://stackoverflow.com/questions/1008019/c-singleton-design-pattern/1008289#1008289\">C++ Singleton design pattern</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T14:55:40.917", "Id": "13082", "ParentId": "13059", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T05:19:45.447", "Id": "13059", "Score": "1", "Tags": [ "c++", "c++11", "singleton" ], "Title": "Thread-safe singleton class using std::shared_ptr in C++(11)" }
13059
<p>Could someone review my linked list code? Specificially, is the design to separate <code>Node</code> and actions to create linked list appropriate?</p> <pre><code>template &lt;typename T&gt; class Node { public: Node() : next(0) { } Node(T value) : val(value), next(0) { } T val; Node* next; private: Node(const Node&amp; nd) { } Node&amp; operator=(const Node&amp; nd) { } }; template &lt;typename T&gt; class List { public: List() { begin = new Node&lt;T&gt;(); } List(T initval) { begin = new Node&lt;T&gt;(initval); } List(const List&amp; inp) { begin = new Node&lt;T&gt;(inp.begin-&gt;val); Node&lt;T&gt; *tempInitial = inp.begin-&gt;next; Node&lt;T&gt; *tempFinal = begin; while(tempInitial-&gt;next) { tempFinal-&gt;next = new Node&lt;T&gt;(); tempFinal = tempFinal-&gt;next; tempFinal-&gt;val = tempInitial-&gt;val; tempInitial = tempInitial-&gt;next; } } void addVal(const T&amp; val) { if(!begin-&gt;next &amp;&amp; begin-&gt;val == 0) { begin-&gt;val = val; } else { Node&lt;T&gt; *temp = begin; while(temp-&gt;next) { temp = temp-&gt;next; } temp-&gt;next = new Node&lt;T&gt;(val); } } bool deleteVal(const T&amp; val) { Node&lt;T&gt;* pos = isPresentN(val); if( pos == 0) return 0; if(pos == begin) { begin = pos-&gt;next; delete pos; return 1; } Node&lt;T&gt;* temp = begin; while(temp-&gt;next != pos) { temp = temp-&gt;next; } Node&lt;T&gt;* delnode = temp-&gt;next; temp-&gt;next = temp-&gt;next-&gt;next; delete delnode; return 1; } Node&lt;T&gt;* isPresentN(const T&amp; val) { Node&lt;T&gt;* temp = begin; while(temp) { if(temp-&gt;val == val) return temp; temp = temp-&gt;next; } return 0; } bool isPresent(const T&amp; val) { if(isPresentN(val)) return 1; return 0; } ~List() { Node&lt;T&gt;* temp= begin, *t; while(temp) { t = temp; temp = temp-&gt;next; delete t; } } private: Node&lt;T&gt; *begin; }; </code></pre>
[]
[ { "body": "<p>The overall structure looks ok, but two things:</p>\n\n<ol>\n<li><p>If T is int and you repeatedly call <code>addVal(0)</code>, the list stays unchanged. Consider just setting <code>begin</code> to NULL, it's a more reliable way to tell if the list is empty.</p></li>\n<li><p><code>isPresentN</code> should either be private (or at least protected), or you should return a <code>const</code> pointer to the node. Otherwise, someone could accidentally change the node's <code>next</code> field.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T08:46:35.267", "Id": "21117", "Score": "0", "body": "Thanks a lot. Since I'm using isPresentN as a helper function within the class, isn't it better if I make it a private function? [ compared to returning a const pointer ]" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:00:19.637", "Id": "21118", "Score": "0", "body": "Yep. It's always a good idea to only expose the absolutely necessary functions. And I can't imagine a scenario where you'd need to override it in a subclass, so private should be the right choice." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T08:38:50.257", "Id": "13061", "ParentId": "13060", "Score": "3" } }, { "body": "<p>By no means an expert at C++, but a few notes:</p>\n<p><strong>Node Constructor</strong></p>\n<p>I would get rid of the first constructor and change the second constructor a bit:</p>\n<pre><code>Node(const T&amp; value = T()) : val(value), next(NULL) { }\n</code></pre>\n<p>Two things are happening here:</p>\n<ul>\n<li>I would make it just use a default-constructed instance if one isn't passed</li>\n<li>You should be passing a const reference as to avoid an unnecessary copy (<code>val(value)</code> is already copying it)</li>\n</ul>\n<p><strong><code>isPresentN</code> is badly named</strong></p>\n<p>Any time a method starts with <code>is</code> I expect a <code>bool</code> return. I would consider renaming this to <code>findNode</code> or something similar. (And, as Benjamin Kloster said, I would make it private.)</p>\n<p><strong>Remember that your class is a template</strong></p>\n<p>I suspect that most people, me included, tend to develop templated classes while pretending that T is just a plain-old-int. You have to be careful about this though.</p>\n<pre><code>if(!begin-&gt;next &amp;&amp; begin-&gt;val == 0) {\n</code></pre>\n<p>If <code>T</code> were <code>string</code>, or basically anything that doesn't implement <code>operator==(int)</code>, this line would keep your class from compiling.</p>\n<p>As Benjamin said, just use a <code>NULL</code> <code>begin</code> when the list is empty.</p>\n<p><strong><code>addVal</code> and <code>deleteVal</code></strong></p>\n<p>I would consider renaming these <code>add</code> (or <code>append</code>) and <code>remove</code> since the consumer already knows that he's adding a value.</p>\n<p><strong>Edit</strong></p>\n<p>I previously suggested to use <code>NULL</code>. After the note in the comments and a bit of googling, I've decided that my suggestion to use <code>NULL</code> was in error. For anyone interested though, the following links outline a few interesting reasons for and against NULL:</p>\n<ul>\n<li>SO: <a href=\"//stackoverflow.com/questions/176989/do-you-use-null-or-0-zero-for-pointers-in-c\">&quot;<em>Do you use NULL or 0 (zero) for pointers in C++?</em>&quot;</a></li>\n<li>Stroustrup: <a href=\"//www.stroustrup.com/bs_faq2.html#null\" rel=\"nofollow noreferrer\">&quot;<em>Should I use NULL or 0?</em>&quot;</a>\n[3]: SO: <a href=\"//stackoverflow.com/questions/1296843/what-is-the-difference-between-null-0-and-0\">&quot;<em>What is the difference between NULL, '\\0' and 0?</em>&quot;</a></li>\n<li>comp.lang.c faq: <a href=\"http://c-faq.com/null/nullor0.html\" rel=\"nofollow noreferrer\">&quot;<em>If NULL and 0 are equivalent as null pointer constants, which should I use?</em>&quot;</a></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:07:46.020", "Id": "21119", "Score": "0", "body": "Brilliant. I had totally missed the `begin->val == 0` part. Thanks for the suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:17:38.707", "Id": "21120", "Score": "0", "body": "@ersran9 Once I have a templated class finished, I typically test it with int, string and a user defined type that does lots of dynamic memory allocation and deallocation. Then I run the program through valgrind. That usually takes care of forgotten lines like that one or any kind of memory issues the class may have. (Can be a bit overkill for simple classes though.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:32:28.453", "Id": "21124", "Score": "0", "body": "I disagree strongly with using `NULL`. There is no difference for the compiler, so using `NULL` can be highly misleading. `int x = NULL;` compiles just fine, so `NULL` doesn’t actually offer any information about usage to the reader. This changes with C++11 and `nullptr`, but for now, sticking to `0` is fine and encouraged by most professional C++ programmers who write about this." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T09:45:35.540", "Id": "21125", "Score": "0", "body": "@KonradRudolph For some reason I've always assumed that `NULL` is standard usage, but after some heavy googling, I've been swayed. Will edit the post in the minute." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T15:11:56.123", "Id": "21150", "Score": "0", "body": "@KonradRudolph: I disagree with you about NULL. I think the visual queue for the developer reading the code provides information. I now know it is meant to initialize a pointer. I see no advantage/disadvantage in using `0` and no disadvantage to using `NULL` but there is the advantage of the visual que. Though I am looking forward to being able upgrade my compiler to use nullptr." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T15:58:57.017", "Id": "21153", "Score": "0", "body": "@Loki But the disadvantage vanishes because `int x = NULL;` compiles so you effectively cannot rely on the visual cue. In fact, you need to be on constant guard of being misled." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:24:36.660", "Id": "21167", "Score": "0", "body": "@KonradRudolph: I don't see that as a disadvantage (as nothing bad is happening). And the advantage still remains. Also that is not relavant in this context. Here we are initializing next. It is either `next(0)` or `next(NULL)`. The latter lets me know that next is `probably` a pointer and that is what I expect (thus reinforcement)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T18:29:25.120", "Id": "21256", "Score": "0", "body": "Actually, there can be a difference for the compiler -- GCC, for example, will warn if NULL is converted to an int." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-03T22:47:17.370", "Id": "23157", "Score": "1", "body": "@KonradRudolph: http://max0x7ba.blogspot.com/2010/03/0-vs-null-in-c.html" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-04T09:12:54.350", "Id": "23170", "Score": "1", "body": "@Loki You are aware that this breaks the standard though? Is it enabled with `-pedantic`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-04T11:09:36.100", "Id": "23172", "Score": "0", "body": "@KonradRudolph: No. But I had an inkling you might. I just wanted to see if the author was being silly." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-05T09:54:27.183", "Id": "23215", "Score": "0", "body": "@Loki I did a bit of digging and [even though there’s a bit of controversy over the reading](http://gcc.gnu.org/bugzilla/show_bug.cgi?id=35669) it’s probably legal. Regardless of legality, I agree that it’s a good behaviour to have, that probably causes no problems. And yes, it makes my above comment obsolete. *Do* use `NULL` instead of `0`. (But better yet, `#define` your own `nullptr` as `__null` if on GCC pre-C++11)." } ], "meta_data": { "CommentCount": "12", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-06-26T08:48:00.833", "Id": "13062", "ParentId": "13060", "Score": "4" } }, { "body": "<h3>Major problem:</h3>\n<p>You are breaking the rule of three (or five).</p>\n<p>Your class contains a RAW pointer. This means you need to override Copy Constructor/Assignment operator/Destructor. You missed the assignment operator.</p>\n<pre><code>{\n List&lt;int&gt; x;\n List&lt;int&gt; y;\n\n x = y; // This is going to cause problems.\n}\n// At this point when it is destroyed.\n// As both x and y point at the same begin object.\n</code></pre>\n<p>Since you have a valid copy constructor you can just use the copy-and-swap idiom to build the assignment operator:</p>\n<pre><code>List&amp; operator=(List rhs) // pass by value to get copy\n{\n std::swap(begin, rhs.begin); // Now swap all data members.\n // You could write your own swap member\n return *this;\n}\n</code></pre>\n<h3>Sentinels</h3>\n<p>You create your list with an initial 'Sentinel' value. This is a common technique to remove the need to check for NULL pointers in your code and can make the other functions easier to write (as you don't need to check for NULL). <strong>BUT</strong> to use it usefully, the list needs to be circular (last element points at first) and you must always have this unused 'Sentinel' node.</p>\n<p>When you use this technique you should never use the sentinel as a value holding node. You should always skip over it. Your loop then is always from <code>begin-&gt;next</code> (as the first node) until <code>begin</code> (when you reach <code>begin</code> again you have gone one past the last node (hence the need for a circle).</p>\n<p>Unfortunately your code is a mix of using sentinel and using NULL terminated list. You need to pick one and stick with it. Using a sentinel makes the code much easier to write (as you don't need to check for NULL and special case the empty list).</p>\n<h3>Need a tail pointer</h3>\n<p>You currently only have a head pointer.<br />\nThis means when you insert into the list you always chain all the way to the end before inserting. This makes an operation that could be O(1) be O(n). Most list implementations use head/tail pointer or use a doubly linked list (one chain for each direction). This makes finding the tail trivial and maintaining the extra pointer has practically no cost.</p>\n<h3>Other comments:</h3>\n<p>The rest of the code assumes you were trying to use a sentinel value to make the use of the list more efficient. If you want to use NULL to indicate the end of a list rather than a sentinel, the comments will change slightly (but using sentinels is the better solution so I will move ahead from there).</p>\n<p>Not all types have a default value (or are default constructable). So you need two versions of your node class. One to use as the sentinel and one to use that holds the data payload. Let us assume that <code>Node</code> is the version that holds the payload and inherits from the base class that just contains pointer information:</p>\n<p>When constructing Nodes:</p>\n<pre><code>// Remove the default constructor.\n// When creating a payload node it should be initialized with a value.\nNode() : next(0) { }\n\n// The constructor should take a value by const reference\n// This will make sure that expensive to copy objects are not over copied.\n// You should also pass a pointers to link it into the list.\n// At the point it is constructed you should have that information by putting\n// this code in the constructor you will make creation and use easier.\nNode(T value) : val(value), next(0) { }\n\n// Since Node is a publicly available class and not designed to be copied\n// You should (and have) disable the copy constructor and assignment operator.\n//\n// Alternatively if you make Node a private Type inside the List class then\n// this is not needed. \nprivate:\nNode(const Node&amp; nd) { }\nNode&amp; operator=(const Node&amp; nd) { } \n</code></pre>\n<p>Construct list and insert sentinel as expected.</p>\n<pre><code>List() {\n begin = new BaseNode(); // Note I changed the type BaseNode\n // Note: BaseNode constructor will make next point\n // back at itself.\n}\n</code></pre>\n<p>When you use this constructor, you should also insert a sentinel. So the list always has a sentinel value no matter how it is created. Then you can just add the value as normal.</p>\n<pre><code>List(T initval) { \n begin = new BaseNode();\n addVal(initval);\n}\n</code></pre>\n<p>Adding a node is a common task with its own specific method <code>addVal()</code> of doing this. Use this common method to do the actual work of adding a node. This prevents duplicating of code and makes sure that adding a node is consistently done (Note your current <code>addVal()</code> is not very efficient but I will address that separately.</p>\n<pre><code> List(const List&amp; inp) {\n begin = new Node&lt;T&gt;(inp.begin-&gt;val);\n Node&lt;T&gt; *tempInitial = inp.begin-&gt;next;\n Node&lt;T&gt; *tempFinal = begin;\n\n while(tempInitial-&gt;next) {\n tempFinal-&gt;next = new Node&lt;T&gt;();\n tempFinal = tempFinal-&gt;next;\n tempFinal-&gt;val = tempInitial-&gt;val;\n tempInitial = tempInitial-&gt;next;\n } \n }\n\n// Could look like this:\nList(List const&amp; rhs)\n{\n begin = new BaseNode&lt;T&gt;(); // sentinel.\n\n Node&lt;T&gt;* begin = inp.begin;\n for(Node&lt;T&gt;* loop = begin-&gt;next; loop != begin; loop = loop-&gt;next);\n {\n addVal(loop-&gt;val);\n }\n}\n</code></pre>\n<p>In your version here you seem to overwrite the sentinel.<br />\nThis is wrong as if you add 0 multiple times it will only be added once. Leave the sentinel alone and just concentrate on adding a new node each time.</p>\n<pre><code>void addVal(const T&amp; val) {\nif(!begin-&gt;next &amp;&amp; begin-&gt;val == 0) {\n begin-&gt;val = val;\n}\n</code></pre>\n<p>Here you assume that last node is NULL-terminated.<br />\nBut in the copy constructor you assume that the list is circular.</p>\n<pre><code>else {\n Node&lt;T&gt; *temp = begin;\n while(temp-&gt;next) { \n temp = temp-&gt;next;\n</code></pre>\n<p>I would go with the circular list (using sentinels). Also each time you add a value you must traverse the whole list to find the end. It would be easier to keep track of the last value using two pointers in List object; <code>begin</code> (points at the sentinel) and <code>end</code> (points at the last inserted node (or at the sentinel if empty list)).</p>\n<p>Using a sentinel the insert becomes.</p>\n<pre><code>void addVal(const T&amp; val)\n{\n Node&lt;T&gt;* last = findlast(begin); // not needed if you have a last member.\n \n Node&lt;T&gt;* newNode = new Node(val, last, begin);\n // ^^^^ node before the new node\n // ^^^^^ node after the new node.\n}\n</code></pre>\n<p>Deleting items from a singly linked list is a pain (as you need the proceeding item). Doubly linked lists are a lot easier (in my opinion) to use because of this. But again you are potentially deleting the sentinel here.</p>\n<p>You also search the list twice: the first time you search to find the value, then you search the list to find the node preceding the one you want to delete.</p>\n<pre><code> bool deleteVal(const T&amp; val) {\n Node&lt;T&gt;* pos = isPresentN(val);\n if( pos == 0) return 0;\n if(pos == begin) { begin = pos-&gt;next; delete pos; return 1; }\n\n Node&lt;T&gt;* temp = begin;\n while(temp-&gt;next != pos) {\n temp = temp-&gt;next;\n }\n</code></pre>\n<p>You can simplify this and just look for the value by checking the value of the next node. Note: The same code works for a NULL-terminated list (just change <code>begin</code> into <code>NULL</code>).</p>\n<pre><code>Node&lt;T&gt;* loop = begin;\nwhile(loop-&gt;next != begin &amp;&amp; loop-&gt;next.val != val)\n{\n loop = loop-&gt;next;\n}\n// Now loop-&gt;next is either begin or points at the node we are looking for.\nif (loop-&gt;next != begin)\n{\n Node&lt;T&gt; old = loop-&gt;next;\n loop-&gt;next = old-&gt;next;\n delete old;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:05:24.577", "Id": "21225", "Score": "0", "body": "Thanks a lot for the suggestions.I have some doubts though 1. the std::swap uses the copy constructor [ which performs the deep copies anyway- hence suited in this scenario. ] - Is my understanding correct here? 2 . When you say circular linked list - you mean => [sentinal] -> [some elements here] -> [last element] -> [the initial sentinal]. Is this right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:10:37.877", "Id": "21226", "Score": "0", "body": "Also, you remarked that \"But in the copy constructor you assume that the list is circular.\". I didn't get that part - the loop `while(tempInitial->next)` will go on till the last element. I wrote that code for a singly linked list. Did I make a mistake here, or am I not understanding this right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:39:53.353", "Id": "21240", "Score": "0", "body": "Opps. Your copy constructor does assume NULL termination. You confused me with your naming convention `tempFinal`. mea culpa." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:43:47.950", "Id": "21242", "Score": "0", "body": "If your first comment is about the assignment operator then: 1: std::swap() on pointers just swaps the pointers (there is no deep copy). **But** the assignment operator **must** do a deep copy and thus is achieved by using the copy constructor which is used implicitly when we pass by value (please read up on the copy swap idiom)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:44:28.447", "Id": "21243", "Score": "0", "body": "The circular list: `you mean => [sentinal] -> [some elements here] -> [last element] -> [the initial sentinel]`. **Yes**." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:52:52.633", "Id": "21245", "Score": "0", "body": "You can either use a sentinel or not. Either way is fine. But you can't combine the two methods (which you seem to be doing). This will cause problems (like you have when adding zero and dropping values). Using a sentinel value makes the resulting code easier to read. Try it both ways; when you are complete compare the results. The first time you do it, it will take slightly more time as you need to think threw a couple of situations. But after you understand it you will find the resulting code is tighter easier to read and has fewer special cases." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-06-26T18:15:05.410", "Id": "13087", "ParentId": "13060", "Score": "11" } }, { "body": "<p>There's an unnecessary copy of <code>value</code> here:</p>\n<blockquote>\n<pre><code> Node(T value) : val(value), next(0) { }\n</code></pre>\n</blockquote>\n<p>Other reviews suggest taking <code>value</code> as a const ref, but better is to accept by value but then <em>move</em> into the member. That way, the only copying is done by the caller, and only for lvalues (and the code can work for move-only types).</p>\n<pre><code>#include &lt;utility&gt;\n\n Node(T value)\n : val{std::move(value)},\n next{nullptr}\n { }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-13T10:57:44.273", "Id": "254645", "ParentId": "13060", "Score": "0" } } ]
{ "AcceptedAnswerId": "13062", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T07:48:04.747", "Id": "13060", "Score": "13", "Tags": [ "c++", "linked-list" ], "Title": "Linked list in C++" }
13060
<p>A Linked List is a data structure in which the elements contain references to the next (and optionally the previous) element. Lists, where nodes have links to both the next and the previous element are usually referred to as <em>doubly-linked</em>. Another form of the Linked List is the <em>Circular Linked List</em>, in which the last element contains link of the first element as next and the first element has a link to the last element as previous.</p> <p>Linked Lists offer \$O(n)\$ insert and removal at any position, \$O(1)\$ list concatenation, and \$O(1)\$ access at the front position (and the back, in the case of <em>doubly-linked</em> lists) as well as \$O(1)\$ next element access. This makes them ideal for sequential operations (and recursive functions operating on sequential data); indexed data structures (e.g. maps, vectors, arrays) can only offer \$O(log \space n)\$ speed.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T08:52:30.927", "Id": "13063", "Score": "0", "Tags": null, "Title": null }
13063
A linked list is a data structure in which the elements contain references to the next (and optionally the previous) element.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T08:52:30.927", "Id": "13064", "Score": "0", "Tags": null, "Title": null }
13064
<p>I'm not used with perl but had the need to add a couple of features, I wish I can adopt a more perl-ish coding.</p> <p>Any help is welcome.</p> <p>This is to add style classes to paragraphs if strarting with <code>!</code>, <code>?</code> and a <code>clear: both</code> with <code>%</code></p> <p>Original:</p> <pre><code>foreach (@grafs) { unless (defined( $g_html_blocks{$_} )) { $_ = _RunSpanGamut($_); s/^([ \t]*)/&lt;p&gt;/; $_ .= "&lt;/p&gt;"; } } </code></pre> <p>Modded:</p> <pre><code>foreach (@grafs) { unless (defined( $g_html_blocks{$_} )) { $_ = _RunSpanGamut($_); if ( m/^[ \t]*\?/ ){ s/^([ \t]*\?[ \t]*)/&lt;p class="Introduction"&gt;/; } elsif ( m/^[ \t]*\!/ ){ s/^([ \t]*\![ \t]*)/&lt;p class="Important"&gt;/; } elsif ( m/^[ \t]*%/ ){ s/^([ \t]*%[ \t]*)/&lt;p style="clear: both;"&gt;/; } else { s/^([ \t]*)/&lt;p&gt;/; } $_ .= "&lt;/p&gt;"; } } </code></pre> <p>This is to add float to images like: <code>!&lt;[alt](url)</code> to get a float right (and form this the <code>%</code> above to clear)</p> <pre><code>if (defined($align)) { if ($align eq "&lt;") { $result .= " style=\"float: left; margin: 0 ${padding}px ${padding}px 0;\""; } else { $result .= " style=\"float: right; margin: 0 0 ${padding}px ${padding}px;\""; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-31T23:43:44.890", "Id": "22947", "Score": "0", "body": "If you can I would move towards using [Markdent](http://p3rl.org/Markdent), which is easier to extend." } ]
[ { "body": "<p>Note that a substitution only occurs if there is a match, and then it will return the number of substitutions it makes. This means that a <code>true</code> value is returned if a match/substitution happens.</p>\n\n<p>With that in mind, you don't need the <code>m/.../</code> in addition to the substitution. You can also make use of <code>or</code> to achieve the short-circuiting that you had with the <code>if ... elsif ... else ...</code> statements.</p>\n\n<pre><code>foreach (@grafs) {\n unless (defined $g_html_blocks{$_}) {\n $_ = _RunSpanGamut($_);\n s/^([ \\t]*\\?[ \\t]*)/&lt;p class=\"Introduction\"&gt;/\n or\n s/^([ \\t]*\\![ \\t]*)/&lt;p class=\"Important\"&gt;/ \n or\n s/^([ \\t]*%[ \\t]*)/&lt;p style=\"clear: both;\"&gt;/\n or\n s/^([ \\t]*)/&lt;p&gt;/;\n $_ .= \"&lt;/p&gt;\";\n }\n}\n</code></pre>\n\n<p>For the image floating, you could use a hash instead of <code>if ... else ...</code>:</p>\n\n<pre><code>my %float = (\n '&lt;' =&gt; 'float: left',\n '&gt;' =&gt; 'float: right',\n '%' =&gt; 'clear: both'\n);\nif (defined $align) {\n $result .= \" style=\\\"$float{$align}; margin: 0 ${padding}px ${padding}px 0;\\\"\";\n}\n</code></pre>\n\n<p>A minor point: I also removed the parens from the <code>defined</code> checks because they're not needed and it gives you a little more white space to reduce a little clutter.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:24:57.630", "Id": "13085", "ParentId": "13071", "Score": "3" } } ]
{ "AcceptedAnswerId": "13085", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T12:09:22.333", "Id": "13071", "Score": "2", "Tags": [ "perl" ], "Title": "Markdown.pl extending" }
13071
<p>I'm trying to develop a base for a blog using some of the new tags introduced in HTML5 and I want to not only make sure I'm using them correctly, but my code is also semantic. </p> <p>Here is just the <em>'sample'</em> document.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta http-equiv="content-type" content="text/html;charset=utf-8"/&gt; &lt;title&gt;page title&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="container"&gt; &lt;header&gt; &lt;hgroup&gt; &lt;h1&gt;Blog title&lt;/h1&gt; &lt;h2&gt;Blog tagline goes here&lt;/h2&gt; &lt;/hgroup&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#top-level-link"&gt;Top Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#top-level-link"&gt;Top Link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#top-level-link"&gt;Top Link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/header&gt; &lt;!-- &lt;hr&gt; commenting out so the answers still make sense --&gt; &lt;aside&gt; &lt;nav&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;sidebar link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;sidebar link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;sidebar link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/nav&gt; &lt;/aside&gt; &lt;div class="content"&gt; &lt;article&gt; &lt;h3&gt;Article Header&lt;/h3&gt; &lt;section&gt; &lt;h4&gt;Section header&lt;/h4&gt; &lt;p&gt;Article section content&lt;/p&gt; &lt;/section&gt; &lt;section&gt; &lt;h4&gt;Section header&lt;/h4&gt; &lt;p&gt;Article section content&lt;/p&gt; &lt;/section&gt; &lt;section&gt; &lt;h4&gt;Section header&lt;/h4&gt; &lt;p&gt;Article section content&lt;/p&gt; &lt;/section&gt; &lt;footer&gt; posted by &lt;a rel="author" href="#"&gt;user&lt;/a&gt; on &lt;time datetime="2012-01-01T00:00+00:00"&gt;January 1st, 2012. 12:00pm&lt;/time&gt; &lt;/footer&gt; &lt;/article&gt; &lt;article&gt; &lt;h3&gt;Article Header&lt;/h3&gt; &lt;section&gt; &lt;h4&gt;Section header&lt;/h4&gt; &lt;p&gt;Article section content&lt;/p&gt; &lt;/section&gt; &lt;!-- more sections may exist per article --&gt; &lt;footer&gt; posted by &lt;a rel="author" href="#"&gt;user&lt;/a&gt; on &lt;time datetime="2012-01-01T00:00+00:00"&gt;January 1st, 2012. 12:00pm&lt;/time&gt; &lt;/footer&gt; &lt;/article&gt; &lt;article&gt; &lt;h3&gt;Article Header&lt;/h3&gt; &lt;section&gt; &lt;h4&gt;Section header&lt;/h4&gt; &lt;p&gt;Article section content&lt;/p&gt; &lt;/section&gt; &lt;!-- more sections may exist per article --&gt; &lt;footer&gt; posted by &lt;a rel="author" href="#"&gt;user&lt;/a&gt; on &lt;time datetime="2012-01-01T00:00+00:00"&gt;January 1st, 2012. 12:00pm&lt;/time&gt; &lt;/footer&gt; &lt;/article&gt; &lt;/div&gt; &lt;!-- &lt;hr&gt; Don't wanna make these guys look crazy --&gt; &lt;footer&gt; Page footer. &lt;/footer&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Can anyone see any misuse of the new tags or any better - cleaner way to write this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:12:57.133", "Id": "21164", "Score": "2", "body": "Also, `<meta charset=\"utf-8\">`. It's probably simpler." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:30:13.280", "Id": "21168", "Score": "0", "body": "lol probably. :)" } ]
[ { "body": "<p>In my opinion for the most part, that looks good. However, there are a few small things I would question.</p>\n\n<ul>\n<li><p>Do you really need the wrapper <code>div</code> element? I would remove it so you have the <code>header</code> as the first child of the <code>body</code>.</p></li>\n<li><p>I would probably get rid of the <code>section</code> elements of each <code>article</code>. While their use is probably semantically valid, I think just the <code>p</code> elements would suffice.</p></li>\n<li><p>The contents of the <code>time</code> elements currently causes your document not to validate. See the <a href=\"http://www.w3.org/TR/2010/WD-html5-20100624/text-level-semantics.html#the-time-element\">relevant part of the HTML5 spec</a> for more details. Here's the error from the <a href=\"http://validator.w3.org/\">validator</a>:</p>\n\n<blockquote>\n <p>The text content of element time was not in the required format: The\n literal did not satisfy the date or time format.</p>\n</blockquote></li>\n</ul>\n\n<p><strong>Update</strong></p>\n\n<ul>\n<li><p>The <code>hr</code> element is not semantically valid in the way you have used it. It could be replaced with CSS targeting the page <code>header</code> and <code>footer</code>. <a href=\"http://www.w3.org/TR/2010/WD-html5-20100624/grouping-content.html#the-hr-element\">From the spec</a> (emphasis added):</p>\n\n<blockquote>\n <p>The <code>hr</code> element represents a <strong>paragraph-level thematic break</strong>, e.g. a\n scene change in a story, or a transition to another topic within a\n section of a reference book.</p>\n</blockquote></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:16:28.833", "Id": "21133", "Score": "0", "body": "I gave him the same answer about `section` in `article` tags. Then after reading the specs and some posts about that, it seems that for big articles, `section` is really appropriate to subdivide a blog post, and then add `header`, `headings` and `footer` to every `section`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:25:40.793", "Id": "21134", "Score": "0", "body": "Ahh I also misread the `TIME` tag spec... Adding `datetime` attribute (with a valid value) will correct the validator errors. Thanks:)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:32:48.477", "Id": "21137", "Score": "0", "body": "ahh also did not know that about the `HR` element.." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:34:07.667", "Id": "21140", "Score": "0", "body": "@DieVarDump - I'm not sure that each `section` in this case would need a `header` and `footer`, hence the suggestion to remove the `section` elements. I'm not entirely sure on that point though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:36:50.830", "Id": "21141", "Score": "0", "body": "I think having a header is probably prudent... but a footer may not be needed for each section. (but this should be reviewed per article basis... not every article will need more than one section.)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T12:49:12.293", "Id": "13074", "ParentId": "13073", "Score": "7" } }, { "body": "<p>Quick review:</p>\n\n<ul>\n<li>Remove this damn <code>&lt;hr&gt;</code>, styling is for CSS.</li>\n<li>In each <code>&lt;section&gt;</code>, you better have an <code>&lt;h2&gt;</code> :-)</li>\n<li>You can add <code>rel=\"author\"</code> to your <code>&lt;a&gt;</code> link on the author. Even better, you can use <code>&lt;a href=\"https://url.to.google.plus/user?rel=author\" rel=\"author\"&gt;The author's name&lt;/a&gt;</code> (Google will recognize this as a \"rich snippet\" and show your face in google results. Take a look at <a href=\"http://schema.org\" rel=\"nofollow noreferrer\">http://schema.org</a> for more information). Rich snippets are a whole other topic, so I'll stop talking about it :)</li>\n</ul>\n\n<p>Edit after your comment:</p>\n\n<ul>\n<li>Each article should contain an <code>&lt;h2&gt;</code> for its article sections.</li>\n<li>Each article should have its title in an <code>&lt;h1&gt;</code>. Yes, even if there are multiple <code>&lt;h1&gt;</code> in the main page. If there is just the titles on the main page (no article's text), feel free to use <code>&lt;h2&gt;</code>.</li>\n<li>The <code>&lt;h1&gt;</code> on the frontpage is tolerated, not on the blog pages. Feel free to use it or not on the frontpage, but make sure that each blog page has the title of the post as an <code>&lt;h1&gt;</code>, not the site's name.</li>\n</ul>\n\n<p>Related picture:</p>\n\n<p><img src=\"https://i.stack.imgur.com/qBcBR.png\" alt=\"flowchart\"></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:02:30.293", "Id": "21162", "Score": "0", "body": "Primary headers in the page, `<article>`s, and `<sections>` should use `<h1>` elements. If the region has a secondary header `<h2>` should be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:05:32.910", "Id": "21163", "Score": "0", "body": "@zzzzBov even though semantic html is nice, we also can't forget about SEO. That's why using H1 elements everywhere is often not an option (or rather, not the *best* option)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:37:25.463", "Id": "21169", "Score": "0", "body": "@FlorianMargaine, the question was about semantic HTML, and not optimizing for search engines. Besides, google's (not worth pretending that anyone uses a different search engine) algorithms follow common web practices, and are adapting to support HTML5." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:37:58.333", "Id": "21170", "Score": "0", "body": "@zzzzBov still, it is real life :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:40:15.647", "Id": "21171", "Score": "0", "body": "@FlorianMargaine, your right, life is real, and this *is* a blog format. SEO lost/gained from use of `h1` elements is negligible in comparison to the gains from people sharing links to the page. More important to emphasize the quality of the content over the structure of the markup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T12:19:33.583", "Id": "21207", "Score": "0", "body": "To satisfy both of you; the question is first and foremost about semantic html and using the new html5 tags properly. This does however entail optimizing them for SEO (where it still conforms with the semantic parts)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-06-19T01:31:13.563", "Id": "379038", "Score": "0", "body": "\"Remove this damn `<hr>`\" ... Not even self-closed or anything." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:31:51.630", "Id": "13075", "ParentId": "13073", "Score": "13" } } ]
{ "AcceptedAnswerId": "13075", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T12:36:11.460", "Id": "13073", "Score": "14", "Tags": [ "html5" ], "Title": "Semantic HTML5 and proper use of tags" }
13073
<p>Is there a more elegant way of doing this? I really think this looks ugly.</p> <pre><code>private static string InsertMethodNameHere( bool hasCondition1, bool hasCondition, bool hasCondition3) { if (!hasCondition1 &amp;&amp; !hasCondition2 &amp;&amp; !hasCondition3) return "0"; if (hasCondition1 &amp;&amp; !hasCondition2 &amp;&amp; !hasCondition3) return "1"; if (!hasCondition1 &amp;&amp; hasCondition2 &amp;&amp; !hasCondition3) return "2"; if (hasCondition1 &amp;&amp; hasCondition2 &amp;&amp; !hasCondition3) return "3"; if (!hasCondition1 &amp;&amp; !hasCondition2 &amp;&amp; hasCondition3) return "4"; if (hasCondition1 &amp;&amp; !hasCondition2 &amp;&amp; hasCondition3) return "5"; if (!hasCondition1 &amp;&amp; hasCondition2 &amp;&amp; hasCondition3) return "6"; if (hasCondition1 &amp;&amp; hasCondition2 &amp;&amp; hasCondition3) return "7"; throw new Exception("Unable to determine."); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T00:40:29.090", "Id": "21310", "Score": "0", "body": "Might I ask why you think it's ugly? It looks perfectly readable to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-07T12:37:48.230", "Id": "21685", "Score": "0", "body": "I suppose it is readable but, I didn't like so many returns within the method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T15:26:55.933", "Id": "21873", "Score": "1", "body": "I guess it's a matter of preference but it's important to note that beauty isn't typically an aspect of software quality. I personally prefer the original to the accepted answer in terms of readability." } ]
[ { "body": "<p>How about this?</p>\n\n<pre><code>private static string InsertMethodNameHere(bool hasCondition1, bool hasCondition2, bool hasCondition3)\n{\n return ((hasCondition1 ? 1 : 0) +\n (hasCondition2 ? 2 : 0) +\n (hasCondition3 ? 4 : 0)).ToString(CultureInfo.InvariantCulture);\n}\n</code></pre>\n\n<p>If you want a more general solution, you could write an extension method that converts a list of bools to an int:</p>\n\n<pre><code>public static int ToInt(this IEnumerable&lt;bool&gt; bools)\n{\n return bools.Select((t, i) =&gt; (t ? 1 : 0) &lt;&lt; i).Sum();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T19:40:32.640", "Id": "21182", "Score": "0", "body": "Nice, very neat and readable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T11:17:24.137", "Id": "21205", "Score": "0", "body": "I like this. It looks clean and simple. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T15:10:07.040", "Id": "22071", "Score": "3", "body": "Since my answer's all the way at the bottom and this is a good answer, just one thing; you could use the \"params\" keyword and make `bools` an array, and then the user wouldn't have to set up an actual IEnumerable of bools. You could set it up as an overload of this one, then you could turn a list of bools or a set of disparate variables into an int." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:49:18.880", "Id": "13077", "ParentId": "13076", "Score": "27" } }, { "body": "<p>You are representing some state using 3 individual boolean variables. It may be better to represent such a state using an enum with flags. Then this complicated test to figure what state you're in wouldn't have to be done. You could then combine flags to represent each of the separate states then switch off of that.</p>\n\n<pre><code>[Flags]\npublic enum MyState\n{\n // your flags\n Default = 0x00,\n Condition1 = 0x01,\n Condition2 = 0x02,\n Condition3 = 0x04,\n\n // your state\n State0 = Default,\n State1 = Condition1,\n State2 = Condition2,\n State3 = Condition3,\n State4 = Condition1 | Condition2,\n State5 = Condition1 | Condition3,\n State6 = Condition2 | Condition3,\n State7 = Condition1 | Condition2 | Condition3,\n}\n</code></pre>\n\n\n\n<pre><code>private static void DispatchMethod(MyState state)\n{\n switch (state)\n {\n case MyState.State0:\n // do something for state 0\n break;\n case MyState.State1:\n // do something for state 1\n break;\n case MyState.State2:\n // do something for state 2\n break;\n case MyState.State3:\n // do something for state 3\n break;\n case MyState.State4:\n // do something for state 4\n break;\n case MyState.State5:\n // do something for state 5\n break;\n case MyState.State6:\n // do something for state 6\n break;\n case MyState.State7:\n // do something for state 7\n break;\n }\n}\n</code></pre>\n\n<p>You could still set and clear individual flags using simple bitwise logic.</p>\n\n<pre><code>state |= MyState.Condition1; // sets condition 1\nstate &amp;= ~MyState.Condition3; // clears condition 3\n</code></pre>\n\n<p>You could even wrap this up in a library to make doing these operations more intuitive.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T14:04:49.153", "Id": "21144", "Score": "0", "body": "Just a warning, calling `ToString()` on such an enum will not yield what you would probably expect. Since there are overlapping values, the default implementation will return possibly multiple values that applies." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:48:27.057", "Id": "21172", "Score": "0", "body": "perhaps it would be better to put the 'flags' into a separate enum in order to avoid the overlapping ToString()?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T18:11:04.073", "Id": "21176", "Score": "0", "body": "I considered that but the problem is that you would have to map out the values so that they would correspond between the types. But you don't necessarily need the result of what `ToString()` returns anyway, you can get the name of the value through other means. And in practice, I don't think there's much need for the string representation anyway, we only care about the value." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:56:20.507", "Id": "13078", "ParentId": "13076", "Score": "21" } }, { "body": "<p>Using the <code>MyState</code> flag enum from Jeff's answer you can do the method in Scroog1's answer like so:</p>\n\n<pre><code>private static string InsertMethodNameHere(bool hasCondition1, bool hasCondition2, bool hasCondition3)\n{\n var state = MyState.Default;\n if(hasCondition1) state |= MyState.Condition1;\n if(hasCondition2) state |= MyState.Condition2;\n if(hasCondition3) state |= MyState.Condition3;\n return ((int)state).ToString(CultureInfo.InvariantCulture);\n}\n</code></pre>\n\n<p>(the int cast is there to match your initial return state)</p>\n\n<p>see also: <a href=\"http://weblogs.sqlteam.com/mladenp/archive/2007/01/12/57541.aspx\">http://weblogs.sqlteam.com/mladenp/archive/2007/01/12/57541.aspx</a></p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:03:19.803", "Id": "13084", "ParentId": "13076", "Score": "5" } }, { "body": "<pre><code>private static string InsertMethodNameHere(params bool[] conditions)\n{\n conditions.Select((x,i)=&gt;Convert.ToByte(x) &lt;&lt; i).Sum().ToString();\n}\n</code></pre>\n\n<p>In your particular situation, this would drop right in, which IMO makes it better than Scroog's because his requires the user to put the conditions into IEnumerable format. The <code>params</code> keyword is beautiful that way. This function (like many answers) assumes that the desired State will always be the concatenation of a big-endian bit array of the conditions, in order.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T19:22:20.303", "Id": "13092", "ParentId": "13076", "Score": "4" } } ]
{ "AcceptedAnswerId": "13077", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T13:36:35.930", "Id": "13076", "Score": "20", "Tags": [ "c#" ], "Title": "Multiple if then return with conditions" }
13076
<p>I'm learning F# and have a couple of routines much of whose functionality looks common so I am looking to refactor them together.</p> <p>Here are the routines (which for the record I lifted from elsewhere:</p> <pre><code>let Prices time ID (polling:float) = let sync = System.Threading.SynchronizationContext.Current let obs = new Event&lt;int&gt;() let raiseEvent (value:int) = sync.Post((fun _ -&gt; obs.Trigger(value)), null) let interval = TimeSpan.FromSeconds(polling) let rec loop nextTime= async { // Generate next value (on the GUI thread) do getPrices nextTime |&gt; List.filter (fun price -&gt; price.ID = ID) |&gt; List.iter (fun price -&gt; raiseEvent price.Price) // Wait some short time do! Async.Sleep(1000) // Continue looping do! loop (nextTime.Add(interval)) } loop time |&gt; Async.Start obs.Publish </code></pre> <p>and </p> <pre><code>let Volumes time ID (polling:float) = let sync = System.Threading.SynchronizationContext.Current let obs = new Event&lt;VolumeDTO&gt;() let raiseEvent (value:VolumeDTO) = sync.Post((fun _ -&gt; obs.Trigger(value)), null) let interval = TimeSpan.FromSeconds(polling) let rec loop nextTime= async { // Generate next value (on the GUI thread) do getVolumes nextTime |&gt; List.filter (fun volume -&gt; volume.ID = ID) |&gt; List.iter (fun volume -&gt; raiseEvent volume) // Wait some short time do! Async.Sleep(1000) // Continue looping do! loop (nextTime.Add(interval)) } loop time |&gt; Async.Start obs.Publish </code></pre> <p>The external function calls are hopefully reasonable self explanatory retrieving data from a db</p> <pre><code>let getPrices lastTime = createList&lt;PriceDTO&gt;((getPriceSql lastTime), priceReader) let getVolumes lastTime = createList&lt;VolumeDTO&gt;((getVolumeSql lastTime), volumeReader) </code></pre> <p>The types are very simple, but I'm not sure I've got this 'right':</p> <pre><code>type IID = abstract member ID : int64 type PriceDTO(ID:int64, Price:int) = interface IID with member this.ID = ID member x.ID = ID member x.Price = Price type VolumeDTO(ID:int64, Amount:decimal, Price:int32) = interface IID with member this.ID = ID member x.ID = ID member x.Amount = Amount member x.Price = Price </code></pre> <p>I've played around with something but I'm not at all there as yet:</p> <pre><code>let publish&lt;'a&gt; time ID (polling:float) dataRetriever = let sync = System.Threading.SynchronizationContext.Current let obs = new Event&lt;'a&gt;() let raiseEvent (value:'a) = sync.Post((fun _ -&gt; obs.Trigger(value)), null) let interval = TimeSpan.FromSeconds(polling) let rec loop (nextTime:DateTime)= async { // Generate next value (on the GUI thread) do dataRetriever nextTime |&gt; List.filter (fun item -&gt; item.ID = ID) |&gt; List.iter (fun item -&gt; raiseEvent item) // Wait some short time do! Async.Sleep(1000) // Continue looping do! loop (nextTime.Add(interval)) } loop time |&gt; Async.Start obs.Publish </code></pre> <p>I may well have not quite implemented this correctly. I'm obviously getting a list of prices or volumes filtering them and publishing them. In order to achieve the filtering I've created an interface, but I'm not really happy with this since I'd prefer to keep the DTOs as simple as possible. Intellisense is telling me that my <code>dataRetriever</code> function takes a <code>DateTime</code> and returns an 'a list, but I'm not sure I quite want that since I need to cast it to an IID interface for filtering and then back to the underlying DTO for publishing.</p> <p>Is there a more 'functional' (or perhaps just better) way to do this?</p>
[]
[ { "body": "<p>This is a bit difficult to answer, because you did not share code sample that fully type-checks (and so it is hard to make sure the answer is correct). However, I think you're very close. When refactoring two similar functions, you just need to abstract out the bits that differ.</p>\n\n<p>In your case, there are two places:</p>\n\n<ul>\n<li>One is the function that is used to retrieve the data (either <code>getPrices</code> or <code>getVolumes</code>) </li>\n<li>Second is the projection that is used when triggering the event (either <code>item</code> or <code>item.Price</code>)</li>\n</ul>\n\n<p>If you take these two operations as functions, then you can write the following:</p>\n\n<pre><code>open System\n\ntype IID = \n abstract member ID : int64 \n\nlet Publish (dataRetriever:TimeSpan -&gt; list&lt;#IID&gt;) valueSelector time ID (polling:float) = \n let sync = System.Threading.SynchronizationContext.Current \n let obs = new Event&lt;int&gt;() \n let raiseEvent (value:int) = sync.Post((fun _ -&gt; obs.Trigger(value)), null) \n let interval = TimeSpan.FromSeconds(polling) \n let rec loop nextTime= async { \n // Generate next value (on the GUI thread) \n dataRetriever nextTime \n |&gt; List.filter (fun item -&gt; item.ID = ID) \n |&gt; List.iter (fun item -&gt; raiseEvent (valueSelector item)) \n // Wait some short time \n do! Async.Sleep(1000) \n // Continue looping \n do! loop (nextTime.Add(interval)) } \n loop time |&gt; Async.Start \n obs.Publish \n</code></pre>\n\n<p>The type annotation <code>TimeSpan -&gt; list&lt;#IID&gt;</code> is interesting. It says that the argument is a function that returns a list of some values that implement the <code>IID</code> interface - but it turns this type into a generic type argument that is then passed to the other function (<code>valueSelector</code>), so when you use the function, the compiler knows that the argument of <code>valueSelector</code> has the same type as the thing that you obtain from <code>dataRetriever</code>. The annotation allows you to write <code>item.ID</code> in the filtering function.</p>\n\n<p>The two functions can now be defined as follows:</p>\n\n<pre><code>let Prices = Publish getPrices (fun price -&gt; price.Price)\nlet Volumes = Publish getVolumes id\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T08:04:18.480", "Id": "21149", "Score": "1", "body": "Tomas, this is fantastic. TVM. 1Q - with prices I am just publishing a series of prices for each id (a list/set of prices), but for volume I am publishing series of amounts at various prices (a list/set of price/amount pairs). I notice you have removed what I had declared as a generic and made it Event<int> rather than Event<'a>. Was this by design? I was rather hoping to \"put in\" the different data 'under' the generic hood." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T06:19:46.980", "Id": "13081", "ParentId": "13080", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T05:43:32.760", "Id": "13080", "Score": "2", "Tags": [ "f#" ], "Title": "Getting prices and volume" }
13080
<p>I have a form written in the usual way. After submitting, if there are errors in the form, the form page itself is the target of the redirect, with a query string appended. The query string contains the error messages, but also the values submitted with the form. The query string and its format are provided by a 3<sup>rd</sup>-party, so I cannot switch to using POST, nor make any other changes on their processing logic. I just get the string and make the best of it.</p> <p>Since the URL is "different", the form's values aren't preserved. The browser treats it as a fresh form and therefore blanks it. Not good, since the user won't want to re-enter everything. So, the first step was deciding whether to use JavaScript or PHP to repopulate the form, and I went with PHP.</p> <p>Consequently, the form now has entries that look a little something like this:</p> <pre><code>&lt;li id="li_business_years" &gt; &lt;label class="description" for="partner_business_years"&gt;How many years have you been in business?&lt;/label&gt; &lt;div&gt; &lt;input id="partner_business_years" name="partner_business_years" class="element text small" type="text" maxlength="255" value="&lt;?php echo $_GET['partner_business_years']; ?&gt;"/&gt; &lt;/div&gt; &lt;/li&gt; </code></pre> <p>Is this considered a ridiculous approach? If I used JavaScript, I could use an iterator to run through all the fields in one little loop, instead of individually populating each value attribute with PHP. But server-side seems to be the right place to do this since the form doesn't otherwise rely on JavaScript.</p> <p>The next question: I have some Yes/No questions in radio button form. The query string will therefore contain values like <code>will_relocate=yes</code>. In my mind, I want to just say "Select the appropriate radio based on the query string", but there's no real concept of selecting for radios... there's a shared name with different value options.</p> <p>Here's the original HTML:</p> <pre><code>&lt;span&gt; &lt;input id="relocate_1" name="will_relocate" class="element radio" type="radio" value="yes" /&gt; &lt;label class="choice"&gt;Yes&lt;/label&gt; &lt;/span&gt; &lt;span&gt; &lt;input id="relocate_2" name="will_relocate" class="element radio" type="radio" value="no" /&gt; &lt;label class="choice"&gt;No&lt;/label&gt; &lt;/span&gt; </code></pre> <p>I can get it working by doing something like this:</p> <pre><code>&lt;input id="relocate_2" name="will_relocate" class="element radio" type="radio" value="no" &lt;?php if($_GET['will_relocate'] &amp;&amp; $_GET['will_relocate'] == "no") { echo 'checked'; } ?&gt;/&gt; </code></pre> <p>(with a matching one for "yes"... and as many pairs of these as needed)</p> <p>But it strikes me as hideous. I'm just a hack at PHP, and I'm sure I could break this out into a function, but I would still have a pair of <code>&lt;?php selectRadio('will_relocate') ?&gt;</code> - type calls throughout my document, which is barely better.</p> <p>Any ideas? Is my approach just completely nasty from the get-go? Should I use JavaScript after all?</p> <p>I'm open to JavaScript-based suggestions for form re-populating, but not as the sole validator (I don't have and wouldn't choose that option).</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:11:15.283", "Id": "21154", "Score": "0", "body": "Rather than unpacking the returned form contents from your PHP validator, have you considered doing client-side form validation in JavaScript?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:19:14.900", "Id": "21155", "Score": "3", "body": "I would never do client-side validation \"only\". It's a nice-to-have and I will probably implement it in some variety, but sanitizing on the server-side is a must-have. More to the point, though, I have no choice. If the form encounters an error on the server side, it WILL redirect to this page and I will want the form to be pre-filled. Might be a JavaScript snippet that will cookie and restore a form, though. Could be a decent compromise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T18:24:57.137", "Id": "21178", "Score": "0", "body": "Greg, I agree. There's always the possibility that someone might have JavaScript disabled, for example." } ]
[ { "body": "<p>I went ahead with the one-by-one re-populating from GET (on a timeline and all that!). The form doesn't need to be highly reusable and won't be modified very frequently after roll-out, so in this particular case, it was a matter of 'getr done' rather than 'getr done the best way'.</p>\n\n<p>For the radio buttons, I ended up with a series of these:</p>\n\n<pre class=\"lang-php prettyprint-override\"><code>&lt;span&gt;\n &lt;input id=\"partner_systemIntegration_1\" name=\"partner_systemIntegration\" class=\"element radio\" type=\"radio\" value=\"yes\" &lt;?php if(($_GET['partner_systemIntegration']) &amp;&amp; $_GET['partner_systemIntegration'] == \"yes\") { echo 'checked'; } ?&gt; /&gt;\n &lt;label class=\"choice\" for=\"partner_systemIntegration_1\"&gt;Yes&lt;/label&gt;\n&lt;/span&gt;\n&lt;span&gt;\n &lt;input id=\"partner_systemIntegration_2\" name=\"partner_systemIntegration\" class=\"element radio\" type=\"radio\" value=\"no\" &lt;?php if(($_GET['partner_systemIntegration']) &amp;&amp; $_GET['partner_systemIntegration'] == \"no\") { echo 'checked'; } ?&gt; /&gt;\n &lt;label class=\"choice\" for=\"partner_systemIntegration_2\"&gt;No&lt;/label&gt;\n&lt;/span&gt;\n</code></pre>\n\n<p>It's klunky, but when I tried to break it out into a function it failed. I'm using WordPress and a plugin that allowed PHP in the post/page content itself. When trying to define and use a function, I got some sort of eval error/warning, so I'm just doing it one at a time. Not the epitome of elegance and not my ideal choice, but now I can move on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T18:31:23.167", "Id": "13090", "ParentId": "13083", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T15:59:51.697", "Id": "13083", "Score": "3", "Tags": [ "php" ], "Title": "Populating form contents from GET - especially radio buttons" }
13083
<p>I just recently learned about Project Euler and have started doing the problems on there. I cleared problem 1 and 2, had no idea how to do 3 and 4, and started to do 5. I've seen the post regarding the quick mathematic solution, but I'd like to know if there are better ways to do it programmatically.</p> <p>For those that don't know, question #5 is as follows:</p> <blockquote> <p>2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.</p> <p>What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?</p> </blockquote> <p>The logic behind my algorithm is simple:</p> <p>The number in question must be divisible by all of the numbers between 1 and 20 (assume inclusive for the ranges). As a result, it must be divisible by all of the numbers between 1 and 10. The smallest number that is divisible by all the numbers between 1 and 10 (given by Project Euler) is 2520. Thus, the number in question must be a multiple of 2520. (As I'm writing this, I'm starting to question whether or not this is a necessary truth, but the program does work. Don't really want to go about proving it right now. I'm fairly certain however.) Thus, I can start at 2520 + 2520 and simply add 2520 every iteration.</p> <p>It is guaranteed that these multiples will be divisible by all the numbers between 1 and 10, so there is no need to check those numbers. So I start from 11 and go to 20.</p> <pre><code>public static long problem5() { long i = 2520; boolean found = false; while (!found) { i += 2520; boolean divis = true; for (int j = 11; j &lt;= 20; j++) { if (i % j != 0) { divis = false; //System.out.println(i + &quot; is not divisible by &quot; + j); break; } else { //System.out.println(i + &quot; is divisible by &quot; + j); } } if (divis) { found = true; } } return i; } </code></pre> <p>I made this quick program to check my math regarding my statement &quot;Thus, the number in question must be a multiple of 2520.&quot; It returns true if it finds a number not divisible by 2520 but divisible by all of the numbers between 1 and 10, and false if it does not find such a number. I feel that I set the limit to a reasonable limit. It indeed returns false.</p> <pre><code>public static boolean checkMath() { int start = 2520; int end = start * (232792560/2520); boolean result = true; for (int i = start + 1; i &lt; end; i++) { result = true; for (int j = 1; j &lt;= 10; j++) { if (i % j != 0) { result = false; break; } } if (result) { if (i % 2520 != 0) { break; } } } return (result); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:47:53.083", "Id": "21160", "Score": "0", "body": "If your solution works, in what way do you want to make it \"better\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:52:08.260", "Id": "21161", "Score": "0", "body": "@JohnDibling Hmm. I suppose you are right. A working solution is a solution. This solution is _more_ optimal than simply starting from 1 and looping until the largest possible integer and checking every integer between 1 and 20, but I feel (feel is indeed a weak word) that there is an even better way to achieve the result and if there is, would certainly like to see it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:50:50.293", "Id": "21174", "Score": "0", "body": "You're probably right that faster is better. I got my code working for #5 and moved on to the next one, however. Figured there will be plenty of better opportunities to do some serious optimizing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T17:55:01.917", "Id": "21175", "Score": "0", "body": "@JohnDibling Haha, that's true. There are plenty of I suppose more useful opportunities to do optimizing where optimizing would actually make an impact. By no means am I saying that I'm stopping here and waiting to optimize this before I continue. I'm going to continue of course, but I suppose this just piqued my curiosity." } ]
[ { "body": "<p>Maybe you can reason as follows:</p>\n\n<p>Multiplying all the numbers together from 1->10 gives you <code>3628800</code> which is indeed divisible by the numbers 1->10, but it is not the minimum number. Ask yourself why? take the last number 10 for instance. Do we really need to multiply 10 into our answer 10, when we know that our number already has a factor of 2 and a factor of 5?</p>\n\n<p>Consider the prime factors of the numbers 1->10</p>\n\n<p>factors:</p>\n\n<pre><code> 1 - 1\n 2 - 2\n 3 - 3\n 4 - 2*2 (2^2)\n 5 - 5\n 6 - 2*3\n 7 - 7\n 8 - 2*2*2 (2^3)\n 9 - 3*3 (3^2)\n10 - 2*5\n</code></pre>\n\n<p>What's the most number of 2's you need to create any of the values 1->10...? 3 (8=2^3)<br>\nWhat's the most number of 3's? 2 (9=3^2)<br>\nWhat's the most number of 5's? 1 (5)<br>\nWhat's the most number of 7's? 1 (7)<br>\nThus, the answer for the minimum number that is a multiple of 1->10, is 2^3*3^2*5*7 = 2520.<br>\nYou can extend this logic for 1->20 and you'll get a much quicker algorithm than what you've proposed.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T18:28:19.740", "Id": "13089", "ParentId": "13086", "Score": "18" } }, { "body": "<p>The basic idea of all Project Euler problems is to find an efficient solution to the problem, by knowing enough math to simplify the computation your program must do. You can brute-force all of these with enough computing power, but there is a way to reduce the complexity such that a program that solves the problem will give you an answer in under one minute with a 5-year-old computer.</p>\n\n<p>The brute-force answer would be to start at 21 and try every number in order until we found our answer. That's not a great idea, as the answer is quite large, and while, with a powerful computer, you might arrive at the answer in good time, brute force simply won't work in other Project Euler problems (you'll exceed hardware/firmware limitations, or end up with an exponential algorithm taking longer than the estimated heat-death of the universe to compute). In this case, with a few smarts, we can break down the problem and work with smaller numbers, thus taking fewer steps. </p>\n\n<p>You want to know the smallest number divisible by every number from 1 to 20. Well, for one number to be divisible by another, all of the prime factors of the divisor must be present in the prime factorization of the dividend. For instance, 20 is divisible by 10 because 10's factors, 5 and 2, are both present in 20's factorization of 2<sup>2</sup>*5. The quotient is the product of the remaining prime factors; in this case there's only one, 2.</p>\n\n<p>Now, the solution of the problem becomes more apparent; the smallest number divisible by every number from 1 to 20 is the smallest number that contains all the prime factors of every number from 1 to 20. So, the solution is to find the prime factorization of every number from 1 to 20 and keep a count of how many of each prime factor is necessary. Prime factorization is technically an inefficient process (you have to start with the number and divide by every known prime number until you get a whole-number quotient, then repeat from the beginning with that quotient until you're left with 1) but the numbers are so small it doesn't matter.</p>\n\n<p>The solution is the smallest number for which the prime factorization of every number from 1 to 20 is a subset of its own prime factorization. At the least, you'll need one of every prime number from 1 to 20. You will also discover that in order to be divisible by 16, the number must have 4 2s in its prime factorization, and to be divisible by 9 and 18, the number must have 2 3s. The smallest such number is the number that has ONLY the needed factors, so the answer is </p>\n\n<blockquote class=\"spoiler\">\n <p> 2<sup>4</sup>*3<sup>2</sup>*5*7*11*13*17*19 = 232792560.</p>\n</blockquote>\n\n<p>The program to find this number will start at 2, iterate to 20, and for each of those numbers it will divide by every known prime less than that number (technically any prime less than the square root of the number but you won't save much that way) to determine their factorization. You will find the numbers that are prime as you go (they won't be divisible by any lesser prime, by definition). Any number that requires more than one of a particular prime factor should be tracked, and the maximum number of each factor remembered (I'll tell you for this problem that only 2 and 3 will require multiples). Then, simply multiply the necessary number of the necessary factors to produce the answer.</p>\n\n<p>If this sounds like a lot, meh; the computer can whip through it pretty quickly, and it will take far less time than counting multiples of 2520. As a point of reference, the correct answer, if you didn't peek, is 5 orders of magnitude greater than this number, requiring about 10,000 iterations * dividing by 20 numbers on each one = 200,000 steps, versus a worst-case of 20 (number of divisors) * 8 (primes less than 20) * 7 / 2 (naive worst case of every number &lt;= 20 being divisible by every prime &lt;=20; not possible but the result's still nowhere close) = 560 steps to find the prime factorizations of the first 20 numbers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T18:44:06.173", "Id": "13091", "ParentId": "13086", "Score": "17" } }, { "body": "<p>I thought of a quick way to solve this without having to use prime factorization or finding prime numbers. The code I am going to paste is in java.</p>\n\n<pre><code> int[] answers = new int[20];\n for (int i = 0; i &lt; 20; i++) {\n answers[i] = i + 1;\n }\n int answer = 1;\n for (int i = 0; i &lt; answers.length; i++) {\n if (answers[i] != 1) {\n answer *= answers[i];\n j = 2\n while (answers[i] * j &lt; answers[i].length) {\n answers[answers[i] * j] /= answers[i]\n j += 1\n }\n }\n }\n return answer;\n</code></pre>\n\n<p>What this does is first it creates an array of all numbers: </p>\n\n<pre><code>answers[]=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];\n</code></pre>\n\n<p>Then for each number that isn't one, I multiply that number to the answer and update the array (divide all elements in the array, divisible by that number, by that number) so:</p>\n\n<pre><code>answer = 2; answers[] = [1,1,3,2,5,3,7,4,9,5,11,6,13,7,15,8,17,9,19,10];\nanswer = 6; answers[] = [1,1,1,2,5,1,7,4,3,5,11,2,13,7,5,8,17,3,19,10];\nanswer = 12;answers[] = [1,1,1,1,5,1,7,2,3,5,11,1,13,7,5,4,17,3,19,5];\n</code></pre>\n\n<p>etc.</p>\n\n<p>Go through the entire array once and you get the answer. This is much much faster and easier than prime factoring.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-29T01:19:19.143", "Id": "78929", "ParentId": "13086", "Score": "3" } }, { "body": "<p>As has been expressed in other answers to this problem, the critical insight is that </p>\n\n<p>$$LCM(1..1) = 1$$\n$$LCM(1..n) = \\frac{LCM(1..n-1) * n}{gcd(LCM(1..n-1), n)}$$</p>\n\n<p>From that, you can build up to an arbitrary \\$n\\$ by applying the second formula repeatedly. </p>\n\n<pre><code>static long leastCommonMultiple(long n) {\n long multiple = 1;\n\n for ( long i = 2; i &lt;= n; i++ ) {\n multiple *= i / gcd(i, multiple);\n }\n\n return multiple;\n}\n</code></pre>\n\n<p>The recursive greatest common denominator (gcd) function is </p>\n\n<pre><code>static long gcd(long a, long b) {\n return ( 0 == b ) ? a : gcd(b, a%b);\n}\n</code></pre>\n\n<p>And you can get this iteratively with </p>\n\n<pre><code>static long gcd(long a, long b) {\n while ( 0 != b ) {\n long temp = a;\n a = b;\n b = temp % b;\n }\n\n return a;\n}\n</code></pre>\n\n<p>On my computer, the iterative version runs in about ten microseconds. The recursive version is a few microseconds slower. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-05-07T11:25:45.713", "Id": "238904", "Score": "0", "body": "It's a mystery to me why people vote up the other answers with solutions that are needlessly complicated, and so few vote this answer which is sweet, correct and to the point..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-29T02:02:48.140", "Id": "78933", "ParentId": "13086", "Score": "6" } }, { "body": "<p>My solution arrives at the same and correct answer, but I think is easier to understand.</p>\n\n<pre><code>public class SmallestMultiple {\n\npublic static void main(String [] args){\n\n boolean notFound = true;\n int base = 20, current = base;\n\n while(notFound){\n for(int i = base; i&gt;10; i--){\n if(current%i != 0){\n current=current+base;\n notFound = true;\n break;\n }else{\n notFound= false;\n }\n } \n }\n System.out.println(current); \n} \n</code></pre>\n\n<p>All you really are concerned with is 11 through the upper limit (in this case 20), as it is guaranteed that 2 through 10 are factors of some greater number (11 through 20), so there is no need to iterate over 2 through 10.</p>\n\n<p>Also, the answer MUST be evenly divisible by the max (i.e. 20).. So, start iterating downward from there, AND the first iteration that fails, simply stop and increase the potential answer by adding the base value (i.e. 20) to it, as this is guaranteed to also be evenly divisible by the max (i.e. 20) and you can start the iteration process over again from there. Simply keep repeating this until all values 11 through 20 evenly divide into the current value, and that value will be your answer.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-11-30T19:58:00.010", "Id": "208787", "ParentId": "13086", "Score": "0" } } ]
{ "AcceptedAnswerId": "13091", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T16:34:48.860", "Id": "13086", "Score": "13", "Tags": [ "java", "performance", "programming-challenge" ], "Title": "Smallest Multiple" }
13086
<p>Currently my below code takes an average 9.27300 every time I run it. This is an iOS application and I can't expect the user to sit there for roughly 10 seconds.</p> <p>This code takes an array (originalData) of <code>placeObjects</code> and calculates the distance from the selected location (CLLocation* searched). It does by <code>[searched distanceFromLocation:currentLoc];</code> Each time the distance is calculated, the distance is stored into <code>keysArray</code>. After the first for loop the numbers are then sorted from ascending order.</p> <p>After that another for loop is made to line up the originalData to follow the same ascending order as the <code>keysArray</code>. </p> <p>A side note: I am currently doing this for 500 objects in originalData.</p> <p>I am calling this method <code>[self sortLocations];</code> from viewDidLoad.</p> <pre><code>-(void)sortLocations{ NSLog(@"Start"); [keysArray removeAllObjects]; //originalData is an NSMutableArray for (int i = 0; i &lt; [originalData count]; i++) { /* f is global but its: * f = [[NSNumberFormatter alloc] init]; * [f setNumberStyle:NSNumberFormatterDecimalStyle]; */ NSNumber* cLat = [f numberFromString:[[originalData objectAtIndex:i] latitude]]; NSNumber* cLng = [f numberFromString:[[originalData objectAtIndex:i] longitude]]; CLLocation* currentLoc = [[CLLocation alloc] initWithLatitude:[cLat doubleValue] longitude:[cLng doubleValue]]; //searched is a CLLocation CLLocationDistance distance = [searched distanceFromLocation:currentLoc]; NSNumber* num = [NSNumber numberWithInt:distance]; [keysArray addObject:num]; } //lowToHight is this: // lowToHigh = [NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]; [keysArray sortUsingDescriptors:[NSArray arrayWithObject:lowToHigh]]; [orderedArray removeAllObjects]; for (int i = 0; i &lt; [keysArray count]; i++) { NSNumber* keyNum = [keysArray objectAtIndex:i]; for (placeObjects* x in originalData){ NSNumber* cLat = [f numberFromString:[x latitude]]; NSNumber* cLng = [f numberFromString:[x longitude]]; CLLocation *currentLoc = [[CLLocation alloc] initWithLatitude:[cLat doubleValue] longitude:[cLng doubleValue]]; CLLocationDistance distance = [searched distanceFromLocation:currentLoc]; NSNumber* num = [NSNumber numberWithInt:distance]; if ([num intValue] == [keyNum intValue]) { [orderedArray addObject:x]; } } } NSLog(@"End"); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-29T00:10:20.657", "Id": "104701", "Score": "1", "body": "Please do not edit new code into the question after receiving reviews." } ]
[ { "body": "<p>Your problem is with the code after the actual sort. For each item in the final array you scan over the whole original array recalculating the distance each time. That means that you'll calculate a distance some 500*500=250000 times.</p>\n\n<p>The simplest solution would be to add a <code>distance</code> property to your objects. Then you sort by:</p>\n\n<ol>\n<li>Iterating over all objects, setting the distance property</li>\n<li>Sort on the <code>distance</code> property using <code>sortUsingSelector</code> method</li>\n</ol>\n\n<p>Another solution would be decorate-sort-undecorate pattern. In this method:</p>\n\n<ol>\n<li>Create a new array of objects with a <code>distance</code> and <code>originalObject</code> properties.</li>\n<li>Sort on the distance property</li>\n<li>Create a new array from the originalObject properties</li>\n</ol>\n\n<p>Another solution would be to define a custom comparator. You write your own function that calculates whether one object is closer then another. You'd pass this function to <code>sortUsingFunction</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:00:10.177", "Id": "21224", "Score": "0", "body": "Your first statement is wrong. I only calculate the distance 500 times. `searched` is the same every time it is used in the loop. 'currentLoc' is what `searched` is being compared too. \nAnyways, I'll try adding in a new distance property to my objects and see how that turns out. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:06:36.780", "Id": "21232", "Score": "0", "body": "@JohnRiselvato, no, you calculate the distance much more than 500 times. Clearly, you code calls `distanceFromLocation` 500*500 times, this means you'll calculate the distance 500*500 times. Whether or not the parameters are changing makes no difference." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:12:54.033", "Id": "21235", "Score": "0", "body": "Oh are we looking in the second loop? Sorry, you are right. Ha my bad." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T16:22:25.493", "Id": "21251", "Score": "0", "body": "Thanks mate for the tips. I got it down to 0.022 seconds. I added the updated code to the question. cheers" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T00:06:10.117", "Id": "13100", "ParentId": "13088", "Score": "4" } }, { "body": "<p>Winston's answer points out some improvements to your algorithm. There are other ways in which we can slightly improve the speed of this.</p>\n\n<p>In Objective-C, <code>for</code> loops (and <code>while</code> and <code>do...while</code>) loops are handled one iteration at a time and the exit condition is checked on each iteration of the loop. Meanwhile, a <code>forin</code> loop is handled in batches. When we're dealing with an array for example, a <code>forin</code> loop might cache the first 8 objects and work with them before it goes back and grabs more objects. In this way, we save time by calling fewer messages on the collection. Moreover, when it caches these objects, you've already got a reference to the object, so you don't have to waste yet another message to the collection to grab a reference to the object. Long story short, <code>forin</code> loops are faster than <code>for</code> loops in Objective-C, and you should use them when you can, even if you don't need the reference to the objects in the collection...</p>\n\n<p>In this case though, we're actually wasting tons of execution time making calls back to the collection.</p>\n\n<p>Moreover, <code>NSString</code> has a method called <code>doubleValue</code> which shouldn't have any trouble pulling a double value out of a string...</p>\n\n<p>So let's clean up the first loop to look like this:</p>\n\n<pre><code>for (id object in originalData) {\n double latitude = [[object latitude] doubleValue];\n double longitude = [[object longitude] doubleValue];\n CLLocation* currentLoc = [[CLLocation alloc] initWithLatitude:latitude\n longitude:longitude];\n\n CLLocationDistance distance = [searched distanceFromLocation:currentLoc];\n NSNumber* num = [NSNumber numberWithInt:distance];\n [keysArray addObject:num];\n}\n</code></pre>\n\n<p>There are some things that are curious to me however. </p>\n\n<p>What's the data type of the objects in the array? Why does it have properties <code>latitude</code> and <code>longitude</code> which you clearly need to do math things with yet they're stored as <code>NSString</code> objects? These should be stored as <code>NSNumber</code> objects or just <code>double</code> primitives preferably.</p>\n\n<p><code>CLLocationDistance</code> is a <code>typedef</code> for <code>double</code>. Why are we then taking this double and instantiating an <code>NSNumber</code> object with <code>numberWithInt:</code>?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-29T00:23:16.797", "Id": "58333", "ParentId": "13088", "Score": "8" } } ]
{ "AcceptedAnswerId": "13100", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T18:15:53.977", "Id": "13088", "Score": "4", "Tags": [ "objective-c", "ios" ], "Title": "Optimize sorting of Array according to Distance (CLLocation)" }
13088
<p>I have been reading <a href="https://stackoverflow.com/questions/254514/php-and-enums">this</a> thread on Stack Overflow about simulating enums in PHP and it seems that the most common approach is to use class constants. My problem with that is I can't use it for type hints, so I have added a static function that checks if a value is defined as one of the constants.</p> <pre><code>class DataType { const BIT = 'BIT'; const TINYINT = 'TINYINT'; const SMALLINT = 'SMALLINT'; const MEDIUMINT = 'MEDIUMINT'; const INT = 'INT'; const INTEGER = 'INTEGER'; const BIGINT = 'BIGINT'; const FLOAT = 'FLOAT'; const DECIMAL = 'DECIMAL'; const NUMERIC = 'NUMERIC'; const DATE = 'DATE'; const TIME = 'TIME'; const TIMESTAMP = 'TIMESTAMP'; const DATETIME = 'DATETIME'; const YEAR = 'YEAR'; const CHAR = 'CHAR'; const VARCHAR = 'VARCHAR'; static public function Defines($const) { $cls = new ReflectionClass(__CLASS__); foreach($cls-&gt;getConstants() as $key=&gt;$value) { if($value == $const) { return true; } } return false; } } </code></pre> <p>Any thoughts on improving the code are welcome.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T16:25:44.590", "Id": "21417", "Score": "0", "body": "I'm not really sure I understand what you are trying to accomplish here... Maybe [this](http://us3.php.net/manual/en/function.gettype.php) will help?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T18:16:07.213", "Id": "21463", "Score": "0", "body": "Thank you for the comment. The class is supposed to be used for other class property values. For example MySqlColumn::Type property should be one of the above constants. It would be ideal if I could use a type hint for MySqlColumn::Type getter method, but I think this is not possible without without having class instancess passed to it. My workaround is to use the static method (Defines) to check if a value passed to a property getter is valid, which is not ideal." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T18:43:05.113", "Id": "21465", "Score": "0", "body": "Alright... I think I'm beginning to understand, though I still feel like I'm holding a match in a dark room. Anyways, have you tried `mysql_field_type()`? This seems like it accomplishes what you are trying to do. Which, if I understand you correctly, is simply to retrieve the data type from a MySQL result. If you are trying to limit these types to the list that you provided, I think the easiest way would be to check it while fetching it and throw an error or return FALSE if not of the right type, rather than try to filter it after already being set." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T18:55:32.297", "Id": "21468", "Score": "0", "body": "Sorry for not being clear. I have a PHP class that represents a MySql column that would help me (along with a class that represents a table) dynamically generate and execute MySql DDL statements, like CREATE TABLE, ALTER TABLE etc. One of my column class property is Type which value should be limited to one of MySql data types. Having an enum (like in JAVA or C#) would be ideal for this because if a wrong value is passed to Column::get_Type() it would simply throw an exception. But according to the SO discussion I linked in my post you can't really have enums in PHP so the above class is my..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T18:59:27.533", "Id": "21469", "Score": "0", "body": "...replacement. It works but it is not ideal because I can't use it for a type hint (function get_Type(DataType $value) will not work because I don't create DataType instances, I just use class constants) This is why I added a static function DataType::Defines(), I use it in my getter to check if a value is one of the DataType constants. This works, but I'm not really happy with it, this is why I posted the code for review. Thanks." } ]
[ { "body": "<p>Why not just pass the data type you are looking for as a second argument to <code>get_Type()</code> then call the <code>Defines()</code> or similar method inside to verify it is the correct type? You can even provide a default data type should you use one more frequently.</p>\n\n<pre><code>function get_Type( $value, $DataType = VARCHAR ) {\n if( ! $this-&gt;Defines( $DataType ) ) { return FALSE; }\n\n //rest of method\n}\n</code></pre>\n\n<p>Since you only want to test a given \"DataType\", I'd rewrite <code>Defines()</code> to use <code>in_array()</code> rather than loop through all the constants manually. Which BTW, you don't need to declare the <code>$key=&gt;</code> bit in a foreach loop unless you are actually going to use the key. </p>\n\n<pre><code>function Defines( $const ) { return in_array( $const, $this-&gt;getConstants() ); }\n</code></pre>\n\n<p>I wrote this non-static, don't know if it needs to be static or not, but I tend to avoid static if at all possible.</p>\n\n<p>I'd also like to point out that your method names conflict with PHP functions or aren't very descriptive. With the former you run the chance of your code conflicting with something else, or confusing people as to its purpose. With the latter you just confuse people. <code>define()</code> is a PHP function, so <code>Defines()</code> is close enough that it might cause issues or become confusing. <code>get_Type()</code> looks too much like you are fetching the data type rather than comparing it.</p>\n\n<p>I hope this answer helps, if not then I'd add those last two comments to your actual question so more people might be able to help. That's what helped me to understand what you were trying to accomplish a lot better than the original explanation. If I actually understood it. Anyways, it seems much clearer now. Good Luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T17:37:56.567", "Id": "21514", "Score": "0", "body": "Thank you for the answer. Both points taken, choosing function names and not iterating the constants array manually. I'm still learning PHP so I tend to overlook common functions." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T20:25:25.763", "Id": "13292", "ParentId": "13093", "Score": "2" } } ]
{ "AcceptedAnswerId": "13292", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T19:31:04.303", "Id": "13093", "Score": "3", "Tags": [ "php", "enum", "constants" ], "Title": "Class to simulate enums in PHP" }
13093
<p>I am looking to refactor the three lines of code in the else part of the conditional, you'll see where I have it commented.</p> <p>You'll notice a naming convention for the id's: id, id-div, as seen in the first line: club-community-service, club-community-service-id</p> <p>I want to shorten that up. I thought maybe storing all names into an array, then looping thru them like (below). If there is a better way to go about this, I am all ears, thanks!</p> <pre><code>//in theory array names = [names...]; foreach(names as n) { $("#" + n + "-div").toggle($("#" + n).get(0).checked); } $('#high-school-student').bind('click', function() { if($("input[id=high-school-student]").is(":checked")) { $('.field.full.club-community-service, .field.full.other-campus-activities, .field.full.community-public-service, .field.full.other-community-event-activity, .field.honors-program, .field.full.out-of-hs-5-years').hide(); $('#club-community-service-div, #other-campus-activities-div, #community-public-service-div, #other-community-event-activity-div').hide(); } else { $('.field.full.club-community-service, .field.full.other-campus-activities, .field.full.community-public-service, .field.full.other-community-event-activity, .field.honors-program, .field.full.out-of-hs-5-years').show(); // ------ RIGHT HERE - best way to refactor these next three lines $("#club-community-service-div").toggle($('#club-community-service').get(0).checked); $("#other-campus-activities-div").toggle($('#other-campus-activities').get(0).checked); $("#community-public-service-div").toggle($('#community-public-service').get(0).checked); } }); $('.watch-for-toggle').bind('click', function() { var id = $(this).attr('id'); $('#' + id + '-div').toggle(); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-05T13:34:37.487", "Id": "195378", "Score": "1", "body": "As we all want to make our code more efficient or improve it in one way or another, try to write a title that summarizes what your code does, not what you want to get out of a review. For examples of good titles, check out [Best of Code Review 2014 - Best Question Title Category](http://meta.codereview.stackexchange.com/q/3883/23788) You may also want to read [How to get the best value out of Code Review - Asking Questions](http://meta.codereview.stackexchange.com/a/2438/41243)." } ]
[ { "body": "<p>If you have control over the <code>div</code> tags and can make the html something like this:</p>\n\n<pre><code>&lt;div id='club-community-service-div' data-rel='club-community-service' class='check-toggle'&gt;\n</code></pre>\n\n<p>then you can do something like this:</p>\n\n<pre><code>$('.check-toggle').toggle(function () { return document.getElementById($(this).data('rel')).checked; });\n</code></pre>\n\n<p>However, a much better change to this code would be to cache the various DOM traversals.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T02:51:32.997", "Id": "13106", "ParentId": "13095", "Score": "4" } }, { "body": "<p>I didn't figure out a way to shorten those three lines without being too tangled (without modifying the html), but I would rewrite your code in this way:</p>\n\n<pre><code>$('#high-school-student').bind('click', function() {\n\n var highSchoolStudent = $(this).is(\":checked\");\n $('.field.full.club-community-service, .field.full.other-campus-activities, .field.full.community-public-service, .field.full.other-community-event-activity, .field.honors-program, .field.full.out-of-hs-5-years').toggle(!highSchoolStudent);\n\n if (highSchoolStudent) { \n\n $('#club-community-service-div, #other-campus-activities-div, #community-public-service-div, #other-community-event-activity-div').hide();\n\n } else {\n\n //Use a multiselector, convert the result to array and iterate over it.\n //I used replace to remove the '-div'. A regular expression would be a more elegant solution.\n $.each($('#club-community-service-div, #other-campus-activities-div, #community-public-service-div').toArray(), function(i,v) { \n $(v).toggle($(v.id.replace('-div', '')).is(':checked'))\n });​​​​​​​​​​​​​​​​​​​\n\n }\n\n});\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T09:24:34.373", "Id": "21202", "Score": "1", "body": "You can do `$('#foo, #bar').each(function(elem() {});`, it's better and more concise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T16:01:32.127", "Id": "21249", "Score": "0", "body": "@ANeves is right. You can use: \n`$('#club-community-service-div, #other-campus-activities-div, #community-public-service-div').each(function(i,elem) {$(elem).toggle(elem.id.replace('-div',''))});`" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T06:34:16.080", "Id": "13112", "ParentId": "13095", "Score": "3" } }, { "body": "<p>@BillBarry proposes a good way to address your problem.</p>\n\n<h2>Other improvements</h2>\n\n<ol>\n<li>Write <code>$(\"input#high-school-student\")</code> instead of <code>$(\"input[id=high-school-student]\")</code>;</li>\n<li>But in your particular use, write <code>$(this)</code>, since the element is the one raising the event;</li>\n<li>Use JQuery 1.7's <code>.on()</code> instead of <code>.bind()</code>;</li>\n<li>What if the checkbox changes without being clicked? You should bind to other events as well: <code>input</code> (mind IE!), <code>change</code>, etc.</li>\n<li>You can use <code>.toggle(bool)</code> to show/hide the element list, instead of doing the if and repeating the selector;</li>\n<li>You should <strong>cache and re-use</strong> the JQuery DOM elements, where possible, instead of repeatedly getting them (but avoid polluting the global scope);</li>\n<li>Naming an id <code>foo-div</code> raises alarm bells, it's \"hungarian notation\" for HTML! Why aren't you just targeting <code>#foo &gt; div</code> or <code>#foo div</code> instead?? Even if you have other divs in there, you can give it a class - <code>#foo &gt; .bar</code>. Or if it's adjacent, <code>#foo + div</code>. Etc.;</li>\n</ol>\n\n<p>5:</p>\n\n<pre><code>var isHighSchoolStudent = $(this).is(':checked');\n$('.field.full.club-community-service, .field.full.other-campus-activities, .field.full.community-public-service, .field.full.other-community-event-activity, .field.honors-program, .field.full.out-of-hs-5-years'\n ).toggle(!isHighSchoolStudent);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T09:30:36.220", "Id": "13116", "ParentId": "13095", "Score": "1" } } ]
{ "AcceptedAnswerId": "13112", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T20:07:15.867", "Id": "13095", "Score": "-1", "Tags": [ "javascript", "jquery" ], "Title": "refactor 3 lines of javascript to minimize code" }
13095
<p>This function combines a Twitter feed and an Instagram feed and sorts the items by date. I just want to write better, more efficient code, so any tips on how to transform this into more of a "pro" JavaScript function would be much appreciated! Would it work to combine all these functions into one namespace?</p> <p>The result of this code can be seen <a href="http://fwy.pagodabox.com/" rel="nofollow">here</a> (scroll down, it's in the right sidebar)</p> <pre><code>function extract_relative_time(date) { var toInt = function(val) { return parseInt(val, 10); }; var relative_to = new Date(); var delta = toInt((relative_to.getTime() - date) / 1000); if (delta &lt; 1) delta = 0; return { days: toInt(delta / 86400), hours: toInt(delta / 3600), minutes: toInt(delta / 60), seconds: toInt(delta) }; } function format_relative_time(time_ago) { if ( time_ago.days &gt; 2 ) return 'about ' + time_ago.days + ' days ago'; if ( time_ago.hours &gt; 24 ) return 'about a day ago'; if ( time_ago.hours &gt; 2 ) return 'about ' + time_ago.hours + ' hours ago'; if ( time_ago.minutes &gt; 45 ) return 'about an hour ago'; if ( time_ago.minutes &gt; 2 ) return 'about ' + time_ago.minutes + ' minutes ago'; if ( time_ago.seconds &gt; 1 ) return 'about ' + time_ago.seconds + ' seconds ago'; return 'just now'; } $j(document).ready(function($){ var fwyFeed = [], feedIndex, feedResponse, feedHeight, feedOutput = '', user = 'friendswithyou', $feedBox = $('.fwy-feed-content'), $feedWrap = $('.fwy-feed'), $feedLoad = $('.fwy-feed-load'), $imgWrap, $imgs, imgLen; $feedWrap.find('h2').html('Loading Feed... &lt;span class="fwy-feed-load ic-icon fr f16"&gt;$&lt;/span&gt;'); // Get instagram feed $.ajax({ type: "GET", dataType: "jsonp", cache: false, url: "https://api.instagram.com/v1/users/5774772/media/recent/?access_token=5774772.cf44785.bdf87268cff04f98b33581ad4ef60732", success: function(data) { for (var i = 0; i &lt; 3; i++) { var thedata = data.data[i], created = thedata.created_time*1000, url = thedata.images.low_resolution.url, link = thedata.link; fwyFeed[i] = {}; fwyFeed[i]["type"] = 'photo'; fwyFeed[i]["created"] = created; fwyFeed[i]["text"] = url; fwyFeed[i]["link"] = link; fwyFeed[i]["date"] = format_relative_time(extract_relative_time(created)); } } }); // Wait 1.25 seconds for the instagram request to return window.setTimeout(function() { feedIndex = fwyFeed.length; $.getJSON('http://twitter.com/statuses/user_timeline.json?screen_name=' + user + '&amp;count=5&amp;callback=?', function(data) { for (i = 0; i &lt; data.length; i++) { var thedata = data[i], created = data[i].created_at, id = thedata.id_str, tweetDex = i + 1 + feedIndex; // Twitter time object given in human time, convert to timestamp created = new Date(created); created = created.getTime(); created = created.toString(); fwyFeed[tweetDex] = {}; fwyFeed[tweetDex]["type"] = 'tweet'; fwyFeed[tweetDex]["created"] = created; fwyFeed[tweetDex]["text"] = thedata.text; fwyFeed[tweetDex]["link"] = id; fwyFeed[tweetDex]["date"] = format_relative_time(extract_relative_time(created)); } }); // Wait 1.25 seconds for the twitter request to return window.setTimeout(function() { // Sort our feed array by time fwyFeed.sort(function(a,b) { return parseInt(b.created,10) - parseInt(a.created,10); }); // Loop through each tweet/photo for (var i = 0; i &lt; fwyFeed.length; i++) { if(i in fwyFeed) { var type = fwyFeed[i]["type"], created = fwyFeed[i]["created"], text = fwyFeed[i]["text"], link = fwyFeed[i]["link"], date = fwyFeed[i]["date"]; if(type === 'photo') { feedOutput += '&lt;div class="bbd fwy-feed-item fwy-feed-photo"&gt;&lt;a class="bgpale img-wrap pr ic-img block" target="_blank" href="' + link + '"&gt;&lt;img class="pr img-loading center block" src="' + text + '" /&gt;&lt;/a&gt;&lt;a href="' + link + '" class="cpink f11" target="_blank"&gt;' + date + '&lt;/a&gt;&lt;/div&gt;'; } else { feedOutput += '&lt;div class="group bbd fwy-feed-item fwy-feed-tweet"&gt;&lt;p class="f11"&gt;' + text + ' &lt;a target="_blank" class="cpink" href="http://twitter.com/Friendswithyou/status/' + link + '"&gt;' + date + '&lt;/a&gt;&lt;/p&gt;'; feedOutput += '&lt;div class="fr fwy-feed-share tdn"&gt;'; feedOutput += '&lt;a href="http://twitter.com/intent/tweet?in_reply_to=' + link + '" target="_blank" class="ic-reply"&gt;&lt;/a&gt;'; feedOutput += '&lt;a href="http://twitter.com/intent/retweet?tweet_id=' + link + '" target="_blank" class="ic-retweet pr"&gt;&lt;/a&gt;'; feedOutput += '&lt;a href="http://twitter.com/intent/favorite?tweet_id=' + link + '" target="_blank" class="ic-fav"&gt;&lt;/a&gt;'; feedOutput += '&lt;/div&gt;'; feedOutput += '&lt;/div&gt;'; } } } if(feedOutput){ $feedBox.append(feedOutput); $imgs = $feedBox.find('img'); imgLen = $imgs.length; $feedBox.addClass('show'); // Fade in images if(imgLen &gt; 0) { $imgs.imgpreload({ each: function(){ $(this).removeClass('img-loading'); }, all: function() { $feedWrap.addClass('loaded').find('h2').html('tweet/instagram'); $feedLoad.remove(); } }); } } else { $feedWrap.addClass('loaded error').find('h2').html('Error loading feed'); } }, 1250); }, 1250); }); </code></pre>
[]
[ { "body": "<p><a href=\"https://codereview.stackexchange.com/questions/11233/optimizing-and-consolidating-a-big-jquery-function/11235#11235\">Starting with the steps here</a>, I am left with <a href=\"http://jsfiddle.net/Qt5Ns/\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>From here the first thing I notice is that you are abusing <code>window.setTimeout</code> in order to do something with the ajax responses. This is leaving you with some pretty nasty arrow code and what happens if it takes more than 1.25 seconds for either of those sites to return?</p>\n\n<p>I'll start by making the inner timeout into a named function, for now calling it <code>render</code>:</p>\n\n<pre><code>function render(fwyFeed, $feedBox, $feedWrap) {\n var i,\n type,\n created,\n text,\n link,\n date,\n feedOutput='',\n $imgs,\n imgLen;\n\n // Sort our feed array by time\n fwyFeed.sort(function (a, b) {\n return +b.created - +a.created;\n });\n\n // Loop through each tweet/photo\n for (i = 0; i &lt; fwyFeed.length; i += 1) {\n if (fwyFeed[i]) {\n type = fwyFeed[i].type;\n created = fwyFeed[i].created;\n text = fwyFeed[i].text;\n link = fwyFeed[i].link;\n date = fwyFeed[i].date;\n\n if (type === 'photo') {\n feedOutput += '&lt;div class=\"bbd fwy-feed-item fwy-feed-photo\"&gt;&lt;a class=\"bgpale img-wrap pr ic-img block\" target=\"_blank\" href=\"' + link + '\"&gt;&lt;img class=\"pr img-loading center block\" src=\"' + text + '\" /&gt;&lt;/a&gt;&lt;a href=\"' + link + '\" class=\"cpink f11\" target=\"_blank\"&gt;' + date + '&lt;/a&gt;&lt;/div&gt;';\n } else {\n feedOutput += '&lt;div class=\"group bbd fwy-feed-item fwy-feed-tweet\"&gt;&lt;p class=\"f11\"&gt;' + text + ' &lt;a target=\"_blank\" class=\"cpink\" href=\"http://twitter.com/Friendswithyou/status/' + link + '\"&gt;' + date + '&lt;/a&gt;&lt;/p&gt;';\n feedOutput += '&lt;div class=\"fr fwy-feed-share tdn\"&gt;';\n feedOutput += '&lt;a href=\"http://twitter.com/intent/tweet?in_reply_to=' + link + '\" target=\"_blank\" class=\"ic-reply\"&gt;&lt;/a&gt;';\n feedOutput += '&lt;a href=\"http://twitter.com/intent/retweet?tweet_id=' + link + '\" target=\"_blank\" class=\"ic-retweet pr\"&gt;&lt;/a&gt;';\n feedOutput += '&lt;a href=\"http://twitter.com/intent/favorite?tweet_id=' + link + '\" target=\"_blank\" class=\"ic-fav\"&gt;&lt;/a&gt;';\n feedOutput += '&lt;/div&gt;';\n feedOutput += '&lt;/div&gt;';\n }\n }\n }\n\n if (feedOutput) {\n $feedBox.append(feedOutput);\n $imgs = $feedBox.find('img');\n imgLen = $imgs.length;\n $feedBox.addClass('show');\n\n // Fade in images\n if (imgLen &gt; 0) {\n $imgs.imgpreload({\n each: function () {\n $(this).removeClass('img-loading');\n },\n all: function () {\n $feedWrap.addClass('loaded').find('h2').html('tweet/instagram');\n }\n });\n }\n } else {\n $feedWrap.addClass('loaded error').find('h2').html('Error loading feed');\n }\n}\n</code></pre>\n\n<p>and replace the <code>setTimeout</code> with:</p>\n\n<pre><code>window.setTimeout(function () { render(fwyFeed, $feedBox, $feedWrap); }, 1250);\n</code></pre>\n\n<p>This I would then append it to the getJSON twitter call:</p>\n\n<pre><code>$.getJSON(...\n ...\n}).then(function () { render(fwyFeed, $feedBox, $feedWrap); });\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/Qt5Ns/1/\" rel=\"nofollow noreferrer\">Full result so far</a></p>\n\n<p>The next change I would make would be to change <code>fwyFeed[i] =</code> into <code>fwyFeed.push(</code> so that you don't need to concern yourself with its length so much.</p>\n\n<p>The next change I would make would be to change the logic of:</p>\n\n<pre><code>$.ajax({\n ...\n});\n\nwindow.setTimeout(function () {\n $.getJSON(...\n ...\n }).then(function () { render(fwyFeed, $feedBox, $feedWrap); }); \n}, 1250);\n</code></pre>\n\n<p>Knowing that both <code>$.ajax</code> and <code>$.getJSON</code> return <a href=\"http://api.jquery.com/category/deferred-object/\" rel=\"nofollow noreferrer\">deferred objects</a>. This can be written as:</p>\n\n<pre><code>$.when(\n $.ajax({\n ...\n }),\n $.getJSON(...\n ...\n })\n).then(function () { render(fwyFeed, $feedBox, $feedWrap); }); \n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/Qt5Ns/3/\" rel=\"nofollow noreferrer\">Which already looks significantly cleaner.</a></p>\n\n<p>Afterword I would name the functions which take the data from instagram and twitter and move them out of the ajax promises (naming them <code>addInstagram</code> and <code>addTwitter</code> respectively). I'd also change the instagram call to use <code>getJSON</code> to be more consistent and I'd make these string urls into constant variables defined at the top of the script. This would leave me with the ajax logic:</p>\n\n<pre><code>$.when(\n $.getJSON(instagram, addInstagram),\n $.getJSON(twitter, addTwitter)\n).then(function () { render(fwyFeed, $feedBox, $feedWrap); });\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/Qt5Ns/4/\" rel=\"nofollow noreferrer\">Leaving us with this.</a></p>\n\n<p>The next puzzle here is the fact that you shouldn't need to wait for the page to be ready before making these requests. If we store these promises in a variable we can move them out of the <code>ready</code> event function (along with the <code>fwyFeed</code> variable and the two functions). This leaves the full <code>ready</code> event function as:</p>\n\n<pre><code>$(function () {\n var $feedBox = $('.fwy-feed-content'),\n $feedWrap = $('.fwy-feed');\n\n $feedWrap.find('h2').html('Loading Feed... &lt;span class=\"fwy-feed-load ic-icon fr f16\"&gt;$&lt;/span&gt;');\n requests.then(function () { render(fwyFeed, $feedBox, $feedWrap); });\n});\n</code></pre>\n\n<p>Much more can be done:</p>\n\n<ul>\n<li>make the render function nicer</li>\n<li>doing something about how that <code>h2</code> tag is all over the place</li>\n<li>the <code>$feedBox</code> and <code>$feedWrap</code> variables can probably be written with better selectors</li>\n<li>could be nice to be able to add other services in an easier manner</li>\n</ul>\n\n<p><a href=\"http://jsfiddle.net/Qt5Ns/5/\" rel=\"nofollow noreferrer\">Full result:</a></p>\n\n<pre><code>(function ($, Date, Math) {\n 'use strict';\n\n var instagram = \"https://api.instagram.com/v1/users/5774772/media/recent/?access_token=5774772.cf44785.bdf87268cff04f98b33581ad4ef60732&amp;callback=?\",\n user = 'friendswithyou',\n twitter = 'http://twitter.com/statuses/user_timeline.json?screen_name=' + user + '&amp;count=5&amp;callback=?',\n fwyFeed = [],\n extract_relative_time = function (date) {\n var relative_to = new Date(),\n delta = (relative_to.getTime() - date) / 1000;\n\n return {\n days: Math.floor(delta / 86400),\n hours: Math.floor(delta / 3600),\n minutes: Math.floor(delta / 60),\n seconds: Math.floor(delta)\n };\n },\n format_relative_time = function (time_ago) {\n if (time_ago.days &gt; 2) { return 'about ' + time_ago.days + ' days ago'; }\n if (time_ago.hours &gt; 24) { return 'about a day ago'; }\n if (time_ago.hours &gt; 2) { return 'about ' + time_ago.hours + ' hours ago'; }\n if (time_ago.minutes &gt; 45) { return 'about an hour ago'; }\n if (time_ago.minutes &gt; 2) { return 'about ' + time_ago.minutes + ' minutes ago'; }\n if (time_ago.seconds &gt; 1) { return 'about ' + time_ago.seconds + ' seconds ago'; }\n return 'just now';\n },\n addInstagram = function (data) {\n var i, thedata, created, url, link;\n for (i = 0; i &lt; 3; i += 1) {\n thedata = data.data[i];\n created = +(thedata.created_time * 1000);\n url = thedata.images.low_resolution.url;\n link = thedata.link;\n\n fwyFeed.push({\n type: 'photo',\n created: created,\n text: url,\n link: link,\n date: format_relative_time(extract_relative_time(created))\n });\n }\n },\n addTwitter = function (data) {\n var i, thedata, created, id;\n\n for (i = 0; i &lt; data.length; i += 1) {\n thedata = data[i];\n created = data[i].created_at;\n id = thedata.id_str;\n\n // Twitter time object given in human time, convert to timestamp\n created = new Date(created);\n created = created.getTime();\n\n fwyFeed.push({\n type: 'tweet',\n created: created,\n text: thedata.text,\n link: id,\n date: format_relative_time(extract_relative_time(created))\n });\n }\n },\n requests = $.when(\n $.getJSON(instagram, addInstagram),\n $.getJSON(twitter, addTwitter)\n );\n\n function render(fwyFeed, $feedBox, $feedWrap) {\n var i,\n type,\n created,\n text,\n link,\n date,\n feedOutput = '',\n $imgs,\n imgLen;\n\n // Sort our feed array by time\n fwyFeed.sort(function (a, b) {\n return +b.created - +a.created;\n });\n\n // Loop through each tweet/photo\n for (i = 0; i &lt; fwyFeed.length; i += 1) {\n if (fwyFeed[i]) {\n type = fwyFeed[i].type;\n created = fwyFeed[i].created;\n text = fwyFeed[i].text;\n link = fwyFeed[i].link;\n date = fwyFeed[i].date;\n\n if (type === 'photo') {\n feedOutput += '&lt;div class=\"bbd fwy-feed-item fwy-feed-photo\"&gt;&lt;a class=\"bgpale img-wrap pr ic-img block\" target=\"_blank\" href=\"' + link + '\"&gt;&lt;img class=\"pr img-loading center block\" src=\"' + text + '\" /&gt;&lt;/a&gt;&lt;a href=\"' + link + '\" class=\"cpink f11\" target=\"_blank\"&gt;' + date + '&lt;/a&gt;&lt;/div&gt;';\n } else {\n feedOutput += '&lt;div class=\"group bbd fwy-feed-item fwy-feed-tweet\"&gt;&lt;p class=\"f11\"&gt;' + text + ' &lt;a target=\"_blank\" class=\"cpink\" href=\"http://twitter.com/Friendswithyou/status/' + link + '\"&gt;' + date + '&lt;/a&gt;&lt;/p&gt;';\n feedOutput += '&lt;div class=\"fr fwy-feed-share tdn\"&gt;';\n feedOutput += '&lt;a href=\"http://twitter.com/intent/tweet?in_reply_to=' + link + '\" target=\"_blank\" class=\"ic-reply\"&gt;&lt;/a&gt;';\n feedOutput += '&lt;a href=\"http://twitter.com/intent/retweet?tweet_id=' + link + '\" target=\"_blank\" class=\"ic-retweet pr\"&gt;&lt;/a&gt;';\n feedOutput += '&lt;a href=\"http://twitter.com/intent/favorite?tweet_id=' + link + '\" target=\"_blank\" class=\"ic-fav\"&gt;&lt;/a&gt;';\n feedOutput += '&lt;/div&gt;';\n feedOutput += '&lt;/div&gt;';\n }\n }\n }\n\n if (feedOutput) {\n $feedBox.append(feedOutput);\n $imgs = $feedBox.find('img');\n imgLen = $imgs.length;\n $feedBox.addClass('show');\n\n // Fade in images\n if (imgLen &gt; 0) {\n $imgs.imgpreload({\n each: function () {\n $(this).removeClass('img-loading');\n },\n all: function () {\n $feedWrap.addClass('loaded').find('h2').html('tweet/instagram');\n }\n });\n }\n } else {\n $feedWrap.addClass('loaded error').find('h2').html('Error loading feed');\n }\n }\n\n $(function () {\n var $feedBox = $('.fwy-feed-content'),\n $feedWrap = $('.fwy-feed');\n\n $feedWrap.find('h2').html('Loading Feed... &lt;span class=\"fwy-feed-load ic-icon fr f16\"&gt;$&lt;/span&gt;');\n requests.then(function () { render(fwyFeed, $feedBox, $feedWrap); });\n });\n}(jQuery, Date, Math));\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T00:46:12.067", "Id": "13103", "ParentId": "13096", "Score": "2" } } ]
{ "AcceptedAnswerId": "13103", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T20:53:07.073", "Id": "13096", "Score": "1", "Tags": [ "javascript", "jquery", "twitter", "instagram" ], "Title": "Combining Twitter and Instagram feeds" }
13096
<p>I'm quite new to JavaScript, and I'm trying to understand the idea behind inheritance in JavaScript. I've read a bit about it, and I don't want to mess with prototypes (which I don't yet fully understand) so, I wrote this code using the <a href="https://github.com/Raynos/xtend" rel="nofollow noreferrer"><code>xtend</code> module</a> for node.js.</p> <pre><code>var xtend = require("xtend"); // Human constructor. // Human is a base class, it can introduce itself, and knows it's age. function createHuman(name, age) { function getName() { return name; } function getAge() { return age; } return { getName : getName, getAge : getAge, }; } // Boy constructor // Boy *is a* Human // Boy can play football (but not yet) function createBoy(name, age) { function playFootball() { console.warn("Football skills not implemented yet, but trying", "-", this.getName()); // TODO: implement this } return xtend(createHuman(name, age), { playFootball: playFootball, }) } // Girl constructor // Girl *is a* Human // Girl can sing (well, almost) function createGirl(name, age) { function singASong() { console.warn("Singing not implemented yet, but trying", "-", this.getName()); // TODO: implement this } return xtend(createHuman(name, age), { singASong: singASong, }) } // Hermaphrodite constructor // Hermaphrodite *is a* Girl **and** Hermaphrodite *is a* Boy, so we have multiple inheritance? // Hermaphrodite can do what boys and girls can function createHermaphrodite(name, age) { return xtend(createGirl(name, age), createBoy(name, age)); } // Tests: var boy = createBoy("John", 12); var boy2 = createBoy("Frank", 10); var girl = createGirl("Daisy", 7); var herm = createHermaphrodite("Mel", 24); console.info("Boy: ", boy.getName(), boy.getAge()); console.info("Boy: ", boy2.getName(), boy2.getAge()); console.info("Girl: ", girl.getName(), girl.getAge()); console.info("Hermaphrodite: ", herm.getName(), herm.getAge()); boy.playFootball(); boy2.playFootball(); girl.singASong(); herm.playFootball(); herm.singASong(); </code></pre> <p>As you can see, I'm not using the usual <code>Class</code> approach, but instead have <em>a kind of</em> constructors that create objects. The inheritance is made using the <code>xtend</code> module, which copies properties from another objects. This - I think - also allows for multiple inheritance (see <code>Hermaphrodite</code>).</p> <p>Questions:</p> <ol> <li><p>Can this code be considered good practice? I always thought of JS as a more functional (than OO) language, so not trying to imitate classes, not using the <code>new</code> keyword and so on sounded good to me.</p></li> <li><p>Is this fast / memory-efficient? I mean - there is an additional object created every time the sub-class instance is created, just to copy the properties (for example, if I create a <code>Boy</code> instance, there is a <code>Human</code> created just to copy the properties to <code>Boy</code>).</p></li> <li><p>Is there a better / faster / more efficient (or simply: <em>proper</em>) way of doing this? (Pointing to one, remember that I'm a beginner, so be descriptive or I might not understand the answer.)</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:07:38.193", "Id": "21212", "Score": "2", "body": "To learn how to create factory objects, try reading Addy Osmoni's \"JavaScript Design Patterns\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:56:57.593", "Id": "21221", "Score": "0", "body": "Wow, this is really something. I've also found the [Eloquent JavaScript](http://eloquentjavascript.net/contents.html). Going to have a lot to read, thank you!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T20:00:07.640", "Id": "21597", "Score": "0", "body": "The first question of the day that made me laugh :) if you're playing about with inheritance, prototypes really aren't that difficult. I'd suggest you take a look into them." } ]
[ { "body": "<p>The real problem with this is that if you create a lot of objects with this, each Human has its own copies of the <code>getName()</code> and <code>getAge()</code> functions, each Boy has his own copy of the <code>playFootball()</code> function, and each Girl has her own copy of the <code>singASong()</code> function.</p>\n\n<p>The power of prototypes is that they allow multiple objects to share these functions, to share even the references to these functions, each carrying only a single reference to its prototype object, which then contains the references to these shared functions.</p>\n\n<p>There is nothing inherently wrong with what you're doing. But it uses tremendously more memory than a prototype-based solution would. It's not good for situations where you want many thousands or millions of such objects.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T19:55:14.660", "Id": "13374", "ParentId": "13098", "Score": "1" } }, { "body": "<p>Q1: I wouldn't say it was good or particularly bad practice for some of the reasons I will go into below.</p>\n\n<p>Q2: It's not memory efficient if you compare the code you have to a class / prototype based solution.</p>\n\n<p>Q3: Take a look below, i've tried to keep it to as skeletal structure as possible to demonstrate how prototypes can be very useful.</p>\n\n<p><strong>xtend</strong></p>\n\n<p>xtend is great for smaller, intricate pieces of code and it has helped me loads recently. The caveat: In larger code bases you want to avoid the level of blind inheritance that xtend provides. Potentially in the future you may create a class that uses an object that has many layers of inheritance as an array of options for example. When that object squares up to the media and asked it's name and occupation, how does it know where all its components came from and what they do? In your code, how does the boy know he's a boy as well as a human for example.</p>\n\n<p><strong>Public / Private Methods</strong></p>\n\n<p><a href=\"http://phrogz.net/js/classes/OOPinJS.html\" rel=\"nofollow\">OOP in JS : Public / Private Variables</a> will explain alot, if you are used to OOP in other languages this will probably click straight away.</p>\n\n<p>Your first function is a class constructor with two private methods declared. I prefer to only set information in a constructor and then use public methods (prototypes) to deal with the workload.</p>\n\n<p><strong>Prototypes</strong></p>\n\n<p>Many objects can use prototypes and they're never duplicated within each object that is created.</p>\n\n<p>Take this piece of code for example, first the class structure:</p>\n\n<pre><code>function CreateHuman(params) {\n // We create a new human object using params as initial data\n this.human = {\n name : params.name,\n age : params.age,\n gender : 'unknown'\n }\n}\n\n// first prototype, updates the gender with the one specified in the call\nCreateHuman.prototype.setGender = function (gender) {\n this.human.gender = gender;\n}\n\nCreateHuman.prototype.setName = function (name) {\n this.human.name = name;\n} \n\nCreateHuman.prototype.setAge = function (age) {\n this.human.age = age;\n}\n\n// this method does more work than any of the others\nCreateHuman.prototype.setHobby = function() {\n\n // If the gender has been set, the hobby will be applied\n // You could use functions here as well\n\n switch(this.gender) {\n case('male') :\n this.person.hobby = 'football';\n this.person.hobbyActive = (this.age &gt;= 6) ? true : false;\n break;\n case('female') :\n this.person.hobby = 'singing';\n this.person.hobbyActive = (this.age &gt;= 4) ? true : false;\n break;\n deafult :\n this.person.hobby = 'no hobby';\n this.person.hobbyActive = true;\n }\n}\n\n// And a return method to get the object from the class\nCreateHuman.prototype.getPerson = function() {\n return this.person; // We return the object with all collected data\n}\n</code></pre>\n\n<p>We could then use the class very easily to create a number of humans with different names, ages and genders.</p>\n\n<pre><code>var params = \n{\n name : \"Dave\",\n age : 30\n};\n</code></pre>\n\n<p>I've included the <code>params</code> in this example as you may just need one object created and feeding it params is an easy way to make sure your code is useable by anyone else that might use your class.</p>\n\n<pre><code>var human = new CreateHuman(params);\nvar people = {}; // Make people an object to hold all the humans created\n\n// Call our first prototype function\nhuman.setGender('male');\n// 2nd prototype\nhuman.setHobby();\n\npeople.human1 = human.getPerson();\n</code></pre>\n\n<p><code>people.human1</code> if logged in the console would be:</p>\n\n<pre><code>Object {name : 'dave', \n age : 30, \n gender : 'male',\n hobby : 'football', \n hobbyActive : true\n } \n</code></pre>\n\n<p>Start again:</p>\n\n<pre><code>human.setName('Alexa');\nhuman.setAge(28);\nhuman.setGender('female');\nhuman.setHobby();\n\npeople.human2 = human.getPerson()\n\n// And so on\n</code></pre>\n\n<p>I hope that gives you an insight into prototypes, they will be far more useful to you than object inheritance (though I admit it does have its uses).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T07:38:02.667", "Id": "21756", "Score": "0", "body": "Thanks for the excellent explanation! But is it possible to _easily_ do multiple inheritance with prototypes? I've found some examples (like [this one](http://www.steinbit.org/words/programming/multiple-inheritance-in-javascript)) but they seam terribly complicated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-09T10:33:50.533", "Id": "21759", "Score": "0", "body": "@npe I'm sorry to say that JS just doesn't support multiple inheritance natively. If we think about it in detail, with no native support, There has to be a mechanism to copy / reference all parents prototypes, parents parents prototypes etc. and so on... it's never going to have an easy solution." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T20:52:48.773", "Id": "13376", "ParentId": "13098", "Score": "4" } }, { "body": "<p>If you try to make multiple inheritance in JavaScript, you should take a look at this library: <a href=\"http://ringjs.neoname.eu/\" rel=\"nofollow\">Ring.js</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-07-16T20:30:59.340", "Id": "28587", "ParentId": "13098", "Score": "1" } } ]
{ "AcceptedAnswerId": "13376", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-26T22:09:17.773", "Id": "13098", "Score": "4", "Tags": [ "javascript", "object-oriented", "node.js" ], "Title": "JavaScript (multiple) inheritance / mixins" }
13098
<p>What are some advantages and disadvantages of providing default implementations for dependencies. I have chosen to do this because it allows the objects to be easily used in the application but also allows me to mock for unit testing.</p> <pre><code>public class RoleProvider : RoleProviderBase { private IRoleDataProvider _roleDataProvider; private IEntitlementsDataProvider EntitlementsDataProvider { get { if (_roleDataProvider == null) { _roleDataProvider = new RoleDataProvider(); } return _roleDataProvider; } } public RoleProvider(IRoleDataProvider roleDataProvider) { _roleDataProvider = roleDataProvider; } public RoleProvider() { } } </code></pre>
[]
[ { "body": "<p>I personally don't see any problem with this (maybe someone else might provide better insight) but in this situation I do tend to do it differently but instantiating it via constructor overloading and making the private field readonly.</p>\n\n<p>e.g. </p>\n\n<pre><code>public class RoleProvider : RoleProviderBase\n{\n private readonly IRoleDataProvider _roleDataProvider;\n\n public RoleProvider()\n : this(new RoleDataProvider())\n {\n }\n\n public RoleProvider(IRoleDataProvider roleDataProvider)\n {\n _roleDataProvider = roleDataProvider;\n }\n}\n</code></pre>\n\n<p>Perhaps this question might be better asked on PE as well?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T00:16:05.753", "Id": "13101", "ParentId": "13099", "Score": "5" } }, { "body": "<p>The idea is very practical and makes it much easier to reuse the class. It's also easy to test or even substitute very different implementations of composite components on demand in production code.<br>\nHowever, I do have a few suggestions worth considering when doing this sort of thing.</p>\n\n<p><strong>There's no need to code the substitution mechanism until you actually need it for your first test.</strong></p>\n\n<p>So start out with only the parameterless constructor.\nUntil then, the additional code would just be clutter. (I.e. don't add stuff automatically just because you might need it.)</p>\n\n<p><strong>The lazy initialization approach you used isn't thread-safe, so you may want to consider coding the parameterless constructor as follows.</strong></p>\n\n<p>This is of course assuming that the either the composite object will always be used or is 'cheap' to construct. Otherwise you might want to look into a thread-safe lazy initialization technique or ensure the object is not shared across multiple threads.</p>\n\n<pre><code>public RoleProvider()\n{\n _roleDataProvider = new RoleDataProvider();\n}\n</code></pre>\n\n<p><strong>Watch out for the possibility of circular dependencies.</strong></p>\n\n<p>A typical programming problem is handling circular dependencies. This technique can be exposed to that risk, because you're not explicitly specifying the dependencies at construction time. E.g. </p>\n\n<pre><code>new A(); //automatically creates default B which automatically creates default A etc.\n</code></pre>\n\n<p>Whereas forcing the composite object to be provided in the constructor avoids the risk.</p>\n\n<pre><code>//Assuming X and B share a common ancestor which \n//is required as input to A's constructor.\nx = new X(); //Truly doesn't have composite objects.\na1 = new A(x);\nb = new B(a1);\na1 = new A(b);\n</code></pre>\n\n<p>Note that it's impossible to code infinite circular construction dependencies this way.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T09:32:45.507", "Id": "13117", "ParentId": "13099", "Score": "1" } } ]
{ "AcceptedAnswerId": "13117", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T00:03:18.920", "Id": "13099", "Score": "3", "Tags": [ "c#" ], "Title": "Defaulting dependencies" }
13099
<p>This is continuation and implementation of feedback found in this post: <a href="https://codereview.stackexchange.com/questions/12757/basic-user-registration-code-in-php">Basic user registration code</a></p> <p>I just began to use the PDO object, I'm not sure if i'm using it efficiently. Are there any security issues? Is the <code>myEncrypt</code> function suitable enough or still a bit lacking?</p> <p><strong>initialise.php:</strong></p> <pre><code>try { $db = new PDO("mysql:host=$db_hostname;dbname=$db_database", $db_username, $db_password); } catch(PDOException $e) { echo "Failed to connect to server"; } function myEncrypt($password){ $i = "$password"."$salt1"; $hash1 = md5($i); $j = "$salt2"."$hash1"; $hash2 = md5($j); return $hash2; } </code></pre> <p><strong>Registration.php:</strong></p> <pre><code>require 'initialise.php'; //View - Leaving this as is for now. Haven't learnt css/html in depth yet. echo &lt;&lt;&lt;_REGFORM &lt;form align=center action="registration.php" method ="post"&gt;&lt;pre&gt; Register an account: Username &lt;input type="text" name="regusername"/&gt; Password &lt;input type="password" name="regpassword"/&gt; Retype Password &lt;input type="password" name ="checkregpassword"/&gt; &lt;input type="submit" value="Register"/&gt; &lt;/pre&gt;&lt;/form&gt; _REGFORM; //Checks inputs for length requirements, if two passwords are the same, if filter was successful if ($_SERVER['REQUEST_METHOD'] === "POST") { filter_input(INPUT_POST, $_POST, FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE); $usernameclean = $_POST['regusername']; $password = $_POST['regpassword']; $checkpassword = $_POST['checkregpassword']; if (isset($username, $password, $checkpassword)) { if (strlen($username) &lt; 5) { $errors['username'][] = "Usernames must be at least 5 characters in length."; } if (strlen($username) &gt; 32) { $errors['username'][] = "Usernames have a maximum limit of 32 characters."; } if (strlen($password) &lt; 5) { $errors['password'][] = "Passwords must be at least 5 characters in length."; } if ($password &lt;&gt; $checkpassword) { $errors['password'][] = "Your passwords must be the same."; } } if (!count($errors)) { $hashedpassword = myEncrypt($password); //function defined in initialise.php $checkUsername_query = "SELECT user_id FROM users WHERE username='$usernameclean'"; $checkUsername_result = $db-&gt;query($checkUsername_query)-&gt;fetch(); if (!$checkUsername_result) { //SETS UP USER ACCOUNTS, DEFINES 5 FILE SLOTS try { $db-&gt;beginTransaction(); $createUser_query = "INSERT INTO users(username,password) VALUES('$usernameclean','$hashedpassword')"; $createUser_result = $db-&gt;exec($createUser_query); $getuserid_query = "SELECT user_id FROM users WHERE username='$usernameclean'"; $getuserid = $db-&gt;query($getuserid_query); $user_id = $getuserid-&gt;fetch(); //ASSIGNS 5 File slots into "files" (File-information) for ($i = 1; $i &lt;= 5; $i++) { $assignfileslots = "INSERT INTO files(user_id) VALUES('$user_id[0]')"; $db-&gt;exec($assignfileslots); } $db-&gt;commit(); echo "Thanks " . htmlspecialchars($usernameclean) . ", your account has been created! Please login.&lt;br/&gt;"; } catch (PDOException $e) { $db-&gt;rollback(); echo "Your account could not be created, please try again later."; } } else { echo "Username Unavailable, please try another username"; } } if (count($errors)) { echo '&lt;ul&gt;'; foreach ($errors as $elements =&gt; $errs) { foreach ($errs as $err) { echo '&lt;li&gt;' . htmlspecialchars($err) . '&lt;/li&gt;'; } } echo '&lt;ul&gt;'; } } ?&gt; </code></pre>
[]
[ { "body": "<p>Will edit this when I have time, but for now a few brief notes:</p>\n\n<p><strong>Assuming POST keys exist</strong></p>\n\n<p>Review the section in <a href=\"https://codereview.stackexchange.com/a/12769/7308\">my other post</a>.</p>\n\n<p><strong>Exception handling</strong></p>\n\n<p>Catching an exception, outputting a message and letting the script continue does not make sense. If an exception happens at a high level like that, it means that the page should probably be halted and the user informed that something went horribly wrong. If you continue to use <code>$db</code> after that exception, you'll get a fatal error because <code>$db</code> will not be an object.</p>\n\n<p><strong>filter_input</strong></p>\n\n<p>Your use of <a href=\"http://us2.php.net/filter_input\" rel=\"nofollow noreferrer\">filter_input</a> is wrong (as is your assumption that it somehow alters <code>$_POST</code>).</p>\n\n<p><strong>isset logic</strong></p>\n\n<p>Your isset logic is flawed. An empty post request will manage to pass through with an empty <code>$errors</code> array. <code>$username</code>, <code>$password</code> and <code>$checkpassword</code> would all be null.</p>\n\n<p><strong>username existence handling</strong></p>\n\n<p>Why not treat this as any other validation?</p>\n\n<p>Use a structure like:</p>\n\n<pre><code>if (valid username provided) {\n //check if the username exists\n if (user name exists) {\n $errors['username'][] = \"Your username is taken\";\n }\n}\n</code></pre>\n\n<p>The <code>valid username provided</code> could just be <code>!isset($errors['username'])</code> if you were positive that all username errors were put into the <code>username</code> key (this is currently the case, so the snippet in this sentence would work).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T02:47:06.977", "Id": "21276", "Score": "0", "body": "Thanks again Corbin! I edited the code to include some of your comments.. 1. Assuming POST keys exist-> So Array_key_exists checks whether a variable is null, and isset checks if isset is empty? Do I need to use both array_key_exists and isset to access a possibly null variable? Also like you said that $_POST variables are never null (from your previous answer, unless I'm misinterpreting) is it okay to access \"empty\" $_POST variables? For example In the updated code I used mysql_escape_string on a possibly empty $_POST without checking isset." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T02:48:41.330", "Id": "21278", "Score": "0", "body": "filter_input -> You're right. I had no idea how to use this. I'll stick to mysql_escape_string (is this enough to prevent sql injection?) for sql, htmlspecialchars for html, (and possibly some other things for javascript)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T02:49:28.940", "Id": "21279", "Score": "0", "body": "isset logic -> I swear I had an else clause...Possibly deleted it. Either way I've edited it in the code. Awesome pick up!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T02:51:14.353", "Id": "21280", "Score": "0", "body": "Exception handling -> If you're refering to the catch and try statement on db connect. Yeah you're right, there no need to try and catch there. I've just set it to or die(), although that might be redundant because I have require(). For the second try and catch I assume that's fine as is" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T02:53:08.780", "Id": "21281", "Score": "0", "body": "username existence handling -> Yeah definitely. The more elegant error handling as a whole doesn't come naturally to me yet, need to work on it actively. \n\nAlso I've just posted a number of comments, please let me know if this is inappropriate/another method/ or something along the lines of \"google XXXXX\" if its quite trivial." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T07:16:06.503", "Id": "21284", "Score": "0", "body": "@JY Not to discourage you, but your edit has actually made a few things worse :-(. Can't do it tonight, but when I have more time I will edit my answer to explain some of my points more, and do some comments in the code to better illustrate issues." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T18:42:29.843", "Id": "21402", "Score": "0", "body": "Any mistake I make is just an opportunity to improve :)" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T08:36:27.927", "Id": "13114", "ParentId": "13102", "Score": "3" } }, { "body": "<p>In addition to @Corbin's reply:</p>\n\n<p>1) <code>$salt1</code> and <code>$salt2</code> variables are undefined in <code>myEncrypt()</code> function.</p>\n\n<p>2) Double hashing in <code>myEncrypt()</code> probably makes sense if you store salts in different storage (at least not in one table), or if hashing algorithm is unknown (though it is a bit obvious in this case).</p>\n\n<p>3) My general concern is that code logic goes together with view (HTML code). I'd refactor the code according the <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC pattern</a> (as a most common one) or some other (MVP, for example).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T18:44:36.707", "Id": "21403", "Score": "0", "body": "1) Yeah I did have those defined, not in the function itself, I didn't want to paste them in but essentially they were a static string like 134FdgE3.\n\n2. I stored the salts in the .php files where should they be stored exactly?\n\n3. I'm thinking of learning cakePHP, my concern is it's a steep learning curve and also I might learn more from building from the ground up, do you think I'm ready to learn a framework, or should I just refactor into an MVC pattern without a framework?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T09:34:29.953", "Id": "13151", "ParentId": "13102", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T00:17:52.287", "Id": "13102", "Score": "2", "Tags": [ "php", "mysql", "pdo" ], "Title": "Basic user registration code in PHP: Part 2" }
13102
<p>So this question is prompted by two things.</p> <ol> <li>I found some code in our source control doing this sort of things.</li> <li>These SO questions: <ul> <li><a href="https://stackoverflow.com/questions/297213/translate-an-index-into-an-excel-column-name">https://stackoverflow.com/questions/297213/translate-an-index-into-an-excel-column-name</a></li> <li><a href="https://stackoverflow.com/questions/837155/fastest-function-to-generate-excel-column-letters-in-c-sharp">https://stackoverflow.com/questions/837155/fastest-function-to-generate-excel-column-letters-in-c-sharp</a></li> <li><a href="https://stackoverflow.com/questions/4075656/how-to-get-continuous-characters-in-c/4077835#4077835">https://stackoverflow.com/questions/4075656/how-to-get-continuous-characters-in-c/4077835#4077835</a></li> <li><a href="https://stackoverflow.com/questions/1011732/iterating-through-the-alphabet-c-sharp-a-caz">https://stackoverflow.com/questions/1011732/iterating-through-the-alphabet-c-sharp-a-caz</a></li> </ul></li> </ol> <p>So when I thought about this problem this popped into my head almost immediately. </p> <pre class="lang-cs prettyprint-override"><code>class Util { private static string[] alphabetArray = { string.Empty, "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" }; public static IEnumerable&lt;string&gt; alphaList = alphabetArray.Cast&lt;string&gt;(); public static string IntToAA(int value) { while (Util.alphaList.Count() -1 &lt; value) { Util.IncreaseList(); } return Util.alphaList.ElementAt(value); } private static void IncreaseList() { Util.alphaList = Util.alphabetArray.Take(1).Union( Util.alphaList.SelectMany(currentLetter =&gt; Util.alphabetArray.Skip(1).Select(innerLetter =&gt; currentLetter + innerLetter) ) ); } } </code></pre> <p>My question is this: Is this approach a better solution (performance wise)? or is a recursive / computed value better (eg. <a href="https://stackoverflow.com/a/297214/684890">this answer</a> )?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T03:20:51.100", "Id": "21189", "Score": "3", "body": "Using LINQ to perform trivial transformations repeatedly will always hurt you performance-wise. If you specifically want performance, stay away from LINQ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T03:29:38.943", "Id": "21191", "Score": "0", "body": "@JeffMercado jeff I don't see the values going much past 50 something so it would only be hit once/twice. What specifically then should I change?" } ]
[ { "body": "<p>Calling any function in general will give you a small (miniscule) performance hit. Recursive functions (AFAIK) cannot be inlined so that can't be optimized away. LINQ revolves around calling other functions so that's the worst choice to make if you want to write good performing code. I've said it before, LINQ is not for writing fast code, it's for writing concise code. This is a simple algorithm that doesn't need to be bogged down by that.</p>\n\n<p><sup><sub><sup><sub><sup><sub>* It doesn't help if you don't use LINQ correctly, you have a number of no-no's in your code.</sub></sup></sub></sup></sub></sup></p>\n\n<p>If you want the <em>fastest</em> approach (without resorting to mapping out all possible values in memory), you'd stay away from these and do a more direct conversion. To be the absolutely fastest, you have to get down low-level and use <code>unsafe</code> (unmanaged) code. I won't go there. On the other hand, if you want fastest managed code, you'd want to do this iteratively. In any case, my proposal is not a claim to be the fastest implementation, it could very well not be but I don't know, you would have to profile it to find out.</p>\n\n<p>We're doing a base conversion from base-10 numbers to base-26 \"numbers\". I don't know if there's a faster algorithm to do this but here's a straight conversion using a <code>StringBuilder</code> as a buffer.</p>\n\n<pre><code>const int ColumnBase = 26;\nconst int DigitMax = 7; // ceil(log26(Int32.Max))\nconst string Digits = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\npublic static string IndexToColumn(int index)\n{\n if (index &lt;= 0)\n throw new IndexOutOfRangeException(\"index must be a positive number\");\n\n if (index &lt;= ColumnBase)\n return Digits[index - 1].ToString();\n\n var sb = new StringBuilder().Append(' ', DigitMax);\n var current = index;\n var offset = DigitMax;\n while (current &gt; 0)\n {\n sb[--offset] = Digits[--current % ColumnBase];\n current /= ColumnBase;\n }\n return sb.ToString(offset, DigitMax - offset);\n}\n</code></pre>\n\n<p>On the other hand, since your inputs are constrained to up to 50'ish, you could just use an array (and not an <code>IEnumerable&lt;&gt;</code>) for the lookups.</p>\n\n<pre><code>static readonly string[] Columns = new[]{\"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\",\"AA\",\"AB\",\"AC\",\"AD\",\"AE\",\"AF\",\"AG\",\"AH\",\"AI\",\"AJ\",\"AK\",\"AL\",\"AM\",\"AN\",\"AO\",\"AP\",\"AQ\",\"AR\",\"AS\",\"AT\",\"AU\",\"AV\",\"AW\",\"AX\",\"AY\",\"AZ\",\"BA\",\"BB\",\"BC\",\"BD\",\"BE\",\"BF\",\"BG\",\"BH\"};\npublic static string IndexToColumn(int index)\n{\n if (index &lt;= 0)\n throw new IndexOutOfRangeException(\"index must be a positive number\");\n\n return Columns[index - 1];\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T05:45:03.297", "Id": "21196", "Score": "0", "body": "I'm confused. So if mapping the numbers out into an in memory field is quicker ... why would this be quicker than the approach I suggested?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T05:59:21.337", "Id": "21197", "Score": "0", "body": "Well you're doing a form of memoization (very strangely I might add). After calling certain inputs, your code essentially becomes a (linear) lookup. _However_ you are paying _a lot_ just to get that memoization to work. To be able to get the corresponding column for the index 50, you needed to calculate all the values from 1 through 49 (which attributes to an even bigger hit on your first call). Now that might be fine if you're accessing this using indices in incremental order (ignoring the costs of using LINQ), for a utility method to have such a limited use, I'd question its existence." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T07:28:56.427", "Id": "21198", "Score": "0", "body": "So keeping it as a `List` rather than an `IEnumerable` is better as it is a linear look up? (assuming the values are precalculated?)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T09:39:55.787", "Id": "21203", "Score": "0", "body": "@JamesKhoury Almost everything is better than a linear lookup." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T09:42:49.950", "Id": "21204", "Score": "0", "body": "@JeffMercado I believe LINQ can be used to write good performing code and I certainly wouldn't call it “worst choice”. Yes, it does have some overhead, but that's going to be negligible most of the time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T00:48:54.570", "Id": "21311", "Score": "0", "body": "@svick I believe Jeff was referring to using functions over calculations. If you have a different answer I encourage you to submit one of your own." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T16:49:44.790", "Id": "59095", "Score": "0", "body": "I found this very helpful, but also needed a reverse - which brought me to the Hexavigesimal wikipedia entry, and allowed me to create this:\n\n public static int ConvertStringToInt(string str)\n {\n int index = (Digits.IndexOf(str[0]) + 1);\n for (int i = 1; i < str.Length; i++)\n {\n index *= ColumnBase;\n index += (Digits.IndexOf(str[i]) + 1);\n }\n return index;\n }" } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T04:42:42.167", "Id": "13110", "ParentId": "13105", "Score": "19" } }, { "body": "<p>Math! Simple math is certainly the nicest way, no lists to deal with, just old fashion ASCII and math. If you want to be able to toggle the capitalization of this method, simply use a ternary operator like this <code>isCapital ? 'A' : 'a'</code> I just left it capital as that is how the OP seemed to want it. Jeff Mercado's <a href=\"https://codereview.stackexchange.com/a/13110/38054\">Answer</a> explained well enough the differences between calculated, recursive and such... I mostly wanted to provide a simplistic calculated answer that did not involve using lists.</p>\n\n<pre><code>public static string IntToLetters(int value)\n{\n string result = string.Empty;\n while (--value &gt;= 0)\n {\n result = (char)('A' + value % 26 ) + result;\n value /= 26;\n }\n return result;\n}\n</code></pre>\n\n<p>Edit: To meet the requirement of A being 1 instead of 0, I've added <code>--</code> to the while loop condition, and removed the value-- from the end of the loop, if anyone wants this to be 0 for their own purposes, you can reverse the changes, or simply add <code>value++;</code> at the beginning of the entire method.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T01:26:55.273", "Id": "76392", "Score": "1", "body": "Your version puts 'A' at 0 not 1. How would you propose to acheive this in a simplistic way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T01:32:23.757", "Id": "76393", "Score": "1", "body": "@JamesKhoury Oh sorry about that, didn't realize... just `value-;` at the beginning of the entire method, I actually went to extra lengths to make it base 0." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T22:39:33.580", "Id": "76601", "Score": "0", "body": "Thats great. Does this implementation provide a performance increase over other implementations?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-06T04:15:00.277", "Id": "163087", "Score": "0", "body": "To base 26 string, this simply better" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-09-14T18:07:56.597", "Id": "191486", "Score": "2", "body": "You might want to consider using a `StringBuilder` and initialize it with a capacity of `value / 26 + 1`." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-11T19:46:43.580", "Id": "44094", "ParentId": "13105", "Score": "32" } } ]
{ "AcceptedAnswerId": "13110", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T02:42:56.410", "Id": "13105", "Score": "33", "Tags": [ "c#", "performance", "strings", "converting" ], "Title": "Integer to Alphabet string (\"A\", \"B\", ....\"Z\", \"AA\", \"AB\"...)" }
13105
<p>I wrote a script to scroll pages when menu buttons are clicked, similar effect like: <a href="http://css-tricks.com/examples/SmoothPageScroll">http://css-tricks.com/examples/SmoothPageScroll</a></p> <pre><code>var m1 = document.getElementById('m1'), m2 = document.getElementById('m2'), m3 = document.getElementById('m3'), m4 = document.getElementById('m4'), m5 = document.getElementById('m5'), m2PositionY = document.getElementById('id2').offsetTop, m3PositionY = document.getElementById('id3').offsetTop, doneValue = true, windowPageYOffset = 0; function Scroll(ScrollValue1) { windowPageYOffset = window.pageYOffset; if(windowPageYOffset == ScrollValue1) { doneValue = true; } // scroll up else if(windowPageYOffset &gt;= ScrollValue1) { window.scrollBy(0, -(1 + ((windowPageYOffset - ScrollValue1) / 10))); } // scroll down else { window.scrollBy(0, 1 + ((ScrollValue1 - windowPageYOffset) / 10)); } if(windowPageYOffset != ScrollValue1) { var setTimeoutScrollValue1 = setTimeout('Scroll(' + ScrollValue1 + ')', 20); } } function doneOrNot(doneOrNotValue1) { if(doneValue &amp;&amp; doneOrNotValue1 != windowPageYOffset) { Scroll(doneOrNotValue1); doneValue = false; } } m1.onclick = function () { doneOrNot(0); // no need for a id since top is allways 0 } m2.onclick = function () { doneOrNot(m2PositionY); } m3.onclick = function () { doneOrNot(m3PositionY); } </code></pre> <p>I am using a "true or false variable" (<code>doneValue</code>) to determine if previous <code>Scroll</code> is finished before next can start. I wonder if there is any better method to do this in JavaScript?</p> <p>Please give other feedback if you have any :)</p>
[]
[ { "body": "<p>There are a few things you can do differently</p>\n\n<ol>\n<li>Animations are most often accomplished by getting the difference between start and end values, and animating a factor from zero to 1. Multiply that with the difference, and you get an offset.</li>\n<li>Instead of relying on an interval (which may be slow, since JS is single-threaded), most animation libraries compare the start time to the current time, to see how far along the animation should be.</li>\n<li>Instead of waiting for the animation to stop and a boolean to flip, you can clear the animation's timer, and forcibly stop the animation, before starting a new one. That way the user's clicks aren't ignored, but override previous clicks instead.</li>\n</ol>\n\n<p>Here's an alternative implementation using that approach and other good stuff:</p>\n\n<pre><code>var smoothScrollTo = (function () {\n var timer, start, factor;\n\n return function (target, duration) {\n var offset = window.pageYOffset,\n delta = target - window.pageYOffset; // Y-offset difference\n duration = duration || 1000; // default 1 sec animation\n start = Date.now(); // get start time\n factor = 0;\n\n if( timer ) {\n clearInterval(timer); // stop any running animation\n }\n\n function step() {\n var y;\n factor = (Date.now() - start) / duration; // get interpolation factor\n if( factor &gt;= 1 ) {\n clearInterval(timer); // stop animation\n factor = 1; // clip to max 1.0\n } \n y = factor * delta + offset;\n window.scrollBy(0, y - window.pageYOffset);\n }\n\n timer = setInterval(step, 10);\n return timer; // return the interval timer, so you can clear it elsewhere\n };\n}());\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/DruwJ/1/\">Here's a demo</a></p>\n\n<p>Another advantage of always animating a factor between zero and 1 is that you can run it through other expressions, and (for instance) animated the scroll with a sine wave.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:47:12.623", "Id": "21230", "Score": "0", "body": "I [refactored](http://jsfiddle.net/DruwJ/2/) out the general animation logic from the specific act of scrolling and added support for easing functions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:56:39.757", "Id": "21231", "Score": "0", "body": "And added back in the canceling animation functionality: http://jsfiddle.net/DruwJ/3/" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:19:55.383", "Id": "21239", "Score": "0", "body": "Very nice, but it seems you're assigning `change = to - from` _before_ you've checked the `from` and `to` arguments. I think you're going to get some NaN-nonsense there if you omit the `from` and `to` args but include an easing function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T16:52:42.123", "Id": "21252", "Score": "0", "body": "[Good catch](http://jsfiddle.net/DruwJ/4/)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T07:49:04.167", "Id": "21285", "Score": "0", "body": "Thank you both so much! It looks really good! I have much to learn... Some questions: What does this \"window.smoothScrollTo = function (...) {}\" differ from \"function smoothScrollTo(target, duration)\"? Bill, can you show me a working example with easing out function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T08:34:31.443", "Id": "21286", "Score": "0", "body": "@user1087110 `function xyz() ...` and `xyz = function () ...` are equivalent - no difference whatsoever. The reason I'm using `window.smoothScrollTo` in the demo is just to ensure that the function is available globally. This is generally _not_ a good idea. I just did it for demo-purposes, but it's bad practice to pollute the global scope." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T09:21:02.647", "Id": "21289", "Score": "0", "body": "Thanks for clearing that out! Also I don't understand \"animation(function (position) { window.scroll(0,position); }, duration, start, target);\"?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T07:19:02.940", "Id": "21330", "Score": "0", "body": "@user1087110 the `animation` function simply animates a number's value over a certain duration. The way Bill set it up, the `animation` function, calls a function you provide with the value as an argument, each time it updates. In this case, the function provided scrolls the window, but it could just as easily move an element or do something else. Passing a function to another function is a common javascript technique, so you'll see it again." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-06T13:59:53.470", "Id": "86175", "Score": "0", "body": "Please note that neither of the code snippets posted above use requestAnimationFrame, which has many advantages over using setInterval - see http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ and other resources elsewhere online (many linked at the bottom of the article)" } ], "meta_data": { "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T12:10:47.677", "Id": "13118", "ParentId": "13111", "Score": "7" } } ]
{ "AcceptedAnswerId": "13118", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T06:18:26.423", "Id": "13111", "Score": "6", "Tags": [ "javascript" ], "Title": "Smooth page scrolling in JavaScript" }
13111
<p>I am pretty new to Rails and in fact this is the first thing I have made. This is a todo list type app. My JS and Rails is a big mess. I have just kinda hacked it up to work. Please suggest better ways to do things. Styling suggestions are welcome too.</p> <pre><code>class UsersController &lt; ApplicationController def index @users = User.all end def create @newuser = User.new params[:user] if @newuser.save flash[:notice] = "Successfully created your account. You can now log in" redirect_to root_path else flash[:error]=@newuser.errors.full_messages; render :action =&gt; 'new' end end def show @user = User.find(params[:id]) if session[:user_id] != @user.id flash[:notice] = "not authorised!!" redirect_to User.find(session[:user_id]) end @tasks = @user.tasks end def add_task #render text: params.inspect Task.create(job:params[:task][:job],user_id:params[:id]) flash[:notice]="Task has been added Successfully" redirect_to user_path(params[:id]) end def authenticate #render text: params.inspect @user = User.where(:username =&gt; params[:username], password:params[:password]).first if @user.nil? flash[:notice]="Invalid Username and/or Password" redirect_to root_path else session[:user_id] =@user.id flash[:notice]="Welcome #{@user.username}!!" redirect_to @user end end def delete_task #render text: params.inspect Task.destroy(params[:task_id]) flash[:notice]="Task was marked as done and hence deleted!!" redirect_to User.find(session[:user_id]) end def home if session[:user_id] redirect_to User.find(session[:user_id]) else flash[:notice]="Please sign in!" redirect_to root_path end end def signout session[:user_id]=nil redirect_to root_path end def updatetask @task = Task.find(params[:task_id]) if session[:user_id] != @task.user_id flash[:notice] = "not authorised!!" redirect_to User.find(session[:user_id]) else @task.planned = params[:planned] @task.started = params[:started] #@task.color = params[:color] @task.finished = params[:finished] @task.save redirect_to root_path end end end </code></pre> <p><strong>show.html.erb</strong></p> <pre><code>&lt;% if flash[:notice] %&gt; &lt;div id="notice"&gt;&lt;%=flash[:notice]%&gt;&lt;/div&gt; &lt;% end %&gt; &lt;% if @tasks.any? %&gt; &lt;table border="1"&gt; &lt;tr&gt; &lt;th class="task-column"&gt;Task&lt;/th&gt; &lt;th&gt;Planned&lt;/th&gt; &lt;th&gt;Started&lt;/th&gt; &lt;th&gt;Finished&lt;/th&gt; &lt;th&gt;Delete Task&lt;/th&gt; &lt;/tr&gt; &lt;% @tasks.each do |t| %&gt; &lt;tr&gt; &lt;td class="task-column"&gt;&lt;%= t.job %&gt;&lt;/td&gt; &lt;td&gt;&lt;%= check_box_tag "planned[#{t.id}]","#{t.id}", t.planned, :class =&gt; 'planned'%&gt;&lt;/td&gt; &lt;td&gt;&lt;%= check_box_tag "started[#{t.id}]","#{t.id}",t.started, :class =&gt; 'started'%&gt;&lt;/td&gt; &lt;td&gt;&lt;%= check_box_tag "finished[#{t.id}]","#{t.id}", t.finished, :class =&gt; 'finished' %&gt;&lt;/td&gt; &lt;td&gt;&lt;%=link_to "Delete", delete_task_path(t)%&gt;&lt;/td&gt; &lt;/tr&gt; &lt;%end%&gt; &lt;/table&gt; &lt;div id="done-container"&gt;&lt;div id="done"&gt;&lt;/div&gt;&lt;/div&gt; &lt;%end%&gt; &lt;% if @tasks.empty? %&gt; &lt;p&gt;Please Add Some Tasks.&lt;/p&gt; &lt;% end %&gt; </code></pre> <p><strong>jQuery</strong></p> <pre><code>$(document).ready(function() { $("input:checkbox:checked.started").parent().css("background-color","yellow").siblings().css("background-color","yellow"); $("input:checkbox:checked.finished").parent().css("background-color","green").siblings().css("background-color","green"); function doneDisplay() { var done_div =$("#done"); var done = Math.floor(($(":checked").length)/($(":checkbox").length)*100); done_div.html( "you are " + (done||"0") +"% done!!").css("width",done+"%"); //$(done_div.children()[0]).css("font-color","blue"); if (done &lt;= 33){ done_div.css("background-color","red"); } if (done &gt; 33){ done_div.css("background-color","yellow"); } if (done &gt; 66){ done_div.css("background-color","green"); } if (done == 0){ done_div.css("width","100%").css("background-color","inherit"); } } doneDisplay(); $(":checkbox").change(function(){ var $this = $(this); var color,finished,started,planned; var task_id = $this.attr("value"); if (($this.attr("class") =="finished") &amp;&amp; ($this.attr("checked")=="checked")){ $this.parent().css("background-color","green").siblings().css("background-color","green") .children().attr("checked",true); //color ="green"; finished = started = planned =true; } if ($this.attr("class") =="planned" &amp;&amp; !$this.attr("checked")){ $this.parent().css("background-color","red").siblings().css("background-color","red") .children().attr("checked",false); //color = "red"; finished = started = planned =false; } if (($this.attr("class") =="started") &amp;&amp; ($this.attr("checked")=="checked")){ $this.parent().css("background-color","yellow").siblings().css("background-color","yellow") .children(".planned").attr("checked",true); //color = "yellow"; started = planned =true; finished = false; } if ($this.attr("class") =="started" &amp;&amp; !$this.attr("checked")){ $this.parent().css("background-color","red").siblings().css("background-color","red") .children(".finished").attr("checked",false); //color = "red"; planned =true; finished =started= false; } if ($this.attr("class") =="finished" &amp;&amp; !$this.attr("checked")){ $this.parent().css("background-color","yellow").siblings().css("background-color","yellow"); //color = "yellow"; started = planned =true; finished = false; } if (($this.attr("class") =="planned") &amp;&amp; ($this.attr("checked")=="checked")){ $this.parent().css("background-color","red").siblings().css("background-color","red") //color ="green"; finished = started =false; planned =true; } $.ajax({ type: "POST", url : "/updatetask/"+task_id+"/"+planned+"/"+started+"/"+finished, success: doneDisplay, //error: function(xhr){ alert("The error code is: "+xhr.statusText);} }); }) }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T12:31:58.080", "Id": "21210", "Score": "0", "body": "should i include the controller and views then ? Copying all the code doesn't seem a good idea." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-21T18:11:26.727", "Id": "22420", "Score": "2", "body": "‘( Some CSS advise too please)’ where is css?" } ]
[ { "body": "<p>A few quick suggestions, without really looking thoroughly into the code:</p>\n\n<ul>\n<li>Saving <strong>any</strong> passwords in clear text is a Very Bad Idea™.</li>\n<li>Why are you limiting the max-length of the password?</li>\n<li>Do not set styles in JS, set classes instead and then style them with CSS.</li>\n<li>Use <code>$this.hasClass(\"finished\")</code> instead of <code>$this.attr(\"class\") ==\"finished\"</code>.</li>\n<li>You repeatedly access <code>$this.attr(\"checked\")</code>, so it might be a good idea to store it in a var at the beginning of the <code>change</code> handler.</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:40:33.143", "Id": "21219", "Score": "0", "body": "Thanks..I am really new to rails. So just needed to build a basic authentication system. I will look into encryption :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:48:15.473", "Id": "21220", "Score": "0", "body": "(I would wait a few days for other good input, before marking anything as answer.) Maybe it would be overwhelming to learn too much at once. But when you feel motivated, there are good resources to learn about it. I find [railscasts](http://railscasts.com/) to be a good source." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:58:15.570", "Id": "21222", "Score": "0", "body": "ok then i take your suggestion and unmarking it . Btw I actually made this authentication thing by mixing up stuff i learned from Rails for zombies and one of the railscast.I am currently trying to make the layout better, once I am done I will clean up the js and make a better authentication system. :)" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:22:48.667", "Id": "13124", "ParentId": "13119", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T12:21:19.227", "Id": "13119", "Score": "1", "Tags": [ "javascript", "jquery", "ruby", "ruby-on-rails", "to-do-list" ], "Title": "To-do-list web app in Ruby on Rails and CSS" }
13119
<p>Here is my progress calculator class. It is used for downloads/uploads. It takes bytes in and calculates the percentage(to the nearest 5%) that should show on a progress bar. Please let me know how I could improve it. Thanks a lot!!</p> <pre><code>public class ProgressCalculator { private int totalAmount; private int progressAmount; private int amountProgressItems; private int progressBarPercentage; //returns if the progress bar needs to change public boolean progress(int amount) { progressAmount = progressAmount + amount; return updateProgressbarPercentage(); } public int getCurrentValue() { return progressBarPercentage; } //returns if the progressbar needs to change public boolean addProgressItem(int itemAmount) { totalAmount = totalAmount + itemAmount; amountProgressItems++; return updateProgressbarPercentage(); } //returns true if has been updated; private boolean updateProgressbarPercentage() { int newProgressBarPercentage = round(calculateProgressPercentage()); if (progressBarPercentage == newProgressBarPercentage) { return false; } else { progressBarPercentage = newProgressBarPercentage; return true; } } public int getAmountOfItems() { return amountProgressItems; } public boolean removeProgressItem(int byteAmount) { if (amountProgressItems &gt; 0) { totalAmount = totalAmount - byteAmount; amountProgressItems--; } return updateProgressbarPercentage(); } private int calculateProgressPercentage() { double x = progressAmount; double y = totalAmount; double result = (x / y) * 100; return (int) result; } private int round(int num) { int temp = num % 5; if (temp &lt; 3) return num - temp; else return num + 5 - temp; } public void clear() { totalAmount = 0; progressAmount = 0; amountProgressItems = 0; progressBarPercentage = 0; } } </code></pre>
[]
[ { "body": "<p>It's really hard to tell what this class does. From what you say, I feel like you have a number of <code>TransferTask</code>s and want to have a sort of <code>ProgressTracker</code> for them. So, as for me, your goal is to make user's code look like this:</p>\n\n<pre><code>ProgressTracker progressTracker = new ProgressTracker();\nprogressTracker.setListener(new ProgressTrackerListener() {\n @Override\n public void onProgressChanged(double progressPercentage) {\n // TODO: update your UI here\n }\n});\n...\nTransferTask transferTask = new UploadTask(\"/home/jiduvah/1.txt\");\nprogressTracker.track(transferTask);\ntransferTask.start();\n</code></pre>\n\n<p>Why? Because it doesn't need any comments to describe what happens here: you just write it in English.</p>\n\n<p><strong>Update</strong> - In case you're absolutely sure you like your approach.</p>\n\n<p>First, in this code:</p>\n\n<pre><code>private int round(int num) {\n int temp = num % 5;\n if (temp &lt; 3)\n return num - temp;\n else\n return num + 5 - temp;\n}\n</code></pre>\n\n<p>I see magic like <code>5</code> and <code>3</code>. Looks like it does exactly what you need to do, and you've even wrote about meaning of 5, but 3 is still a mystery.</p>\n\n<p>Then:</p>\n\n<pre><code>double x = progressAmount;\ndouble y = totalAmount;\ndouble result = (x / y) * 100;\nreturn (int) result;\n</code></pre>\n\n<p>When you divide <code>int</code> by <code>int</code>, you get <code>int</code>. When you divide <code>int</code> by <code>double</code> or <code>double</code> by <code>int</code>, you get <code>double</code>. So you may just write:</p>\n\n<pre><code>double result = 100 * progressAmount / (double)totalAmount;\n</code></pre>\n\n<p>Regarding the whole idea, I'm not sure whether this code works at all, because it's hard to understand how one should use it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:18:57.640", "Id": "21213", "Score": "0", "body": "Sorry I wasn't so clear but you got it right. I have a number of transferTasks and I need to track the overall progress. It looks like a very logical way to do it. Is the maths side of it ok? I was unsure with casting the int from a double to work out the percentage. EDIT - never mind, it was answered below" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:28:13.547", "Id": "21214", "Score": "0", "body": "Updated my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:30:29.657", "Id": "21215", "Score": "0", "body": "with regards to the 3 and 5, Its rounding to the nearest 5%. Is there a better way to do it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:34:51.793", "Id": "21216", "Score": "0", "body": "http://ideone.com/pI4TN" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:39:33.200", "Id": "21218", "Score": "0", "body": "I find the syntax a little hard to understand but the results are not what I want. I wanted to round to the nearest 5 not round up to the nearest 5. (nevertheless your help is much appreciated)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:00:02.520", "Id": "21223", "Score": "1", "body": "To get the same that you already have, fix like this: `quantizer * ((i + quantizer / 2) / quantizer)`, where quantizer is still 5." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:14:36.537", "Id": "13122", "ParentId": "13121", "Score": "4" } }, { "body": "<p>The only thing that sticks out to me is <code>amountProgressItems</code>. Why do you need it?</p>\n\n<p>It's only internal use is to prevent <code>removeProgressItem</code> from being called more times than <code>addProgressItem</code> was called. Furthermore, we do not have an guarantee that <code>remove</code> will be called with the same <code>byteAmount</code> parameters that <code>add</code> was called.</p>\n\n<p>Personally, I would change these methods into <code>increaseTotalAmount(int)</code> and <code>decreaseTotalAmount(int)</code>. </p>\n\n<p>All that said, if you have an external use for progress items, it's not <em>horrible</em>, so don't feel the need to change it.</p>\n\n<p><hr>\nOne last thing, don't divide by zero, and <code>calculateProgressPercentage</code> can be one lined:</p>\n\n<pre><code>private int calculateProgressPercentage() {\n if(totalAmount == 0) return 0;\n return (int) (progressAmount * 100.0 / totalAmount);\n}\n</code></pre>\n\n<p>Using <code>100.0</code> (not <code>100</code>) will result in the numerator being a double, causing the result to likewise be a double.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:17:27.567", "Id": "21227", "Score": "0", "body": "thanks for that, I up voted instead of marking correct as the other answer was a little more involved" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:21:34.877", "Id": "13123", "ParentId": "13121", "Score": "3" } } ]
{ "AcceptedAnswerId": "13122", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T12:38:29.483", "Id": "13121", "Score": "3", "Tags": [ "java", "android" ], "Title": "Download Progress Calculator" }
13121
<p>I seem to have this tendency to write custom methods, i.e. code that isn't reusable. The following seems to be one example of trying to do too much in a single method. But the point I'm not sure about is, in order to split it up, I'd have to redo the for loop each time. Is that acceptable?</p> <p>Any general pointers on how this should be structured would really be appreciated.</p> <pre><code>public static void ShowInputs(DataTable dtSProcList, List&lt;Label&gt; inputLabels, ComboBox cbSProcList, List&lt;TextBox&gt; inputTxtboxes, List&lt;TextBox&gt; selectedSProcInputs, List&lt;String&gt; selectedSprocDataTypes, List&lt;string&gt; selectedSprocParamterNames) { int counter = 0; for (int i = 0; i &lt; dtSProcList.Rows.Count; i++) { if (dtSProcList.Rows[i][0].ToString() == cbSProcList.SelectedItem.ToString()) { string temp = dtSProcList.Rows[i][0].ToString(); if (dtSProcList.Rows[i][1] != DBNull.Value) { inputLabels[counter].Text = dtSProcList.Rows[i][1].ToString().Remove(0, 1); inputLabels[counter].Visible = true; inputLabels[counter].Enabled = true; inputTxtboxes[counter].Visible = true; inputTxtboxes[counter].Enabled = true; selectedSProcInputs.Add(inputTxtboxes[counter]); selectedSprocDataTypes.Add(dtSProcList.Rows[i][2].ToString()); counter++; } else { //Returns control to calling method if the parameter name is null. return; } } } } </code></pre> <p>EDIT: <a href="https://stackoverflow.com/questions/11227505/design-issues-tendency-to-write-custom-methods">I had originally posted this on SO</a> and was asked to report it here.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:23:51.560", "Id": "21228", "Score": "0", "body": "How exactly are you thinking about splitting the method? Why do you think it would require redoing the loop? Why do you think that would be a problem?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T14:40:22.693", "Id": "21229", "Score": "0", "body": "i was originally thinking of having 1 method display the labels, 2nd method display the necessary number of textboxes, 3rd method populate a list/array of parameter names and datatypes (i think thats a bad idea). Someone on SO suggested (kind of anyway) i just write one method to obtain a list of all the necessary rows. then call a second method to display the necessary labels and inputs. Would you agree with that or do u think there is a better way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:16:01.160", "Id": "21237", "Score": "0", "body": "Judging by your use of the controls, I'd guess this is part of some WinForms code? (as opposed to WPF)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T18:00:22.160", "Id": "21254", "Score": "0", "body": "@JeffMercado yeah its winforms, i havent gotten around to wpf yet + sorry for the late reply." } ]
[ { "body": "<p>Just a few small notes:</p>\n\n<ol>\n<li><p>The method has seven parameters which isn't a good smell. Maybe some of them could be class field.</p></li>\n<li><p>First, I'd reverse some conditions and use guard clauses to make the code flatten.</p>\n\n<pre><code>for (int i = 0; i &lt; dtSProcList.Rows.Count; i++)\n{\n if (dtSProcList.Rows[i][0].ToString() != cbSProcList.SelectedItem.ToString())\n {\n continue;\n }\n\n string temp = dtSProcList.Rows[i][0].ToString();\n if (dtSProcList.Rows[i][1] == DBNull.Value)\n {\n //Returns control to calling method if the parameter name is null.\n return;\n }\n\n inputLabels[counter].Text = dtSProcList.Rows[i][1].ToString().Remove(0, 1);\n inputLabels[counter].Visible = true;\n inputLabels[counter].Enabled = true;\n inputTxtboxes[counter].Visible = true;\n inputTxtboxes[counter].Enabled = true;\n\n selectedSProcInputs.Add(inputTxtboxes[counter]);\n selectedSprocDataTypes.Add(dtSProcList.Rows[i][2].ToString());\n\n counter++;\n}\n</code></pre>\n\n<p>References: </p>\n\n<ul>\n<li><em>Replace Nested Conditional with Guard Clauses</em> in <em>Refactoring: Improving the Design of Existing Code</em>; </li>\n<li><a href=\"http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html\">Flattening Arrow Code</a></li>\n</ul></li>\n<li><p><code>0</code>, <code>1</code> and <code>2</code> are magic numbers. Using named constants instead of numbers would make the code more readable and less fragile.</p></li>\n<li><p>What does the <code>counter</code> count? You should give it a name which shows the intent of the variable.</p></li>\n<li><p><code>dtSProcList.Rows[i]</code> repeats five times in the code. A named local variable could remove this duplication.</p></li>\n<li><p>The <code>temp</code> variable seems to be unused. If it's superfluous remove it.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T12:15:03.797", "Id": "13216", "ParentId": "13125", "Score": "5" } } ]
{ "AcceptedAnswerId": "13216", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T13:55:03.077", "Id": "13125", "Score": "5", "Tags": [ "c#", "design-patterns" ], "Title": "Design issues, tendency to write custom methods" }
13125
<p>I'm wondering about the difference between these two linq statements</p> <pre><code>bool overlap = GetMyListA().Intersect(GetMyListB()).Any(); // 1. </code></pre> <p>vs</p> <pre><code>bool overlap = GetMyListA().Any(i =&gt; GetMyListB().Contains(i)); // 2. </code></pre> <p>Will statement 2. call GetMyListB() for each item in ListA?</p> <p>Which is more readable?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:10:58.543", "Id": "21233", "Score": "0", "body": "Both will yield the same result (assuming there are no side-effects in `GetMyListA()` or `GetMyListB()`). I'd say 1 is the most readable and 2 the most logical." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:18:59.610", "Id": "21238", "Score": "0", "body": "Is there any difference in performance? Would 'GetMyListB()' be called multiple times?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:40:26.807", "Id": "21241", "Score": "3", "body": "Assuming you're working with lists, there would likely be a performance difference. Using `Intersect()` would utilize hash sets to determine uniqueness. The other code would perform linear searches through list B and would return on the first match (and yes, `GetMyListB()` will be called for each item in list A)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T16:56:51.883", "Id": "21253", "Score": "1", "body": "It really depends on the linq provider and the types of the objects. This question would be better for stackoverflow though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-13T22:30:50.140", "Id": "22094", "Score": "0", "body": "A similar question of me: http://stackoverflow.com/questions/10110013/order-of-linq-extension-methods-does-not-affect-performance Short answer: In LINQ-To-Objects they are equal, but the first is more readable (imho):" } ]
[ { "body": "<p>Assuming LINQ to objects (i. e. these are in-memory collections not LINQ to Entities IQueryables or something):</p>\n\n<blockquote>\n <p>Will statement 2. call GetMyListB() for each item in ListA?</p>\n</blockquote>\n\n<p>Yes. If you want to avoid this, you'll have to store the result of GetMyListB() outside the function.</p>\n\n<blockquote>\n <p>Which is more readable?</p>\n</blockquote>\n\n<p>In my opinion two are about equally readable, although I would change #2 to be:</p>\n\n<pre><code>bool overlap = GetMyListA().Any(GetMyListB().Contains); // 2.\n</code></pre>\n\n<p>As far as performance, #1 will probably perform better in most cases, since it will dump all of one list into a hash table and then do an O(1) lookup for each element in the other list. Two exceptions to this that I can think of are (1) if the lists are very small, then building the hash table data structure might not be worth the overhead and (2) option 2 can theoretically return without having considered every element in either list. If the lists are large lazy enumerables and you expect this to return true in most cases then this could lead to a performance increase.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-01T20:26:23.040", "Id": "15268", "ParentId": "13127", "Score": "6" } } ]
{ "AcceptedAnswerId": "15268", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:02:34.950", "Id": "13127", "Score": "8", "Tags": [ "c#", "linq" ], "Title": "Which linq statement is better to find there is an overlap between two lists of ints?" }
13127
<p>I want to simplify this C code into different functions:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;stdlib.h&gt; #include &lt;libxml/xmlmemory.h&gt; #include &lt;libxml/parser.h&gt; // Declare functions void parseSystemProperties(char *xmlFileName); void parseSystemModules(xmlDocPtr doc, xmlNodePtr cur); void parseSystemConfiguration(xmlDocPtr doc, xmlNodePtr cur); void parseProfiles(xmlDocPtr doc, xmlNodePtr cur); void parseMonitoringPort(xmlDocPtr doc, xmlNodePtr cur); void parseWebServicePort(xmlDocPtr doc, xmlNodePtr cur); void parseBindingInterfaces(xmlDocPtr doc, xmlNodePtr cur); void parseExtensions(xmlDocPtr doc, xmlNodePtr cur); int main(int argc, char **argv) { char *xmlFileName; if (argc &lt;= 1) { printf("Usage: %s inputfile.xml\n", argv[0]); return (0); } // Get the file name from the argv[1] xmlFileName = argv[1]; // Custom function to parse XML file parseSystemProperties(xmlFileName); return (1); } // Parsing the XML file and Reading the Element Nodes void parseSystemProperties(char *xmlFileName) { xmlDocPtr doc; // pointer to parse xml Document xmlNodePtr cur; // node pointer. It interacts with individual node // Parse XML file doc = xmlParseFile(xmlFileName); // Check to see that the document was successfully parsed. if (doc == NULL) { fprintf(stderr, "Error!. Document is not parsed successfully. \n"); return; } // Retrieve the document's root element - system-properties cur = xmlDocGetRootElement(doc); // Check to make sure the document actually contains something if (cur == NULL) { fprintf(stderr, "Document is Empty\n"); xmlFreeDoc(doc); return; } /* We need to make sure the document is the right type. * "system-properties" is the root type of the documents used in user Config XML file */ if (xmlStrcmp(cur-&gt;name, (const xmlChar *) "system-properties")) { fprintf(stderr, "Cannot find system-properties"); xmlFreeDoc(doc); return; } /* Get the first child node of cur. * At this point, cur points at the document root, * which is the element "root" */ cur = cur-&gt;xmlChildrenNode; // This loop iterates through the elements that are children of "root" while (cur != NULL) { // Get the data from system-modules if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "system-modules"))) { parseSystemModules(doc, cur); } // Get the values from system-configuration if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "system-configuration"))) { parseSystemConfiguration(doc, cur); } cur = cur-&gt;next; } /* Save XML document to the Disk * Otherwise, you changes will not be reflected to the file. * Currently it's only in the memory */ // xmlSaveFormatFile (xmlFileName, doc, 1); /* free the document */ xmlFreeDoc(doc); /* * Free the global variables that may * have been allocated by the parser. */ xmlCleanupParser(); return; } // end of function // Get Modules part // ------------------------------------------- void parseSystemModules(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; xmlAttrPtr attr; // Get the sub Element Node of system-configuration node cur = cur-&gt;xmlChildrenNode; // This loop iterates through the elements that are children of system-configuration while (cur != NULL) { if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "extensions"))) { parseExtensions(doc, cur); } cur = cur-&gt;next; } return; } // end of function() void parseExtensions(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; xmlAttrPtr attr; // Get the sub Element Node of Profiles node cur = cur-&gt;xmlChildrenNode; // This loop iterates through the elements that are children of Profiles while (cur != NULL) { if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "extension"))) { key = xmlGetProp(cur, (const xmlChar*) "module"); fprintf(stderr, "module: %s\n", key); xmlFree(key); } cur = cur-&gt;next; } return; } // end of function() // Get Configuration part // ------------------------------------------- void parseSystemConfiguration(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; xmlAttrPtr attr; // Get the sub Element Node of system-configuration node cur = cur-&gt;xmlChildrenNode; // This loop iterates through the elements that are children of system-configuration while (cur != NULL) { if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "profiles"))) { parseProfiles(doc, cur); } cur = cur-&gt;next; } return; } // end of function() void parseProfiles(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; xmlAttrPtr attr; // Get the sub Element Node of Profiles node cur = cur-&gt;xmlChildrenNode; // This loop iterates through the elements that are children of Profiles while (cur != NULL) { if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "profile"))) { // Get monitoring-port parseMonitoringPort(doc, cur); // Get web-service-port parseWebServicePort(doc, cur); parseBindingInterfaces(doc, cur); } cur = cur-&gt;next; } return; } // end of function() // Monitoring Port void parseMonitoringPort(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; xmlAttrPtr attr; // Get the sub Element Node of Profile node cur = cur-&gt;xmlChildrenNode; // This loop iterates through the elements that are children of Profile while (cur != NULL) { if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "monitoring-port"))) { key = xmlGetProp(cur, (const xmlChar*) "port"); fprintf(stderr, "monitoring-port: %s\n", key); xmlFree(key); } cur = cur-&gt;next; } return; } // end of function() // web service port void parseWebServicePort(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; xmlAttrPtr attr; // Get the sub Element Node of Profile node cur = cur-&gt;xmlChildrenNode; // This loop iterates through the elements that are children of "root" while (cur != NULL) { if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "web-service-port"))) { //parseMonitoringPort (doc, cur); key = xmlGetProp(cur, (const xmlChar*) "port"); fprintf(stderr, "web-service-port: %s\n", key); xmlFree(key); } cur = cur-&gt;next; } return; } // end of function() // binding interface void parseBindingInterfaces(xmlDocPtr doc, xmlNodePtr cur) { xmlChar *key; xmlAttrPtr attr; // Get the sub Element Node of Profile node cur = cur-&gt;xmlChildrenNode; // This loop iterates through the elements that are children of "root" while (cur != NULL) { if ((!xmlStrcmp(cur-&gt;name, (const xmlChar *) "socket-binding"))) { //parseMonitoringPort (doc, cur); key = xmlGetProp(cur, (const xmlChar*) "interface"); fprintf(stderr, "interface: %s\n", key); xmlFree(key); key = xmlGetProp(cur, (const xmlChar*) "ipaddress"); fprintf(stderr, "ipaddress: %s\n", key); xmlFree(key); key = xmlGetProp(cur, (const xmlChar*) "port"); fprintf(stderr, "port: %s\n", key); xmlFree(key); } cur = cur-&gt;next; } return; } // end of function() </code></pre> <p>I use <code>while</code> cycle to parse xml document and to call <code>parseSystemModules</code> and <code>parseSystemConfiguration</code>. Is there more simple ways to split the <code>while</code> cycle into C functions. I want to add more and more functions without any problem in future time.</p> <p>This is the XML file:</p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;system-properties version="1.0"&gt; &lt;system-modules&gt; &lt;extensions&gt; &lt;extension module="NetworkModule"/&gt; &lt;extension module="MonitoringModule"/&gt; &lt;extension module="OracleModule"/&gt; &lt;extension module="DataFilterModule"/&gt; &lt;/extensions&gt; &lt;/system-modules&gt; &lt;system-configuration&gt; &lt;profiles&gt; &lt;profile name="default"&gt; &lt;monitoring-port port="6051"/&gt; &lt;web-service-port port="7050"/&gt; &lt;socket-binding interface="management" ipaddress="192.168.1.101" port="6050"/&gt; &lt;socket-binding interface="monitoring" ipaddress="192.168.1.106" port="7050"/&gt; &lt;network-pool threads="40"/&gt; &lt;/profile&gt; &lt;/profiles&gt; &lt;/system-configuration&gt; &lt;/system-properties&gt; </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:13:56.247", "Id": "21236", "Score": "0", "body": "Briefly looking at the code (ignoring correctness), I'd say you should worry more about trimming off your comments. Any time you have more comments than you have code, that should be a warning sign." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:57:08.103", "Id": "21247", "Score": "0", "body": "Your comments are delimiting some blocks, which can be functions." } ]
[ { "body": "<p>A few observations, Avoid comments that do not tell the reader any thing that they can not understand by reading the code. They just add to the visual noice. Instead add comments as to how the function fits in with the rest of the program, or how the function is to be used.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#include &lt;string.h&gt;\n#include &lt;stdlib.h&gt;\n#include &lt;libxml/xmlmemory.h&gt;\n#include &lt;libxml/parser.h&gt;\n</code></pre>\n\n<p>A small observation about your code is that it prints the error to the error stream in the case of errors. This is not always the best solution. A better idea is to indicate the error with a return error code and let the caller decide what to do about the error. (This is not implemented in below code.)</p>\n\n<pre><code>typedef enum {\n SUCCESS,\n NO_DOC,\n NO_PARSE,\n NO_ELEM\n} ParseResult;\n\ntypedef void (*xmlFn)(xmlDocPtr, xmlNodePtr);\n\nParseResult parseXml(char *xmlFileName);\nvoid parseSystemProperties(xmlDocPtr doc, xmlNodePtr cur);\nvoid parseSystemModules(xmlDocPtr doc, xmlNodePtr cur);\nvoid parseSystemConfiguration(xmlDocPtr doc, xmlNodePtr cur);\nvoid parseProfiles(xmlDocPtr doc, xmlNodePtr cur);\nvoid parseMonitoringPort(xmlDocPtr doc, xmlNodePtr cur);\nvoid parseWebServicePort(xmlDocPtr doc, xmlNodePtr cur);\nvoid parseBindingInterfaces(xmlDocPtr doc, xmlNodePtr cur);\nvoid parseExtensions(xmlDocPtr doc, xmlNodePtr cur);\n</code></pre>\n\n<p>Always indicate success in main with <code>0</code> rather than <code>1</code>. We do this because we have to interact with the system outside where <code>0</code> is considered a success any any other value is considered an error code.</p>\n\n<p>Also avoid extra <code>((()))</code> in the function arguments. Especially, it is not required in <code>return</code> statements.</p>\n\n<pre><code>int main(int argc, char **argv) {\n if (argc &lt;= 1) {\n printf(\"Usage: %s inputfile.xml\\n\", argv[0]);\n return 1;\n }\n parseXml(argv[1]);\n return 0;\n}\n\n\nvoid xprint(xmlNodePtr cur, const char* var, const char* msg) {\n xmlChar *key = xmlGetProp(cur, (const xmlChar*) var);\n fprintf(stderr, \"%s: %s\\n\", msg, key);\n xmlFree(key);\n}\n</code></pre>\n\n<p>From looking at your cdode, it seems that you have primarily two types of functions. Abstracting them away can help you to avoid duplication.</p>\n\n<pre><code>void parseFn(xmlDocPtr doc, xmlNodePtr cur, const char* check, xmlFn myfn) {\n if (xmlStrcmp(cur-&gt;name, (const xmlChar*) check)) return;\n for(cur = cur-&gt;xmlChildrenNode; cur; cur=cur-&gt;next) myfn(doc, cur);\n}\n\nvoid parseForFn(xmlDocPtr doc, xmlNodePtr cur, const char* check, xmlFn myfn) {\n for(cur = cur-&gt;xmlChildrenNode; cur; cur=cur-&gt;next) {\n if (xmlStrcmp(cur-&gt;name, (const xmlChar*) check)) continue;\n myfn(doc, cur);\n }\n}\n</code></pre>\n\n<p>Another recommendation I have is to move the checks for <code>system-modules</code> and <code>system-configuration</code> into the respective functions as pre-conditions. This will allow you to simplify.</p>\n\n<pre><code>ParseResult parseXml(char *xmlFileName) {\n xmlDocPtr doc; \n xmlNodePtr cur;\n ParseResult result = SUCCESS;\n doc = xmlParseFile(xmlFileName);\n if (!doc) return NO_DOC;\n cur = xmlDocGetRootElement(doc);\n if (cur == NULL) {\n result = NO_PARSE;\n goto cleanup;\n }\n\n /* We need to make sure the document is the right type.\n * \"system-properties\" is the root type of the documents used in user Config XML file\n */\n /* I decided to extract this to parseSystemProperties, but in doing\n do, I lost the NO_SYSTEM_PROP output. It could be added to the current\n framework by making the functions return NO_ELEM, and checking for\n it here. */\n parseSystemProperties(doc, cur);\ncleanup:\n xmlFreeDoc(doc);\n xmlCleanupParser();\n return result; \n}\n</code></pre>\n\n<p>Note the use of <code>goto</code>, I feel that it is better to do this than to distribute the cleanup code every where else in the function.</p>\n\n<p>Now, observe the functions below. Another way to do them is populate them into a table rather than defining function wrappers as below. An advantage of that approach is that, you could avoid defining too many helper_x functions.</p>\n\n<pre><code>void parseSystemProperties_x(xmlDocPtr doc, xmlNodePtr cur) {\n parseSystemModules(doc, cur);\n parseSystemConfiguration(doc, cur);\n}\n\nvoid parseSystemProperties(xmlDocPtr doc, xmlNodePtr cur) {\n parseFn(doc,cur, \"system-properties\",parseSystemProperties_x);\n}\n\nvoid parseSystemModules(xmlDocPtr doc, xmlNodePtr cur) {\n parseFn(doc,cur, \"system-modules\",parseExtensions);\n}\n\nvoid parseSystemConfiguration(xmlDocPtr doc, xmlNodePtr cur) {\n parseFn(doc,cur, \"system-configuration\",parseProfiles);\n}\n\nvoid parseProfiles_x(xmlDocPtr doc, xmlNodePtr cur) {\n parseMonitoringPort(doc, cur);\n parseWebServicePort(doc, cur);\n parseBindingInterfaces(doc, cur);\n}\n\nvoid parseProfiles(xmlDocPtr doc, xmlNodePtr cur) {\n parseFn(doc,cur, \"profiles\", parseProfiles_x);\n}\n</code></pre>\n\n<p>printing attribute values is the other kind of function. </p>\n\n<pre><code>void parseExtensions_x(xmlDocPtr doc, xmlNodePtr cur) {\n if (xmlStrcmp(cur-&gt;name, \"extension\")) return;\n xprint(cur, \"module\", \"module\");\n}\n\nvoid parseExtensions(xmlDocPtr doc, xmlNodePtr cur) {\n parseFn(doc,cur, \"extensions\", parseExtensions_x);\n}\n\nvoid parseMonitoringPort_x(xmlDocPtr doc, xmlNodePtr cur) {\n xprint(cur, \"port\", \"monitoring-port\");\n}\n\nvoid parseMonitoringPort(xmlDocPtr doc, xmlNodePtr cur) {\n parseForFn(doc,cur, \"monitoring-port\", parseMonitoringPort_x);\n}\n\nvoid parseWebServicePort_x(xmlDocPtr doc, xmlNodePtr cur) {\n xprint(cur, \"port\", \"web-service-port\");\n}\n\nvoid parseWebServicePort(xmlDocPtr doc, xmlNodePtr cur) {\n parseForFn(doc,cur, \"web-service-port\", parseWebServicePort_x);\n}\n\nvoid parseBindingInterfaces_x(xmlDocPtr doc, xmlNodePtr cur) {\n xprint(cur, \"interface\", \"interface\");\n xprint(cur, \"ipaddress\", \"ipaddress\");\n xprint(cur, \"port\", \"port\");\n}\n\nvoid parseBindingInterfaces(xmlDocPtr doc, xmlNodePtr cur) {\n parseForFn(doc,cur, \"socket-binding\", parseBindingInterfaces_x);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T16:01:27.203", "Id": "21248", "Score": "0", "body": "I posted the full code. Looking at the full source code how I can simplify it and make it more robust for future XML update?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:45:31.550", "Id": "13131", "ParentId": "13128", "Score": "2" } } ]
{ "AcceptedAnswerId": "13131", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:03:32.377", "Id": "13128", "Score": "1", "Tags": [ "c", "xml" ], "Title": "Parsing an XML configuration file for network monitoring" }
13128
<p>I find my self often doing things like this in Ruby on Rails:</p> <pre><code>@count = 0 LineItem.all.each do |item| if (item.cart_id == @cart.id) @count += item.quantity end end </code></pre> <p>So many things look wrong with this, but I want to initialize my variable (@count) before the loop, and then be able to use it after I'm out of the loop.</p> <p>Is there a better way to do this?</p>
[]
[ { "body": "<p>From what I can see, you are just collecting the <code>item.quantity</code> of all matching\nitems. This can be accomplished by</p>\n\n<pre><code>@count = LineItem.all.find_all{|i| i.cart_id == @cart.id}.map{|i| i.quantity}.inject(0,:+)\n</code></pre>\n\n<p>Do you mean that you might be doing something else with in the cart_id check?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T17:41:17.263", "Id": "21300", "Score": "0", "body": "Both this and the other answer work. This one seems to complete the queries faster. I'm using Postgres. Thank you both!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:54:48.880", "Id": "13132", "ParentId": "13130", "Score": "1" } }, { "body": "<p>If you work with database you can do this more efficiently with sql request:</p>\n\n<pre><code>LineItem.where(:card_id =&gt; @card.id).sum('quantity')\n</code></pre>\n\n<p>This is equivalent sql query</p>\n\n<pre><code>SELECT SUM(items.identity) FROM items WHERE items.card_id = ?;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T22:23:08.553", "Id": "13136", "ParentId": "13130", "Score": "6" } } ]
{ "AcceptedAnswerId": "13132", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T15:25:41.887", "Id": "13130", "Score": "3", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Instance variables and do loops in ruby on rails" }
13130
<p>Any suggestions to improve the performance of the following code? This code is exceeding the time limit for the last four cases. This is a solution to the problem <a href="https://www.interviewstreet.com/challenges/dashboard/#problem/4fcf919f11817" rel="nofollow">https://www.interviewstreet.com/challenges/dashboard/#problem/4fcf919f11817</a> </p> <pre><code>def main(): N = int(raw_input()) if(0&lt;=N&lt;=100000): x = [] ans=[] l=[] m=[] for i in xrange(0, N): tmp = raw_input() a, b = [xx for xx in tmp.split(' ')] l.append(a) m.append(int(b)) for i in xrange(0, N): if l[i]=='r': if len(x)&lt;1 or m[i] not in x: ans.append('Wrong!') elif m[i] in x: x.remove(m[i]) q=len(x) if q%2==1: ans.append(x[(q/2)]) elif q%2==0: if q==0: ans.append('Wrong!') else: k=x[q/2]+x[(q/2)-1] if k%2==0: ans.append(int(k)/2) else: ans.append(k/2.0) elif l[i]=='a': x.append(m[i]) x=sorted(x) p=len(x) if p%2==1: ans.append(x[(p/2)]) else: k=x[p/2]+x[(p/2)-1] if k%2==0: ans.append(int(k)/2) else: ans.append(k/2.0) for i in ans: print i if __name__ == "__main__": main() </code></pre> <hr> <pre><code>from sys import stdin,stdout from bisect import bisect,insort def main(): N = int(raw_input()) x = [] ans = [] append = x.append ans_append = ans.append remove = x.remove read = stdin.readline for i in xrange(0, N): tmp = read() a, b = tmp.split(' ') b = int(b) if a == 'r': search_result = search(x,b) if len(x) &lt; 1 or not(search_result): ans_append('Wrong!') else: remove(b) ans_append(median(x)) else: insort(x, b) ans_append(median(x)) for i in ans: print i def median(arr): q = len(arr) if q==0: return 'Wrong!' if q%2 == 1: return arr[(q/2)] else: k = arr[q/2] + arr[(q/2)-1] if k%2 == 0: return int(k)/2 else: return k/2.0 def search(arr,element): position = bisect(arr, element) if len(arr) &gt;= position and len(arr)!=0: if arr[position-1] == element: return True else: return False else: return False if __name__ == "__main__": main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T03:42:32.043", "Id": "62778", "Score": "0", "body": "How about rewriting it to be a bit clearer? I see at least one function in there you can factor out, there're probably more. As is it's difficult to understand and unmaintainable." } ]
[ { "body": "<pre><code>def main():\n N = int(raw_input())\n if(0&lt;=N&lt;=100000):\n</code></pre>\n\n<p>There really isn't much point in checking this. Your code works regardless of the value, and you don't need to worry about whether the contest will feed you larger values</p>\n\n<pre><code> x = []\n ans=[]\n l=[]\n m=[]\n</code></pre>\n\n<p>I suggest using longer names even in a contest scenario</p>\n\n<pre><code> for i in xrange(0, N):\n tmp = raw_input()\n a, b = [xx for xx in tmp.split(' ')]\n</code></pre>\n\n<p>Actually this line is the same as <code>a, b = tmp.split(' ')</code> The list comphrension just wastes processing power. Since there isn't going to be any unusual whitespcae, you can skip the parameter to split as well</p>\n\n<pre><code> l.append(a)\n m.append(int(b)) \n</code></pre>\n\n<p>Its not clear why you store this in a list. Just perform the operation as soon as you read it. No need to store things into the lists just to read them in another loop.</p>\n\n<pre><code> for i in xrange(0, N):\n</code></pre>\n\n<p>Here you should have used something like <code>for action, number in zip(l,m):</code></p>\n\n<pre><code> if l[i]=='r':\n if len(x)&lt;1 or m[i] not in x:\n</code></pre>\n\n<p>There isn't really a point to checking for <code>len &lt; 1</code>, since the second condition will fail in that case anyways</p>\n\n<pre><code> ans.append('Wrong!')\n</code></pre>\n\n<p>Just print out the output, don't store it up</p>\n\n<pre><code> elif m[i] in x:\n</code></pre>\n\n<p>You should be able to just make this an else</p>\n\n<pre><code> x.remove(m[i])\n</code></pre>\n\n<p>This is going to be slow. The checks for <code>m[i] in x</code> and the call to remove have to scan over the whole list to find the elements. But the list is sorted, which means you should be able to find elements faster. Check out the <code>bisect</code> module which enables provides binary search to make finding elements faster in sorted lists.</p>\n\n<pre><code> q=len(x)\n if q%2==1:\n ans.append(x[(q/2)])\n elif q%2==0:\n if q==0:\n ans.append('Wrong!')\n</code></pre>\n\n<p>This case is somewhat odd here, it'd make more sense to check for this on level out, before checking for odd and even</p>\n\n<pre><code> else:\n k=x[q/2]+x[(q/2)-1]\n if k%2==0:\n ans.append(int(k)/2)\n else:\n ans.append(k/2.0)\n elif l[i]=='a':\n x.append(m[i])\n x=sorted(x)\n</code></pre>\n\n<p>This is better written as <code>x.sort()</code> so as to sort in place. However, its going to be slow constantly resorting the list. Before adding the element, the list is almost sorted, so you can use that to your advantage. The <code>bisect</code> module has operations to make that easy</p>\n\n<pre><code> p=len(x)\n if p%2==1:\n ans.append(x[(p/2)])\n else:\n k=x[p/2]+x[(p/2)-1]\n if k%2==0:\n ans.append(int(k)/2)\n else:\n ans.append(k/2.0)\n</code></pre>\n\n<p>Ok, you're doing this again. You should have put this in a function or something</p>\n\n<pre><code> for i in ans:\n print i\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>Maintaining a sorted list is too expensive. Everytime you insert or remove elements, the computer has to shift the whole array in memory. Knowing this the contest site will devise questions to give you the worst case scenario. You are going to have to do something else.</p>\n\n<p>One possibility to explore would be to use a binary tree. Binary trees have faster insertion/removal times, and a reasonably fast way to calculate the median. Their disadvantage here is the complexity required to implement it. A binary tree itself isn't that complicated, but the problem is in a balancing strategy.</p>\n\n<p>A second possibility is to try and use heaps implemented in the heapq module. The idea would be that at any point in time, you maintain two heaps. One has the element less then the median and the other has the elements greater then the median. There is some trickiness there in how you would handle deletions, but I think it could be done.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T14:43:13.823", "Id": "21291", "Score": "0", "body": "Thank's for the suggestions. There is a lot of improvement in performance." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T04:35:06.203", "Id": "13144", "ParentId": "13133", "Score": "5" } } ]
{ "AcceptedAnswerId": "13144", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T16:48:12.293", "Id": "13133", "Score": "2", "Tags": [ "python", "performance", "contest-problem" ], "Title": "Median solving from Interview street in Python" }
13133
<p>Is this an acceptable use of typedef in the class, Inventory?</p> <p><strong>Inventory.h</strong></p> <pre><code>#ifndef INVENTORY_H #define INVENTORY_H #include "Item.h" #include &lt;unordered_map&gt; class Inventory { public: typedef std::unordered_map&lt;Item, int&gt; ItemTable; ///&lt; Items and their quantities const ItemTable&amp; items() const; void add_item(Item item, int quantity); int quantity(Item item); bool remove_item(Item item, int quantity); private: ItemTable items_; }; #endif </code></pre> <p><strong>Inventory.cpp</strong></p> <pre><code>#include "Inventory.h" #include "Item.h" #include &lt;cstddef&gt; const Inventory::ItemTable&amp; Inventory::items() const { return items_; } void Inventory::add_item(Item item, int quantity) { int total_of_item = items_[item]; items_[item] = total_of_item + quantity; } int Inventory::quantity(Item item) { return items_[item]; } bool Inventory::remove_item(Item item, int quantity) { int total_of_item = items_[item]; if (quantity &gt; total_of_item) { return false; } items_[item] = total_of_item - quantity; return true; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T21:34:10.047", "Id": "21306", "Score": "0", "body": "Normally, I absolutely hate typeset but you've used it very nicely." } ]
[ { "body": "<p>Very much so. It reduces typing on your part and increases readability on the reader's part.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T15:54:15.000", "Id": "21297", "Score": "0", "body": "It also reduces maintenance effort. I think that's the big win, here." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T03:55:57.973", "Id": "13142", "ParentId": "13138", "Score": "2" } }, { "body": "<p>Yes. I like it because it will make maintenance easier.</p>\n<p>If you change the type of the container then you only need to change it in one place in the code. I would even go and define other things in relation to the typedef.</p>\n<pre><code>// For example:\ntypedef ItemTable::iterator Iter;\ntypedef ItemTable::const_iterator CIter;\n</code></pre>\n<p>But I would not expose the internal object with this:</p>\n<pre><code>const Inventory::ItemTable&amp; Inventory::items() const\n</code></pre>\n<p>Any object that uses this method not becomes very tightly bound to this interface. I would question the need for this functionality. I prefer to expose methods that manipulate the object as a whole.</p>\n<p>An alternative is to expose the iterators. Iterators are a much looser coupling.</p>\n<p>As a result I would make <code>ItemTable</code> a private type. While the <code>Iter</code> and <code>CIter</code> would be public.</p>\n<h3>Edit:</h3>\n<pre><code>class X\n{\n typedef std::vector&lt;int&gt; Cont;\n Cont data;\n\n public:\n typedef Cont::iterator Iter;\n typedef Cont::const_iterator CIter;\n\n\n Iter begin() { return data.begin();}\n Iter end() { return data.end();}\n\n CIter begin() const { return data.begin();}\n CIter end() const { return data.end();}\n};\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T15:56:39.893", "Id": "21298", "Score": "1", "body": "Thanks, I just have a little convention question regarding your answer: Where should I place the private typedef so the public two iterator typedefs can see it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T22:10:08.783", "Id": "21307", "Score": "0", "body": "@kisplit: See edit." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T03:57:53.130", "Id": "13143", "ParentId": "13138", "Score": "7" } } ]
{ "AcceptedAnswerId": "13143", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T01:57:37.470", "Id": "13138", "Score": "7", "Tags": [ "c++" ], "Title": "Acceptable use of typedef in class?" }
13138
<p>In C++ (and C++11), classes defining a <code>+</code> and <code>+=</code> operators often define a <code>-</code> and <code>-=</code> operators that do nearly the same thing (except <code>+</code> is replaced with <code>-</code> in the function). </p> <p>What is the best way to avoid duplicated code here (and still achieve good performance)? I am sure there is a good way to do it with functors:</p> <p><strong>Here's what I've tried:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;functional&gt; struct num { int val; const num &amp; operator +=(const num &amp; rhs) { return op_equals&lt;std::plus&lt;int&gt; &gt;(rhs); } const num &amp; operator -=(const num &amp; rhs) { return op_equals&lt;std::minus&lt;int&gt; &gt;(rhs); } template &lt;typename op&gt; const num &amp; op_equals(const num &amp; rhs) { op operation; val = operation(val, rhs.val); return *this; } }; int main() { num x{1}; num y{2}; x += y; std::cout &lt;&lt; x.val &lt;&lt; std::endl; return 0; } </code></pre> <p>Note that this is a simple example; in reality the code in the <code>+=</code> and <code>-=</code> operators is more complex.</p> <p>Also, I am not married to functors in the solution-- any suggestions or advice?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:52:15.900", "Id": "21261", "Score": "1", "body": "Have you looked at [Boost.Operators](http://www.boost.org/libs/utility/operators.htm)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:52:33.953", "Id": "21262", "Score": "1", "body": "Also, what's wrong with your current code?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:52:55.050", "Id": "21263", "Score": "2", "body": "Is replacing duplicated code with more code in total a win?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:52:56.843", "Id": "21264", "Score": "0", "body": "@ildjarn As with most C++ questions on SO, I'm sure there's a solution in Boost, but I'm trying to learn better practice. If you know how they work, I'd love to hear it!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:53:05.660", "Id": "21265", "Score": "4", "body": "A common pattern is to implement `operator+` in terms of `operator+=`, which minimises repeated code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:53:51.720", "Id": "21266", "Score": "2", "body": "@Oliver: So using Boost is bad practice?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:54:04.300", "Id": "21267", "Score": "6", "body": "I think in this particular case, KISS is the best practice." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:55:37.973", "Id": "21268", "Score": "1", "body": "@Jon Not necessarily but in general: yes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:55:41.603", "Id": "21269", "Score": "0", "body": "@NiklasB. I'm definitely not disparaging Boost! I mean I want to learn how a seasoned programmer would feel about this problem (and not simply use someone elses code). Boost is great though, not insulting Boost!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:56:23.010", "Id": "21270", "Score": "0", "body": "http://stackoverflow.com/questions/4421706/operator-overloading-in-c/4421719#4421719" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:57:43.863", "Id": "21271", "Score": "0", "body": "@Jon No need to be snarky- as I'm sure you know, this is an example. In reality, I'm doing something like addition/subtraction of multivariate sparse vectors. In the past I simply copied code, but would sometimes need to propagate changes 2x. And if that's the best solution, I acquiesce. What do you think is the best solution?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T22:09:44.533", "Id": "21272", "Score": "0", "body": "@Oliver: It is perhaps not *that* obvious that this is an example (vs. a thought experiment). The question was genuine. I applaud your intellectual curiosity, but on the other hand am inclined to believe this is over-engineering things and of doubtful practical benefit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T22:12:50.043", "Id": "21273", "Score": "0", "body": "If operators `+` and `-` delegate to the `+=` and `-=` you show, is there anything left in them to which you need to _propagate changes_? It seems like you'd have 4, rather than 2 operators delegating to a single template, and any complexity goes in there." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T02:12:23.703", "Id": "21274", "Score": "0", "body": "I think that your code is perfectly fine. It's understandable as to what it does. You may want to check how well you compiler optimizes it -- the construction of the `op` instance may linger and mess things up." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T02:48:24.640", "Id": "21277", "Score": "0", "body": "@KubaOber Can `op` cause problems even if it instantiates no data? I'd assumed it would simply be treated as a global function call underneath..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T03:51:47.743", "Id": "21282", "Score": "0", "body": "The obvious reply: look at the assembly and see if it does in fact look like a global function call :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-07T10:57:20.707", "Id": "34361", "Score": "0", "body": "For class types, you'll still have to define operator+ and operator- as two separate functions." } ]
[ { "body": "<p>I actually quite like this pattern and use it relatively often. I'm not sure if there is something better than functors for this - if there is, I'm not really aware of it. That being said, with C++11, I'd write this in a slightly different way:</p>\n\n<pre><code>struct num {\n int val;\n\n const num&amp; operator +=(const num &amp; rhs) {\n return op_equals(rhs, std::plus&lt;int&gt;());\n }\n\n const num&amp; operator -=(const num &amp; rhs) {\n return op_equals(rhs, std::minus&lt;int&gt;());\n }\n\n template &lt;typename op&gt;\n const num &amp; op_equals(const num &amp; rhs, op&amp;&amp; o) {\n val = o(val, rhs.val);\n return *this;\n }\n};\n</code></pre>\n\n<p>Note the rvalue reference (which is actually a \"universal reference\", so can bind to either an lvalue or rvalue reference), and the movement of <code>op</code> to a parameter - I don't really like having to specify it as a template parameter which then gets instantiated and called in the function. I think this way is slightly cleaner.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T16:03:59.107", "Id": "35345", "Score": "0", "body": "+1 Nice suggestions. I know to some people this feels like overkill, but to me it feels elegant (no duplicated code = no finding errors twice...)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-02-21T01:56:51.657", "Id": "22945", "ParentId": "13140", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "17", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-27T21:50:40.713", "Id": "13140", "Score": "8", "Tags": [ "c++", "c++11", "operator-overloading" ], "Title": "Avoid duplicated += -= operator code" }
13140
<p>i had made a small code snippet for multiple inheritance in js. this code is working for me but actually i like to get the review, that its good and if any problem; provide the solution. etc. the code snippet is below.</p> <pre><code>/** * WebbaseUtility provide the bundle of utilities used for support the webbase * functionalities; * @package : WebbaseUtility; * @version : 1.0.0; */ var WebbaseUtility = {}; /** * ObjectExt module extends the object properties and functionalities like inheritance etc; * @module : ObjectExt; * @package : Webbase; * @version : 1.0.0; * @return Object; */ var ObjectExt = WebbaseUtility.ObjectExt = (function() { /** * ObjectExt Constructor; */ var ObjectExt = function() { }; /** * This method provide inheritance to the object supplied; this method inherit the * public methods from the Parent class to the Child class. this also provide * multiple inheritance, in which the method ambiguity is solved by the overriding * the last inherited class's method; * @access public; * @method inherit; * @param Object Parent; * @param Object Child; * @return Object; */ ObjectExt.prototype.inherit = function(Parent, Child) { var TempObj = function(){}, MultipleInheritanceTempObj = function(){}; MultipleInheritanceTempObj.prototype = Child.prototype; TempObj.prototype = Parent.prototype; for(var key in MultipleInheritanceTempObj.prototype) { TempObj.prototype[key] = MultipleInheritanceTempObj.prototype[key]; } MultipleInheritanceTempObj = null; Child.prototype = new TempObj(); if(Child.uber === undefined) { Child.uber = Parent.prototype; }else { for(var key in Parent.prototype) { Child.uber[key] = Parent.prototype[key]; } } Child.prototype.constructor = Child; return Child; }; return new ObjectExt(); })(); Child = WebbaseUtility.ObjectExt.inherit(ParentA, Child); Child = WebbaseUtility.ObjectExt.inherit(ParentB, Child); </code></pre>
[]
[ { "body": "<p>First of all, I responded to the <a href=\"http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/2ba05b0f5e4a9648\" rel=\"nofollow\">post in c.l.js</a>, and this content in part reiterates the comments there.</p>\n\n<p>My first thought is that you should look at some of the available mixin libraries. There are many mixin techniques available. And on top of that, there are many interesting approaches layered on top of them. Peter Michaux <a href=\"http://peter.michaux.ca/articles/mixins-and-constructor-functions\" rel=\"nofollow\">published one recently</a> on applying mixins to constructor functions. Angus Croll published one on <a href=\"http://javascriptweblog.wordpress.com/2011/05/31/a-fresh-look-at-javascript-mixins/\" rel=\"nofollow\">creating functions out of mixins</a>, and together with Dan Webb he also <a href=\"https://speakerdeck.com/u/anguscroll/p/how-we-learned-to-stop-worrying-and-love-javascript\" rel=\"nofollow\">presented this technique</a> at the recent Fluent Conference. I published a rough draft of an article on a still <a href=\"http://scott.sauyet.com/Javascript/Drafts/2012-05-04a/\" rel=\"nofollow\">different approach to mixins</a>.</p>\n\n<p>I don't understand the reason for your complex syntactic structure.\nYou assign your ObjectExt variable to the result of an immediately\ninvoked function expression (IIFE). That IIFE involves defining a\nconstructor function, attaching the <code>inherit</code> function to its\nprototype`, and then constructing and returning an instance of that\nconstructor:</p>\n\n<pre><code> var ObjectExt = (function () {\n var ObjectExt = function () { };\n ObjectExt.prototype.inherit = function (Parent, Child) {\n // content here\n };\n return new ObjectExt();\n })();\n</code></pre>\n\n<p>I don't see that any of that serves any purpose over the much simpler\nversion here:</p>\n\n<pre><code> var ObjectExt = {inherit: function (Parent, Child) {\n // content here\n };\n</code></pre>\n\n<p>Can you give any reason for the existence of this constructor\nfunction, the IIFE, the prototype, etc? It seems to be plain\noverhead, and serves only to obfuscate your code.</p>\n\n<p>One other minor point is that you probably should declare your <code>key</code>\nvariable once in the top of the <code>inherit</code> function. </p>\n\n<p>But the main issue is that you add properties to the parent.prototype object. In this code:</p>\n\n<pre><code>if(Child.uber === undefined) {\n Child.uber = Parent.prototype; // (1)\n} else {\n for(var key in Parent.prototype) {\n Child.uber[key] = Parent.prototype[key]; // (2)\n }\n}\n</code></pre>\n\n<p>in the line marked (1), you create the <code>Child.uber</code> property as <strong>reference</strong> to the <code>Parent.prototype</code>. So any properties you add when you come through the if-block again and hit (2) will be added to the orignial prototype object. This is a pretty fundamental flaw. An example would be the following:</p>\n\n<pre><code>var Pet = function(name) {this.name = name;}\nPet.prototype.speak = function(){\n console.log(this.name + \" speaks.\");\n};\nvar WalkingAnimal = function() {};\nWalkingAnimal.prototype.walk = function() {\n console.log(this.name + \" is walking.\");\n};\nvar SwimmingAnimal = function() {};\nSwimmingAnimal.prototype.swim = function() {\n console.log(this.name + \" is swimming.\");\n};\nvar Dog = function(name) {this.name = name;};\nWebbaseUtility.ObjectExt.inherit(Pet, Dog);\nWebbaseUtility.ObjectExt.inherit(WalkingAnimal, Dog);\n\nvar ClownFish = function(name) {this.name = name;};\nWebbaseUtility.ObjectExt.inherit(Pet, ClownFish);\nWebbaseUtility.ObjectExt.inherit(SwimmingAnimal, ClownFish);\n\nvar rover = new Dog(\"Rover\");\nvar nemo = new ClownFish(\"Nemo\");\nrover.walk(); // \"Rover is walking\";\nnemo.swim(); // \"Nemo is swimming\";\nnemo.walk(); // \"Nemo is walking\"; // WTF?\n</code></pre>\n\n<p>This is a fairly fundamental design flaw. I think you need to rethink your approach to this problem.</p>\n\n<p>Cheers,</p>\n\n<p>-- Scott</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-01T11:03:22.940", "Id": "53895", "Score": "0", "body": "Very good review!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T20:30:47.980", "Id": "13375", "ParentId": "13147", "Score": "3" } } ]
{ "AcceptedAnswerId": "13375", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T07:28:24.850", "Id": "13147", "Score": "1", "Tags": [ "javascript", "object-oriented" ], "Title": "javascript multiple inheritance code review" }
13147
<p>I had code that violated the Single Responsibility Principle in a <a href="https://stackoverflow.com/questions/11224170/refactoring-code-to-avoid-anti-pattern">question on Stack Overflow</a>.</p> <p>In order to overcome that problem, I changed the code as follows.</p> <ol> <li>Is this a good practice in order to overcome the problem? </li> <li>Is this a pattern?</li> <li>Is there a better way?</li> <li>Does it satisfy the Unit Of Work pattern using LINQ-to-SQL?</li> </ol> <p></p> <pre><code>namespace DomainObjectsForBank { public interface IBankAccount { int BankAccountID { get; set; } string AccountStatus { get; set; } void FreezeAccount(); RepositoryLayer.IRepository&lt;RepositoryLayer.BankAccount&gt; AccountRepository { get; set; } } public class FixedBankAccount : IBankAccount { public int BankAccountID { get; set; } public string AccountStatus { get; set; } public void FreezeAccount() { //ChangeAccountStatus(); AccountStatus = "Frozen"; } //private void ChangeAccountStatus() //{ // AccountStatus = "Frozen"; // RepositoryLayer.BankAccount repositoryBankAccEntity = new RepositoryLayer.BankAccount(); // repositoryBankAccEntity.BankAccountID = this.BankAccountID; // accountRepository.UpdateChangesByAttach(repositoryBankAccEntity); // repositoryBankAccEntity.Status = "Frozen"; // accountRepository.SubmitChanges(); //} private RepositoryLayer.IRepository&lt;RepositoryLayer.BankAccount&gt; accountRepository; public RepositoryLayer.IRepository&lt;RepositoryLayer.BankAccount&gt; AccountRepository { get { return accountRepository; } set { accountRepository = value; } } } } </code></pre> <hr> <pre><code>using System.Collections.Generic; using System; namespace ApplicationServiceForBank { public class BankAccountService { RepositoryLayer.IRepository&lt;RepositoryLayer.BankAccount&gt; accountRepository; ApplicationServiceForBank.IBankAccountFactory bankFactory; public BankAccountService(RepositoryLayer.IRepository&lt;RepositoryLayer.BankAccount&gt; repo, IBankAccountFactory bankFact) { accountRepository = repo; bankFactory = bankFact; } public void FreezeAllAccountsForUser(int userId) { IEnumerable&lt;RepositoryLayer.BankAccount&gt; accountsForUser = accountRepository.FindAll(p =&gt; p.BankUser.UserID == userId); foreach (RepositoryLayer.BankAccount oneOfRepositroyAccounts in accountsForUser) { DomainObjectsForBank.IBankAccount domainBankAccountObj = bankFactory.CreateAccount(oneOfRepositroyAccounts); if (domainBankAccountObj != null) { domainBankAccountObj.BankAccountID = oneOfRepositroyAccounts.BankAccountID; domainBankAccountObj.FreezeAccount(); this.accountRepository.UpdateChangesByAttach(oneOfRepositroyAccounts); oneOfRepositroyAccounts.Status = domainBankAccountObj.AccountStatus; this.accountRepository.SubmitChanges(); } } } } public interface IBankAccountFactory { DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositroyAccount); } public class MySimpleBankAccountFactory : IBankAccountFactory { //Is it correct to accept repository inside factory? public DomainObjectsForBank.IBankAccount CreateAccount(RepositoryLayer.BankAccount repositroyAccount) { DomainObjectsForBank.IBankAccount acc = null; if (String.Equals(repositroyAccount.AccountType, "Fixed")) { acc = new DomainObjectsForBank.FixedBankAccount(); } if (String.Equals(repositroyAccount.AccountType, "Savings")) { //acc = new DomainObjectsForBank.SavingsBankAccount(); } return acc; } } } </code></pre>
[]
[ { "body": "<p>I'm not sure about some of your questions, but a few ideas I have are:</p>\n\n<ol>\n<li>Could you make the the account status and even account types an\nenumeration? I tend to try and err on the use of enumerations over string literals. I believe the latest version of Linq to SQL supports this?</li>\n<li>Why do you need to expose the repository on your IBankAccount interface. Why would the interface even care about a repository? I think this is better being supplied to any concrete classes via it's constructor? It would also make unit testing easier I would think.</li>\n<li>I personally wouldn't pass in the whole BankAccount object into the factory method. It only needs the account type so I would pass in that. Probably I would look at using a switch or if else in that factory method as well and throwing an exception if you can't create it (depends on your requirements of this method).</li>\n</ol>\n\n<p>Just a few thoughts.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T20:00:40.783", "Id": "13167", "ParentId": "13148", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T07:37:08.053", "Id": "13148", "Score": "3", "Tags": [ "c#", "object-oriented", "design-patterns", ".net", "finance" ], "Title": "Usage of Single Responsibility Principle with bank account services implementation" }
13148
<p>I have written an algorithm in C#. It is recursive, but it is not optimal. Maybe you have suggestions for improvement? (I already posted this question on stackoverflow but the question was closed there).</p> <p>This is the exercise (I made it up myself). There are 3 or more buckets and there are 4 or more balls. The goal is to calculate every combination to distribute all balls over all buckets. There must be at least 1 ball in a bucket.</p> <p>For example: if you have 3 buckets and 5 balls you get these combinations (as produced by the program):</p> <pre><code>Balls:3 1 1 | Total = 5 Balls:2 2 1 | Total = 5 Balls:1 3 1 | Total = 5 Balls:1 2 2 | Total = 5 &lt;-- This one is unwanted Balls:2 1 2 | Total = 5 Balls:1 2 2 | Total = 5 Balls:1 1 3 | Total = 5 </code></pre> <p>Explanation: There is a separate class Balls, which is a list of integers. Depth and branchingfactor determine the number of buckets and the number of balls. The first combination starts with the maximum number of balls in the first bucket and 1 in the other buckets. Then 1 ball is taken out of the first bucket and is put in the second bucket and so on.</p> <p>This is the code:</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; namespace BallBruteForce { class Program { //Final result is stored in List static List&lt;Balls&gt; BallsList=new List&lt;Balls&gt;(); static int Depth = 5; static int BranchingFactor = 10; static int minComp; static int maxComp; static void Main(string[] args) { minComp = 1; maxComp= BranchingFactor - (Depth-1)*minComp; Stopwatch sw = new Stopwatch(); sw.Start(); startBruteForce(Depth); sw.Stop(); Console.WriteLine("Time elapsed: " + sw.Elapsed); Console.WriteLine("Press Enter to Exit"); Console.ReadLine(); } private static void startBruteForce(int keyLength) { var ratioArray = createArray(keyLength); BallsList.Add(ratioArray); int count = 1; Console.WriteLine(count +". " + ratioArray); createNewArray(0, keyLength, ratioArray, ref count); Console.WriteLine("Total processed: " + count); } private static void createNewArray(int curCol, int length, Balls ratioArray, ref int count) { Balls copyArray = new Balls(ratioArray); if (ratioArray[0] &gt; minComp) { if (curCol == 0) { Balls baseArray = new Balls(ratioArray); for (int i = 1; i &lt; length; i++) { createNewArray(i, length, copyArray, ref count); } } else { copyArray[0]--; copyArray[curCol]++; BallsList.Add(copyArray); count++; Console.WriteLine(count + ". " + copyArray); createNewArray(0, length, copyArray, ref count); } } } private static Balls createArray(int length) { Balls ballsC = new Balls(); ballsC.Add(maxComp); for (int i = 1; i &lt; length; i++) { ballsC.Add(minComp); } return ballsC; } class Balls : List&lt;int&gt; { public Balls() { } public Balls(Balls newSds) { newSds.ForEach((item) =&gt; { this.Add(item); }); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("Balls:"); foreach (int sd in this) { sb.AppendFormat("{0} ", sd); } sb.AppendFormat("| Total = {0} ", this.Sum()); return sb.ToString(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T09:05:21.937", "Id": "21287", "Score": "2", "body": "Why is that one unwanted?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-19T17:28:56.947", "Id": "22326", "Score": "1", "body": "Looks like it's because a different permutation of putting balls in buckets produces the same combination of balls in buckets. See the combination two rows down; same thing, probably produced with a different sequence." } ]
[ { "body": "<p>The obvious answer (for the unwanted duplicate) is to maintain a set of the previous column counts. So when it comes to (the second) [1,2,2], you can check whether it's in the set of { [3,1,1], [2,2,1], [1,3,1], [1,2,2], [2,1,2] } and conclude that you don't want to print the line and so exit the recursion.</p>\n\n<p>This won't block the specific one you want, but I don't think it should matter wrt the results.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T13:39:47.523", "Id": "13158", "ParentId": "13149", "Score": "1" } }, { "body": "<p>This is a base 3 number, of 5 digits (with the extra note that each digit must have +1 to it and total for all digits must equal 5). I based this on my own SO answer here: <a href=\"https://stackoverflow.com/a/9315076/360211\">https://stackoverflow.com/a/9315076/360211</a></p>\n\n<pre><code>class Program\n {\n static void Main()\n {\n int balls = 5;\n int buckets = 3;\n int maxInBucket = balls - buckets + 1; //because of rule about must be 1\n int baseN = maxInBucket;\n int maxDigits = buckets;\n var max = Math.Pow(baseN, maxDigits);\n for (int i = 0; i &lt; max; i++)\n { // each iteration of this loop is another unique permutation \n var digits = new int[maxDigits];\n int value = i;\n int place = digits.Length - 1;\n while (value &gt; 0)\n {\n int thisdigit = value % baseN;\n value /= baseN;\n digits[place--] = thisdigit;\n }\n var totalBallsInThisCombo = digits.Sum(d =&gt; d + 1); //+1 because each bucket always has one in it\n if (totalBallsInThisCombo != balls) //this is the implementation of rule about must = 5\n {\n continue;\n }\n Console.Write(\"Balls: \");\n foreach (var digit in digits)\n {\n Console.Write(digit + 1); //+1 because each bucket always has one in it\n Console.Write(\" \");\n }\n Console.WriteLine(\"| Total = {0}\", totalBallsInThisCombo);\n }\n Console.ReadLine();\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T12:19:51.890", "Id": "13184", "ParentId": "13149", "Score": "0" } }, { "body": "<h3>There's a better way</h3>\n\n<p>If there are 5 balls and 3 buckets, but each bucket must contain at least 1 ball, imagine the following set of balls:</p>\n\n<pre><code>O O O O O\n</code></pre>\n\n<p>Rather than moving the balls around, we can move buckets.</p>\n\n<p>That is, I will mark 3 balls with an 'x' and that ball and the balls to the left of it (until the next 'x') are part of the bucket, (since all balls are in a bucket, the right-most ball must be marked.\n So we get:</p>\n\n<pre><code>x x O O x , x O x O x , x O O x x , O x x O x , O x O x x , O O x x x\n</code></pre>\n\n<h3>Code to solve 3 buckets, N balls</h3>\n\n<pre><code>private static readonly int NumOfBuckets = 3; \nprivate static readonly int NumOfBalls = 8;\n\nprivate static string getCombinations()\n{\n int numBuckets = 3;\n int numBalls = 5;\n\n StringBuilder sb = new StringBuilder();\n\n for (int i = 1; i &lt;= numBalls - 2; i++)\n {\n int ballsInBucket1 = i;\n\n for (int j = i + 1; j &lt;= numBalls - 1; j++)\n {\n int ballsInBucket2 = (j - 1);\n\n int k = numBalls;\n\n int ballsInBucket3 = k - j;\n\n string s = \"Balls:\" + ballsInBucket1 + \" \" + ballsInBucket2 + \" \" + ballsInBucket3 + \" | Total = 5\";\n sb.AppendLine(s);\n }\n }\n return sb.ToString();\n}\n\nstatic void Main(string[] args)\n{\n string result = getCombinations();\n Console.WriteLine(result);\n Console.ReadLine();\n}\n</code></pre>\n\n<p>Basically the code is using i,j, and k to mark x's on the balls, and then we get the number of balls out. We don't need to remove any duplicates, since we generated just Combinations, and not permutations.</p>\n\n<p>This code works for 3 buckets and n balls. </p>\n\n<p>But because of the 2 hard-coded For loops this won't work for more or less buckets.</p>\n\n<h3>Using Recursion to Infinitely Nest the For Loops</h3>\n\n<p>The real difficulty here is that each possible combination needs to be written as a line on the console. This means that our recursive function needs to be able to return multiple lines, and add to each line as the recursion comes back.</p>\n\n<p>The Base case of the recursion is easy, if there is just 1 bucket, put all the rest of the balls in it.</p>\n\n<p>Otherwise we loop through the number of balls we can put in the first bucket, and recurse with a smaller problem size, then add the first number of balls to each of those results coming back.</p>\n\n<p>We use a recursive function which is called by a helper function so that we can move the timing code into a separate place.</p>\n\n<h3>Code to solve M buckets, N balls</h3>\n\n<pre><code>private static string getCombinationsRecursiveHelper()\n{\n StringBuilder sb = new StringBuilder();\n\n string[] subResult = getCombinationsRecursive(NumOfBuckets, NumOfBalls);\n\n for( int i = 0; i &lt; subResult.Length; i++)\n {\n sb.AppendLine( \"Balls:\" + subResult[i] + \" | Total = \" + NumOfBalls );\n }\n\n return sb.ToString();\n}\n\nprivate static string[] getCombinationsRecursive( int numBuckets, int numBalls)\n{\n if (numBuckets == 1)\n {\n return new string[]{numBalls.ToString()};\n }\n\n int numBuckets_minus_1 = numBuckets - 1;\n\n int bound = numBalls - numBuckets_minus_1;\n\n long numOfPossibilities = NChooseK( numBalls - 1, numBuckets_minus_1);\n\n string[] result = new string[ numOfPossibilities ];\n\n int current = 0;\n\n for (int i = 0; i &lt; bound; i++)\n {\n string[] subResult = getCombinationsRecursive(numBuckets - 1, numBalls - (i+1));\n for (int j = 0; j &lt; subResult.Length; j++)\n {\n result[current] = (i+1).ToString() + \" \" + subResult[j];\n current++;\n }\n }\n\n return result;\n}\n\nprivate static long NChooseK(long n, long k)\n{\n long result = 1;\n\n for (long i = Math.Max(k, n - k) + 1; i &lt;= n; ++i)\n result *= i;\n\n for (long i = 2; i &lt;= Math.Min(k, n - k); ++i)\n result /= i;\n\n return result;\n}\n\nstatic void Main(string[] args)\n{\n Console.WriteLine(\"Starting Program\");\n Console.WriteLine(\"\");\n\n string result = getCombinationsRecursiveHelper();\n\n Console.BufferHeight = result.Length;\n\n Console.WriteLine( result );\n\n Console.WriteLine(\"\");\n Console.WriteLine(\"Press Enter to Exit\");\n Console.ReadLine();\n */\n} \n</code></pre>\n\n<p>I make use of an NChooseK function so we can determine how large the string[] needs to be to hold the results from the subproblems which will be carried out at the next level down in recursion.</p>\n\n<h3>Full Code with Timing Code</h3>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Diagnostics;\n\nnamespace BallsInBins\n{\n class Program\n {\n private static readonly int NumOfBuckets = 8; \n private static readonly int NumOfBalls = 12;\n private static double AverageMilliseconds = -1.0;\n\n static void Main(string[] args)\n {\n Console.WriteLine(\"Starting Program\");\n Console.WriteLine(\"\");\n\n string result = DoTiming( getCombinationsRecursiveHelper );\n\n Console.BufferHeight = result.Length;\n\n Console.WriteLine( result );\n\n Console.WriteLine(\"\");\n Console.WriteLine(\"ElapsedTime: {0:N8} Milliseconds.\", AverageMilliseconds);\n Console.WriteLine(\"\");\n Console.WriteLine(\"Press Enter to Exit\");\n Console.ReadLine(); \n }\n\n private static readonly int MinTimingVal = 1000;\n private static readonly int MinLoopTimingVal = 1000;\n\n /// &lt;summary&gt;\n /// Times how long in Milliseconds a function takes which returns a string.\n /// Complies with best timing practices.\n /// Does not make timings of less than 1 full second, warms up the code \n /// for the JIT compiler before timing, gets average time spent per iteration,\n /// and accounts for the looping overhead in a similar manner.\n /// &lt;/summary&gt;\n /// &lt;param name=\"a\"&gt; Func&lt;string&gt; theActionToTime&lt;/param&gt;\n /// &lt;returns&gt;The string result of the function.&lt;/returns&gt; \n private static string DoTiming(Func&lt;string&gt; a)\n {\n string result = a.Invoke();\n\n Stopwatch watch = new Stopwatch();\n Stopwatch loopWatch = new Stopwatch();\n\n bool shouldRetry = false;\n\n int numOfIterations = 1;\n\n do\n {\n watch.Start();\n\n for (int i = 0; i &lt; numOfIterations; i++)\n {\n a.Invoke();\n }\n\n watch.Stop();\n\n shouldRetry = false;\n\n if (watch.ElapsedMilliseconds &lt; MinTimingVal) //if the time was less than the minimum, increase load and re-time.\n {\n shouldRetry = true;\n numOfIterations *= 2;\n watch.Reset();\n }\n\n } while (shouldRetry);\n\n long totalTime = watch.ElapsedMilliseconds;\n\n double avgloopingTime = getLoopingTime(numOfIterations);\n\n double avgMilliseconds = (((double)totalTime) / (double)numOfIterations) - avgloopingTime;\n TimeSpan t = TimeSpan.FromMilliseconds(avgMilliseconds);\n\n AverageMilliseconds = avgMilliseconds;\n\n Debug.WriteLine(\"ElapsedTime: {0:N8} Milliseconds.\", avgMilliseconds);\n\n return result;\n }\n\n private static double getLoopingTime(int numOfIterations)\n {\n int wrmUpTimes = 3;\n int outerLoop = 2;\n long elapsedTime = -1L;\n double avg = 0.0;\n\n Stopwatch watch = new Stopwatch();\n\n for (int wrm = 0; wrm &lt; wrmUpTimes; wrm++)\n {\n watch.Start();\n for (int i = 0; i &lt; outerLoop; i++)\n {\n for (int j = 0; j &lt; numOfIterations; j++)\n {\n ; //time how long an empty loop takes.\n }\n\n }\n watch.Stop();\n\n elapsedTime = watch.ElapsedMilliseconds;\n\n if (elapsedTime &lt; MinLoopTimingVal)\n {\n wrm--;\n outerLoop *= 2;\n }\n else\n {\n avg = elapsedTime / (double)outerLoop;\n }\n }\n return avg;\n }\n\n private static string getCombinationsRecursiveHelper()\n {\n StringBuilder sb = new StringBuilder();\n\n string[] subResult = getCombinationsRecursive(NumOfBuckets, NumOfBalls);\n\n for( int i = 0; i &lt; subResult.Length; i++)\n {\n sb.AppendLine( \"Balls:\" + subResult[i] + \" | Total = \" + NumOfBalls ); \n }\n\n return sb.ToString();\n }\n\n private static string[] getCombinationsRecursive( int numBuckets, int numBalls)\n {\n if (numBuckets == 1)\n {\n return new string[]{numBalls.ToString()};\n }\n\n int numBuckets_minus_1 = numBuckets - 1;\n\n int bound = numBalls - numBuckets_minus_1;\n\n long sumOfPossibilities = NChooseK( numBalls - 1, numBuckets_minus_1);\n\n string[] result = new string[ sumOfPossibilities ];\n\n int current = 0;\n\n for (int i = 0; i &lt; bound; i++)\n {\n string[] subResult = getCombinationsRecursive(numBuckets - 1, numBalls - (i+1));\n for (int j = 0; j &lt; subResult.Length; j++)\n {\n result[current] = (i+1).ToString() + \" \" + subResult[j];\n current++;\n }\n }\n\n return result;\n }\n\n private static long NChooseK(long n, long k)\n {\n long result = 1;\n\n for (long i = Math.Max(k, n - k) + 1; i &lt;= n; ++i)\n result *= i;\n\n for (long i = 2; i &lt;= Math.Min(k, n - k); ++i)\n result /= i;\n\n return result;\n }\n }\n}\n</code></pre>\n\n<p>This includes timing code which runs the algorithm enough times to take longer than a full second, then divides by the number of iterations so you can get an average time elapsed (also it subtracts the average amount of time it took to loop that many times).</p>\n\n<p>On my computer this computes 16 buckets and 24 balls in an average 2,278 milliseconds.</p>\n\n<p>(Of course, printing the solution to the console takes a lot longer)</p>\n\n<h3>Other Optimizations/Changes</h3>\n\n<ol>\n<li><p>To make this run faster, use memoization for the function getCombinationsRecursive().</p></li>\n<li><p>Use BigInteger in the NChooseK instead of longs to support larger numbers, but then you will also need to use something other than string[] for the results for very large instances.</p></li>\n<li><p>Use parallelism if you don't care about the order in which the results get written (although as it stands, that could be difficult with this implementation).</p></li>\n<li><p>Write the results right to left by appending instead of putting the new values in front of the subResults.</p></li>\n<li><p>Completely change the algorithm to do a depth-first search over the possibilities instead of a breadth first search, that way each result could be written one at a time, instead of needing to store it all back out of the recursion.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-19T10:25:36.290", "Id": "13830", "ParentId": "13149", "Score": "2" } }, { "body": "<p>I would approach the algorithm in the following way:</p>\n\n<ul>\n<li>All cases start with either one, two or three balls being places in the first bucket. So, do each of these.</li>\n<li>For each of the above cases, recurse through putting balls in the second bucket, following your rules (meaning that you cannot put so many balls in the second bucket that you cannot put at least one ball in the third bucket).</li>\n<li>For each of THOSE cases, put all remaining balls in the third bucket.</li>\n</ul>\n\n<p>Doing it this way, there's only one algorithmic path to follow that will result in the balls being in the buckets in a particular combination; 1-3-1 is arrived at by putting one ball in the first, then three balls in the second, then one ball in the last; not by starting with 3-1-1 and then moving balls to produce the progressions 2-2-1 -> 2-1-2 -> 1-2-2 OR 2-2-1 -> 1-3-1 -> 1-2-2, as your algorithm is currently doing.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-19T17:36:07.750", "Id": "13846", "ParentId": "13149", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T08:32:46.093", "Id": "13149", "Score": "2", "Tags": [ "c#", "algorithm", "recursion" ], "Title": "How can I remove unwanted combinations from my algorithm in C#?" }
13149
<p>I wrote the following code for printing all the paths to the leaf nodes in a tree (NOT a binary tree ) without using recursion. I have used a stack and performed dfs on the tree. Whenever I reach a leaf node I pop all the elements in the stack right till the root so that the function starts over again from the root and prints a path to another leaf.</p> <p>The tree that I have assumed in the program is as follows</p> <blockquote> <pre><code> 0 1 2 3 4 5 6 7 8 </code></pre> </blockquote> <p>Explanation:</p> <ul> <li><code>1</code>, <code>2</code> and <code>3</code> are children of <code>0</code>; </li> <li><code>4</code>, <code>5</code>, <code>6</code> are children of <code>1</code>; </li> <li><code>7</code> and <code>8</code> are children of <code>3</code>.</li> </ul> <p><a href="http://ideone.com/a6xHq" rel="nofollow">My code</a></p> <pre><code>//print paths in a tree without recursion #include&lt;iostream&gt; #include&lt;vector&gt; #include&lt;stack&gt; using namespace std; struct node { int data; vector&lt;node*&gt;children; }; int visited[100]; stack &lt;node*&gt; st; int count=0; int n; void printpath(node * root) //dfs starts here { st.push(root); while(visited[0]==0) { node* v=st.top(); if(visited[v-&gt;data]!=0) // leaf nodes or nodes whose all children st.pop(); // are visited are only popped from the stack if(visited[v-&gt;data]) continue; cout&lt;&lt;v-&gt;data&lt;&lt;" "; int flag=0; for(int i=0;i&lt;v-&gt;children.size();i++) /*check if any of the children have not been visited*/ { if(visited[v-&gt;children[i]-&gt;data]==0) { flag=flag||1; st.push(v-&gt;children[i]); } else flag=flag||0; } /*if this is the leaf node then mark it visited and along with other intermediate nodes whose all the children have been visited.this is continued till we reach root which has the value 0 in its data*/ if(flag==0) { visited[v-&gt;data]=1; while(v-&gt;data!=0) { v=st.top(); int flag=0; for(int i=0;i&lt;v-&gt;children.size();i++) { if(visited[v-&gt;children[i]-&gt;data]==0) flag=flag||1; else flag=flag||0; } if(flag==0 &amp;&amp; v-&gt;children.size()!=0) visited[v-&gt;data]=1; if(v-&gt;data!=0) st.pop(); } cout&lt;&lt;endl; } } } main() { n=8; for(int i=0;i&lt;9;i++) visited[i]=0; node*root = new node(); //tree construction root-&gt;data=0; node* d = new node(); d-&gt;data=1; node* m = new node(); m-&gt;data=2; node* n = new node(); n-&gt;data=3; root-&gt;children.push_back(d); root-&gt;children.push_back(m); root-&gt;children.push_back(n); node* x = new node(); x-&gt;data=4; node* y = new node(); y-&gt;data=5; node* z = new node(); z-&gt;data=6; d-&gt;children.push_back(x); d-&gt;children.push_back(y); d-&gt;children.push_back(z); node* o = new node(); o-&gt;data=7; node* p = new node(); p-&gt;data=8; n-&gt;children.push_back(o); n-&gt;children.push_back(p); printpath(root); } </code></pre> <p>My algorithm seems really inefficient. Can anyone suggest some ways to improve it?</p> <p><strong>The output is:</strong></p> <blockquote> <pre><code>0 3 8 0 3 7 0 2 0 1 6 0 1 5 0 1 4 </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:51:40.560", "Id": "21338", "Score": "0", "body": "Obvious question: why not do it recursively? This will make the code much simpler, and potentially more efficient. Furthermore, your code isn’t valid C++ and leaks memory. You should fix those two things." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T11:46:40.993", "Id": "21378", "Score": "0", "body": "it is a interview question and it was specially mentioned to not use recursion. Can u please clarify what you mean by your code isn't valid c++ ??" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T12:15:56.493", "Id": "21379", "Score": "0", "body": "Well, my compiler has this to say: “foo.cpp:66:6: warning: ISO C++ forbids declaration of 'main' with no type [-pedantic]” Incidentally, I just noted that the code contains more bugs (`flag=flag||0` does nothing, and using boolean operations to manipulate an integer `flag`, while working, isn’t meaningful anyway)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T13:22:38.220", "Id": "21380", "Score": "0", "body": "my compiler does not show warning regarding implementation of strict ISO standards.That's why i tend to overlook them. But thanks for pointing that out.And i also need help with better implementation of the algorithm. It would be really great if you can help me with that." } ]
[ { "body": "<p>In order that things appear in the code:</p>\n\n<pre><code>using namespace std;\n</code></pre>\n\n<p>This is unnecessary and generally bad practice. I would ask about it if I saw it in an interview question, although it is not harmful in this case.</p>\n\n<pre><code>struct node\n{\n node(int d) : data(d) {}\n int data;\n boost::ptr_vector&lt;node&gt; children;\n};\n</code></pre>\n\n<p>Indentation is generally done in powers of two, and should in any case be consistent. I'm switching to four-space indent everywhere, as you don't seem to be following any style.</p>\n\n<p>This is also a great chance to use pointer containers. Each node owns all of its children, so use something that will enforce that. (In some cases, an <code>std::vector</code> of <code>std::shared_ptr</code>s would make more sense.)</p>\n\n<p>You do not need any of the globals you've defined, and are definitely bad practice. You should also strive to be more const-correct.</p>\n\n<pre><code>void printpath(node const* root)\n{\n std::stack&lt;node const*&gt; path;\n std::set&lt;node const*&gt; visited;\n path.push(root);\n while (visited.find(root) != visited.end())\n {\n node const* v = path.top();\n if (visited.find(v) != visited.end())\n {\n path.pop();\n continue;\n }\n std::cout &lt;&lt; v-&gt;data &lt;&lt; \" \";\n bool has_unvisited_child = false; // Use bools for booleans.\n // See standard comments on iterators vs indices and preincrement\n // vs postincrement.\n for (auto it = v-&gt;children.cbegin(); it != v-&gt;children.cend(); ++it)\n {\n if (visited.find(&amp;*it) != visited.end())\n {\n has_unvisited_child = true;\n st.push(&amp;*it);\n }\n }\n\n // Don't rely on the root node having value 0 in its data.\n // You were given a pointer to it, use that. Your algorithm\n // should not depend on the data stored in the tree.\n\n // Avoids some nesting.\n if (!has_unvisited_child)\n continue;\n\n visited.insert(v); \n while(v != root) \n {\n v = st.top();\n // Avoid shadowing.\n bool unvisited_child = 0;\n // Splitting this off into a function may be meaningful,\n // or using some standard algorithm such as std::any_of\n for (auto it = v-&gt;children.cbegin(); it != v-&gt;children.cend(); ++it)\n unvisited_child |= visited.find(&amp;*it) != visited.end();\n if (!unvisited_child &amp;&amp; !v-&gt;children.empty())\n visited.insert(v);\n if (v != root)\n st.pop();\n }\n std::cout&lt;&lt;endl;\n }\n}\n\n// main must return int\nint main()\n{\n node* root = new node(0);\n node* d = new node(1);\n node* m = new node(2);\n node* n = new node(3);\n root-&gt;children.push_back(d);\n root-&gt;children.push_back(m);\n root-&gt;children.push_back(n);\n node* x = new node(4);\n node* y = new node(5);\n node* z = new node(6);\n d-&gt;children.push_back(x);\n d-&gt;children.push_back(y);\n d-&gt;children.push_back(z);\n node* o = new node(7);\n node* p = new node(8);\n n-&gt;children.push_back(o);\n n-&gt;children.push_back(p);\n printpath(root);\n}\n</code></pre>\n\n<p>Now for the performance part: My advice on that end is to not bother with the stack of next nodes and just keep track of the path:</p>\n\n<pre><code>void print_path(node const* root)\n{\n std::vector&lt;node const*&gt; path{root};\n std::set&lt;node const*&gt; visited;\n while (!path.empty())\n {\n node const* n = path.back();\n if (std::all_of(n-&gt;children.cbegin(), n-&gt;children.cend(), [&amp;](node const&amp; a) { return visited.find(&amp;a) != visited.end(); }))\n {\n if (n-&gt;children.empty()) {\n for (auto it = path.cbegin(); it != path.cend(); ++it)\n {\n if (it != path.cbegin())\n std::cout &lt;&lt; \", \";\n std::cout &lt;&lt; (*it)-&gt;data;\n }\n std::cout &lt;&lt; '\\n';\n }\n visited.insert(n);\n path.pop_back();\n } else {\n path.push_back(&amp;*std::find_if(n-&gt;children.cbegin(), n-&gt;children.cend(), [&amp;](node const&amp; a) { return visited.find(&amp;a) == visited.end(); }));\n }\n }\n}\n</code></pre>\n\n<p>I am not sure which is more efficient.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T13:16:09.127", "Id": "21933", "Score": "0", "body": "Thank you,your answer was really helpful but could you tell me why is it wrong to use \" using namespace std \". Does n't that save us the trouble of including std in front of cin and cout etc. ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-11T13:20:33.787", "Id": "21934", "Score": "1", "body": "See, amongst others [this](http://stackoverflow.com/q/1452721/559931) question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-06-30T01:42:35.080", "Id": "97645", "Score": "1", "body": "You should probably make the `int main()` part more apparent here, in case the OP hasn't already noticed it (and it's quite important)." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-05T12:02:51.957", "Id": "13349", "ParentId": "13150", "Score": "7" } } ]
{ "AcceptedAnswerId": "13349", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T08:45:22.180", "Id": "13150", "Score": "5", "Tags": [ "c++", "performance", "algorithm", "tree", "stack" ], "Title": "Tree-traversal without recursion" }
13150
<p>This was for an assignment. I had to write a function to compare two roman numerals. This had to return <code>true</code> only if the second number was larger than the first and had to be done without converting the letters into integers. Also prefix subtraction didn't apply so all the letters came in descending order.</p> <p>Here is what I came up with:</p> <pre><code>&lt;?php function x_smaller_than_y($x_num,$y_num) { //Create array with ordered list of roman numerals. $evaluation= array("M","D","C","L","X","V","I"); //Splits submitted numbers into arrays $x_num_arr = str_split($x_num); $y_num_arr = str_split($y_num); //Loops through each roman numeral in the given list for ($evaluate = 0; $evaluate&lt;7;$evaluate++) { //For every letter in the numerals' list loops through //every letter in the given numbers looking for a match. $counter = 0; while ($counter &lt; ((strlen($x_num)))&amp;&amp; $counter &lt; ((strlen($y_num)))) { //If in any specific position x=y, it simply ignores it and moves forward. if ($x_num_arr[$counter]==$y_num_arr[$counter]) {$counter++;} //If in any given position the letter in Y is higher in the list than //the letter in X then Y is larger than X and the function is true. //"break" ends the while loop and "$evaluate=8" ends the for loop. elseif(($x_num_arr[$counter]!=$evaluation[$evaluate])&amp;&amp;($y_num_arr[$counter]==$evaluation[$evaluate])) {return true; $evaluate=8; break;} //Same as above but this time the letter in X is before the letter //in Y so the function is false. elseif(($x_num_arr[$counter]==$evaluation[$evaluate])&amp;&amp;( $y_num_arr[$counter]!=$evaluation[$evaluate])) {return false; $evaluate=8; break;} //If none of the above cases apply simply move to the next letter. else {$counter++;} } } //Since the number of iterations in the while loop is determined by the //shorter number there can still be a case in which 2 numbers are exactly //the same up to a point but one is simply longer than the other, //eg. MXVI and MXVII. //When this happens the for loop will have run through its natural //course, $evaluate will be equal to 7, and the code below will determine //the larger number by looking at their lenght. if ($evaluate&lt;8&amp;&amp;(strlen($x_num) &lt; strlen($y_num))) {return true;} elseif ($evaluate&lt;8&amp;&amp;(strlen($x_num) &gt; strlen($y_num))) {return false;} } </code></pre> <p>How could have I made it better?</p>
[]
[ { "body": "<p>It gives wrong results for <code>9</code> (<code>IX</code>) and <code>5</code> (<code>V</code>).</p>\n\n<p>Some notes about the code:</p>\n\n<ol>\n<li><p>In the following block the <code>$evaluate = 8;</code> and the <code>break;</code> statements are unnecessary, they never run because of the <code>return</code> statement.</p>\n\n<pre><code>{\n return true;\n $evaluate = 8;\n break;\n}\n</code></pre></li>\n<li><p>Instead of commenting name the variable to what the comment says. </p>\n\n<pre><code>//Create array with ordered list of roman numerals. \n$evaluation= array(\"M\",\"D\",\"C\",\"L\",\"X\",\"V\",\"I\");\n</code></pre>\n\n<p>It could be <code>$numerals</code> or <code>$numerals_in_order</code>, for example.</p></li>\n<li><p><code>7</code> and <code>8</code> are a magic numbers. They should be named constants or computed values. Do they come from the size of the array? If they do make it clear, it would improve readability.</p></li>\n<li><pre><code>while ($counter &lt; ((strlen($x_num)))&amp;&amp; $counter &lt; ((strlen($y_num))))\n</code></pre>\n\n<p>This could be simplified to the following:</p>\n\n<pre><code>$size = min(strlen($x_num), strlen($y_num));\nwhile ($counter &lt; $size)\n</code></pre></li>\n<li><p>Instead of big <code>if-elseif</code> structures you could use <code>continue</code> and simple <code>if</code>s since some of them returns the function if the condition is <code>true</code>, so the remaining code won't run. The last <code>else</code> also would be unnecessary.</p>\n\n<pre><code>$size_min = min(strlen($x_num), strlen($y_num));\nwhile ($counter &lt; $size_min) {\n if ($x_num_arr[$counter] == $y_num_arr[$counter]) {\n $counter++;\n continue;\n }\n\n if(($x_num_arr[$counter]!=$evaluation[$evaluate])&amp;&amp;($y_num_arr[$counter]==$evaluation[$evaluate])) { \n return true;\n }\n\n if(($x_num_arr[$counter]==$evaluation[$evaluate])&amp;&amp;( $y_num_arr[$counter]!=$evaluation[$evaluate])) {\n return false;\n } \n\n $counter++;\n}\n</code></pre></li>\n<li><p>Inside the <code>for</code> loop the <code>$evaluation</code> array is always indexed with <code>$evaluate</code>. You should create a local variable for this.</p></li>\n<li><p>The same is true for <code>$y_num_arr[$counter]</code> and <code>$x_num_arr[$counter]</code> inside the <code>while</code> loop. (They could be <code>$current_x</code> and <code>$current_y</code>).</p></li>\n<li><p>It might not be an issue (depending on the specification) but the function currently accepts invalid Roman numerals too (like <code>IIX</code>).</p></li>\n<li><p>At the end of the function it returns with implicit <code>NULL</code> if both conditions are <code>false</code> in the following snippet:</p>\n\n<pre><code>if ($evaluate&lt;8&amp;&amp;(strlen($x_num) &lt; strlen($y_num)))\n{return true;}\n\nelseif ($evaluate&lt;8&amp;&amp;(strlen($x_num) &gt; strlen($y_num)))\n{return false;}\n</code></pre>\n\n<p>You should make this explicit (add a <code>return false</code> as the last statement) or use an <a href=\"http://php.net/manual/en/function.assert.php\" rel=\"nofollow\"><code>assert</code></a> call if it should never happen.</p></li>\n<li><p>You could easily write some test code to check that the comparison is fine for every possible Roman numeral.</p>\n\n<pre><code>for ($i = 1; $i &lt;= $max; $i++) {\n for ($j = 1; $j &lt;= $max; $j++) {\n $i_r = numberToRoman($i);\n $j_r = numberToRoman($j);\n $smaller = x_smaller_than_y($i_r, $j_r);\n if ($i &gt;= $j &amp;&amp; $smaller) {\n echo \"error: $i, $j, $i_r, $j_r\\n\";\n }\n }\n}\n</code></pre>\n\n<p>If I'm right <code>$max</code> should be <code>3888</code> and it finishes in a few minutes. <a href=\"http://www.go4expert.com/forums/showthread.php?t=4948\" rel=\"nofollow\">You can find a <code>numberToRoman</code> function here, for example.</a>.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T12:02:36.147", "Id": "13156", "ParentId": "13153", "Score": "1" } }, { "body": "<p>My first comment is that your function needs a more meaningful name. The current name tells us that it's for comparing something, but doesn't convey what. If you rename it to something like <code>whichRomanNumeralIsSmaller ()</code> you'll convey more information about what the function does and what it's expecting as input. Readability of code is one of the key contributors to the maintainability of the code. </p>\n\n<p>On a similar note, your function's local variables don't have very descriptive names. Again, a well chosen name is much more helpful than one like $counter. What is $counter counting? </p>\n\n<p>A lookup table for converting the numerals to values might make more sense than your $evaluation array.</p>\n\n<pre><code>$numeralLookup = array (\n 'I' =&gt; 1,\n 'V' =&gt; 5, \n 'X' =&gt; 10, \n 'L' =&gt; 50,\n 'C' =&gt; 100,\n 'D' =&gt; 500,\n 'M' =&gt; 1000\n)\n</code></pre>\n\n<p>You can now just pull the value for any valid numeral from the array. What's more, you can now also validate your input because if the numeral doesn't have a key in the array it must be invalid. You can throw an exception or whatever you think is suitable in this case. </p>\n\n<p>Finally, from a design point of view, I think maybe you might want to decompose the problem (break it down into smaller parts) further. Your current solution provides you the ability to compare 2 numeral strings, but what if all you want to do is decode a numeral into an Arabic number? The code is all there in your function but you can't directly use it because it's part of a bigger process.</p>\n\n<p>I'd recommend that you simply write a decodeNumeral() function and then use PHP's internal number comparison features. </p>\n\n<pre><code>echo (decodeNumeral ($var1) &gt; $decodeNumeral ($var2)? $var1: $var2) . ' is bigger';\n</code></pre>\n\n<p>(Yes, I know it will give a spurious result if $var1 and $var2 are equal, it's just for illustration)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T14:03:17.320", "Id": "21290", "Score": "0", "body": "Thanks for the feedback. However the assignment was precisely to compare the numerals without converting them to integers." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T12:34:20.443", "Id": "13157", "ParentId": "13153", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T11:18:53.003", "Id": "13153", "Score": "3", "Tags": [ "php", "algorithm", "homework" ], "Title": "PHP function to compare two Roman numerals" }
13153
<p><a href="http://stackoverflow.com/tags/srp/info">Source: the SRP tag wiki on StackOverflow</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T11:59:06.417", "Id": "13154", "Score": "0", "Tags": null, "Title": null }
13154
In object-oriented programming, the single responsibility principle states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. All its services should be narrowly aligned with that responsibility.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T11:59:06.417", "Id": "13155", "Score": "0", "Tags": null, "Title": null }
13155
<p>I'm looking to bullet-proof this method. Specifically, I never want an item to be left without calling the following:</p> <pre><code>MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message); </code></pre> <p><strong>The Method</strong></p> <pre><code>private static void SendMail(MailItemViewModel item) { var r = new MailItemRepository(); // Repository var c = new CompanyRepository(); // Repository try { var toAddresses = ((item.Mail_Recipient) ?? "").Split(';'); var ccAddresses = ((item.Mail_CC) ?? "").Split(';'); var bccAddresses = ((item.Mail_BCC) ?? "").Split(';'); var totalAddresses = 0; var fotmattingInfo = c.GetMailHeaderFooterByCompany(item.CompanyId ?? 0); try { var attachments = r.GetMailAttachmentsByMailId(item.Mail_ID); var attachmentsCloud = r.GetMailAttachmentsCloudByMailId(item.Mail_ID).ToList(); var mailMsg = new MailMessage() { From = new MailAddress(item.MailAgent_FromEmail, item.MailAgent_FromName), Subject = item.Mail_Subject, SubjectEncoding = Encoding.UTF8, Body = String.Format("{0}{1}{2}", fotmattingInfo.Header, item.Mail_Body, fotmattingInfo.Footer), BodyEncoding = Encoding.UTF8, IsBodyHtml = true }; //attachments foreach (var att in attachments.Where(x =&gt; x.Filename != "")) mailMsg.Attachments.Add(new Attachment(att.Filename)); foreach (var attCloud in attachmentsCloud.Where(x =&gt; x.DocumentId &gt; 0)) { Stream s = new MemoryStream(LayerFiles.CloudFileMethods.GetUniqueFile("", attCloud.Document.CloudFileName)); mailMsg.Attachments.Add(new Attachment(s, attCloud.Document.Document_Filename, attCloud.Document.Content_Type)); } //client creds var basicAuthenticationInfo = new NetworkCredential(item.MailAgent_Username, item.MailAgent_Password); var client = new SmtpClient() { Port = item.MailAgent_Port ?? 25, Host = item.MailAgent_SMTP, UseDefaultCredentials = false, Credentials = basicAuthenticationInfo, EnableSsl = item.MailAgent_UseSSL ?? false }; foreach (var addressTo in toAddresses.Where(x =&gt; x != "")) // to addresses { try { mailMsg.To.Add(addressTo); totalAddresses++; } catch (FormatException e0) { logger.Info(e0.Message); } } foreach (var addressCC in ccAddresses.Where(x =&gt; x != "")) // cc addresses { try { mailMsg.CC.Add(addressCC); totalAddresses++; } catch (FormatException e1) { logger.Info(e1.Message); } } foreach (var addressBCC in bccAddresses.Where(x =&gt; x != "")) // bcc addresses { try { mailMsg.Bcc.Add(addressBCC); totalAddresses++; } catch (FormatException e2) { logger.Info(e2.Message); } } //For Synchronous Execution.... client.Send(mailMsg); if (item.Mail_ID &gt; 0) { MailMethods.UpdateMessageState(item.Mail_ID, 3, "OK"); } } catch (SmtpException ex) { MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message); if (item.TaskId != null) TaskMethods.UpdateFailure(item.TaskId, true); logger.Info(ex.Message); } catch (NullReferenceException ex) { MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message); if (item.TaskId != null) TaskMethods.UpdateFailure(item.TaskId, true); logger.Info(ex.Message); } catch (Exception ex) { MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message); if (item.TaskId != null) TaskMethods.UpdateFailure(item.TaskId, true); logger.Info(ex.Message); } } catch (Exception ex) { logger.Info(ex.Message); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T14:59:09.267", "Id": "21292", "Score": "0", "body": "You should consider refactoring this code. The method is too long and is \"[arrow code](http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html)\"... in some places you even have a `try` inside a `try` inside a `try` - that really is too much!" } ]
[ { "body": "<p>There are a couple things I would do:</p>\n\n<ul>\n<li>You can collapse your catch for SmtpException,\nNullReferenceException, and Exception into a single catch block,\nsince all blocks have identical code.</li>\n<li>You can split off your handling of To, CC, and BCC addresses into a\nhelper method that takes in the appropriate view model property and\ncollection on the mail message, as all three sections of code are\nidentical.</li>\n<li>Consider making your SendMail method a method on an object. You can \nsplit off the instantiation of the repository objects into a<br>\nconstructor of this object to clean up the SendMail some more.</li>\n</ul>\n\n<p>Other notes:</p>\n\n<ul>\n<li>I left the totalAddresses variable in the SendMail method, though it\ndoesn't look like it's useful.</li>\n<li>If it isn't useful, then feel free to remove it from both SendMail\nand ProcessAddressList. I'm not sure where the logger object is\ncoming from. It should probably be something injected into the\nclass.</li>\n<li>I noticed an if check on mail ID being greater than 0 just after the\nsend in order to say it had an OK status, but there is no code I saw\nat a glance that sets this ID. If it should be set prior to the\nmethod, you should probably add a check on the ID at the top of the\nmethod and return early with a failure status if it is less than or\nequal to 0.</li>\n<li>I removed the nested try/catch, as it did not appear to provide much value.</li>\n</ul>\n\n<p>Here is what I have thus far (over a lunch break, so bear with me on the time crunch ;)</p>\n\n<pre><code>public class MailHelper\n{\n\npublic MailHelper ()\n{\n MailRepo = new MailItemRepository();\n CompanyRepo = new CompanyRepository();\n}\n\nprivate MailItemRepository MailRepo { get; set; }\nprivate CompanyRepository CompanyRepo { get; set; }\n\npublic void SendMail(MailItemViewModel item)\n{\n try\n {\n var totalAddresses = 0;\n var fotmattingInfo = CompanyRepo.GetMailHeaderFooterByCompany(item.CompanyId ?? 0);\n\n var attachments = MailRepo.GetMailAttachmentsByMailId(item.Mail_ID);\n var attachmentsCloud = r.GetMailAttachmentsCloudByMailId(item.Mail_ID).ToList();\n\n var mailMsg = new MailMessage()\n {\n From = new MailAddress(item.MailAgent_FromEmail, item.MailAgent_FromName),\n Subject = item.Mail_Subject,\n SubjectEncoding = Encoding.UTF8,\n Body = String.Format(\"{0}{1}{2}\", fotmattingInfo.Header, item.Mail_Body, fotmattingInfo.Footer),\n BodyEncoding = Encoding.UTF8,\n IsBodyHtml = true\n };\n\n foreach (var att in attachments.Where(x =&gt; x.Filename != \"\"))\n mailMsg.Attachments.Add(new Attachment(att.Filename));\n\n foreach (var attCloud in attachmentsCloud)\n {\n if (attCloud.DocumentId &lt;= 0)\n continue;\n\n var s = new MemoryStream(LayerFiles.CloudFileMethods.GetUniqueFile(\"\", attCloud.Document.CloudFileName));\n mailMsg.Attachments.Add(new Attachment(s, attCloud.Document.Document_Filename, attCloud.Document.Content_Type));\n }\n\n var basicAuthenticationInfo = new NetworkCredential(item.MailAgent_Username, item.MailAgent_Password);\n\n var client = new SmtpClient()\n {\n Port = item.MailAgent_Port ?? 25,\n Host = item.MailAgent_SMTP,\n UseDefaultCredentials = false,\n Credentials = basicAuthenticationInfo,\n EnableSsl = item.MailAgent_UseSSL ?? false\n };\n\n totalAddresses += ProcessAddressList (item.Mail_Recipient, mailMsg.To);\n totalAddresses += ProcessAddressList (item.Mail_CC, mailMsg.CC);\n totalAddresses += ProcessAddressList (item.Mail_BCC, mailMsg.BCC);\n\n client.Send(mailMsg);\n MailMethods.UpdateMessageState(item.Mail_ID, 3, \"OK\");\n }\n catch (Exception ex)\n {\n HandleFailure (item, ex);\n }\n}\n\nprivate int ProcessAddressList (string addresses, MailAddressCollection addressCol)\n{\n if (string.IsNullOrWhiteSpace (addresses))\n return 0;\n\n var totalAddresses = 0;\n var addressList = addresses.Split (';');\n\n foreach (var address in addressList)\n {\n if (string.IsNullOrWhiteSpace (address))\n continue;\n\n try\n {\n addressCol.Add(address);\n totalAddresses++;\n }\n catch (FormatException ex)\n {\n logger.Info(ex.Message);\n }\n }\n\n return totalAddresses;\n}\n\nprivate void HandleFailure (MailItemViewModel item, Exception ex)\n{\n MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message);\n\n if (item.TaskId != null)\n TaskMethods.UpdateFailure(item.TaskId, true);\n\n logger.Info(ex.Message);\n}\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T18:38:15.897", "Id": "13165", "ParentId": "13159", "Score": "6" } }, { "body": "<p>Wrap your <code>IDisposable</code> objects in <code>using</code> statements to ensure the proper disposal of unmanaged resources. I also did a few smaller things, like use <code>string.IsNullOrWhiteSpace</code> (if not .NET 4, use <code>string.IsNullOrEmpty</code>), for example.</p>\n\n<pre><code> private static void SendMail(MailItemViewModel item)\n {\n var r = new MailItemRepository(); // Repository\n var c = new CompanyRepository(); // Repository\n\n try\n {\n var toAddresses = ((item.Mail_Recipient) ?? string.Empty).Split(';');\n var ccAddresses = ((item.Mail_CC) ?? string.Empty).Split(';');\n var bccAddresses = ((item.Mail_BCC) ?? string.Empty).Split(';');\n var totalAddresses = 0;\n var fotmattingInfo = c.GetMailHeaderFooterByCompany(item.CompanyId ?? 0);\n\n try\n {\n var attachments = r.GetMailAttachmentsByMailId(item.Mail_ID);\n var attachmentsCloud = r.GetMailAttachmentsCloudByMailId(item.Mail_ID).ToList();\n\n using (var mailMsg = new MailMessage\n {\n From = new MailAddress(item.MailAgent_FromEmail, item.MailAgent_FromName),\n Subject = item.Mail_Subject,\n SubjectEncoding = Encoding.UTF8,\n Body = string.Format(\"{0}{1}{2}\", fotmattingInfo.Header, item.Mail_Body, fotmattingInfo.Footer),\n BodyEncoding = Encoding.UTF8,\n IsBodyHtml = true\n })\n {\n // attachments\n foreach (var att in attachments.Where(x =&gt; x.Filename() != string.Empty))\n {\n mailMsg.Attachments.Add(new Attachment(att.Filename()));\n }\n\n foreach (var attCloud in attachmentsCloud.Where(x =&gt; x.DocumentId &gt; 0))\n {\n using (var s = new MemoryStream(LayerFiles.CloudFileMethods.GetUniqueFile(string.Empty, attCloud.Document.CloudFileName)))\n {\n mailMsg.Attachments.Add(new Attachment(s, attCloud.Document.Document_Filename, attCloud.Document.Content_Type));\n }\n }\n\n foreach (var addressTo in toAddresses.Where(x =&gt; !string.IsNullOrWhiteSpace(x))) // to addresses\n {\n try\n {\n mailMsg.To.Add(addressTo);\n totalAddresses++;\n }\n catch (FormatException e0)\n {\n logger.Info(e0.Message);\n }\n }\n\n foreach (var addressCC in ccAddresses.Where(x =&gt; !string.IsNullOrWhiteSpace(x))) // cc addresses\n {\n try\n {\n mailMsg.CC.Add(addressCC);\n totalAddresses++;\n }\n catch (FormatException e1)\n {\n logger.Info(e1.Message);\n }\n }\n\n foreach (var addressBCC in bccAddresses.Where(x =&gt; !string.IsNullOrWhiteSpace(x))) // bcc addresses\n {\n try\n {\n mailMsg.Bcc.Add(addressBCC);\n totalAddresses++;\n }\n catch (FormatException e2)\n {\n logger.Info(e2.Message);\n }\n }\n\n //client creds\n var basicAuthenticationInfo = new NetworkCredential(item.MailAgent_Username, item.MailAgent_Password);\n\n using (var client = new SmtpClient()\n {\n Port = item.MailAgent_Port ?? 25,\n Host = item.MailAgent_SMTP,\n UseDefaultCredentials = false,\n Credentials = basicAuthenticationInfo,\n EnableSsl = item.MailAgent_UseSSL ?? false\n })\n {\n //For Synchronous Execution....\n client.Send(mailMsg);\n }\n }\n\n if (item.Mail_ID &gt; 0)\n {\n MailMethods.UpdateMessageState(item.Mail_ID, 3, \"OK\");\n }\n }\n\n catch (SmtpException ex)\n {\n MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message);\n if (item.TaskId != null)\n {\n TaskMethods.UpdateFailure(item.TaskId, true);\n }\n\n logger.Info(ex.Message);\n }\n catch (NullReferenceException ex)\n {\n MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message);\n if (item.TaskId != null)\n {\n TaskMethods.UpdateFailure(item.TaskId, true);\n }\n\n logger.Info(ex.Message);\n }\n\n catch (Exception ex)\n {\n MailMethods.UpdateMessageState(item.Mail_ID, 2, ex.Message);\n if (item.TaskId != null)\n {\n TaskMethods.UpdateFailure(item.TaskId, true);\n }\n\n logger.Info(ex.Message);\n }\n }\n catch (Exception ex)\n {\n logger.Info(ex.Message);\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:35:06.447", "Id": "13191", "ParentId": "13159", "Score": "1" } } ]
{ "AcceptedAnswerId": "13165", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T13:51:50.677", "Id": "13159", "Score": "1", "Tags": [ "c#" ], "Title": "Bullet-proofing an email scheduler in C#" }
13159
<p>Can someone critique this Java code?</p> <pre><code>package javaapplication; import java.util.Date; import java.lang.Long; interface infix_operator { public int apply(int x, int y); } class f implements infix_operator { public int apply(int x, int y) { return x + (2 * y); } } class g implements infix_operator { public int apply(int x, int y) { return (2*x) + y; } } class h implements infix_operator { public int apply(int x, int y) { return x + y; } } class k implements infix_operator { public int apply(int x, int y) { return x * y; } } public class JavaApplication { static long to_64bit_signed_integer (long value) { long bit16 = value &amp; 65535; value = (bit16 &lt;&lt; 16) | bit16; value = (value &lt;&lt; 16) | bit16; value = (value &lt;&lt; 16) | bit16; return Long.reverse(value); } public static void main(String[] args) { long current_time_value = new Date().getTime(); System.out.println("Current Time: " + current_time_value); infix_operator[] operator_array = {new f(), new g(), new h(), new k()}; int [] node = new int[31]; int [] to_signed_value = new int[] {0,-2,1,-1}; int [] to_unsigned_value = new int[] {0,2,1,3}; long value = to_64bit_signed_integer (current_time_value); value = value &gt;&gt; 2; for (int leaf_index=30; leaf_index&gt;=15; leaf_index--) { node[leaf_index] = to_signed_value [(int)(value &amp; 3)]; value = value &gt;&gt; 2; } for (int internal_index = 14; internal_index &gt;= 0; internal_index--) { int op = to_unsigned_value [(int)(value &amp; 3)]; int child_index = 2*internal_index + 1; node [internal_index] = operator_array[op].apply(node[child_index], node[child_index+1]); value = value &gt;&gt; 2; } System.out.println("Hash Value: " + node[0]); } } </code></pre>
[]
[ { "body": "<p>Just a couple of points which are more from a stylistic point-of-view rather than strict language requirements or algorithmic correctness:</p>\n\n<ul>\n<li>Classes should be named upper-case: <code>Car</code>, <code>House</code>, <code>TwoTimesPlusOne</code>, <code>Addition</code></li>\n<li>Interfaces should also be named upper-case: <code>InfixOperator</code></li>\n<li>Variable names should use camel-case: <code>leafIndex</code>, <code>unsignedValue</code></li>\n<li><code>i</code>, <code>j</code> and <code>k</code> are used as iterator variables (the more you reference a variable, the shorter it should be named)</li>\n<li><p>Prefer lists over arrays and make use of the enhanced for loop</p>\n\n<pre><code>for(InfixOperator i : operators) {\n //...\n}\n</code></pre></li>\n</ul>\n\n<p>Adhering to common language standards will make your code more easily understandable for other programmers.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T21:29:31.513", "Id": "21305", "Score": "0", "body": "I agree. Class and variable names should carry meaning otherwise they're confusing for the reader and the programmer. I really loathe it when people are so lazy that they only give single letter names to variables/classes. That sort of thing should really only be limited to for loops." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T16:05:53.260", "Id": "21347", "Score": "0", "body": "Instead of \"limited to loops\", I'd say that very short names are nice as long as their visibility / line-span is limited to a few lines (which is about the same as you said)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T11:03:41.733", "Id": "21440", "Score": "2", "body": "*\"These are by no means hard rules, feel free to break them as the need arises.\"* - But only if you never intend another programmer to see your code. IMO, you **should** treat these as hard and fast rules, and only break them when you have no sensible alternative. Folks, this is a Code Review site. We should teach good habits, not excuses for bad habits." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-01-23T11:11:43.177", "Id": "289981", "Score": "0", "body": "@StephenC Agree, I removed it." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T16:59:20.017", "Id": "13163", "ParentId": "13161", "Score": "6" } }, { "body": "<p>You can replace <code>new Date().getTime()</code> by <code>System.currentTimeMillis()</code></p>\n\n<p>For the rest of the code, it would help if you explain the algorithm you are implementing, or if you name it (if it's a known hash algorithm)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:46:07.230", "Id": "13192", "ParentId": "13161", "Score": "5" } }, { "body": "<p>The algorithm takes the current time and hashes it somehow. If you want to implement a hash function, so you should do it, not only provide a composite thing. The way you did it you can only provide a single random number, that's not really very general use.</p>\n\n<p>Is the algorithm you implemented any good? This depends on the goals (which you haven't stated).</p>\n\n<p>Should it provide an unguessable long value? If so, it fails as there is just a thousand possible candidates each second. Compare it to <code>new SecureRandom().nextLong()</code>.</p>\n\n<p>Should the hash function be fast? <a href=\"http://code.google.com/p/caliper\" rel=\"nofollow\">Measure it</a> and compare it to existing secure ones, there are <a href=\"http://www.saphir2.com/sphlib\" rel=\"nofollow\">dozens of them</a> implemented in Java, including the SHA-3 candidates.Or compare it to the non-secure but fast ones <a href=\"http://code.google.com/p/guava-libraries/source/browse/guava/src/com/google/common/hash\" rel=\"nofollow\">like here</a>.</p>\n\n<p>Should it be secure? This is a nearly impossible task even for the smartest guys having studied all the theory behind.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T16:22:48.170", "Id": "13197", "ParentId": "13161", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T16:26:37.613", "Id": "13161", "Score": "2", "Tags": [ "java", "hashcode" ], "Title": "Retrieving current time and computing a hash value" }
13161
<p>In <a href="https://github.com/GCorbel/comment-my-projects" rel="nofollow noreferrer">my project</a>, I have this kind of code to test my controllers:</p> <pre><code>#encoding=utf-8 require 'spec_helper' describe ProjectsController do let!(:project) { build_stubbed(:project, user: user) } let(:user) { build_stubbed(:user) } before(:each) { sign_in user } describe "GET 'index'" do it "render index template" do get 'index' should render_template('index') end end describe "GET 'show'" do let!(:comment) { build_stubbed(:comment) } before(:each) { Project.stubs(:find).returns(project) } it "render show template" do get 'show', id: project.id should render_template('show') end it "create a new comment" do Comment.expects(:new).returns(comment) get 'show', id: project.id end end describe "GET 'new'" do it "render new template" do get 'new' should render_template('new') end end describe "POST 'create'" do before(:each) do Project.stubs(:new).returns(project) end context "with valid data" do before(:each) { project.stubs(:save).returns(true) } it "redirect to project's path" do post 'create' should redirect_to(project) end it "save the project" do lambda do post 'create' end.should change(user.projects, :size).by(1) end it "set a flash message" do post 'create' should set_the_flash[:notice].to("Votre projet a été ajouté") end end context "with invalid data" do before(:each) { project.stubs(:save).returns(false) } it "render new template" do post 'create' should render_template('new') end end end describe "GET 'edit'" do before(:each) do Project.stubs(:find).returns(project) end it "render edit template" do get 'edit', id: project.id should render_template('edit') end end describe "POST 'update'" do before(:each) do Project.stubs(:find).returns(project) end context "when valid" do before(:each) { project.stubs(:update_attributes).returns(true) } it "redirect to project's path" do post 'update', id: project.id should redirect_to(project) end it "update the project" do project.expects(:update_attributes) post 'update', id: project.id end it "set a flash message" do post 'update', id: project.id should set_the_flash[:notice].to("Votre projet a été modifié") end end context "when invalid" do before(:each) { project.stubs(:update_attributes).returns(false) } it "render edit template" do post 'update', id: project.id should render_template('edit') end end end describe "DELETE 'destroy'" do before(:each) do Project.stubs(:find).returns(project) project.stubs(:destroy) end it "redirect to project's path" do delete 'destroy', id: project.id should redirect_to(root_path) end it "delete the project" do project.expects(:destroy) delete 'destroy', id: project.id end it "set a flash message" do delete 'destroy', id: project.id should set_the_flash[:notice].to("Votre projet a été supprimé") end end end </code></pre> <p>I do this for:</p> <ul> <li>Isolate my tests: I don't want to retest the model and I don't want to hit the database. It's faster.</li> <li>Test all actions that should be do by the controller</li> </ul> <p>And I have these questions:</p> <ul> <li>Should I test the assignments or is to long for nothing?</li> <li><p>How should I to stub my models? Is it better to place all stubs in a global <code>before(:each)</code> like this?</p> <pre><code>... before(:each) do sign_in user Project.stubs(:find).returns(project) Project.stubs(:new).returns(project) project.stubs(:destroy) end ... </code></pre> <p>It's DRYer and cleaner but less efficient.</p></li> <li><p>Should I really isolate my tests? I tested it without stubs and I lose 10 seconds. What do you think about that?</p></li> </ul>
[]
[ { "body": "<p>I found <a href=\"https://codereview.stackexchange.com/a/695\">this answer</a> helpful; I also like using the shoulda matchers to clean things up.</p>\n\n<p>Yes, I think you should test your assignments. If you use the shoulda matchers, this becomes much less painful, for example:</p>\n\n<pre><code>describe \"POST 'update'\" do\n\n context \"when invalid\" do\n before(:each) do\n project.stubs(:update_attributes).returns(false)\n post 'update', id: project.id\n end\n\n it { should render_template('edit') }\n it { should assign_to(:project).with(project) }\n end\nend\n</code></pre>\n\n<p>I usually stub where it's relevant rather than at a global level, but I don't have a good argument as to why besides that it's easier for me to understand when I'm reading it.</p>\n\n<p>It's fine to test in isolation as long as you're testing your full stack somewhere like with cucumber or integration tests.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-05-14T23:17:35.230", "Id": "26182", "ParentId": "13162", "Score": "2" } } ]
{ "AcceptedAnswerId": "26182", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T16:35:23.893", "Id": "13162", "Score": "1", "Tags": [ "ruby", "unit-testing", "ruby-on-rails", "controller", "rspec" ], "Title": "Refactoring my controller specs" }
13162
<p>I'm working code sample <a href="http://jsbin.com/ugilev" rel="nofollow">here</a>.</p> <p>Note: <em>Above <strong>only</strong> tested in Firefox 13.0.1, iPad (non-retina) and Chrome 20.0.x.</em></p> <p>Here's the relevant code:</p> <pre><code>var $outside = $(document) .add($('html')) .add($(':not[' + data.target + ']')); $outside.on('focusin.goober click.goober', function(e) { if ($(e.target).closest(data.target).length === 0) { $outside.off('.goober'); data.divs.hide(); // Collection of sub menu divs. } else { return true; } }).css('-webkit-tap-highlight-color', 'rgba(0, 0, 0, 0)'); // Hide tap highlight color via Mobile Safari. </code></pre> <p><strong>I'm looking for feedback on two issues:</strong></p> <ol> <li><p>Clicking and/or focusing outside: Where you see</p> <pre><code>var $outside = $(document).add($('html')).add($(':not[' + data.target + ']')); </code></pre> <p>that's where I check for focusin/click events <strong>outside</strong> the target menu. I have my reservations about applying event handlers to everything just to detect an outside focus/click. Without <a href="http://benalman.com/projects/jquery-outside-events-plugin/" rel="nofollow">using a plugin</a>, is there a better way to detect focus/click outside of a target element? Could this code be improved?</p></li> <li><p>I'm also concerned about how <code>-webkit-tap-highlight-color</code> behaves when tapping outside via iPad. As a quick monkey patch, I've added</p> <pre><code>.css('-webkit-tap-highlight-color', 'rgba(0, 0, 0, 0)') </code></pre> <p>but I don't yet see that as the perfect solution.</p></li> </ol> <p><strong>In regards to #2 above:</strong></p> <p>I wonder if I should add a CSS class to the <code>&lt;html&gt;</code> element, something like "<code>disable-highlight</code>", and have in my CSS</p> <pre><code>.disable-highlight * { -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } </code></pre> <p>and have JS add the class when the menu is being interacted with (and remove it when its not)? I rarely use <code>*</code> selector in my CSS these days, but as a temporary way to hide the tap/click highlight, maybe that's not a bad idea?</p>
[]
[ { "body": "<p>After several days of hard work, I think that I've found the answers to my questions.</p>\n\n<ol>\n<li><p>The best element I've found to check for outside click/focus is <code>$(document)</code>.</p>\n\n<p>Caveat: When on iPad, the event needs to be <code>touchstart</code>, not <code>click</code>.</p>\n\n<p>I've got a question <a href=\"https://stackoverflow.com/questions/11406285/determine-and-bind-click-or-touch-event\">going here</a>, but here's the \"trick\" I'm using currently:</p>\n\n<pre><code>var foo = (('ontouchstart' in window) || (window.DocumentTouch &amp;&amp; document instanceof DocumentTouch)) ? 'touchstart' : 'click';\n</code></pre>\n\n<p>I'm using <a href=\"https://stackoverflow.com/a/9440580/922323\">this technique here</a> to handle <code>focus</code>/<code>click</code>. Essentially, when there's keyboard tab focus, I call <code>click</code> and within that event handler, I call my code to check for outside <code>focus</code>/<code>click</code>/<code>touch</code>.</p></li>\n<li><p>The idea I had to add a CSS class to <code>&lt;html&gt;</code> works pretty good. When the event handlers are setup to listen for <code>focus</code>/<code>click</code>/<code>touch</code> outside, I add the class. Once there's been <code>focus</code>/<code>click</code>/<code>touch</code> on the outside, I remove the class.</p>\n\n<p>My CSS looks like so:</p>\n\n<pre><code>html.mw-outside * { -webkit-tap-highlight-color: rgba(0, 0, 0, 0); }\n</code></pre>\n\n<p>It kinda feels a little hacky, though.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-02-05T04:16:51.407", "Id": "144236", "Score": "0", "body": "Not sure if it will help, but [here's a real-world jQuery plugin I wrote (a few years back) that uses this technique](https://github.com/mhulse/jquery-megawhale); also, [here's more recent JS code I use to detect of touch is supported](https://gist.github.com/mhulse/4704893#file-no-x-js-L9-L14). (thanks for edit @Jamal)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-10T04:27:12.000", "Id": "13488", "ParentId": "13166", "Score": "1" } } ]
{ "AcceptedAnswerId": "13488", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-28T18:41:06.143", "Id": "13166", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Click and/or focus outside & -webkit-tap-highlight-color" }
13166
<p>I've previously posted this on Stack Overflow, and am considering submitting it to Boost for wider distribution, but thought perhaps it would be best to put it up here for peer review first, and see whether there are clear improvements that can be made first.</p> <pre><code>// infix_iterator.h // #if !defined(INFIX_ITERATOR_H_) #define INFIX_ITERATOR_H_ #include &lt;ostream&gt; #include &lt;iterator&gt; template &lt;class T, class charT=char, class traits=std::char_traits&lt;charT&gt; &gt; class infix_ostream_iterator : public std::iterator&lt;std::output_iterator_tag,void,void,void,void&gt; { std::basic_ostream&lt;charT,traits&gt; *os; charT const* delimiter; bool first_elem; public: typedef charT char_type; typedef traits traits_type; typedef std::basic_ostream&lt;charT,traits&gt; ostream_type; infix_ostream_iterator(ostream_type&amp; s) : os(&amp;s),delimiter(0), first_elem(true) {} infix_ostream_iterator(ostream_type&amp; s, charT const *d) : os(&amp;s),delimiter(d), first_elem(true) {} infix_ostream_iterator&lt;T,charT,traits&gt;&amp; operator=(T const &amp;item) { // Here's the only real change from ostream_iterator: // We don't print the delimiter the first time. After that, // each invocation prints the delimiter *before* the item, not // after. As a result, we only get delimiters *between* items, // not after every one. if (!first_elem &amp;&amp; delimiter != 0) *os &lt;&lt; delimiter; *os &lt;&lt; item; first_elem = false; return *this; } infix_ostream_iterator&lt;T,charT,traits&gt; &amp;operator*() { return *this; } infix_ostream_iterator&lt;T,charT,traits&gt; &amp;operator++() { return *this; } infix_ostream_iterator&lt;T,charT,traits&gt; &amp;operator++(int) { return *this; } }; #endif </code></pre> <p>This is (at least intended to be) pretty much a drop-in replacement for <a href="http://en.cppreference.com/w/cpp/iterator/ostream_iterator"><code>std::ostream_iterator</code></a>, the sole difference being that (at least in normal use) it only prints out delimiters <em>between</em> items instead of after every item. Code using it looks something like:</p> <pre><code>#include "infix_iterator.h" std::vector&lt;int&gt; numbers = {1, 2, 3, 4}; std::copy(begin(numbers), end(numbers), infix_ostream_iterator&lt;int&gt;(std::cout, ", ")); </code></pre> <p>The motivation for this is pretty simple -- with a <code>std::ostream_iterator</code>, your list would come out like <code>1, 2, 3, 4,</code>, but with the infix_iterator, it comes out as <code>1, 2, 3, 4</code>.</p> <p>As a side-note, although I've used a couple of C++11 features in this demo code, I believe the iterator itself should be fine with C++03 -- though if somebody sees anything that would be a problem for a compiler without C++11 support, I'd like to hear about that too.</p> <p>Edit: In case anybody cares, here's the new version incorporating input from both @Konrad and @Loki. Thanks to both of you.</p> <pre><code>// infix_iterator.h #if !defined(INFIX_ITERATOR_H_) #define INFIX_ITERATOR_H_ #include &lt;ostream&gt; #include &lt;iterator&gt; #include &lt;string&gt; template &lt;class T, class charT=char, class traits=std::char_traits&lt;charT&gt; &gt; class infix_ostream_iterator : public std::iterator&lt;std::output_iterator_tag, void, void, void, void&gt; { std::basic_ostream&lt;charT,traits&gt; *os; std::basic_string&lt;charT&gt; delimiter; std::basic_string&lt;charT&gt; real_delim; public: typedef charT char_type; typedef traits traits_type; typedef std::basic_ostream&lt;charT, traits&gt; ostream_type; infix_ostream_iterator(ostream_type &amp;s) : os(&amp;s) {} infix_ostream_iterator(ostream_type &amp;s, charT const *d) : os(&amp;s), real_delim(d) {} infix_ostream_iterator&lt;T, charT, traits&gt; &amp;operator=(T const &amp;item) { *os &lt;&lt; delimiter &lt;&lt; item; delimiter = real_delim; return *this; } infix_ostream_iterator&lt;T, charT, traits&gt; &amp;operator*() { return *this; } infix_ostream_iterator&lt;T, charT, traits&gt; &amp;operator++() { return *this; } infix_ostream_iterator&lt;T, charT, traits&gt; &amp;operator++(int) { return *this; } }; #endif </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T12:58:46.360", "Id": "21441", "Score": "0", "body": "Why do you take a `charT const *d` instead of a `const std::basic_string<charT>&`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T07:33:15.987", "Id": "66745", "Score": "0", "body": "@Dave: To mimic the interface of `std::ostream_iterator`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-19T10:56:31.583", "Id": "128497", "Score": "0", "body": "Have you submitted to Boost upstream? I can't seem to find neither `infix_iterator` nor `infix_ostream_iterator` in Boost." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-19T17:24:07.800", "Id": "128583", "Score": "0", "body": "@sukhmel: No--I've gotten somewhat caught up in a few other things, and that got dropped in a crack, so to speak." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-11-06T18:50:58.807", "Id": "202719", "Score": "0", "body": "@JerryCoffin: that's a most useful tool; I really hate those trailing delims. Mind if I link here if use a q'n'd downsized version in answers on SO? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T16:06:56.433", "Id": "210408", "Score": "0", "body": "Did you have any involvement in the [ostream joiner](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4257)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T16:10:48.483", "Id": "210410", "Score": "0", "body": "@Barry: No, not directly anyway. Based on the timing, it's entirely possible they based their proposal off of code I posted to Usenet long ago, but it's also possible they re-invented it completely independently." } ]
[ { "body": "<p>The only thing at all that I can criticise in the code is the inconsistent placement of whitespace between infix operators and in pointer / reference declarations.</p>\n\n<pre><code>class charT=char,\npublic std::iterator&lt;std::output_iterator_tag,void,void,void,void&gt;\n</code></pre>\n\n<p>… etc., missing spaces.</p>\n\n<pre><code>: os(&amp;s),delimiter(0), first_elem(true)\n</code></pre>\n\n<p>… etc., inconsistent use of spaces.</p>\n\n<pre><code>infix_ostream_iterator&lt;T,charT,traits&gt;&amp; operator=(T const &amp;item)\ninfix_ostream_iterator&lt;T,charT,traits&gt; &amp;operator*() {\n</code></pre>\n\n<p>… etc., Inconsistent placement of <code>&amp;</code>.</p>\n\n<p>I’d also unify the use of blank lines between function definitions, and remove the blank line between the <code>template &lt;…&gt;</code> block and the class header, as well as at the end of the class definition.</p>\n\n<p>Nitpicking, sure, but that’s literally the only thing to criticise.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T12:07:53.730", "Id": "13183", "ParentId": "13176", "Score": "15" } }, { "body": "<p>Nothing major (just some personal opinion ones):</p>\n\n<h3>Consistent Spacing</h3>\n\n<pre><code> infix_ostream_iterator(ostream_type&amp; s)\n : os(&amp;s),delimiter(0), first_elem(true)\n {} // ^^^ No Space ^^^Trailing space\n</code></pre>\n\n<h3>Consistent type Naming</h3>\n\n<pre><code>// Here we have &amp; on the left\ninfix_ostream_iterator&lt;T,charT,traits&gt;&amp; operator=(T const &amp;item)\n\n// Here we have it on the right\ninfix_ostream_iterator&lt;T,charT,traits&gt; &amp;operator*() {\n</code></pre>\n\n<h3>Spelling of <code>delimter</code></h3>\n\n<p>I mistypes it a lot when writing this => <code>delimiter</code></p>\n\n<h3>Easier to read initializer list</h3>\n\n<p>Just like I prefer one statement per line, I prefer one variable initialized per line in the initializer list (easier to read).</p>\n\n<pre><code>infix_ostream_iterator(ostream_type&amp; s, charT const *d)\n : os(&amp;s)\n , delimiter(d)\n , first_elem(true)\n{}\n</code></pre>\n\n<h3>Remove the if from the main body.</h3>\n\n<p>It probably makes no difference to performance, but I would remove the <code>if</code> so the code looks like this:</p>\n\n<pre><code>*os &lt;&lt; delimter &lt;&lt; item;\ndelimter = actualDelimter;\nreturn *this;\n</code></pre>\n\n<p>On construction <code>actualDelimter</code> points at the string provided by the user (or empty string) and <code>delimter</code> is set to point at an empty string.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T14:15:20.773", "Id": "21399", "Score": "0", "body": "I've been thinking about this a bit. Instead of storing the user's pointer directly, and initializing `delimiter` to point to an empty string, do you see a problem that I don't with using `std::basic_string<charT>` for both `delimiter` and `real_delim`? Pros: no init to empty string needed, remain valid even if the user's pointer doesn't. Cons: Possibly increased overhead?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T22:21:25.547", "Id": "21406", "Score": "0", "body": "@JerryCoffin: I see no down side to that. The overhead is during construction that happens once. Even if it is copied around a lot the extra cost of the copy is not that significant. And all this is totally outweighed by the usage of `operator<<`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T13:03:14.233", "Id": "21442", "Score": "0", "body": "Is it really a reasonable assumption to say the copy is cheaper than the condition he previously had? Is there some way to quantify that?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-03T15:26:16.497", "Id": "21457", "Score": "0", "body": "@Dave. It is not cheaper it is more expensive. **But** you do not expect to see much copying (as I was trying to say). So I see the extra cost as insignificant, compared to the extra safety we achieve by doing it this way." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T07:30:46.927", "Id": "66744", "Score": "0", "body": "I would leave `delimiter` and `real_delim` as `charT const *`, but in the constructor do as follows: `infix_ostream_iterator(ostream_type &s, charT const *d = 0) : os(&s), delimiter(\"\"), real_delimiter(d ? d : \"\") {}`. That way there even less cost for copying." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T23:41:36.613", "Id": "13209", "ParentId": "13176", "Score": "25" } }, { "body": "<p>I would also declare first constructor as explicit:</p>\n\n<pre><code>explicit infix_ostream_iterator(ostream_type &amp;s)\n : os(&amp;s)\n {}\n</code></pre>\n\n<p>Though I can imagine use of this kind of iterator is rather limited, this way you ensure no unwanted type conversion will take place.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-21T18:23:03.200", "Id": "13890", "ParentId": "13176", "Score": "8" } }, { "body": "<h3>Keep the const char pointers</h3>\n<p>I agree with Lokis proposed changes, except that I would leave <code>delimiter</code> and <code>real_delim</code> as <code>charT const *</code> and change the constructor to:</p>\n<pre><code>infix_ostream_iterator(ostream_type &amp;s, charT const *d = 0)\n : os(&amp;s)\n , delimiter(&quot;&quot;)\n , real_delim(d ? d : &quot;&quot;)\n{\n}\n</code></pre>\n<p>That way we reduce the cost of copying the strings, instead we just copy a pointer.</p>\n<h3>Deduced types</h3>\n<p>Mimicking the changes made to <a href=\"http://en.cppreference.com/w/cpp/utility/functional/less\" rel=\"noreferrer\">std::less</a> in C++14, you could make <code>operator=</code> a template, that way we don't need to specify this type for the class. This would though break the compatibility with the <code>std::ostream_iterator</code> interface.</p>\n<pre><code>template &lt;class T&gt;\ninfix_ostream_iterator&lt;charT, traits&gt; &amp;operator=(T const &amp;item)\n{\n *os &lt;&lt; delimiter &lt;&lt; item;\n delimiter = real_delim;\n return *this;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-03-09T09:10:53.993", "Id": "297931", "Score": "0", "body": "Arguably, the type of `d` might be better as a template argument. I can envisage having it as a string literal (`const char*`) in some code, but as a `std::string` in others." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-01-22T08:57:04.733", "Id": "39789", "ParentId": "13176", "Score": "5" } }, { "body": "<p>First of all, good idea with this class! I agree with the changes already proposed by other users (Loki, Konrad, user15108, dalle).</p>\n\n<p>Additionally, I noticed that <code>infix_ostream_iterator</code> is not default constructible. This is fine for the use case and follows the design of <code>std::ostream_iterator</code>. Therefore you might as well store the <code>std::basic_ostream</code> as a reference member variable. That is,</p>\n\n<pre><code>class infix_ostream_iterator : ... {\n ...\n std::basic_ostream&lt;charT,traits&gt;&amp; os;\n ...\n}\n</code></pre>\n\n<p>Now you can remove the pointer indirection which will simplify the remaining code. E.g., the constructor becomes</p>\n\n<pre><code>infix_ostream_iterator(ostream_type &amp;s, charT const *d)\n : os(s)\n , real_delim(d)\n{}\n</code></pre>\n\n<p>and you can directly write to the stream</p>\n\n<pre><code>os &lt;&lt; delimiter &lt;&lt; item;\n</code></pre>\n\n<p>This is an implementation detail (your interface is the same). I reckon that the compiler will generate the same set of instructions anyhow.</p>\n\n<p>Looking forward to seeing this class in something like Boost! Good luck with the submission.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-11-01T19:06:44.760", "Id": "68614", "ParentId": "13176", "Score": "4" } }, { "body": "<p>I know I'm years late on this but I want to throw out an idea: why do the delimiter and non-delimiter cases have to be the same type? Your initial version used <code>charT const*</code> and your new version uses <code>std::basic_string&lt;charT&gt;</code>... but it seems wasteful to have two <code>string</code>s that we're copying just to handle not having a delimiter.</p>\n\n<p>I'd suggest having an overloaded <code>make_*</code> function that either creates your iterator or creates the standard one:</p>\n\n<pre><code>// no delimiter\ntemplate &lt;class T, class CharT, class Traits&gt;\nstd::ostream_iterator&lt;T, CharT, Traits&gt;\nmake_delim_iterator(std::basic_ostream&lt;CharT,Traits&gt;&amp; );\n\n// yes, delimiter\ntemplate &lt;class T, class CharT, class Traits&gt;\ninfix_ostream_iterator&lt;T, CharT, Traits&gt;\nmake_delim_iterator(std::basic_ostream&lt;CharT,Traits&gt;&amp;, CharT const*);\n</code></pre>\n\n<p>This will allow you to have two member <code>CharT const*</code>'s instead of two <code>basic_string&lt;CharT&gt;</code>'s, and your type just always uses a delimiter. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T16:25:40.693", "Id": "210411", "Score": "0", "body": "Maybe it's just that I'm not awake yet, but I guess I'm uncertain how this would work/be used." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T16:27:41.670", "Id": "210412", "Score": "0", "body": "If you want a delimiter: `make_ostream_iterator<T>(std::cout, \", \")` and if you don't `make_ostream_iterator<T>(std::cout)`. And then your object is only constructible with a delimiter." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T16:33:42.117", "Id": "210415", "Score": "0", "body": "The idea here is to be able to support something like `copy(b, e, out)`, and have the elements of [b...e] come out as something like `a, b, c`, with delimiters between the items, but not after the last one (like `std::ostream_iterator` would produce)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T16:40:38.887", "Id": "210417", "Score": "0", "body": "@JerryCoffin No, I know. But you're also supporting `infix_ostream_iterator<T>{std::cout}` with *no* delim and I'm suggesting you just don't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T16:49:18.233", "Id": "210418", "Score": "0", "body": "Oh, I see--yeah, when you don't have a delimiter, there's no real difference between this and a normal ostream_iterartor." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-11T16:21:12.363", "Id": "113625", "ParentId": "13176", "Score": "3" } } ]
{ "AcceptedAnswerId": "13209", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T05:32:19.730", "Id": "13176", "Score": "68", "Tags": [ "c++", "c++11", "iterator" ], "Title": "infix_iterator code" }
13176
<p><a href="http://en.wikipedia.org/wiki/Roman_numerals" rel="nofollow">Roman numerals on Wikipedia</a></p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T07:28:28.903", "Id": "13178", "Score": "0", "Tags": null, "Title": null }
13178
The Roman numeral system is an ancient way of representing numbers. The most common symbols are I, V, X, L, C, D, M.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T07:28:28.903", "Id": "13179", "Score": "0", "Tags": null, "Title": null }
13179
<p>I am refactoring my controllers, trying to improve the way common data is loaded for the actions. Initially, I was using <code>before_filter</code> methods to do this but read that helper methods were preferred.</p> <pre><code>class CategoriesController &lt; ApplicationController before_filter :authenticate_user! helper_method :category, :categories, :organisation # GET /categories def index end # GET /categories/new def new end # GET /categories/1/edit def edit end # POST /categories def create if category.save redirect_to( categories_path(oid: organisation.id), notice: I18n.t("category.create.success")) else render action: :new end end # PUT /categories/1 def update if category.update_attributes(params[:category]) redirect_to( categories_path(oid: organisation.id), notice: I18n.t("category.update.success")) else render action: :edit end end # DELETE /categories/1 def destroy begin category.destroy redirect_to( categories_path(oid: organisation.id), notice: I18n.t("category.delete.success")) rescue ActiveRecord::DeleteRestrictionError redirect_to( categories_path(oid: organisation.id), alert: I18n.t("category.delete.failure.foreign_key")) end end private # Gets the category being operated on. # def category return @category unless @category.nil? if params[:id] @category = Category.find_by_id(params[:id]) elsif params[:category] @category = Category.new(params[:category]) else @category = Category.new({organisation_id: organisation.id}) end end # Gets the organisation of the Category. # # If no Category exists (e.g. in the case of actions index # and new) there will be a querystring parameter 'oid' indicating the # Organisation. # def organisation return @organisation unless @organisation.nil? if params[:oid] @organisation = Organisation.find_by_id(params[:oid]) elsif params[:category] @organisation = Organisation.find_by_id( params[:category][:organisation_id]) elsif !category.nil? @organisation = category.organisation else @organisation = nil end end # Gets the existing Categories for the organisation. # def categories return @categories unless @categories.nil? if !organisation.nil? @categories = Category .where(organisation_id: organisation.id) .order(:name) .all else @categories = nil end end end </code></pre>
[]
[ { "body": "<p>To load data, you can see the gem <a href=\"https://github.com/ryanb/cancan/\" rel=\"nofollow\">Cancan</a>. It think it can do something like you do. I find your code very clear.</p>\n\n<p>Instead of this:</p>\n\n<pre><code>if !organisation.nil?\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>if organisation.present?\n</code></pre>\n\n<p>Instead of this:</p>\n\n<pre><code>@categories = Category\n .where(organisation_id: organisation.id)\n .order(:name)\n .all\n</code></pre>\n\n<p>You can do this:</p>\n\n<pre><code>organisation.categories.order(:name)\n</code></pre>\n\n<p>Instead of using the method <code>find_by_id</code> you can use just the method <code>find</code>.</p>\n\n<p>You did a good job!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T14:01:15.730", "Id": "13194", "ParentId": "13180", "Score": "1" } }, { "body": "<p>Instead of this:</p>\n\n<pre><code>@category ||= Category.find(params[:id])\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>@category = Category.new\n</code></pre>\n\n<p>and this:</p>\n\n<pre><code>@category = Category.new(params[:category])\n</code></pre>\n\n<p>You can use CanCan like this:</p>\n\n<pre><code>class CategoriesController &lt; ApplicationController\n load_resource\n ...\nend\n</code></pre>\n\n<p>See the <a href=\"https://github.com/ryanb/cancan/wiki/authorizing-controller-actions\" rel=\"nofollow\">doc</a> at <code>load_resource</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T11:44:48.503", "Id": "13215", "ParentId": "13180", "Score": "0" } }, { "body": "<p>Instead of this:</p>\n\n<pre><code>render action: \"new\"\n</code></pre>\n\n<p>you can do this, considered good practice:</p>\n\n<pre><code>respond_to do |format| \n format.html { render action: 'new', status: :ok }\nend\n</code></pre>\n\n<p>For strings without interpolation, it's good to use single quotes:</p>\n\n<pre><code>\"new\"\n\n'new'\n\n# Gets the Category being operated on.\n #\n def category\n @category ||= Category.find(params[:id])\n end\n</code></pre>\n\n<p><code>find()</code> throws exceptions, so it's better to handle exceptions:</p>\n\n<pre><code># Gets the Category being operated on.\n #\n def category\n @category ||= Category.find(params[:id])\n rescue ActiveRecord::RecordNotFound\n flash[:notice] = 'Record Not found'\n @category = Category.new\n end\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-30T17:58:16.347", "Id": "136807", "Score": "0", "body": "It appears that you've partially reviewed the newer revision, which shouldn't have been added. Could you remove that part and maybe replace it with something else in the original?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-30T17:17:48.693", "Id": "75253", "ParentId": "13180", "Score": "0" } } ]
{ "AcceptedAnswerId": "13194", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T07:31:42.503", "Id": "13180", "Score": "1", "Tags": [ "ruby", "ruby-on-rails", "controller" ], "Title": "Loading data in controllers" }
13180
<p>The following search script creates a JSON response for an autocomplete field. The tables and fields search from are flexible to allow using the same script for different type of searches - the idea is to search from each database field separately and see how often a term appears and sort them in descending order.</p> <p>The part about ordering the found hits for a word by number of occurrences seems like it could be improved, but I don't know how to better approach the problem.</p> <pre><code>if (isset($_REQUEST['term']) &amp;&amp; !empty($_REQUEST['term'])) { // define what table -&gt; array(fields) to search from based on a possibly sent // parameter 'type', which is 'customer' or 'admin' or empty or some specific if (!isset($_REQUEST['type']) || $_REQUEST['type'] === 'customer') { $searchFrom = array( 'tuotesarjat' =&gt; array('sarjanimi', 'laattatyyppi'), 'tuotteet' =&gt; array('varikategoria1', 'varikategoria2', 'pinta', 'hakupinta') ); } else if ($_REQUEST['type'] === 'admin') { $searchFrom = array( 'tuotesarjat' =&gt; array('sarjanimi', 'laattatyyppi'), 'tuotteet' =&gt; array('tuotenumero', 'kuvaus1', 'varikategoria1', 'varikategoria2', 'pinta', 'hakupinta') ); } else if ($_REQUEST['type'] === 'tuotesarja') { $searchFrom = array( 'tuotesarjat' =&gt; array('sarjanimi') ); } else if ($_REQUEST['type'] === 'tuotenumero') { $searchFrom = array( 'tuotteet' =&gt; array('tuotenumero') ); } $found = array(); $terms = explode(' ', $_REQUEST['term']); // loop through all split up terms foreach ($terms as $key =&gt; $term) { if (!empty($term)) { $term = mysql_real_escape_string($term); // loop through tables foreach ($searchFrom as $table =&gt; $cols) { // for searches from table 'tuotesarjat' limit hits to published items $andWhere = $table == 'tuotesarjat' ? ' AND arkistoitu != 1 ' : ''; // loop through fields foreach ($cols as $column) { $sql = &quot;SELECT $column FROM $table WHERE $column &quot;; // to limit searches, for 1-2 letter terms search string start, // else from whole term if (strlen($term) &lt; 2) { $sql .= &quot;LIKE '$term%' $andWhere GROUP BY $column&quot;; } else { $sql .= &quot;LIKE '%$term%' $andWhere GROUP BY $column&quot;; } // in case a field does not exist, fail silently // (a json query will still be generated returning the // _other_ fields' searches' results) $res = @mysql_query($sql); if (mysql_num_rows($res) &gt; 0) { while($row = mysql_fetch_assoc($res)) { // insert new found word to array with count 1 // or increment already found words' counts if (!key_exists($row[$column], $found)) { $found[$row[$column]] = 1; } else { $found[$row[$column]] += 1; } } } } } } } // sort by number of hits for each word desc arsort($found); // filter empty strings $found = array_filter(array_keys($found)); // reduce array to global max hits while (count($found) &gt; MAX_LIVESEARCH_SUGGESTIONS) { array_pop($found); } // generate and echo json $json = '['; foreach ($found as $sana) { $json .= '&quot;' . $sana . '&quot;, '; } $json = substr($json, 0, -2) . ']'; echo $json; } </code></pre>
[]
[ { "body": "<p><strong>Upgrading PHP</strong></p>\n\n<p>Upgrade your PHP version. After reading this code I determined that you are running at the most 4.0.6. <code>key_exists()</code> was replaced with <code>array_key_exists()</code> in 4.1.1, and this was some time ago. An old version of PHP runs the risk of having security issues, and you won't be able to get much help because everyone is using the newer version. Some of these suggestions might still work, but others may not be supported in your version, such as this first one.</p>\n\n<p><strong>REQUEST vs. POST/GET</strong></p>\n\n<p>You should stop using <code>$_REQUEST</code>. It is insecure, being that you are running an older version of PHP this is understandable, but if you upgrade, you should definitely update this as well. If you know where the information is coming from, and you should, then you should just use that array. For example, if it is coming from POST use the <code>$_POST</code> array, if it is coming from GET use the <code>$_GET</code> array, etc...</p>\n\n<p><strong>switch vs. if/else</strong></p>\n\n<p>Think of using a switch. It is faster than if/else statements and, in my opinion, cleaner looking and more legible.</p>\n\n<pre><code>$searchFrom = array(\n 'tuotesarjat' =&gt; array('sarjanimi', 'laattatyyppi'),\n 'tuotteet' =&gt; array('varikategoria1', 'varikategoria2', 'pinta', 'hakupinta')\n);\n\nif( isset( $_REQUEST[ 'type' ] ) {\n $type = $_REQUEST[ 'type' ];\n switch( $type ) {\n case 'admin':\n $searchFrom = array( \n 'tuotesarjat' =&gt; array('sarjanimi', 'laattatyyppi'),\n 'tuotteet' =&gt; array('tuotenumero', 'kuvaus1', 'varikategoria1', 'varikategoria2', 'pinta', 'hakupinta')\n );\n break;\n //Use a case for each \"type\", exclude customer as it was defined above as a default\n }\n}\n</code></pre>\n\n<p><strong>Foreach Keys</strong></p>\n\n<p>No need to return <code>$key</code> in your foreach loop, especially since you're not using it. Just remove <code>$key =&gt;</code> from the declaration. You can also just use <code>array_filter()</code> after exploding it into an array to remove any empty array members. This will relieve some overhead and is cleaner. Also, since you probably don't want to search for the same term twice you can use <code>array_unique()</code> to remove duplicates.</p>\n\n<p><strong>Repetition</strong></p>\n\n<p>Try to make it so that you repeat yourself as little as possible. This is so that if you ever need to change something, you'll only have to do so once. So...</p>\n\n<pre><code>$term .= '%';\nif (strlen($term) &gt; 2) { $term = \"%$term\"; }\n\n$sql .= \"LIKE '$term' $andWhere GROUP BY $column\";\n</code></pre>\n\n<p>You'll also find, if you upgrade your PHP version, that <code>mysql()</code> is being deprecated. <code>mysqli()</code> and <code>pdo()</code> are now the preferred methods.</p>\n\n<p><strong>Error Suppressors</strong></p>\n\n<p>DON'T USE ERROR SUPPRESSORS. This is a sign of bad code. If there is an error fix it. If you are doing it just so you don't have to type a couple extra lines, don't. Always ensure your code works 100%. The error suppressor should only be used during debugging.</p>\n\n<p><strong>Incrementing</strong></p>\n\n<p>There's got to be some better way to increment the \"found\" array... I thought of using a ternary operator, but that got a little messy, and at the moment, I can't think of anything else... I'll update this if I think of anything...</p>\n\n<p><strong>Question</strong></p>\n\n<p>How are there empty strings in <code>$found</code>?</p>\n\n<p><strong>MAX_LIVESEARCH_SUGGESTIONS</strong></p>\n\n<p>Not sure what the <code>MAX_LIVESEARCH_SUGGESTIONS</code> is, but would it not make more sense to perform this before creating the <code>$found</code> array?</p>\n\n<pre><code>$length = count( $terms );\nwhile ( $length &gt; MAX_LIVESEARCH_SUGGESTIONS) { array_pop( $terms ); }\n</code></pre>\n\n<p>Notice I moved <code>count()</code> out of the loop. With it in the loop, it will run it every time, which means more overhead. Remove it from the loop to remove the overhead. I'm having difficulties following the program, so unless <code>$found</code> ends up with more elements than <code>$terms</code> the above should work. If there are more, then you should limit how many are recorded by breaking out of the loops once that limit is reached.</p>\n\n<pre><code>$length = count( $found );\nif( $length == MAX_LIVESEARCH_SUGGESTIONS ) { break 4; } //I think its 4... might be 3...\n//perform actions to set $found here\n</code></pre>\n\n<p><strong>JSON</strong></p>\n\n<p>Updating your PHP will also mean that you can use the JSON library that is now standard instead of needing to recreate it.</p>\n\n<p>Hope this helps!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T17:07:55.633", "Id": "21419", "Score": "0", "body": "Thanks so much for the input. Many of your points are very good and I will implement them or see how I can restructure my code. As for my use of `$_REQUEST` I should point out that the script is called both via GET and via POST (as a fallback, in case ajax fails/javascript is turned off), so I though `$_REQUEST` will cover both scenarios. The error suppressing `@` is silly and I should probably just make sure the fields I search from exist. Not sure if you suggestion for the while loop will work. I have x amount of words to suggest for a term, but might want to limit the amount of suggestions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T17:08:26.303", "Id": "21420", "Score": "0", "body": "Also, you are obviously right about the version of PHP, but that is, unfortunately, beyond my control." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T18:41:58.067", "Id": "21421", "Score": "0", "body": "@kontur: GET, POST, and COOKIES are for vastly different data types. As such they are stored separately. So using REQUEST, which combines these arrays, will override information from the others. This means that it is very easy for a user to forge information that you don't want them to have access to. So it is much better to know explicitly where that information is coming from and limit access to it from that array only. While this does not appear to be an issue here, it is still good to be in the habit of using the appropriate array." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T18:42:05.477", "Id": "21422", "Score": "0", "body": "I'd bug whoever you need to to get your PHP updated. If its not possible, then its not possible. But if you, or whoever you are working for, is paying for a server that only has this version I would seriously contemplate switching hosts. If its compatibility issues that are holding you back, know that PHP is pretty backwards compatible. Those things that have been deprecated are usually replaced with similar functions, so a find/replace script shouldn't be too difficult." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T20:16:21.043", "Id": "21424", "Score": "0", "body": "Thanks for the input @showerhead. We are in the progress of moving to a new host, but things are slow :) I did not know `$_REQUEST` also holds `$_COOKIES`. As you rightly pointed out, specifically working with either or might also help to improve the readability of the script. Thanks again." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T15:00:54.243", "Id": "13245", "ParentId": "13181", "Score": "2" } }, { "body": "<ol>\n<li><p><code>isset($variable) &amp;&amp; !empty($variable)</code> is a classic/common anti-pattern that should not exist in anyone's code. Please read this: <a href=\"https://stackoverflow.com/a/4559976/2943403\">https://stackoverflow.com/a/4559976/2943403</a></p>\n</li>\n<li><p>A lookup array will allow you to ditch all those condition blocks.</p>\n<pre><code>$lookup = [\n 'customer' =&gt; [\n 'tuotesarjat' =&gt; ['sarjanimi', 'laattatyyppi'],\n 'tuotteet' =&gt; ['varikategoria1', 'varikategoria2', 'pinta', 'hakupinta']\n ],\n 'admin' =&gt; [\n 'tuotesarjat' =&gt; ['sarjanimi', 'laattatyyppi'],\n 'tuotteet' =&gt; ['tuotenumero', 'kuvaus1', 'varikategoria1', 'varikategoria2', 'pinta', 'hakupinta']\n ],\n ...\n];\n</code></pre>\n</li>\n<li><p><code>!isset($_REQUEST['type']) || $_REQUEST['type'] === 'customer'</code> means that you can fallback to <code>customer</code> when the element is not declare or is <code>null</code>. Now <code>$searchFrom</code> can be populated in clean O(1) action. In modern php, the null coalescing operator makes this syntax sweeter:</p>\n<pre><code>$searchFrom = $lookup[$_REQUEST['type'] ?? 'customer'] ?? $lookup['customer']; \n</code></pre>\n<p>For PHP version that are too old to enjoy the null coalescing operator:</p>\n<pre><code>$searchFrom = isset($_REQUEST['type'], $lookup[$_REQUEST['type']]) ? $lookup[$_REQUEST['type']] : $lookup['customer']; \n</code></pre>\n</li>\n<li><p>In fact, if those lookup values are mostly static, then I would argue that you should refactor the script so that the lookup contains sql string with placeholders. This will set you up to use a single , non-iterative prepared statement. However, if your queries are prohibitively dynamic to consider a single prepared statement then try to create a prepared statement for each table. <a href=\"https://stackoverflow.com/a/51036322/2943403\">Prepared statements that contain a variable number conditions are not impossible to make</a> (notice that the result set object can be iterated with a <code>foreach()</code> instead of iterated <code>fetch()</code> calls). In modern PHP, it no longer best practice to use the deprecated <code>mysql_</code> functions or <code>escape</code>ing functions.</p>\n</li>\n<li><p>You must not manually craft json strings. When you want to create a json string in PHP, always use <code>json_encode()</code> so that nothing can go wrong.</p>\n</li>\n<li><p>An easy fix that be consistent throughout your php applications is that <code>else if</code> should be one word (<code>elseif</code>) to comply with PSR-12 coding standards.</p>\n</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-01-28T07:09:33.340", "Id": "255317", "ParentId": "13181", "Score": "2" } } ]
{ "AcceptedAnswerId": "13245", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2012-06-29T07:36:14.600", "Id": "13181", "Score": "2", "Tags": [ "php", "sorting", "mysql", "json" ], "Title": "Search script for autocomplete suggestions" }
13181
<p>I was solving problem <a href="http://projecteuler.net/problem=18" rel="nofollow noreferrer">18</a> and <a href="http://projecteuler.net/problem=67" rel="nofollow noreferrer">67</a> on Project Euler and came up with an algorithm that actually goes through <em>almost</em> all the possibilities to find the answer in O(n) time. However, ProjecEuler claims that a Brute force solution will take too long. Many have implemented this problem using trees, dp and what not.</p> <p>Is my approach not a Brute force?</p> <pre><code>n = [] for i in range(100): n.append(map(int,raw_input().split())) newresult = [int(59)] n.pop(0) for i in range(99): x = n.pop(0) result = list(newresult) newresult =[] t = len(x) for j in range(t): if(j==0): newresult.append(result[0]+x.pop(0)) elif(j==t-1): newresult.append(result[0]+x.pop(0)) else: newresult.append(max((result.pop(0)+x[0]),result[0]+x.pop(0))) print max(newresult) </code></pre> <p>UPDATE: here's a idea how my algorithm works (taking max when needed) <img src="https://i.stack.imgur.com/E3fW0.png" alt="enter image description here"></p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T17:06:24.517", "Id": "21350", "Score": "0", "body": "Since you seem to understand how dynamic programming works, would you kindly describe your algorithm using words?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T18:26:58.840", "Id": "21351", "Score": "0", "body": "@Leonid checkout the update :)" } ]
[ { "body": "<blockquote>\n <p>Is my approach not a Brute force?</p>\n</blockquote>\n\n<p>Nope, you've implemented dynamic programming</p>\n\n<pre><code>n = []\nfor i in range(100):\n n.append(map(int,raw_input().split()))\nnewresult = [int(59)]\n</code></pre>\n\n<p>I'm not clear why you pass 59 to int, it doesn't do anything. \n n.pop(0)</p>\n\n<p>why didn't you do <code>newresult = n.pop()</code> instead of recreating the first row in the code?</p>\n\n<pre><code>for i in range(99):\n x = n.pop(0)\n result = list(newresult)\n</code></pre>\n\n<p>This makes a copy of newresult, which is pointless here since you don't keep the original around anyways</p>\n\n<pre><code> newresult =[]\n t = len(x)\n for j in range(t):\n\n if(j==0):\n</code></pre>\n\n<p>You don't need the parens</p>\n\n<pre><code> newresult.append(result[0]+x.pop(0))\n</code></pre>\n\n<p>I think the code is a bit clearer if you don't use <code>x.pop</code> just calculate the appropriate indexes </p>\n\n<pre><code> elif(j==t-1):\n newresult.append(result[0]+x.pop(0))\n else:\n newresult.append(max((result.pop(0)+x[0]),result[0]+x.pop(0)))\n</code></pre>\n\n<p>Figuring out the logic of what happens with all this popping is tricky. Again, I think calculating the index will be more straightforward. Also it'll probably be faster since popping the first element of a list is expensive.</p>\n\n<pre><code>print max(newresult)\n</code></pre>\n\n<p>A brute force solution would iterate over every possible path down the triangle. You are iterating over every possible position in the triangle which is much much smaller.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>The dynamic programming solutions starts with a recursive definition of the solution:</p>\n\n<pre><code>cost(i) = number(i) + max( cost(j) for j in predeccesors(i) )\n</code></pre>\n\n<p>Where <code>i</code>, <code>j</code> corresponds to positions on the triangle, and <code>predecessors(i)</code> is the set of all positions which can move onto <code>i</code>. </p>\n\n<p>The top-down approach works by using memoization, remembering a value of <code>cost(j)</code> after it has been calculated. When <code>cost(j)</code> is needed again, it is simply reused. </p>\n\n<p>However, you can also use the bottom-up approach to dynamic programming. In this case, you calculate the values of <code>cost(i)</code> starting from the first cells and work your way forward. Ever cost(i) only depends on the costs of cells before the current cell, and since those have already been calculated they can be reused without even using memoization.</p>\n\n<p>If you look at your code, you'll find that the innermost loop is calculating the same formula as above. Furthermore, you'll find that it is calculating the cost of reach each cell starting from the cells at the top of the triangle and moving its way down. That's why I characterize it as dynamic programming. </p>\n\n<p>I think you don't see this as DP, because you really didn't follow any DP logic in coming up with the solution. I think you are viewing it in terms of repeatedly reducing the complexity of the problem by eliminating the top row. In the end you are doing the same calculations as the DP version although you came at it from a different angle.</p>\n\n<blockquote>\n <p>I think dp uses the same solution again and again, wheras there is\n no need of such memorization here</p>\n</blockquote>\n\n<p>All that's necessary for DP is to reuse solutions more than once. In this case, every number you calculate gets used in two places (one for the right, one for the left)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T23:38:48.330", "Id": "21358", "Score": "0", "body": "\"Nope, you've implemented dynamic programming\" - it does not look like one at first, but I guess it is. One would have to review the definition of the dynamic programming. Obviously, standard dp approach that works in reverse direction is easier to comprehend, but I am curious whether this is another technique for solving problems that I have not encountered yet, or just an over-complication of something that is easy. Perhaps it makes solutions to some other problems easier ..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T04:45:45.597", "Id": "21375", "Score": "0", "body": "@Winston your explanation is appreciated, however I am more concerned of the technique and less of the code (let it be dirty its just for projectEuler). Can you explain why this is dp? I think dp uses the same solution again and again, wheras there is no need of such memoization here" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T07:34:44.033", "Id": "21376", "Score": "0", "body": "@nischayn22, see edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T08:17:42.943", "Id": "21377", "Score": "0", "body": "+1 for the edit, I will try to see if this approach can be used in other dp problems" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:33:28.147", "Id": "13206", "ParentId": "13186", "Score": "6" } } ]
{ "AcceptedAnswerId": "13206", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:27:55.580", "Id": "13186", "Score": "3", "Tags": [ "python", "project-euler" ], "Title": "Isn't this dynamic programming?" }
13186
<p><a href="http://aws.amazon.com/s3/" rel="nofollow"><strong>Amazon S3</strong> (Simple Storage Service)</a> is an online storage web service offered by <a href="http://aws.amazon.com/" rel="nofollow">Amazon Web Services</a>. Amazon S3 provides storage through a simple web services interface. It gives any developer access to the same highly scalable, reliable, secure, fast, inexpensive infrastructure that Amazon uses to run its own global network of web sites.</p> <p><strong>References</strong></p> <ul> <li><a href="http://aws.amazon.com/documentation/s3/" rel="nofollow">Documentation</a></li> <li><a href="http://aws.amazon.com/code/developertools?_encoding=UTF8&amp;jiveRedirect=1" rel="nofollow">Developer Tools</a></li> <li><a href="http://en.wikipedia.org/wiki/Amazon_S3" rel="nofollow">Wikipedia</a></li> </ul>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:28:48.803", "Id": "13187", "Score": "0", "Tags": null, "Title": null }
13187
This tag refers to the Amazon S3 (Simple Storage Service) Web Services from Amazon.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:28:48.803", "Id": "13188", "Score": "0", "Tags": null, "Title": null }
13188
<p>I recently got serious about learning Haskell and upon finishing chapter 4 in Real World Haskell, I decided to try out my accumulated knowledge on a project of my own.</p> <p><a href="https://github.com/linduxed/kalaha-solver/tree/55146b8cb5fb23590aaaf65d9b4cd3d38bfcea3a" rel="nofollow">This code hosted on github is a Kalaha solver.</a> It's just one file of code and I've included information about the game and the rules in the README.</p> <p>While I'm sure there are many problems with the code, the big code smell (from what I can tell) is the use of big tuples as return types. The biggest offender is this piece of code:</p> <pre><code>{- - Determines whether another lap is necessary. -} moveMarbles :: (([Pot], Bool), Int, Bool) -&gt; Int -&gt; ([Pot], Bool) moveMarbles ((listOfPots, landedInStore), marblesInHand, mustContinue) startingPot = resultingPotsAndStoreState where resultingPotsAndStoreState = lapLoop listOfPots landedInStore marblesInHand mustContinue startingPot lapLoop listOfPots landedInStoreLastLap marblesLeftFromLastLap mustContinue startingPot | not $ mustContinue = (listOfPots, landedInStoreLastLap) | otherwise = moveMarbles (moveOneLap listOfPots startingPot marblesLeftFromLastLap) 0 {- - Does the actual movement of marbles. - The top case in each of the loop sections only happens the first time the - loop is called (it's the only time no marbles are held). -} moveOneLap :: [Pot] -&gt; Int -&gt; Int -&gt; (([Pot], Bool), Int, Bool) moveOneLap listOfPots startingPot startingMarblesInHand = ((modifiedPots, landedInStore), marblesLeftInHand, mustDoAnotherLap) where modifiedPots = untouchedFirstPots ++ moveLoop toTraverse startingMarblesInHand landedInStore = storeLoop toTraverse startingMarblesInHand marblesLeftInHand = marbleLoop toTraverse startingMarblesInHand mustDoAnotherLap = continuationLoop toTraverse startingMarblesInHand untouchedFirstPots = take (startingPot - 1) listOfPots toTraverse = drop (startingPot - 1) listOfPots moveLoop [] _ = [] moveLoop (x:xs) marblesInHand | marblesInHand == 0 = returnEmptyPot x : moveLoop xs (marbleCount x) | marblesInHand &gt; 1 = returnPotWithOneMoreMarble x : moveLoop xs (marblesInHand - 1) | isStore x &amp;&amp; marblesInHand == 1 = returnPotWithOneMoreMarble x : xs | (not $ isPotEmpty x) &amp;&amp; marblesInHand == 1 = returnEmptyPot x : moveLoop xs (marbleCount x + 1) | isPotEmpty x &amp;&amp; marblesInHand == 1 = returnPotWithOneMoreMarble x : xs where returnPotWithOneMoreMarble pot = pot { marbleCount = (marbleCount pot + 1) } returnEmptyPot pot = pot { marbleCount = 0 } marbleLoop [] marblesInHand = marblesInHand marbleLoop (x:xs) marblesInHand | marblesInHand == 0 = marbleLoop xs (marbleCount x) | marblesInHand &gt; 1 = marbleLoop xs (marblesInHand - 1) | isStore x &amp;&amp; marblesInHand == 1 = 0 | (not $ isPotEmpty x) &amp;&amp; marblesInHand == 1 = marbleLoop xs (marbleCount x + 1) | isPotEmpty x &amp;&amp; marblesInHand == 1 = 0 continuationLoop [] _ = True continuationLoop (x:xs) marblesInHand | marblesInHand == 0 = continuationLoop xs (marbleCount x) | marblesInHand &gt; 1 = continuationLoop xs (marblesInHand - 1) | isStore x &amp;&amp; marblesInHand == 1 = False | (not $ isPotEmpty x) &amp;&amp; marblesInHand == 1 = continuationLoop xs (marbleCount x + 1) | isPotEmpty x &amp;&amp; marblesInHand == 1 = False storeLoop [] _ = False storeLoop (x:xs) marblesInHand | marblesInHand == 0 = storeLoop xs (marbleCount x) | marblesInHand &gt; 1 = storeLoop xs (marblesInHand - 1) | isStore x &amp;&amp; marblesInHand == 1 = True | (not $ isPotEmpty x) &amp;&amp; marblesInHand == 1 = storeLoop xs (marbleCount x + 1) | isPotEmpty x &amp;&amp; marblesInHand == 1 = False </code></pre> <p>The way I see it, a player makes a lap around the board, and then for the next lap a lot of information needs to be passed on (should he do another lap, what was the state of the board from the last lap...), which both results in a huge return type and multiple loops doing pretty much the same thing but with different results.</p> <p>I guess that this could all be avoided if I had a more clever approach to the problem, but as mentioned, I'm no more than a beginner.</p>
[]
[ { "body": "<p>I would suggest two refactorings:</p>\n\n<p>First note that you can indeed simply merge the four loops by giving them tuple results. After a few smaller changes I arrived at the following code:</p>\n\n<pre><code>moveOneLap :: [Pot] -&gt; Int -&gt; Int -&gt; (([Pot], Bool), Int, Bool)\nmoveOneLap listOfPots startingPot startingMarblesInHand = ((modifiedPots, landedInStore), marblesLeftInHand, mustDoAnotherLap)\n where\n (untouchedFirstPots, toTraverse)\n = splitAt (startingPot - 1) listOfPots\n (newPots, marblesLeftInHand, mustDoAnotherLap, landedInStore)\n = moveLoop toTraverse startingMarblesInHand []\n modifiedPots\n = untouchedFirstPots ++ newPots\n\n moveLoop [] marblesInHand xs' = ([], marblesInHand, True, False)\n moveLoop (x:xs) marblesInHand xs'\n | marblesInHand == 0 = moveLoop xs (marbleCount x) (emptyPot : xs')\n | marblesInHand &gt; 1 = moveLoop xs (marblesInHand - 1) (addMarble : xs')\n | marblesInHand /= 1 = error \"strange - marblesInHand was negative?\"\n | isStore x = (finishedPots, 0, False, True)\n | isPotEmpty x = (finishedPots, 0, False, False)\n | otherwise = moveLoop xs (marbleCount x + 1) (emptyPot : xs')\n where\n addMarble = x { marbleCount = (marbleCount x + 1) }\n emptyPot = x { marbleCount = 0 }\n finishedPots = reverse (addMarble : xs)\n</code></pre>\n\n<p>The second change I would propose comes from the observation that you have two <code>Bool</code> getting passed back - as well as a number that is in two cases always zero! We could easily translate that into an algebraic data type:</p>\n\n<pre><code>data LapResult = LapContinue Int\n | LapLandedInStore\n | LapDone\n</code></pre>\n\n<p>Which leads to well-reading loop code:</p>\n\n<pre><code>moveLoop [] marblesInHand xs' = ([], LapContinue marblesInHand)\nmoveLoop (x:xs) marblesInHand xs'\n ....\n | isStore x = (finishedPots, LapLandedInStore)\n | isPotEmpty x = (finishedPots, LapDone)\n</code></pre>\n\n<p>And an outer loop that involves less plumbing:</p>\n\n<pre><code>moveMarbles :: [Pot] -&gt; Int -&gt; Int -&gt; ([Pot], Bool)\nmoveMarbles listOfPots startingPot marblesInHand =\n let (newPots, lapResult) = moveOneLap listOfPots startingPot marblesInHand in\n case lapResult of\n LapContinue newMarblesInHand -&gt; moveMarbles newPots 0 newMarblesInHand\n LapLandedInStore -&gt; (newPots, True)\n LapDone -&gt; (newPots, False)\n</code></pre>\n\n<p>I didn't test this, so apologies if I introduced a bug at some point. But this is the direction I would go into style-wise.</p>\n\n<p>Final note: Generally, when you find yourself passing in and out big tuples of things, it is often worthwhile to starting looking out whether a <code>State</code> or <code>Reader</code> monad might improve things. For example, you could have a <code>State</code> monad tracking your current pots. However, the rest of your code doesn't look like it would benefit from this transformation, so I left it like this.</p>\n\n<p>Code can be found in my <a href=\"https://github.com/scpmw/kalaha-solver\" rel=\"nofollow\">GitHub fork</a>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T15:52:28.317", "Id": "13246", "ParentId": "13189", "Score": "4" } } ]
{ "AcceptedAnswerId": "13246", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T13:29:33.083", "Id": "13189", "Score": "4", "Tags": [ "haskell" ], "Title": "How to avoid big tuple return types?" }
13189
<p>As with my <a href="https://codereview.stackexchange.com/questions/13189/how-to-avoid-big-tuple-return-types">other question</a> this is regarding my <a href="https://github.com/linduxed/kalaha-solver/tree/55146b8cb5fb23590aaaf65d9b4cd3d38bfcea3a" rel="nofollow noreferrer">Kalaha solver</a>.</p> <p>Currently the way I find out the optimal progression of moves is with a command like this:</p> <pre><code>snd $ head $ reverse $ sortByMostInStore $ pickAllPaths $ generatePotList 4 </code></pre> <p>The <code>snd</code> is there to just get the list of moves from the <code>([Pot], [Int])</code> pair and the <code>reverse</code> is there because the sorting is ascending. My main problem is that <code>pickAllPaths</code> is really taking <strong>every</strong> possible path. This results in manageable execution time for <code>generatePotList 5</code> with 17352 paths, but bring it up to 6 marbles in each pot and that results in 7657399 paths, which takes a significantly longer time to compute.</p> <pre><code>-- The [Int] is the list of starting positions you picked up marbles from. pickAllPaths :: [Pot] -&gt; [([Pot], [Int])] pickAllPaths startingListOfPots = resultingPotsAndPaths where resultingPotsAndPaths = branchLoop startingListOfPots [] branchLoop :: [Pot] -&gt; [Int] -&gt; [([Pot], [Int])] branchLoop listOfPots pathTaken | null validStartingPositions = [(listOfPots, pathTaken)] | otherwise = loopHelper validStartingPositions listOfPots pathTaken [] where validStartingPositions = map position $ filter (not . isPotEmpty) potsOwnedByPlayer potsOwnedByPlayer = take 6 listOfPots loopHelper :: [Int] -&gt; [Pot] -&gt; [Int] -&gt; [([Pot], [Int])] -&gt; [([Pot], [Int])] loopHelper [] _ _ returnList = returnList loopHelper (x:xs) listOfPots pathTaken returnList | not $ landsInStore = loopHelper xs listOfPots pathTaken combinedList | otherwise = branchLoop resultingPots (pathTaken ++ [x]) ++ loopHelper xs listOfPots pathTaken returnList where (resultingPots, landsInStore) = makeStartingMove listOfPots x combinedList = ((resultingPots, (pathTaken ++ [x])) : returnList) </code></pre> <p>Since I'll generally only be interested in the three best (and maybe worst) paths, which is less than 1% of all the calculated paths, I'm sure there must be a better way of doing this.</p> <p>Is there a way to avoid unnecessary recursion?</p>
[]
[ { "body": "<p>The standard trick is to skip portions of the search space that cannot bring a better solution than the ones found so far. For this you need to:</p>\n\n<ul>\n<li>Remember the best solution found so far (or several best solutions, if you want).</li>\n<li>Estimate an upper bound on possible scores that can be achieved from a given game state.</li>\n</ul>\n\n<p>Then, given a partial game state, you compare the estimated upper bound to the current best solution, and if it's lower, there is no need to process the game state. The better the estimate, the more unnecessary processing is skipped.</p>\n\n<p>Depending on the game it's might or it might not be possible to make a precise estimate. If it's not possible, you can use approximate examples. But there is a trade-off: The less precise estimate the higher chance you'll miss the best solution (but most likely the returned solution would be good enough).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-08-09T11:32:42.587", "Id": "14481", "ParentId": "13195", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T14:02:40.173", "Id": "13195", "Score": "5", "Tags": [ "optimization", "haskell", "recursion" ], "Title": "Kalaha Solver: finding the marbles" }
13195
<p>Assume I have an article list, each with the following format:</p> <p><strong>Article</strong><br> <img src="https://i.stack.imgur.com/wnOZY.jpg" alt="enter image description here"><br> In the header I'm placing: the article's title, the author and the image,<br> the paragraph belongs to the section, in the footer all the bottom elements (share, read more).</p> <p><strong>This is my html5 article code:</strong> </p> <pre><code>&lt;h1&gt;HTML5 Website&lt;/h1&gt; &lt;div id="content"&gt; &lt;article id="example1"&gt; &lt;header&gt; &lt;h2&gt; Title of the Article 1&lt;br /&gt; Name of the Author &lt;/h2&gt; &lt;img /&gt; &lt;/header&gt; &lt;section&gt; &lt;p&gt;Paragraph content&lt;/p&gt; &lt;/section&gt; &lt;footer&gt; &lt;!-- Social Links &amp; Read More Button --&gt; &lt;/footer&gt; &lt;/article&gt; &lt;article id="example2"&gt; &lt;header&gt; &lt;h2&gt;Title of the Article 2&lt;/h2&gt; &lt;h3&gt;Name of the Author&lt;/h3&gt; &lt;img /&gt; &lt;/header&gt; &lt;div&gt; &lt;p&gt;Paragraph content&lt;/p&gt; &lt;/div&gt; &lt;footer&gt; &lt;!-- Social Links &amp; Read More Button --&gt; &lt;/footer&gt; &lt;/article&gt; &lt;/div&gt; </code></pre> <p><strong>This is the generated outline:</strong><br> <a href="http://gsnedders.html5.org/outliner/" rel="nofollow noreferrer">http://gsnedders.html5.org/outliner/</a><br> <img src="https://i.stack.imgur.com/4ByJ3.jpg" alt="enter image description here"></p> <p><strong>My Questions:</strong><br> <em>For example1:</em><br> Is it benefit to the outliner to mix Title and Author in the same element? Considering that the outliner reads both as one.</p> <p><em>For example2:</em><br> The problem I find is that when using section it generates an untitled section in the outliner. So the only solution is to use a div instead of a section. Is that semantic?</p> <p><em>General Question:</em><br> I want to know if my whole code is properly semantic, respecting both html5 specification and the outliner.</p>
[]
[ { "body": "<p>You've got things confused a little. </p>\n\n<p>Here's what's wrong:</p>\n\n<ol>\n<li>I prefer to use <code>&lt;header&gt;</code> <strong>only once</strong> on the page. This explains what the header of the page is. You may use it more often if you like.</li>\n<li>I prefer to use <code>&lt;footer&gt;</code> <strong>only once</strong> on the page. This explains what the footer of the page is. You may use it more often if you like.</li>\n<li>Don't use article and section merely to replace divs.</li>\n</ol>\n\n<p>Example of how I would re-write the structure:</p>\n\n<pre><code>&lt;header&gt;\n &lt;h1&gt;HTML5 Website&lt;/h1&gt;\n&lt;/header&gt;\n&lt;div id=\"content\"&gt;\n &lt;article id=\"example1\"&gt;\n &lt;div class=\"articleTitle\"&gt;\n &lt;h2&gt;\n Title of the Article 1\n &lt;p&gt;Name of the Author&lt;/p&gt;\n &lt;/h2&gt;\n &lt;/div&gt;\n &lt;div class=\"articleBody\"&gt;\n Content here\n &lt;/div&gt;\n\n &lt;div class=\"articleFooter\"&gt;\n &lt;!-- Social Links &amp; Read More Button --&gt;\n &lt;/div&gt;\n &lt;/article&gt;\n\n &lt;article id=\"example2\"&gt;\n &lt;div class=\"articleTitle\"&gt;\n &lt;h2&gt;\n Title of the Article 2\n &lt;p&gt;Name of the Author&lt;/p&gt;\n &lt;/h2&gt;\n &lt;/div&gt;\n &lt;div class=\"articleBody\"&gt;\n Content here\n &lt;/div&gt;\n\n\n &lt;div class=\"articleFooter\"&gt;\n &lt;!-- Social Links &amp; Read More Button --&gt;\n &lt;/div&gt;\n &lt;/article&gt;\n&lt;/div&gt;\n&lt;footer&gt;\n Footer Content\n&lt;/footer&gt;\n</code></pre>\n\n<p>I ditched the <code>&lt;section&gt;</code> tags because there really is no specific need for it in your case.</p>\n\n<p>Description of the article tag from W3C:</p>\n\n<blockquote>\n <p>The article element represents a component of a page that consists of\n a self-contained composition in a document, page, application, or site\n and that is intended to be independently distributable or reusable,\n e.g. in syndication. This could be a forum post, a magazine or\n newspaper article, a blog entry, a user-submitted comment, an\n interactive widget or gadget, or any other independent item of\n content.</p>\n</blockquote>\n\n<p>Description of the section tag from W3C:</p>\n\n<blockquote>\n <p>The section element represents a generic document or application\n section…The section element is not a generic container element. When\n an element is needed for styling purposes or as a convenience for\n scripting, authors are encouraged to use the div element instead.</p>\n</blockquote>\n\n<p>I hope this helps!</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-07T21:11:27.557", "Id": "15424", "ParentId": "13200", "Score": "1" } }, { "body": "<h2>Question 1 (title and author in heading)</h2>\n\n<blockquote>\n <p>Is it benefit to the outliner to mix Title and Author in the same element? Considering that the outliner reads both as one.</p>\n</blockquote>\n\n<p>Does the author name needs to be in the article heading? </p>\n\n<p>If so, instead of <code>&lt;h2&gt;Title of the Article 1&lt;br /&gt;Name of the Author&lt;/h2&gt;</code> (the <code>br</code> element is wrong here) you should divide the parts like <code>&lt;h2&gt;TITLE by AUTHOR&lt;/h2&gt;</code> or <code>&lt;h2&gt;TITLE (AUTHOR)&lt;/h2&gt;</code>. Use <code>span</code> if you want to style these parts differently.</p>\n\n<p>The title/author combination in your second example is wrong, because it creates a wrong outline. You should use <code>hgroup</code> here:</p>\n\n<pre><code>&lt;header&gt;\n &lt;hgroup&gt;\n &lt;h2&gt;Title of the Article 2&lt;/h2&gt;\n &lt;h3&gt;Name of the Author&lt;/h3&gt;\n &lt;/hgroup&gt;\n &lt;img /&gt;\n&lt;/header&gt;\n</code></pre>\n\n<p>But I'd advise against putting the author name in a heading (depends on the real site context, though). I'd only put the author name in a heading (next to the title or in a <code>hgroup</code> together with the title), if there is no more than one article per author or if the titles are ambiguous.</p>\n\n<h2>Question 2 (<code>section</code> vs. <code>div</code> in <code>article</code>)</h2>\n\n<blockquote>\n <p>The problem I find is that when using section it generates an untitled section in the outliner. So the only solution is to use a div instead of a section. Is that semantic?</p>\n</blockquote>\n\n<p>Within <code>article</code> you would use <code>section</code> elements for chapters etc. (and other <code>article</code> elements for comments). So yeah, if you don't have/need those chapters (each would have its own heading, whether explicit or implicit = untitled), use <code>div</code>. Or better (if you don't need any special styling hook), don't use any element. Everything within <code>article</code> (which is not within <code>header</code>/<code>footer</code>/<code>nav</code>/'aside') <em>is</em> the \"prose\" content.</p>\n\n<h2>Question 3 (whole markup)</h2>\n\n<blockquote>\n <p>I want to know if my whole code is properly semantic, respecting both html5 specification and the outliner.</p>\n</blockquote>\n\n<p>I'd go with:</p>\n\n<pre><code>&lt;article id=\"example1\"&gt;\n\n &lt;h1&gt;Title of the Article 1&lt;/h1&gt;\n\n &lt;footer&gt;\n &lt;span&gt;Name of the Author&lt;/span&gt;\n &lt;img /&gt;\n &lt;/footer&gt;\n\n &lt;p&gt;Paragraph content&lt;/p&gt;\n\n &lt;nav&gt;\n &lt;!-- Read More Button --&gt;\n &lt;/nav&gt;\n\n &lt;footer&gt;\n &lt;!--Social Links --&gt;\n &lt;/footer&gt;\n\n&lt;/article&gt;\n</code></pre>\n\n<ul>\n<li><code>header</code> is not needed here, because it would only contain the <code>h1</code></li>\n<li>used <code>h1</code> instead of <code>h2</code> (the first heading counts, no matter which level; simply use what you like more)</li>\n<li>used <code>footer</code> instead of <code>header</code> for the author name and author picture; see <a href=\"http://www.w3.org/TR/html5/the-footer-element.html#the-footer-element\" rel=\"nofollow\">HTML5 spec</a>: \"A footer typically contains information about its section such as <strong>who wrote it</strong> …\"</li>\n<li>placed the \"read more\" link in <code>nav</code> because it is the main navigation within this sectioning content\n<ul>\n<li>you are free to give an explicit heading for <code>nav</code> (and maybe visually hide it, so that it is still read by screen-readers), but it's not a must, of course</li>\n</ul></li>\n<li>whether the social links belong in <code>nav</code> or not depends on context; in general, these are not considered major navigation, so I put them in <code>footer</code> (instead, an <code>aside</code> element could be used)</li>\n</ul>\n\n<hr>\n\n<p>Regarding @danchet remark about <code>header</code>/<code>footer</code>: It's totally fine (and often needed!) to have <em>several</em> <code>header</code> and <code>footer</code> elements on the same page page. The <a href=\"http://www.w3.org/TR/html5/the-footer-element.html#the-footer-element\" rel=\"nofollow\"><code>footer</code> element</a> applies to \"its nearest ancestor sectioning content or sectioning root element\", so each <code>section</code>/<code>article</code>/<code>nav</code>/<code>aside</code>/etc. can have its very own <code>footer</code> (and yes, even several).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-09-10T00:39:59.133", "Id": "15456", "ParentId": "13200", "Score": "3" } } ]
{ "AcceptedAnswerId": "15456", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T19:27:01.400", "Id": "13200", "Score": "4", "Tags": [ "html5" ], "Title": "HTML5: Section in Article is Untitled Section in the Outliner" }
13200
<p>So I have a customers site I am remaking into an mvc3 app and they have an existing JavaScript pricing calculator. Is this safe and efficient? I am no JavaScript guy, but it looks pretty solid to me.</p> <pre><code> &lt;script type="text/javascript"&gt; window.onload = function () { //Carpet var ppf = .25; //price per square foot, edit this to suit //tile var ppfTile = .50; //price per square foot, edit this to suit var ppfVCTWood = .60; //price per square foot, edit this to suit var ppfTravertine = .60; //price per square foot, edit this to suit df = document.carpet; df[0].focus(); df[2].onclick = function () { df[0].focus(); }; df[0].onkeyup = function () { if (isNaN(df[0].value)) { alert('numbers only please'); df.reset(); df[0].focus(); return; } df[1].value = '$' + util.formatCurrency(df[0].value * ppf); df[2].value = '$' + util.formatCurrency(df[0].value * ppfTile); df[3].value = '$' + util.formatCurrency(df[0].value * ppfVCTWood); df[4].value = '$' + util.formatCurrency(df[0].value * ppfTravertine); }; }; var util = { formatCurrency: function (num) { num = isNaN(num) || num === '' || num === null ? 0.00 : num; return parseFloat(num).toFixed(2); } }; &lt;/script&gt; </code></pre> <p>And here is the form.</p> <pre><code>&lt;form name="carpet" action="#"&gt; &lt;div id="container"&gt; &lt;h2 style="font-size: 12pt;"&gt; Cost Estimate&lt;/h2&gt; &lt;label&gt; &lt;input class="inp" type="text" /&gt; : Enter Square Footage&lt;/label&gt; &lt;br /&gt; &lt;label&gt; &lt;input class="inp" type="text" value="$0" readonly="readonly" /&gt; : Estimated Cost For Carpet&lt;/label&gt; &lt;br /&gt; &lt;label&gt; &lt;input class="inp" type="text" value="$0" readonly="readonly" /&gt; : Estimated Cost For Tile &lt;/label&gt; &lt;br /&gt; &lt;label&gt; &lt;input class="inp" type="text" value="$0" readonly="readonly" /&gt; : Estimated Cost For VCT and Wood &lt;/label&gt; &lt;br /&gt; &lt;label&gt; &lt;input class="inp" type="text" value="$0" readonly="readonly" /&gt; : Estimated Cost For Travertine Tile &lt;/label&gt; &lt;br /&gt; &lt;input type="reset" /&gt; &lt;/div&gt; &lt;/form&gt; </code></pre> <p>I am worried this is old and outdated. Could I do this more effectively with C# in the app?</p>
[]
[ { "body": "<p>About the only thing that I don't like in it is that you have to edit the code each time a price changes. I'd prefer that to come from a dynamic source, especially if you are going to use it in more than one spot.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T20:55:05.230", "Id": "21354", "Score": "0", "body": "Hmm good point, right now it's only in one spot on one page. I could make some sort of datasource that would be easy to add/delete from. Other than that it seem pretty solid and not too old/outdated?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T20:58:43.790", "Id": "21355", "Score": "0", "body": "Yeah, it seems all right, but if you are recoding to MVC3, how long would it take to recode the calculator? Stylistically, unless it's time prohibitive, having it all in a contiguous language might be preferable, unless they have JS sprinkled all through the code." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T20:51:56.030", "Id": "13202", "ParentId": "13201", "Score": "3" } }, { "body": "<p>Here are a few thoughts. Some are probably overkill, but I'm just brainstorming.</p>\n\n<p>Overall, it seems fairly solid if a little outdated. JohnP mentioned the bit about hard-coded prices, and I agree, but it's a question of maintainability rather than robustness.</p>\n\n<p>I'd be concerned about directly assigning a function to <code>window.onload</code>. While it works, it also precludes you from adding other on-load functions later (you'd have to do some extra work at least), and/or you risk overwriting other onload handlers, or them overwriting yours. Libraries like jQuery will handle multiple event handlers for you, but if you want to avoid loading a library, there are still <a href=\"http://quirksmode.org/dom/events/index.html\" rel=\"nofollow\">alternatives to attaching event handlers directly</a>.</p>\n\n<p>On the markup side, I'd give all the inputs proper IDs or at least name attributes, and refer to them that way in the JavaScript. The <code>someform[nth_input]</code> way of getting elements works, but it's pretty oldschool, impossible to understand without the markup, and easily breaks if you add more inputs to the form. Meanwhile something like <code>document.getElementById(\"square_footage\")</code> is pretty self-explanatory. More verbose, yes, but much clearer.</p>\n\n<p>I'd also consider using something besides <code>input</code> elements for the calculated prices. Technically, any element would work, and be eaiser to style than an <code>input</code> element. Since the fields are all readonly, they really aren't <em>inputs</em> anymore anyway. In your case, I'd probably use a table element (since it's monetary stuff) with ID'd <code>td</code> elements, and set their content with <code>innerHTML</code>. </p>\n\n<p>The <code>df[2].onclick = ...</code> bit makes little sense to me. There are 4 fields with calculated values, so why does one in particular get a click-handler? Furthermore, the click handler makes it difficult for a user to (for instance) select the calculated price in that input and copy it. I just fail to see the point - seems like some old, left-over code.</p>\n\n<p>Lastly, the <code>util</code> object ends up in the global scope, which is generally bad practice. Like <code>window.onload</code> you risk overwriting something or being overwritten by something. It doesn't need to be there, though. If <code>formatCurrency</code> is defined inside the <code>onload</code> function, it'll be available there without polluting the global scope.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T17:10:53.793", "Id": "13228", "ParentId": "13201", "Score": "2" } } ]
{ "AcceptedAnswerId": "13228", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T20:27:56.390", "Id": "13201", "Score": "4", "Tags": [ "javascript", "html", "calculator" ], "Title": "Calculator for calculating price per feet amounts" }
13201
<p>I just started to program Python. As my first application I implemented an interactive console which automatically python modules before a new code block is evaluated. Here is the code:</p> <pre><code>### module "module_reloading_console.py" import sys import code import imp import readline import os class ModuleReloadingConsole(code.InteractiveConsole): def __init__(self): super().__init__() readline.parse_and_bind("tab: complete") self.stored_modifier_times = {} self.check_modules_for_reload() def runcode(self, code): self.check_modules_for_reload() super().runcode(code) self.check_modules_for_reload() # maybe new modules are loaded def check_modules_for_reload(self): for module_name, module in sys.modules.items(): if hasattr(module, '__file__'): module_modifier_time = os.path.getmtime(module.__file__) if module_name in self.stored_modifier_times: if module_modifier_time &gt; self.stored_modifier_times[module_name]: imp.reload(module) self.stored_modifier_times[module_name] = module_modifier_time else: self.stored_modifier_times[module_name] = module_modifier_time ModuleReloadingConsole().interact("Welcome to ModuleReloadingConsole") </code></pre> <p><strong>Usage:</strong></p> <pre><code>~: python3 module_reloading_console.py Welcome to ModuleReloadingConsole &gt;&gt;&gt; import test &gt;&gt;&gt; test.foo 23 &gt;&gt;&gt; test.foo # in the meanwhile change foo to '42' in test.py 42 </code></pre> <p>Because I am really new to Python I want to now which improvements you have for the above code. Are there common Python conventions I have not considered?</p> <p><em>marginal note:</em> <a href="http://code.activestate.com/recipes/160164/" rel="nofollow">this code recipe (automatically upgrade class instances on reload())</a> would be a good improvement. Maybe also <a href="http://www.elifulkerson.com/projects/python-dynamically-reload-module.php" rel="nofollow">this article about dynamically reloading a python code</a> might improve the code...</p>
[]
[ { "body": "<h1>Automatic tools</h1>\n\n<p><em>PEP8</em>: I'd say your code's OK style wise, but this is what the checker said:</p>\n\n<pre><code>1:1: E266 too many leading '#' for block comment\n19:40: E261 at least two spaces before inline comment\n27:80: E501 line too long (86 &gt; 79 characters)\n29:80: E501 line too long (82 &gt; 79 characters)\n31:80: E501 line too long (82 &gt; 79 characters)\n</code></pre>\n\n<p><em>Pylint</em>: Apart for missing doc strings, the only thing it finds is that in your <code>runcode</code> method, you shadow a module name, <code>code</code>. It may be better to call you argument <code>code_to_run</code> or <code>inp</code> so that <code>code</code> always refers to the module. But, as the method's short, its not a big deal.</p>\n\n<h1>Human tool</h1>\n\n<p>Your <code>check_modules_for_reload</code> method looks like this:</p>\n\n<pre><code>def check_modules_for_reload(self):\n for module_name, module in sys.modules.items():\n if hasattr(module, '__file__'):\n module_modifier_time = os.path.getmtime(module.__file__)\n\n if module_name in self.stored_modifier_times:\n if module_modifier_time &gt; self.stored_modifier_times[module_name]:\n imp.reload(module)\n self.stored_modifier_times[module_name] = module_modifier_time\n else:\n self.stored_modifier_times[module_name] = module_modifier_time\n</code></pre>\n\n<p>Things to note:</p>\n\n<ul>\n<li><p>Your <code>if</code> statement checking if you have already seen the module contains the line:</p>\n\n<pre><code>self.stored_modifier_times[module_name] = module_modifier_time\n</code></pre>\n\n<p>As this occurs in both branches of the <code>if</code> statement, you can move it out, after the branching.</p></li>\n<li>Currently your code involves 4 indentation levels. You can reduce this by inverting the <code>check_modules_for_reload</code> logic and using <code>continue</code>.</li>\n</ul>\n\n<p>The code now looks like:</p>\n\n<pre><code>def check_modules_for_reload(self):\n for module_name, module in sys.modules.items():\n if not hasattr(module, '__file__'):\n continue\n module_modifier_time = os.path.getmtime(module.__file__)\n\n if module_name in self.stored_modifier_times:\n if module_modifier_time &gt; self.stored_modifier_times[module_name]:\n imp.reload(module)\n self.stored_modifier_times[module_name] = module_modifier_time\n</code></pre>\n\n<p>We see that the nested <code>if</code> could be reduced to:</p>\n\n<pre><code>if module_name in self.stored_modifier_times and module_modifier_time &gt; self.stored_modifier_times[module_name]\n</code></pre>\n\n<p>That's long and horrid. But we can use <code>dict.get</code> combined with the fact <code>module_modifier_time &gt; module_modifier_time</code> is <code>False</code> to produce:</p>\n\n<pre><code>if self.stored_modifier_times.get(module_name, module_modifier_time) &lt; module_modifier_time\n</code></pre>\n\n<p>Which is slightly shorter. The code is now:</p>\n\n<pre><code>def check_modules_for_reload(self):\n for module_name, module in sys.modules.items():\n if not hasattr(module, '__file__'):\n continue\n\n module_modifier_time = os.path.getmtime(module.__file__)\n if self.stored_modifier_times.get(module_name, module_modifier_time) &lt; module_modifier_time:\n imp.reload(module)\n self.stored_modifier_times[module_name] = module_modifier_time\n</code></pre>\n\n<p>Two lines shorter, two indentation levels and a bit more DRY. It might not be much, but the code was good to start with. Other things:</p>\n\n<ul>\n<li><code>os.getmtime</code> may throw <code>OSError</code>, but assuming no ones deleting modules or doing weird things this should not matter.</li>\n<li><p><code>imp.reload</code> could throw a whole horde of exceptions, crashing the shell. E.g.:</p>\n\n<pre><code>&gt;&gt;&gt; m.a\nTraceback (most recent call last):\nFile \"rl.py\", line 32, in &lt;module&gt;\n ModuleReloadingConsole().interact(\"Welcome to ModuleReloadingConsole\")\nFile \"/usr/lib/python3.4/code.py\", line 234, in interact\n more = self.push(line)\nFile \"/usr/lib/python3.4/code.py\", line 256, in push\n more = self.runsource(source, self.filename)\nFile \"/usr/lib/python3.4/code.py\", line 74, in runsource\n self.runcode(code)\nFile \"rl.py\", line 17, in runcode\n self.check_modules_for_reload()\nFile \"rl.py\", line 28, in check_modules_for_reload\n imp.reload(module)\nFile \"/usr/lib/python3.4/imp.py\", line 315, in reload\n return importlib.reload(module)\nFile \"/usr/lib/python3.4/importlib/__init__.py\", line 149, in reload\n methods.exec(module)\nFile \"&lt;frozen importlib._bootstrap&gt;\", line 1153, in exec\nFile \"&lt;frozen importlib._bootstrap&gt;\", line 1129, in _exec\nFile \"&lt;frozen importlib._bootstrap&gt;\", line 1467, in exec_module\nFile \"&lt;frozen importlib._bootstrap&gt;\", line 1572, in get_code\nFile \"&lt;frozen importlib._bootstrap&gt;\", line 1532, in source_to_code\nFile \"&lt;frozen importlib._bootstrap&gt;\", line 321, in _call_with_frames_removed\nFile \"/home/matthew/m.py\", line 1\n a=5svnls2 \n ^\nSyntaxError: invalid syntax\n</code></pre>\n\n<p>After which the shell exits.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-18T20:10:47.367", "Id": "91096", "ParentId": "13203", "Score": "3" } } ]
{ "AcceptedAnswerId": "91096", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T21:10:11.767", "Id": "13203", "Score": "2", "Tags": [ "python" ], "Title": "Python interactive console which automatically reload modules" }
13203
<p>The below sections of code are part of a list administration project I am working on to teach myself C#. This is from a tab that is used for list administration. There is a drop down box that allows selection of list administrators, which populates a dropdown box with available lists.</p> <p>Once a list is selected, it populates two listboxes with users associated with the list administrators organization (such as a dance school), one has users that are in the list, the others are ones not in the list.</p> <p>Before I start coding the moving of users between boxes and updating the tables, have I approached the methodology in the most efficient way? I know it works, but is there a method of setting it up I should look at to make things easier as I move forward?</p> <p>Code for list selection and listbox population:</p> <pre><code>/* * DATA MANIPULATION AND FORM ROUTINES FOR THE LISTS TAB * */ private void btnEditList_Click(object sender, EventArgs e) { string disp = cmbListAdmins.SelectedValue.ToString(); string listQuery = "SELECT * FROM test.tbl_lists WHERE test.tbl_lists.user_id = " + disp + ";"; dbconn = new MySqlConnection(connString); MySqlDataAdapter listadapter = new MySqlDataAdapter(listQuery, dbconn); DataTable dtAvailLists = new DataTable(); try { listadapter.Fill(dtAvailLists); dtAvailLists.Columns.Add("FullName", typeof(string), "list_name + ' ' + list_description"); BindingSource bindsource1 = new BindingSource(); bindsource1.DataSource = dtAvailLists; cmbListSelect.DataSource = bindsource1; cmbListSelect.DisplayMember = "FullName"; cmbListSelect.ValueMember = "list_id"; cmbListSelect.Enabled = true; } catch (Exception err) { File.AppendAllText(logFileName, string.Format("{0}: Unable to fill list admin combo: Query is {1}, result is {2}.", DateTime.Now, listQuery, err, System.Environment.NewLine)); } dbconn.Close(); } private void cmbListSelect_SelectionChangeCommitted(object sender, EventArgs e) { lstExistingMembers.Items.Clear(); lstAvailableMembers.Items.Clear(); string disp = cmbListSelect.SelectedValue.ToString(); string memberQuery = "SELECT lm.list_id, lm.user_id, ua.user_first_name, ua.user_last_name, ua.user_id " + "FROM test.tbl_listmembers AS lm " + "LEFT JOIN test.tbl_user_accounts AS ua ON (ua.user_id = lm.user_id) " + "WHERE (lm.list_id = '" + disp + "')"; dbconn = new MySqlConnection(connString); MySqlDataAdapter listadapter = new MySqlDataAdapter(memberQuery, dbconn); DataTable dtListMembers = new DataTable(); try { string fullname = ""; string notClause = ""; listadapter.Fill(dtListMembers); foreach (DataRow dr in dtListMembers.Rows) { fullname = dr[2].ToString() + " " + dr[3].ToString(); lstExistingMembers.Items.Add(fullname); lstExistingMembers.ValueMember = dr[4].ToString(); notClause += "'" + dr[4].ToString() + "',"; } notClause = notClause.Substring(0, notClause.Length - 1); string nonMemberQuery = "SELECT concat(user_first_name, ' ', user_last_name) as username, user_id FROM test.tbl_user_accounts " + "WHERE user_id NOT IN (" + notClause + ");"; dbconntwo = new MySqlConnection(connString); MySqlDataAdapter listadaptertwo = new MySqlDataAdapter(nonMemberQuery, dbconntwo); DataTable dtListNonMembers = new DataTable(); try { listadaptertwo.Fill(dtListNonMembers); foreach (DataRow dr2 in dtListNonMembers.Rows) { lstAvailableMembers.Items.Add(dr2[0].ToString()); lstAvailableMembers.ValueMember = dr2[1].ToString(); } } catch (Exception err) { File.AppendAllText(logFileName, string.Format("{0}: Unable to fill list non members listbox: Query is {1}, result is {2}.", DateTime.Now, nonMemberQuery, err, System.Environment.NewLine)); } dbconntwo.Close(); } catch (Exception err) { File.AppendAllText(logFileName, string.Format("{0}: Unable to fill list members listbox: Query is {1}, result is {2}.", DateTime.Now, memberQuery, err, System.Environment.NewLine)); } dbconn.Close(); } </code></pre> <p>If needed, I can post the code from the database class that I have as well.</p>
[]
[ { "body": "<p>It seems to me that if <code>File.AppendAllText</code> throws an exception <code>dbConn</code> won't be closed.\nThe <code>dbConn.Close()</code> should be in a <code>finally</code> block. (<a href=\"https://stackoverflow.com/questions/901149/exception-inside-catch-block\">Exception inside catch block</a>.)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:55:19.667", "Id": "21356", "Score": "0", "body": "well, THAT would never happen :p. How do you trap an error in a catch? Another try catch?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:59:49.647", "Id": "21357", "Score": "0", "body": "It could, see the edit please :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T23:43:59.997", "Id": "21371", "Score": "0", "body": "+1 I agree close() should defo in a finally block. In fact I would put the dbConn = new MySQLConnection and it's 2 following lines in the try as well (to handle db connection errors) and check for null on dbConn in the finally block." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:52:45.223", "Id": "13207", "ParentId": "13204", "Score": "6" } }, { "body": "<p>Current code do the work.</p>\n\n<p>I recommend you have a further reading about \"n-tiers\" because you have dataaccess in your frontend, and this practice brings a high code coupling. Working in layers you could continue your C# developer skills with concepts like unit test (with tools like NUnit) and TDD.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-04T04:51:14.337", "Id": "13302", "ParentId": "13204", "Score": "2" } }, { "body": "<p><strong>MySQL</strong></p>\n\n<p>I can't speak to C# but I have a few ideas to optimize your MySQL queries. There is very likely a way to pass parameters to SQL that is better than concatenating SQL within your code, <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/bb738521%28v=vs.100%29.aspx\" rel=\"nofollow\">I suggest you look into that</a>. </p>\n\n<p>As far as MySQL is concerned, you would obtain multiple benefits from using stored <code>PROCEDURE</code> instead of just passing code to the RDBMS:</p>\n\n<ol>\n<li><p>Better performance for repeat queries.</p></li>\n<li><p>Easier to maintain.</p></li>\n<li><p>Consistent result set.</p></li>\n<li><p>Can be called from multiple scripts in multiple languages easily. </p></li>\n</ol>\n\n<p>Here is the code I would use to create the 3 <code>PROCEDURE</code>s in this case:</p>\n\n<pre><code>DELIMITER |\nCREATE PROCEDURE sp_cmbListAdmins (IN p_cmbListAdmins)\nAS\nBEGIN\n SELECT * \n FROM test.tbl_lists \n WHERE test.tbl_lists.user_id = cmbListAdmins\n ;\nEND|\nCREATE PROCEDURE sp_memberQuery (IN p_list_id)\nAS\nBEGIN\n SELECT \n lm.list_id, \n lm.user_id, \n ua.user_first_name, \n ua.user_last_name, \n ua.user_id\n FROM test.tbl_listmembers AS lm\n LEFT JOIN test.tbl_user_accounts AS ua \n ON ua.user_id = lm.user_id \n WHERE lm.list_id = p_list_id\n ;\nEND|\nCREATE PROCEDURE sp_nonMemberQuery (IN p_notClause)\nAS\nBEGIN\n SELECT concat(user_first_name, ' ', user_last_name) as username, \n user_id \n FROM test.tbl_user_accounts\n WHERE user_id NOT IN notClause\n ;\nEND|\nDELIMITER ;\n</code></pre>\n\n<p>Note that the above code only needs executed once. </p>\n\n<p>Then from C# you can just do something like... </p>\n\n<pre><code> string disp = cmbListAdmins.SelectedValue.ToString();\n\n string listQuery = \"CALL sp_cmbListAdmins(\" + disp + \")\";\n</code></pre>\n\n<p>And...</p>\n\n<pre><code> string disp = cmbListSelect.SelectedValue.ToString();\n string memberQuery = \"CALL sp_memberQuery(\" + disp + \"')\";\n</code></pre>\n\n<p>And finally...</p>\n\n<pre><code> notClause = notClause.Substring(0, notClause.Length - 1);\n\n string nonMemberQuery = \"CALL sp_nonMemberQuery(\" + notClause + \")\";\n</code></pre>\n\n<p>Of course you would want to name things appropriately, I just picked names from the stuff you wrote in your C# script. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-10T01:11:54.033", "Id": "99767", "Score": "0", "body": "awesome. Thank you very much, I am just starting into t-sql." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-10T00:09:21.850", "Id": "56612", "ParentId": "13204", "Score": "5" } }, { "body": "<p>Code duplication is not a nice idea, it's a massive indication of code smell. You can create a helper class for your common code, ex: getting db connections, creating data tables, etc...</p>\n\n<pre><code> private static IDbConnection GetConnection()\n {\n var connectionString = \"\"; //read from config file\n IDbConnection connection = new MySqlConnection(connectionString);\n connection.Open();\n return connection;\n }\n\n public DataTable GetDataTable(string sql, params object[] parameterValues)\n {\n DataTable dataTable = new DataTable();\n using (var connection = GetConnection())\n {\n using (var command = connection.CreateCommand())\n {\n using (var da = new MySqlDataAdapter((MySqlCommand)command))\n {\n command.CommandText = sql;\n CreateCommandParameters(command, parameterValues);\n da.Fill(dataTable);\n\n }\n }\n }\n return dataTable;\n }\n private void CreateCommandParameters(IDbCommand command, object[] parameterValues)\n {\n if (parameterValues != null)\n {\n int index = 1;\n foreach (object paramValue in parameterValues)\n {\n IDbDataParameter param = command.CreateParameter();\n param.ParameterName = \"@P\" + index;\n if (paramValue == null)\n param.Value = DBNull.Value;\n else\n param.Value = paramValue;\n command.Parameters.Add(param);\n index++;\n }\n }\n }\n</code></pre>\n\n<p>Note that here I am using <code>Command Parameters</code> instead of string concatenation, YOU SHOULD always use command parameters to avoid <code>SQL injection attacks</code>.</p>\n\n<p>Moreover, the proper way for closing a connection is not calling <code>Close()</code> explicitly nor calling it in a <code>finally</code>, the proper way is using <code>using</code> statement.\nAnd as mentioned in previous answers your queries can be reworked to stored procedures that accepts parameters from your application, and there is a lot of benefits from doing that.</p>\n\n<ul>\n<li>You gain performance ( you don't need to send the sql command to the database every time, you would perform an ExecuteScalar on procedure call instead).</li>\n<li>Changing the query wouldn't require a code change which requires a build and a release </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-10T01:23:10.103", "Id": "99768", "Score": "0", "body": "Thank you for the pointers. As I noted in the original post (2 years ago), I was teaching myself C#. I have since created a logging class and a database access class that I include when I need those functions. I am working on cleaning up the SQL queries and the rest." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-10T01:27:39.543", "Id": "99769", "Score": "0", "body": "@JohnP brilliant, I've reviewed the code provided in the post" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-10T01:13:37.490", "Id": "56617", "ParentId": "13204", "Score": "1" } } ]
{ "AcceptedAnswerId": "56612", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T21:17:13.997", "Id": "13204", "Score": "5", "Tags": [ "c#", "mysql" ], "Title": "Query and data manipulation" }
13204
<p>I'm using this PHP to modify A elements in a DOM fragment (a vBulletin <code>$post['message']</code> if that matters) so that links to external sites always open new tabs. This is actually the default in vBulletin but it's not always reliable. Anyway, the code works, but looking at the loop makes me think it could be done better. Any suggestions?</p> <pre><code>$as = $doc-&gt;getElementsByTagName('a'); for ( $i = $as-&gt;length; --$i &gt;= 0; ) { $a = $as-&gt;item($i); $aParts = parse_url ( strtolower ( $a-&gt;getAttribute('href') ) ); if ( $aParts['host'] !== $localDomain ) { $a-&gt;setAttribute ( 'title', @$a-&gt;getAttribute ('title') . " [external link to {$aParts['host']}]" ); $a-&gt;setAttribute ( 'target', '_blank' ); } // if } // for </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:24:39.817", "Id": "21359", "Score": "0", "body": "interesting that you inverted the loop and counted down from `NodeList::length` - did you have a particular reason for doing it that way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:31:43.980", "Id": "21360", "Score": "0", "body": "@prodigitalson I adapted that from another area where I'd removed an element during the loop; if you count from the beginning, the index gets messed up when you remove one, but if you count from the end it works. No particular reason for doing it that way this time, just some consistency." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:45:55.743", "Id": "21361", "Score": "0", "body": "Looks OK to me. Not sure how it would perform with a high number of iterations. It might be overkill, but another approach would be to run some XSL on this DOM, using an identity/copy pattern to output the same HTML, but with the tweaks you require." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:48:48.267", "Id": "21362", "Score": "0", "body": "@AndrewRich You know you can just `foreach` over a `DOMNodeList`, right?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:49:16.270", "Id": "21363", "Score": "0", "body": "@Utkanos There aren't usually a large number of links in each message (so not many iterations each time), but the code is called as many times as there are posts on a thread page, which could be as many as 50." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:50:44.820", "Id": "21364", "Score": "0", "body": "@DaveRandom I didn't. Can you give me or point me to an example? Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:52:24.400", "Id": "21365", "Score": "2", "body": "You literally just treat it the same way as you would an array. Like you could do [this](http://codepad.org/6mOXZ5AN)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:54:12.950", "Id": "21366", "Score": "0", "body": "I might get flamed for this, but I'd probably REGEX it. Generally you should favour DOM methods over REGEX for this sort of thing, but REGEX wins on performance in cases where there's potentially a large loop." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:55:25.553", "Id": "21367", "Score": "2", "body": "If you look at the docs you'll see that [`DOMNodeList`](http://php.net/manual/en/class.domnodelist.php) implements the [`Traversable`](http://php.net/manual/en/class.traversable.php) interface - which means it will behave just like an array when used with `foreach`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:58:00.577", "Id": "21368", "Score": "1", "body": "@Utkanos Careful now... You're in danger of getting flogged for heresy or burned as a witch..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:59:42.633", "Id": "21369", "Score": "0", "body": "@DaveRandom Thanks, that's much appreciated." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T23:00:19.707", "Id": "21370", "Score": "0", "body": "@DaveRandom - haha, good job us REGEX sadists are not easily inflamed..." } ]
[ { "body": "<p>To make it elegant clean code I would:</p>\n\n<ul>\n<li>make proper use of blank lines;</li>\n<li>abide by the coding standards defined by <a href=\"http://www.php-fig.org/\" rel=\"nofollow\">PHP-FIG</a>;</li>\n<li>use the <code>DOMNodeList</code> object as an array so I can use <code>foreach()</code>;</li>\n<li>be consistent with either single <code>'</code> or double quotes <code>\"</code>;</li>\n<li>use a <a href=\"http://c2.com/cgi/wiki?GuardClause\" rel=\"nofollow\">guard clause</a>.</li>\n</ul>\n\n<p><strong>Refactored code:</strong></p>\n\n<pre><code>$aEls = $doc-&gt;getElementsByTagName('a');\n\nforeach ($aEls as $a) {\n $url = parse_url(strtolower($a-&gt;getAttribute('href')));\n\n if ($url['host'] === $localDomain) {\n continue;\n }\n\n $title = $a-&gt;getAttribute('title') . ' [external link to ' . $url['host'] . ']';\n\n $a-&gt;setAttribute('title', $title);\n $a-&gt;setAttribute('target', '_blank');\n}\n</code></pre>\n\n<p>(<em>not tested</em>)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-14T08:01:57.870", "Id": "90717", "ParentId": "13208", "Score": "2" } }, { "body": "<p>DOM is a tree structure that consists of well defined objects (nodes) therefore I wouldn't use <em>for</em> loop.<br>\nMoreover, I don't know how <em>for</em> would influence the code if you need to do more radical actions like delete an element. I know for sure that if you delete an element while you are in a <em>foreach</em> loop you get an error and your changes are not committed.</p>\n\n<p>There are 2 other easy ways to find elements in the DOM without using <em>for</em> or <em>foreach</em>:<br>\n- use Xpath - I would say the common and easiest approach because it doesn't need difficult coding<br>\n- use a recursive function to go through DOM; below how I would code this using an abstract class and closures. Another option is just to use a standard function in the global context but closures give some flexibility. </p>\n\n<pre><code>abstract class Utils\n{\n static function loop(&amp;$elem,$func)\n {\n $closure = function(&amp;$el,$func){\n if($el-&gt;nodeType == 1 &amp;&amp; $el-&gt;nodeName == \"a\"){\n $func = $fun-&gt;bindTo($el);\n $func($el);\n }\n else {\n if($el instanceof DOMNode &amp;&amp; $el-&gt;hasChildNodes()){\n $current = $el-&gt;firstChild;\n while($current instanceof DOMNode){\n self::loop($current,$func);\n $current = $current-&gt;nextSibling;\n }\n }\n };\n };\n return $closure($elem,$func);\n }\n}\n\nUtils::loop($documentRootNode,function(&amp;$a){\n//do what you have to do here\n//your A is either $a parameter or $this\n//binding is not necessarily needed but is an option\n});\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-05-14T13:41:56.080", "Id": "90737", "ParentId": "13208", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "12", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-29T22:21:09.923", "Id": "13208", "Score": "2", "Tags": [ "php", "dom" ], "Title": "Looping through DOM to modify elements" }
13208
<p>I am trying to solve a puzzle. I came up with a few classes to represent results. They looked similar, so I defined a common <code>Result</code> class. But what if I need to define different results according to different functions?</p> <p>In other words, do I need <code>TypeOneResult</code> and <code>TypeTwoResult</code> or only <code>CommonResult</code>? </p> <p>If I get rid of the different result classes and rely on <code>CommonResult</code>, how can I store some specific information about the result?</p> <pre><code>public class Result { private String id; private String data; public Result(String id, String data) { super(); this.id = id; this.data = data; } } </code></pre> <hr> <pre><code>class CommonResult extends Result{ private String type; public CommonResult(String id, String data, String type) { super(id, data); this.type = type; } } </code></pre> <hr> <pre><code>class TypeOneResult extends CommonResult{ public TypeOneResult(String id, String data, String type) { super(id, data, type); } } </code></pre> <hr> <pre><code>class TypeTwoResult extends CommonResult{ public TypeTwoResult(String id, String data, String type) { super(id, data, type); } } </code></pre>
[]
[ { "body": "<p>I'm not sure I understood your question fully, but from what I could understand, you do not need to have both TypeOneResult and TypeTwoResult. In fact, you probably do not need either of them. You can use the value of the <code>type</code> member of the CommonResult class to distinguish among the different types.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T01:44:02.730", "Id": "13211", "ParentId": "13210", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T01:22:39.247", "Id": "13210", "Score": "1", "Tags": [ "java" ], "Title": "java code design puzzle for common function result module" }
13210
<p>Is this the best way of doing this. The sample code is a simple lookup of postnr (read zipcode). I'm trying to encapsulate <strong>all</strong> the client side logic inside one "class".</p> <ol> <li>Is this the way of doing callbacks? The this/that stuff sort of creeps me out a little</li> <li>Should the constructor just be a place where you declare variables? I have a init function call here that sets things up. But it is public and I wonder if there is some best practice around this? </li> </ol> <hr> <pre><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt; &lt;head&gt; &lt;title&gt;Untitled Page&lt;/title&gt; &lt;script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function () { var controller = new ClientController("postnr", "poststed"); }); var ClientController = function (postNr, postSted) { this.postNrCtrl = $("#" + postNr); this.postStedCtrl = $("#" + postSted); this.init(); }; ClientController.prototype = function () { // private variables/methods var init = function () { // Keep reference to this var that = this; // Setup event handling this.postNrCtrl.change(function () { that.getPostSted($(this).val()); }); }; var getPostSted = function (postnr) { // keep reference context/this var that = this; $.getJSON("http://fraktguide.bring.no/fraktguide/api/postalCode.json?country=no&amp;pnr=" + postnr + "&amp;callback=?", function (data) { that.postStedCtrl.val(data.result); }); }; // public variables/methods return { init: init, getPostSted: getPostSted }; } (); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;label for="postnr"&gt;Postnr&lt;/label&gt; &lt;input type="text" id="postnr" /&gt; &lt;label for="poststed"&gt;Poststed&lt;/label&gt; &lt;input type="text" id="poststed" /&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p><strong>Update:</strong> To answer your specific questions (which I just now realized I completely neglected):</p>\n\n<ol>\n<li><p>The <code>this/that</code> stuff is one way of doing \"context resolution\" (you used the word \"callback\", but that's when you pass a function to another function). There are other ways, such as <code>Function.bind</code>/<code>jQuery.proxy</code>, but in your case assigning a local <code>that</code> variable is a valid and customary way of doing it.</p></li>\n<li><p>Sure, you can have the constructor do nothing except declare and assign instance variables. But there are no written or unwritten rules regarding a construtor's responsibilities, so it's up to you what it should do. As you say the <code>init</code> method ends up being public, which isn't terribly useful - in fact, <code>init</code> is only useful once in the object's lifetime, so it should probably be in the constructor. And if it's in the constructor, you don't need to assign instance variables; they work fine as local variables and closures. And if they're closures, you don't need the <code>this/that</code> either...</p></li>\n</ol>\n\n<p>... and so you don't actually need a \"class\" anymore, which is how I arrived at the code below.</p>\n\n<hr>\n\n<p>It depends on your specific needs, but with the example you give, it seems like overkill to have a \"class\" (constructor + prototype) to handle that bit of logic. You can make do with:</p>\n\n<pre><code>$(function () { // shorthand for $(document).ready(...)\n var postNrCtrl = $(\"#postnr\"),\n postStedCtrl = $(\"#poststed\");\n\n postNrCtrl.on(\"change\", function () {\n var postnr = jQuery.trim(this.value);\n\n // if the field is empty, clear the postStedCtrl and stop\n if( !postnr ) {\n postStedCtrl.val(\"\");\n return;\n }\n\n // Return if the value isn't 4 digits (i.e.\n // if it isn't a valid Norwegian postal code)\n if( !/^\\d{4}$/.test(postnr) ) {\n // perhaps you want to alert the user here before returning\n return;\n }\n\n // Make an explicit JSONP request to get around same-origin policy\n // jQuery takes care of encoding the params and adding the callback param\n $.ajax({\n type: \"GET\",\n dataType: \"jsonp\",\n url: \"http://fraktguide.bring.no/fraktguide/api/postalCode.json\",\n data: {\n country: \"no\",\n pnr: postnr\n }\n }).done(function (data) {\n if( data &amp;&amp; data.valid ) { // check the response a little\n postStedCtrl.val(data.result); // postStedCtrl is available via closure\n }\n });\n });\n});\n</code></pre>\n\n<p><strong><a href=\"http://jsfiddle.net/T2hde/\" rel=\"nofollow\">Here's a demo</a></strong></p>\n\n<p>On a more general note: For things like controller-logic, I find \"classes\" too cumbersome. You only need 1 instance of a controller, so coding a prototype and construtor only to instantiate it once, seems like overkill in a language like JavaScript that has object literals and closures.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-11T09:02:51.243", "Id": "222715", "Score": "0", "body": "\"But there are no written or unwritten rules regarding a construtor's responsibilities\" - I disagree. There is almost certainly an unwritten rule that a constructor should only ever prepare an object to be used. If there isn't, their should be - I'm having to debug code now that does lots of silly things in the constructor and it's a pain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-02-11T10:21:07.863", "Id": "222732", "Score": "0", "body": "@DanPantry Fair point. My argument was a bit exaggerated. Of course you don't want your constructor to be a tangled mess; I was just rather presenting a counterpoint to the constructor being \"just a place where you declare variables\" as OP wrote. You're right that the constructor should only \"prepare an object\"; I just meant that that can involve more than _just_ declaring vars. In OP's case preparation had been split into constructor and `init` when there was really no need." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T15:30:57.150", "Id": "13224", "ParentId": "13212", "Score": "1" } } ]
{ "AcceptedAnswerId": "13224", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T07:55:33.103", "Id": "13212", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Encapsulation of client side logic in web page" }
13212
<p>I have to display all the numbers between 200 and 600 (both numbers inclusive) that are divisible by 8:</p> <pre><code>for($i=200;$i&lt;=600;$i++) { if($i%8==0) echo $i.','; } </code></pre> <p>It reaches maximum execution time.</p>
[]
[ { "body": "<ol>\n<li><p>Why do you test each number?</p>\n\n<p>Rather than <code>$i++</code> you can use <code>$i += 8</code>. Then the test becomes redundant. </p></li>\n<li><p>Your output is terminated by <code>,</code></p>\n\n<pre><code>...584,592,500,\n ^^^^ Extra trailing comma.\n</code></pre></li>\n</ol>\n\n<p>I would do:</p>\n\n<pre><code>printf('%d', 200);\nfor($i = 208; $i &lt;= 600; $i += 8)\n{\n printf(', %d', $i);\n}\nprintf('\\n');\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T13:06:07.943", "Id": "13218", "ParentId": "13217", "Score": "12" } }, { "body": "<p><code>echo</code><a href=\"http://php.net/implode\"><code>implode</code></a><code>(\",\",</code><a href=\"http://php.net/range/\"><code>range</code></a><code>(200,600,8) );</code></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T21:06:28.970", "Id": "21391", "Score": "3", "body": "about as elegant as it can get. bravo." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T23:45:52.087", "Id": "21408", "Score": "0", "body": "+1 Obviously the best answer. I would delete mine but I can't while it is accepted." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T11:29:26.723", "Id": "21412", "Score": "0", "body": "If one more person upvotes your answer, I get a Populist badge, which would be awesome :D" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T13:16:17.523", "Id": "21413", "Score": "0", "body": "Epic win. Had no idea such a function existed in PHP. Thanks for sharing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-02T13:26:14.650", "Id": "21414", "Score": "0", "body": "Have a gold bade on me then." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T15:28:04.510", "Id": "13223", "ParentId": "13217", "Score": "34" } } ]
{ "AcceptedAnswerId": "13223", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T12:46:35.300", "Id": "13217", "Score": "5", "Tags": [ "php" ], "Title": "Displaying all the numbers between 200 and 600" }
13217
<p>I am trying to learn to format XSL more efficiently. I can tell by the definition of duplicate variables and nearly identical templates that I did not create this efficiently at all. How could I have formed this better?</p> <pre><code>Here is my XSL: you can see all of it at http://wwwstage.samford.edu/calendar/ADCCancel.xsl &lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:r25="http://www.collegenet.com/r25" xmlns:r25fn="http://www.collegenet.com/r25/functions" xmlns:xl="http://www.w3.org/1999/xlink" xmlns:fn="http://www.w3.org/2005/xpath-functions" version="2.0"&gt; &lt;xsl:output method="xml" encoding="UTF-8" version="1.0"/&gt; &lt;xsl:template match="/"&gt; &lt;xsl:variable name="pubdate"&gt; &lt;xsl:value-of select="r25:events/@pubdate"/&gt; &lt;/xsl:variable&gt; &lt;xsl:element name="CALENDAR_ENTERPRISE"&gt; &lt;xsl:attribute name="Created"&gt; &lt;xsl:value-of select="$pubdate"/&gt; &lt;/xsl:attribute&gt; &lt;xsl:element name="TIMEZONE"&gt; &lt;xsl:attribute name="type"&gt;group&lt;/xsl:attribute&gt; &lt;xsl:element name="GMTOffset"&gt; &lt;xsl:attribute name="type"&gt;text&lt;/xsl:attribute&gt; &lt;xsl:text&gt;-6&lt;/xsl:text&gt; &lt;/xsl:element&gt; &lt;/xsl:element&gt; &lt;xsl:apply-templates select="r25:events/r25:event/r25:profile"&gt; &lt;xsl:sort select="r25:init_start_dt"/&gt; &lt;/xsl:apply-templates&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;xsl:template match="r25:profile"&gt; &lt;xsl:variable name="evtname" select="../r25:event_name"/&gt; &lt;xsl:variable name="evttitle" select="../r25:event_title"/&gt; &lt;xsl:variable name="refno" select="../r25:event_locator"/&gt; &lt;xsl:variable name="profilename" select="r25:profile_name"/&gt; &lt;xsl:variable name="desc" select="../r25:event_text[r25:text_type_id=1]/r25:text"/&gt; &lt;xsl:variable name="relweb" select="../r25:custom_attribute[r25:attribute_id=-1]/r25:attribute_value"/&gt; &lt;xsl:variable name="eventImage" select="../r25:custom_attribute[r25:attribute_id=-4]/r25:attribute_value"/&gt; &lt;xsl:variable name="ticket" select="../r25:custom_attribute[r25:attribute_id=4]/r25:attribute_value"/&gt; &lt;xsl:variable name="flyer" select="../r25:custom_attribute[r25:attribute_id=6]/r25:attribute_value"/&gt; &lt;xsl:variable name="contact" select="../r25:role[r25:role_id = -1]/r25:contact"/&gt; &lt;xsl:variable name="catsno" select="count(../r25:category)"/&gt; &lt;xsl:variable name="org" select="../r25:organization[r25:primary='T']/r25:organization_name"/&gt; &lt;xsl:variable name="created_dt" select="../r25:event_history[1]/r25:history_dt"/&gt; &lt;xsl:variable name="usetitle" select="../r25:custom_attribute[r25:attribute_id=6]/r25:attribute_value"/&gt; &lt;xsl:choose&gt; &lt;xsl:when test="r25:rec_type_id != 2"&gt; &lt;xsl:call-template name="RecurringEvent"&gt; &lt;xsl:with-param name="evtname" select="$evtname"/&gt; &lt;xsl:with-param name="evttitle" select="$evttitle"/&gt; &lt;xsl:with-param name="refno" select="$refno"/&gt; &lt;xsl:with-param name="profilename" select="$profilename"/&gt; &lt;xsl:with-param name="desc" select="$desc"/&gt; &lt;xsl:with-param name="relweb" select="$relweb"/&gt; &lt;xsl:with-param name="ticket" select="$ticket"/&gt; &lt;xsl:with-param name="flyer" select="$flyer"/&gt; &lt;xsl:with-param name="evtimg" select="$eventImage"/&gt; &lt;xsl:with-param name="contact" select="$contact"/&gt; &lt;xsl:with-param name="catsno" select="$catsno"/&gt; &lt;xsl:with-param name="org" select="$org"/&gt; &lt;xsl:with-param name="startdate" select="r25:init_start_dt"/&gt; &lt;xsl:with-param name="enddate" select="r25:init_end_dt"/&gt; &lt;xsl:with-param name="spaces" select="r25:reservation/r25:space_reservation"/&gt; &lt;xsl:with-param name="created" select="$created_dt"/&gt; &lt;xsl:with-param name="usetitle" select="$usetitle"/&gt; &lt;/xsl:call-template&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:apply-templates select="r25:reservation"&gt; &lt;xsl:with-param name="evtname" select="$evtname"/&gt; &lt;xsl:with-param name="evttitle" select="$evttitle"/&gt; &lt;xsl:with-param name="refno" select="$refno"/&gt; &lt;xsl:with-param name="profilename" select="$profilename"/&gt; &lt;xsl:with-param name="desc" select="$desc"/&gt; &lt;xsl:with-param name="relweb" select="$relweb"/&gt; &lt;xsl:with-param name="evtimg" select="$eventImage"/&gt; &lt;xsl:with-param name="ticket" select="$ticket"/&gt; &lt;xsl:with-param name="flyer" select="$flyer"/&gt; &lt;xsl:with-param name="contact" select="$contact"/&gt; &lt;xsl:with-param name="catsno" select="$catsno"/&gt; &lt;xsl:with-param name="org" select="$org"/&gt; &lt;xsl:with-param name="created" select="$created_dt"/&gt; &lt;xsl:with-param name="usetitle" select="$usetitle"/&gt; &lt;/xsl:apply-templates&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:template&gt; &lt;xsl:template name="RecurringEvent"&gt; &lt;!-- Setup variables for different parts of the XML for each event --&gt; &lt;xsl:param name="evtname"/&gt; &lt;xsl:param name="evttitle"/&gt; &lt;xsl:param name="refno"/&gt; &lt;xsl:param name="profilename"/&gt; &lt;xsl:param name="desc"/&gt; &lt;xsl:param name="relweb"/&gt; &lt;xsl:param name="ticket"/&gt; &lt;xsl:param name="flyer"/&gt; &lt;xsl:param name="evtimg"/&gt; &lt;xsl:param name="contact"/&gt; &lt;xsl:param name="catsno"/&gt; &lt;xsl:param name="org"/&gt; &lt;xsl:param name="startdate"/&gt; &lt;xsl:param name="laststartdate"/&gt; &lt;xsl:param name="enddate"/&gt; &lt;xsl:param name="spaces"/&gt; &lt;xsl:param name="created"/&gt; &lt;xsl:param name="usetitle"/&gt; XSL TO CREATE EVENTNODES &lt;/xsl:template&gt; &lt;xsl:template match="r25:reservation"&gt; &lt;!-- Setup variables for different parts of the XML for each event --&gt; &lt;xsl:param name="evtname"/&gt; &lt;xsl:param name="evttitle"/&gt; &lt;xsl:param name="refno"/&gt; &lt;xsl:param name="profilename"/&gt; &lt;xsl:param name="desc"/&gt; &lt;xsl:param name="relweb"/&gt; &lt;xsl:param name="evtimg"/&gt; &lt;xsl:param name="ticket"/&gt; &lt;xsl:param name="flyer"/&gt; &lt;xsl:param name="contact"/&gt; &lt;xsl:param name="catsno"/&gt; &lt;xsl:param name="org"/&gt; &lt;xsl:param name="created"/&gt; &lt;xsl:variable name="startdate" select="r25:event_start_dt"/&gt; &lt;xsl:variable name="enddate" select="r25:event_end_dt"/&gt; &lt;xsl:variable name="spaces" select="r25:space_reservation"/&gt; /// xsl to create Event Nodes &lt;/xsl:template&gt; &lt;xsl:template match="r25:category"&gt; &lt;xsl:variable name="goodcategories"&gt; &lt;!-- Only push marketing categories to the calendar. The list below represents their IDs --&gt; &lt;xsl:variable name="isinlist"&gt; &lt;xsl:value-of select="index-of((31,32,33,35,43,46,101,104,105,106,107,108,125,125,127,128,129),number(r25:category_id))" /&gt; &lt;/xsl:variable&gt; &lt;xsl:if test="$isinlist != ''"&gt; &lt;xsl:value-of select="concat(r25:category_name,'||')"/&gt; &lt;/xsl:if&gt; &lt;/xsl:variable&gt; &lt;xsl:value-of select="$goodcategories"/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="r25:rec_type_id"&gt; &lt;!-- This translates the R25 recurrence ID into something ADC understands based on http://knowledge25.collegenet.com/display/WSW/Profile+information--&gt; &lt;xsl:param name="code"/&gt; &lt;xsl:variable name="pattern" select="substring($code,1,2)"/&gt; &lt;xsl:element name="RecurType"&gt; &lt;xsl:choose&gt; &lt;!--rec type of 0 means there are no recurrences. it is just a one-off event --&gt; &lt;xsl:when test=". = 0"&gt; &lt;xsl:text&gt;One Time&lt;/xsl:text&gt; &lt;/xsl:when&gt; &lt;!--rec type of 2 means there are is a meeting pattern. the first 2 letters define the pattern. --&gt; &lt;xsl:when test=". = 1"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="substring($pattern,1,1) = 'W'"&gt; &lt;xsl:text&gt;Weekly&lt;/xsl:text&gt; &lt;xsl:value-of select="substring($pattern,2,1)"/&gt; &lt;/xsl:when&gt; &lt;!--Set if monthly--&gt; &lt;xsl:when test="substring($pattern,1,1) = 'M'"&gt; &lt;xsl:text&gt;Monthly by Date&lt;/xsl:text&gt; &lt;!--Unlike the others, the monthly patterns list the number on the 3rd character --&gt; &lt;xsl:value-of select="substring($code,3,1)"/&gt; &lt;/xsl:when&gt; &lt;!--Set if daily--&gt; &lt;xsl:when test="substring($pattern,1,1) = 'D'"&gt; &lt;xsl:text&gt;Interval&lt;/xsl:text&gt; &lt;xsl:value-of select="substring($pattern,2,1)"/&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt;&lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:when&gt; &lt;xsl:when test=". = 2"&gt; &lt;xsl:text&gt;Custom&lt;/xsl:text&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:text&gt;Otherwise&lt;/xsl:text&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:element&gt; &lt;xsl:element name="RecurEndDate"&gt; &lt;xsl:attribute name="type"&gt;text&lt;/xsl:attribute&gt; &lt;xsl:call-template name="parse-profile-code"&gt; &lt;xsl:with-param name="ProfileCode" select="$code"/&gt; &lt;xsl:with-param name="return"&gt;Date&lt;/xsl:with-param&gt; &lt;/xsl:call-template&gt; &lt;/xsl:element&gt; &lt;xsl:element name="RecurDays"&gt; &lt;xsl:attribute name="type"&gt;text&lt;/xsl:attribute&gt; &lt;!-- The following if statement is to take into account the rule mentioned on pg 8 of the import guide stating this is only supposed to be used if the recur type is weekly --&gt; &lt;xsl:if test="substring($pattern,1,1) = 'W'"&gt; &lt;xsl:call-template name="parse-profile-code"&gt; &lt;xsl:with-param name="ProfileCode" select="$code"/&gt; &lt;xsl:with-param name="return"&gt;Days&lt;/xsl:with-param&gt; &lt;/xsl:call-template&gt; &lt;/xsl:if&gt; &lt;/xsl:element&gt; &lt;/xsl:template&gt; &lt;xsl:template name="parse-profile-code"&gt; &lt;xsl:param name="ProfileCode"/&gt; &lt;xsl:param name="return"/&gt; &lt;xsl:analyze-string select="$ProfileCode" regex="^([DWMY])([MDP]?)([0-9]*)\s?(.*)?"&gt; &lt;xsl:matching-substring&gt; &lt;xsl:variable name="Rest"&gt; &lt;xsl:value-of select="regex-group(4)"/&gt; &lt;/xsl:variable&gt; &lt;xsl:variable name="Until"&gt; &lt;!-- Build the recur end date from the R25 profile code and store in a variable named until--&gt; &lt;xsl:choose&gt; &lt;xsl:when test="$return='Date'"&gt; &lt;xsl:analyze-string select="$Rest" regex="([0-9][0-9]*T[0-9]*([\-+][0-9]*|Z)?|#[0-9]*)"&gt; &lt;xsl:matching-substring&gt; &lt;!--The profile code lacks the necessary dashes to perform the format dateTime function. This inserts them in where needed. --&gt; &lt;xsl:value-of select="substring(regex-group(1),1,4)"/&gt; &lt;xsl:text&gt;-&lt;/xsl:text&gt; &lt;xsl:value-of select="substring(regex-group(1),5,2)"/&gt; &lt;xsl:text&gt;-&lt;/xsl:text&gt; &lt;xsl:value-of select="substring(regex-group(1),7,2)"/&gt; &lt;/xsl:matching-substring&gt; &lt;/xsl:analyze-string&gt; &lt;/xsl:when&gt; &lt;xsl:when test="$return='Days'"&gt; &lt;xsl:analyze-string select="$Rest" regex="([0-9][0-9]*T[0-9]*([\-+][0-9]*|Z)?|#[0-9]*)"&gt; &lt;xsl:matching-substring&gt; &lt;xsl:value-of select="normalize-space(regex-group(1))"/&gt; &lt;/xsl:matching-substring&gt; &lt;/xsl:analyze-string&gt; &lt;/xsl:when&gt; &lt;/xsl:choose&gt; &lt;/xsl:variable&gt; &lt;xsl:variable name="Days"&gt; &lt;xsl:choose&gt; &lt;xsl:when test="string-length($Until) = 0"&gt; &lt;xsl:value-of select="$Rest"/&gt; &lt;/xsl:when&gt; &lt;xsl:otherwise&gt; &lt;xsl:value-of select="normalize-space(substring-before($Rest,$Until))"/&gt; &lt;/xsl:otherwise&gt; &lt;/xsl:choose&gt; &lt;/xsl:variable&gt; &lt;xsl:choose&gt; &lt;xsl:when test="$return = 'Date'"&gt; &lt;xsl:value-of select="format-date($Until,'[M]/[D01]/[Y]')"/&gt; &lt;/xsl:when&gt; &lt;xsl:when test="$return = 'Days'"&gt; &lt;xsl:call-template name="listdays"&gt; &lt;xsl:with-param name="daylist"&gt; &lt;xsl:value-of select="$Days"/&gt; &lt;/xsl:with-param&gt; &lt;/xsl:call-template&gt; &lt;/xsl:when&gt; &lt;/xsl:choose&gt; &lt;/xsl:matching-substring&gt; &lt;/xsl:analyze-string&gt; &lt;/xsl:template&gt; &lt;xsl:template name="listdays"&gt; &lt;xsl:param name="daylist"/&gt; &lt;xsl:variable name="tokenizedDayList" select="tokenize($daylist,'\s+')"/&gt; &lt;xsl:for-each select="$tokenizedDayList"&gt; &lt;xsl:if test=". = 'MO'"&gt;Monday&lt;/xsl:if&gt; &lt;xsl:if test=". = 'TU'"&gt;Tuesday&lt;/xsl:if&gt; &lt;xsl:if test=". = 'WE'"&gt;Wednesday&lt;/xsl:if&gt; &lt;xsl:if test=". = 'TH'"&gt;Thursday&lt;/xsl:if&gt; &lt;xsl:if test=". = 'FR'"&gt;Friday&lt;/xsl:if&gt; &lt;xsl:if test=". = 'SA'"&gt;Saturday&lt;/xsl:if&gt; &lt;xsl:if test=". = 'SU'"&gt;Sunday&lt;/xsl:if&gt; &lt;xsl:if test=". != $tokenizedDayList[last()]"&gt; &lt;xsl:text&gt;,&lt;/xsl:text&gt; &lt;/xsl:if&gt; &lt;/xsl:for-each&gt; &lt;/xsl:template&gt; </code></pre> <p></p> <p>Here is a sample of the xml file being transformed: <a href="http://wwwstage.samford.edu/calendar/sampler25.xml" rel="nofollow">http://wwwstage.samford.edu/calendar/sampler25.xml</a> </p> <p>And here is a sample of the output I am producing: <a href="http://wwwstage.samford.edu/calendar/ADECancel.aspx" rel="nofollow">http://wwwstage.samford.edu/calendar/ADECancel.aspx</a></p>
[]
[ { "body": "<p>Some tips to improve your coding:</p>\n\n<p>(a) don't do this:</p>\n\n<pre><code>&lt;xsl:variable name=\"pubdate\"&gt;\n &lt;xsl:value-of select=\"r25:events/@pubdate\"/&gt;\n&lt;/xsl:variable&gt;\n</code></pre>\n\n<p>when you can do this:</p>\n\n<pre><code>&lt;xsl:variable name=\"pubdate\" select=\"r25:events/@pubdate\"/&gt;\n</code></pre>\n\n<p>The latter is not only one line of code instead of three, it's also much more efficient because it doesn't involve constructing a new tree.</p>\n\n<p>(b) don't do this:</p>\n\n<pre><code>&lt;xsl:element name=\"CALENDAR_ENTERPRISE\"&gt;\n &lt;xsl:attribute name=\"Created\"&gt;\n &lt;xsl:value-of select=\"$pubdate\"/&gt;\n &lt;/xsl:attribute&gt;\n</code></pre>\n\n<p>when you can do this:</p>\n\n<pre><code>&lt;CALENDAR_ENTERPRISE Created=\"{$pubdate}\"&gt;\n</code></pre>\n\n<p>In Saxon it won't make any performance difference, but it's much more readable.</p>\n\n<p>(c) I can't see why you are passing all these parameters. The values are all accessible from the context node, so I don't see why the called template can't get the values it needs by navigating from the context node.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T23:51:51.257", "Id": "13232", "ParentId": "13220", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T14:37:36.037", "Id": "13220", "Score": "1", "Tags": [ "xml", "xslt" ], "Title": "How can I optimize my XSL file?" }
13220
<p>I have used the following code for a stack implementation. The <code>top</code> keeps track of the topmost node of the stack. Now since <code>top</code> is a data member of the node function, each <code>node</code> created will have a <code>top</code> member, which ideally we wouldn't want.</p> <ol> <li>Is this good approach to coding?</li> <li>Will making <code>top</code> as <code>static</code> make it a better coding practice?</li> <li>Should I have a global declaration of <code>top</code>?</li> </ol> <p></p> <pre><code>#include&lt;iostream&gt; using namespace std; class node { int data; node *top; node *link; public: node() { top=NULL; link=NULL; } void push(int x) { node *n=new node; n-&gt;data=x; n-&gt;link=top; top=n; cout&lt;&lt;"Pushed "&lt;&lt;n-&gt;data&lt;&lt;endl; } void pop() { node *n=new node; n=top; top=top-&gt;link; n-&gt;link=NULL; cout&lt;&lt;"Popped "&lt;&lt;n-&gt;data&lt;&lt;endl; delete n; } void print() { node *n=new node; n=top; while(n!=NULL) { cout&lt;&lt;n-&gt;data&lt;&lt;endl; n=n-&gt;link; } delete n; } }; int main() { node stack; stack.push(5); stack.push(7); stack.push(9); stack.pop(); stack.print(); } </code></pre> <p>Any other suggestions welcome. I have also seen codes where there are two classes, where the second one has the top member. What about this?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T15:19:13.240", "Id": "21385", "Score": "0", "body": "making `top` global or static means you can use only one stack in your program! You might want to distinguish between the `node` and `list` classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T15:26:46.333", "Id": "21386", "Score": "0", "body": "Shahbaz, yes I get that. Thanks. :). So you suggest creating two classes where from the list I create an object of node to keep track?" } ]
[ { "body": "<ol>\n<li><p>In the <code>pop</code> and the <code>print</code> function, the <code>new node</code> seems unnecessary, since the next line modifies the pointer to point to the <code>top</code>. It could be simply</p>\n\n<pre><code>node *n = top;\n</code></pre></li>\n<li><p>The <code>delete n;</code> also looks superfluous in the <code>print</code> since <code>n</code> will always be <code>NULL</code> there.</p></li>\n<li><p>If I'm right making <code>top</code> as static or global would result that you can't have more than one stack in an application. Linked lists usually have two classes: one is a <code>Node</code> which stores a reference to the next node and the data, and the second is a <code>LinkedList</code> class which stores the head and the implementation of the <code>push</code>, <code>pop</code>, etc. methods. You can see <a href=\"https://stackoverflow.com/a/25311/843804\">an example in this answer</a>.</p></li>\n<li><p>Take care of the boundary cases. Calling <code>pop</code> on an empty stack gives a segmentation fault error. I suppose that's not the best error handling method :)</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T15:38:58.597", "Id": "21382", "Score": "1", "body": "Thanks. I get that. :). What can I possibly do with `node *top`? Should I create a new class called `list` or something and move the `top` as a member of this class instead?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T15:43:30.620", "Id": "21383", "Score": "0", "body": "I think you should have two classes here, see the update please." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T16:16:00.577", "Id": "21384", "Score": "1", "body": "Alright. :). I accept your solution. And thank you very much!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T15:33:07.603", "Id": "13225", "ParentId": "13226", "Score": "3" } }, { "body": "<p>I'd normally structure the code more like this:</p>\n\n<pre><code>template &lt;class T&gt;\nclass stack { \n class node {\n T data;\n node *next;\n\n node(T const &amp;i, node *n=NULL) : data(i), next(n) {}\n };\n\n node *top;\n\npublic:\n\n void push(T const &amp;in) {\n top = new node(in, top);\n } \n\n stack() : top(NULL) {}\n};\n</code></pre>\n\n<p>With this general structure, you get only one <code>top</code> per stack (instead of one in each node), but you can still create as many <code>stack</code> objects as you want (something that won't work if you make <code>top</code> a static or global).</p>\n\n<p>I've left <code>pop</code> un-implemented for the moment because it's really somewhat tricky to get correct. In particular, the typical definition of <code>pop</code> that removes the top item from the stack and returns its value can't be made exception safe unless you place some fairly tight restrictions on the data that can be stored. The stack class in the standard library takes the route of separating the two actions -- one function to get the value of the top-most item, and a second to remove the top item from the stack.</p>\n\n<p>It's not at all clear to me whether you'd really prefer to do that, or stick with a design that's easy to use, but may be unsafe.</p>\n\n<p>I see a couple of problems with your <code>print</code>. First of all, it leaks memory -- it allocates an object, and <em>attempts</em> to delete it, but before the <code>delete</code>, the pointer has been set to NULL, so the <code>delete</code> is a nop. I think that's a direct consequence of the second problem: it's really quite a bit more complex than necessary. I'd normally use something closer to this:</p>\n\n<pre><code>void print() { \n for (node *p=top; p!=NULL; p=p-&gt;next)\n std::cout &lt;&lt; p-&gt;data &lt;&lt; \"\\n\";\n}\n</code></pre>\n\n<p>One more possibility to consider would be to implement the stack as a linked list of nodes, but have each node capable of holding a number of items instead of just one. This can reduce the overhead of the pointers quite a bit (e.g., as your code is written right now, in a typical implementation you have twice as much space devoted to pointers as to the data).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T16:40:56.243", "Id": "13227", "ParentId": "13226", "Score": "3" } }, { "body": "<p>One alternative to having a separate class is to use the return value. For example:</p>\n\n<pre><code>Node * push(int x)\n{\n node *top = new node;\n top-&gt;data = x;\n top-&gt;link = this;\n return top;\n}\n</code></pre>\n\n<p>Then:</p>\n\n<pre><code>stack = stack-&gt;push(5);\nstack = stack-&gt;push(7);\nstack = stack-&gt;pop();\n</code></pre>\n\n<p>A separate stack class is probably easier to work with, but this is an option.</p>\n\n<p>Additionally, a linked list is a poor choice of data structure for a stack. In almost all circumstances, a resizable array is a much better choice.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-07-01T22:29:46.113", "Id": "21407", "Score": "0", "body": "Good advice for C. Not for C++." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T18:06:06.857", "Id": "13229", "ParentId": "13226", "Score": "3" } }, { "body": "<p>By the time I had this code together lots of people have made similar comments.</p>\n\n<p>Anyway, here is my attempt at refactoring your code.</p>\n\n<p>Main changes:</p>\n\n<ol>\n<li>templated type - more flexible.</li>\n<li>cleanup mechanism - destructor.</li>\n<li>general cleanup - lots of new where not required.</li>\n</ol>\n\n<p>Looks like this:</p>\n\n<pre><code>#include&lt;iostream&gt;\n\nusing namespace std;\n\ntemplate&lt;typename T&gt;\nclass node\n{\n T data;\n node *top;\n node *link;\n\n public:\n node()\n {\n top=NULL;\n link=NULL;\n }\n void push(const T&amp; x)\n {\n node *n=new node;\n n-&gt;data=x;\n n-&gt;link=top;\n top=n;\n cout&lt;&lt;\"Pushed \"&lt;&lt;n-&gt;data&lt;&lt;endl;\n }\n void pop()\n {\n node *n=top;\n top=top-&gt;link;\n n-&gt;link=NULL;\n cout&lt;&lt;\"Popped \"&lt;&lt;n-&gt;data&lt;&lt;endl;\n delete n;\n }\n void print()\n {\n node *n= top;\n while(n!=NULL)\n {\n cout&lt;&lt;n-&gt;data&lt;&lt;endl;\n n=n-&gt;link;\n }\n }\n ~node() {\n if(top) {\n node* current = top;\n node* next = 0;\n while (current != NULL) {\n next = current-&gt;link;\n delete current;\n current = next;\n }\n }\n }\n};\n\n\nint main()\n{\n node&lt;int&gt; stack;\n stack.push(5);\n stack.push(7);\n stack.push(9);\n stack.pop();\n stack.print();\n return 0;\n}\n</code></pre>\n\n<p>See @Loki's comment regarding The Rule of Three. In view of that here is my flawed second attempt:</p>\n\n<pre><code>#include&lt;iostream&gt;\n\nusing namespace std; //should not be in header file - just to remove std:: below\n\ntemplate &lt;class T&gt;\nclass stack { \n class node {\n public:\n T data;\n node* next;\n\n node(T const &amp;d) : data(d), next(0) {}\n\n node() : data(0), next(0) {}\n };\n\n node *top;\n\n public:\n stack() : top(0) {}\n\n stack(const stack&amp; s) {\n node* nextnode = s.top;\n while(nextnode != 0)\n {\n node* newnode = new node;\n newnode-&gt;data = nextnode-&gt;data;\n newnode-&gt;next = nextnode-&gt;next;\n nextnode=nextnode-&gt;next;\n top = newnode;\n cout&lt;&lt;\"copy constructed \"&lt;&lt; newnode-&gt;data &lt;&lt;endl;\n }\n }\n\n stack&amp; operator=(const stack&amp; s) {\n node* nextnode = s.top;\n while(nextnode != 0)\n {\n node* newnode = new node;\n newnode-&gt;data = nextnode-&gt;data;\n newnode-&gt;next = nextnode-&gt;next;\n top = newnode;\n cout&lt;&lt;\"operator = \"&lt;&lt; newnode-&gt;data &lt;&lt;endl;\n delete nextnode;\n nextnode=nextnode-&gt;next;\n } \n }\n\n ~stack() {\n if(top) {\n node* current = top;\n node* next = 0;\n while (current != 0) {\n next = current-&gt;next;\n cout &lt;&lt; \"dtor deleting node \" &lt;&lt; current-&gt;data &lt;&lt; endl;\n delete current;\n current = next;\n }\n }\n }\n\n void push(const T&amp; item)\n {\n node *n=new node;\n n-&gt;data=item;\n n-&gt;next = top;\n top=n;\n cout&lt;&lt;\"Push new'd node \"&lt;&lt; n-&gt;data &lt;&lt; endl;\n }\n void pop()\n {\n node *n=top;\n top=top-&gt;next;\n n-&gt;next=NULL;\n cout&lt;&lt;\"Pop delete'd node \"&lt;&lt; n-&gt;data &lt;&lt; endl;\n delete n;\n }\n void print()\n {\n node *n= top;\n while(n != 0)\n {\n cout&lt;&lt;n-&gt;data&lt;&lt;endl;\n n=n-&gt;next;\n }\n }\n};\n\n\nint main()\n{\n {\n stack&lt;int&gt; mystack;\n mystack.push(5);\n mystack.push(7);\n mystack.push(9);\n\n mystack.pop();\n mystack.print();\n\n //test of copy ctor\n stack&lt;int&gt; second(mystack);\n //test of assign operator\n stack&lt;int&gt; third = mystack;\n\n }\n return 0;\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T19:03:16.177", "Id": "21389", "Score": "0", "body": "Nice try. But this is not good. At a glance you fail the rule of three thus exposing yourself to double deletion and memory leaks all in one go. Try splitting into two classes `List` and `Node`. Then make sure the list implements rule of three." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T19:30:46.000", "Id": "21390", "Score": "0", "body": "@Loki - yes agreed. I just took posters code without really thinking too hard. I will spend time on it later on." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-28T15:40:39.113", "Id": "213973", "Score": "0", "body": "are you sure that your copy and assignment constructor work in correct way? Did you try to print, for example second.print()" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T18:28:50.150", "Id": "13230", "ParentId": "13226", "Score": "2" } } ]
{ "AcceptedAnswerId": "13225", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-06-30T15:12:10.980", "Id": "13226", "Score": "4", "Tags": [ "c++", "stack", "linked-list" ], "Title": "Linked list stack implementation" }
13226